vm

package
v0.0.0-...-cd7e48c Latest Latest
Warning

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

Go to latest
Published: Aug 16, 2025 License: MIT Imports: 10 Imported by: 0

Documentation

Index

Constants

View Source
const (
	StackSize   = 2048
	GlobalsSize = 65536
)

Variables

View Source
var (
	True  = types.NewBool(true)
	False = types.NewBool(false)
	Nil   = types.NewNil()

	// Pre-allocated common integers for performance
	CachedInts = make([]types.Value, 256) // Cache integers 0-255
)
View Source
var GlobalMemoryOptimizer = NewMemoryOptimizer()

Global memory optimizer instance

View Source
var GlobalOptimizedFactory = DefaultOptimizedFactory()

Global optimized factory instance

View Source
var GlobalVMPool = NewVMPool()

Global VM pool instance

Functions

func FormatInstruction

func FormatInstruction(def *Definition, operands []int) string

FormatInstruction formats an instruction for debugging

func Make

func Make(op Opcode, operands ...int) []byte

Make creates an instruction from opcode and operands

func ReadOperands

func ReadOperands(def *Definition, ins []byte) ([]int, int)

ReadOperands reads operands from instruction bytes

func ReleaseOptimizedVM

func ReleaseOptimizedVM(vm *VM)

ReleaseOptimizedVM releases VM resources back to memory pools

func RunOptimizedExpression

func RunOptimizedExpression(bytecode *Bytecode, env map[string]interface{}) (types.Value, error)

RunOptimizedExpression 运行优化表达式的便利方法

Types

type Bytecode

type Bytecode struct {
	Instructions []byte
	Constants    []types.Value
}

Bytecode represents compiled bytecode

type CacheStats

type CacheStats struct {
	Hits      int64
	Misses    int64
	Evictions int64
	Size      int
}

CacheStats tracks cache performance

type CachedExpression

type CachedExpression struct {
	Instructions []byte
	Constants    []types.Value
	UsageCount   int64
	LastUsed     int64
}

CachedExpression represents a cached compiled expression

type CachedSequence

type CachedSequence struct {
	Instructions []byte
	HitCount     int64
	Size         int
}

CachedSequence represents a cached instruction sequence

type CompilationCache

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

CompilationCache integrates with compiler for cached compilation

func NewCompilationCache

func NewCompilationCache() *CompilationCache

NewCompilationCache creates a new compilation cache

func (*CompilationCache) GetOrCompile

func (cc *CompilationCache) GetOrCompile(expression string, compileFunc func(string) ([]byte, []types.Value, error)) ([]byte, []types.Value, error)

GetOrCompile retrieves cached compilation or compiles new expression

type Definition

type Definition struct {
	Name         string
	OperandWidth []int // Width of each operand in bytes
}

Definition describes an instruction definition

func Lookup

func Lookup(op Opcode) (*Definition, error)

Lookup returns the definition for an opcode

type ExpressionCache

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

ExpressionCache caches compiled expressions

func (*ExpressionCache) CacheExpression

func (ec *ExpressionCache) CacheExpression(key string, instructions []byte, constants []types.Value)

CacheExpression stores a compiled expression

func (*ExpressionCache) GetCachedExpression

func (ec *ExpressionCache) GetCachedExpression(key string) (*CachedExpression, bool)

GetCachedExpression retrieves a cached expression

type InstructionCache

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

InstructionCache caches frequently executed instruction sequences

func NewInstructionCache

func NewInstructionCache(maxSize int) *InstructionCache

NewInstructionCache creates a new instruction cache

func (*InstructionCache) Clear

func (c *InstructionCache) Clear()

Clear clears the cache

func (*InstructionCache) Get

func (c *InstructionCache) Get(instructions []byte) (*CachedSequence, bool)

Get retrieves a cached instruction sequence

func (*InstructionCache) GetStats

func (c *InstructionCache) GetStats() CacheStats

GetStats returns cache statistics

func (*InstructionCache) HitRate

func (c *InstructionCache) HitRate() float64

HitRate returns the cache hit rate

func (*InstructionCache) Put

func (c *InstructionCache) Put(instructions []byte)

Put stores an instruction sequence in the cache

type InstructionHandler

type InstructionHandler func(vm *VM, instructions []byte, ip *int) (bool, error)

InstructionHandler represents a function that handles a specific opcode

type MemoryOptimizer

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

MemoryOptimizer implements P1 optimizations from PERFORMANCE_SUMMARY.md - Memory pre-allocation - Instruction buffer pre-allocation - String content pool - Expression parsing cache - Variable lookup cache

func NewMemoryOptimizer

func NewMemoryOptimizer() *MemoryOptimizer

NewMemoryOptimizer creates a new memory optimizer with P1 optimizations

func (*MemoryOptimizer) GetOptimizationStats

func (mo *MemoryOptimizer) GetOptimizationStats() OptimizationStats

GetOptimizationStats returns optimization performance statistics

func (*MemoryOptimizer) GetOptimizedGlobals

func (mo *MemoryOptimizer) GetOptimizedGlobals() []types.Value

GetOptimizedGlobals returns pre-allocated globals array

func (*MemoryOptimizer) GetOptimizedInstructionBuffer

func (mo *MemoryOptimizer) GetOptimizedInstructionBuffer() []byte

GetOptimizedInstructionBuffer returns a pre-allocated instruction buffer

func (*MemoryOptimizer) GetOptimizedStack

func (mo *MemoryOptimizer) GetOptimizedStack() []types.Value

GetOptimizedStack returns a pre-allocated stack

func (*MemoryOptimizer) PutOptimizedGlobals

func (mo *MemoryOptimizer) PutOptimizedGlobals(globals []types.Value)

PutOptimizedGlobals returns globals to the pool

func (*MemoryOptimizer) PutOptimizedInstructionBuffer

func (mo *MemoryOptimizer) PutOptimizedInstructionBuffer(buffer []byte)

PutOptimizedInstructionBuffer returns instruction buffer to pool

func (*MemoryOptimizer) PutOptimizedStack

func (mo *MemoryOptimizer) PutOptimizedStack(stack []types.Value)

PutOptimizedStack returns a stack to the pool

func (*MemoryOptimizer) ReleaseOptimizedGlobals

func (mo *MemoryOptimizer) ReleaseOptimizedGlobals(globals []types.Value)

ReleaseOptimizedGlobals returns a globals slice to the pool

func (*MemoryOptimizer) ReleaseOptimizedStack

func (mo *MemoryOptimizer) ReleaseOptimizedStack(stack []types.Value)

ReleaseOptimizedStack returns a stack slice to the pool

func (*MemoryOptimizer) ResetStats

func (mo *MemoryOptimizer) ResetStats()

ResetStats resets performance counters

type MemoryStats

type MemoryStats struct {
	StartMemory   uint64 // Memory at start of tracking
	CurrentMemory uint64 // Current memory usage
	PeakMemory    uint64 // Peak memory usage
	UsedMemory    uint64 // Memory used by expression execution
	Allocations   uint64 // Number of allocations
	Deallocations uint64 // Number of deallocations
	GCRuns        uint32 // Number of GC runs
}

MemoryStats contains memory usage statistics

type MemoryTracker

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

MemoryTracker tracks memory usage during VM execution

func NewMemoryTracker

func NewMemoryTracker() *MemoryTracker

NewMemoryTracker creates a new memory tracker

func (*MemoryTracker) Disable

func (mt *MemoryTracker) Disable()

Disable disables memory tracking

func (*MemoryTracker) Enable

func (mt *MemoryTracker) Enable()

Enable enables memory tracking

func (*MemoryTracker) GetStats

func (mt *MemoryTracker) GetStats() MemoryStats

GetStats returns current memory statistics

func (*MemoryTracker) IsEnabled

func (mt *MemoryTracker) IsEnabled() bool

IsEnabled returns whether memory tracking is enabled

func (*MemoryTracker) RecordAllocation

func (mt *MemoryTracker) RecordAllocation(size uint64)

RecordAllocation records a memory allocation

func (*MemoryTracker) RecordDeallocation

func (mt *MemoryTracker) RecordDeallocation(size uint64)

RecordDeallocation records a memory deallocation

func (*MemoryTracker) Start

func (mt *MemoryTracker) Start()

Start begins memory tracking

type Opcode

type Opcode byte

Opcode represents a virtual machine instruction

const (
	// Stack operations
	OpConstant Opcode = iota // Load constant onto stack
	OpPop                    // Pop value from stack
	OpDup                    // Duplicate top stack value
	OpSwap                   // Swap top two stack values

	// Arithmetic operations
	OpAdd // Add two values
	OpSub // Subtract two values
	OpMul // Multiply two values
	OpDiv // Divide two values
	OpMod // Modulo operation
	OpPow // Power operation
	OpNeg // Negate value

	// Fast path arithmetic operations (type-specialized)
	OpAddInt64   // Fast int64 addition
	OpSubInt64   // Fast int64 subtraction
	OpMulInt64   // Fast int64 multiplication
	OpDivInt64   // Fast int64 division
	OpModInt64   // Fast int64 modulo
	OpAddFloat64 // Fast float64 addition
	OpSubFloat64 // Fast float64 subtraction
	OpMulFloat64 // Fast float64 multiplication
	OpDivFloat64 // Fast float64 division
	OpModFloat64 // Fast float64 modulo
	OpAddString  // Fast string concatenation

	// Comparison operations
	OpEqual        // Equal comparison
	OpNotEqual     // Not equal comparison
	OpGreaterThan  // Greater than comparison
	OpGreaterEqual // Greater than or equal comparison
	OpLessThan     // Less than comparison
	OpLessEqual    // Less than or equal comparison

	// Logical operations
	OpAnd // Logical AND
	OpOr  // Logical OR
	OpNot // Logical NOT

	// Bitwise operations
	OpBitAnd // Bitwise AND
	OpBitOr  // Bitwise OR
	OpBitXor // Bitwise XOR
	OpBitNot // Bitwise NOT
	OpShiftL // Left shift
	OpShiftR // Right shift

	// Variable operations
	OpGetVar // Get variable value
	OpSetVar // Set variable value

	// Function operations
	OpCall    // Call function
	OpReturn  // Return from function
	OpBuiltin // Call builtin function

	// Collection operations
	OpIndex  // Index access (array[index], map[key])
	OpMember // Member access (obj.field)
	OpSlice  // Create slice literal
	OpMap    // Create map literal
	OpIn     // 'in' operator

	// Control flow
	OpJump      // Unconditional jump
	OpJumpTrue  // Jump if true
	OpJumpFalse // Jump if false
	OpJumpNil   // Jump if nil

	// String operations
	OpConcat     // String concatenation
	OpMatches    // String matches regex
	OpContains   // String contains substring
	OpStartsWith // String starts with prefix
	OpEndsWith   // String ends with suffix

	// Type conversion
	OpToString // Convert to string
	OpToInt    // Convert to int
	OpToFloat  // Convert to float
	OpToBool   // Convert to bool

	// Special operations
	OpHalt // Halt execution
	OpNoop // No operation

	// Collection and functional programming operations
	OpArray              // Create array from stack elements
	OpObject             // Create object from stack key-value pairs
	OpLambda             // Create lambda function
	OpClosure            // Create closure with captured variables
	OpApply              // Apply function to arguments
	OpPipe               // Pipeline operation (data | function)
	OpFilter             // Filter array with predicate
	OpMapFunc            // Map function over array (renamed from OpMap)
	OpReduce             // Reduce array with accumulator function
	OpGetPipelineElement // Get current pipeline element (for placeholder #)

	// Phase 3 optimization instructions
	OpAddVars      // Add two variables directly (var1 + var2)
	OpMulVars      // Multiply two variables directly (var1 * var2)
	OpSubVars      // Subtract two variables directly (var1 - var2)
	OpDivVars      // Divide two variables directly (var1 / var2)
	OpCompareVars  // Compare two variables directly (var1 op var2)
	OpConstantOp   // Constant operation result (pre-computed)
	OpFusedArith   // Fused arithmetic operation (a + b * c)
	OpCachedResult // Cached computation result

	// Null safety operations
	OpOptionalChaining // Optional chaining operation (obj?.property)
	OpNullCoalescing   // Null coalescing operation (a ?? b)

	// Module system operations
	OpModuleCall // Module function call (module.function(args...))

	// Destructuring operations
	OpArrayDestructure  // Array destructuring assignment
	OpObjectDestructure // Object destructuring assignment
	OpRestElement       // Rest element in destructuring
)

func (Opcode) String

func (op Opcode) String() string

String returns the string representation of an opcode

type OptimizationStats

type OptimizationStats struct {
	CacheHits   int64
	CacheMisses int64
	PoolHits    int64
	PoolMisses  int64
	HitRatio    float64
}

OptimizationStats represents optimization performance metrics

type OptimizedJumpTable

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

OptimizedJumpTable for ultra-fast instruction dispatch

func NewOptimizedJumpTable

func NewOptimizedJumpTable() *OptimizedJumpTable

NewOptimizedJumpTable creates the optimized jump table

type OptimizedVM

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

OptimizedVM is a high-performance VM that uses union types instead of interfaces This implements the P0 optimization from PERFORMANCE_SUMMARY.md

func NewOptimizedVM

func NewOptimizedVM(instructions []byte, constants []types.Value) *OptimizedVM

NewOptimizedVM creates a new optimized VM instance

func (*OptimizedVM) GetLastValue

func (vm *OptimizedVM) GetLastValue() types.OptimizedValue

GetLastValue returns the last value on the stack for testing

func (*OptimizedVM) Run

func (vm *OptimizedVM) Run() (types.OptimizedValue, error)

Run executes the optimized VM with maximum performance

type OptimizedVMPool

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

VMPool with optimization support

func NewOptimizedVMPool

func NewOptimizedVMPool() *OptimizedVMPool

NewOptimizedVMPool creates a VM pool that uses optimized VMs

func (*OptimizedVMPool) Get

func (p *OptimizedVMPool) Get(bytecode *Bytecode) *VM

Get retrieves an optimized VM from the pool

func (*OptimizedVMPool) Put

func (p *OptimizedVMPool) Put(vm *VM)

Put returns an optimized VM to the pool

type PoolStats

type PoolStats struct {
	IntCacheSize    int
	FloatCacheSize  int
	StringCacheSize int
	IntCacheHits    int64 // Would need atomic counters in practice
	FloatCacheHits  int64
	StringCacheHits int64
}

Stats returns pool statistics

type SafeJumpTable

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

SafeJumpTable 是一个简化且安全的跳转表实现 专注于正确性和稳定性,而非极端性能优化

func NewSafeJumpTable

func NewSafeJumpTable() *SafeJumpTable

NewSafeJumpTable 创建一个新的安全跳转表

func (*SafeJumpTable) Execute

func (jt *SafeJumpTable) Execute(vm *VM, instructions []byte, ip *int) (bool, error)

Execute 使用安全的跳转表派发指令

type StringPool

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

StringPool manages string value allocation

func (*StringPool) ClearStringPool

func (sp *StringPool) ClearStringPool()

ClearStringPool clears the string pool

func (*StringPool) GetOptimizedString

func (sp *StringPool) GetOptimizedString(value string) *types.StringValue

GetOptimizedString returns a string value from the pool or creates new one

type StructConverter

type StructConverter interface {
	ToMap() map[string]interface{}
}

StructConverter interface for converting structs to maps without reflection

type VM

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

VM represents the virtual machine

func New

func New(bytecode *Bytecode) *VM

New creates a new VM

func NewOptimized

func NewOptimized(bytecode *Bytecode) *VM

NewOptimized creates a new VM with P1 optimizations enabled

func NewOptimizedVMWithMemoryPool

func NewOptimizedVMWithMemoryPool(bytecode *Bytecode) *VM

NewOptimizedVMWithMemoryPool creates a new VM with P1 memory optimizations

func NewOptimizedWithOptions

func NewOptimizedWithOptions(bytecode *Bytecode, memOpt, unionTypes, caching bool) *VM

NewOptimizedWithOptions creates a VM with specific optimization options

func NewWithEnvironment

func NewWithEnvironment(bytecode *Bytecode, envVars map[string]interface{}, adapter interface{}) *VM

NewWithEnvironment creates a new VM with environment variables

func (*VM) CacheDebug

func (vm *VM) CacheDebug() *InstructionCache

func (*VM) GetOptimizedStringValue

func (vm *VM) GetOptimizedStringValue(value string) *types.StringValue

GetOptimizedStringValue returns an optimized string value

func (*VM) GlobalsDebug

func (vm *VM) GlobalsDebug() []types.Value

func (*VM) PoolDebug

func (vm *VM) PoolDebug() *ValuePool

func (*VM) Reset

func (vm *VM) Reset()

Reset clears the VM state for reuse

func (*VM) ResetStack

func (vm *VM) ResetStack()

ResetStack clears the stack

func (*VM) Run

func (vm *VM) Run(bytecode *Bytecode, env map[string]interface{}) (types.Value, error)

Run executes the virtual machine with the given bytecode

func (*VM) RunInstructions

func (vm *VM) RunInstructions(instructions []byte) error

RunInstructions runs instructions without returning result

func (*VM) RunInstructionsWithResult

func (vm *VM) RunInstructionsWithResult(instructions []byte) (types.Value, error)

RunInstructionsWithResult runs instructions and returns the result

func (*VM) SetConstants

func (vm *VM) SetConstants(constants []types.Value)

SetConstants sets the constants for the VM

func (*VM) SetCustomBuiltin

func (vm *VM) SetCustomBuiltin(name string, fn interface{})

SetCustomBuiltin sets a custom builtin function

func (*VM) SetEnvironment

func (vm *VM) SetEnvironment(envVars map[string]interface{}, variableOrder []string) error

SetEnvironment sets up the environment variables for the VM

func (*VM) SetMemoryOptimizer

func (vm *VM) SetMemoryOptimizer(optimizer *MemoryOptimizer)

SetMemoryOptimizer sets the memory optimizer for a VM

func (*VM) StackDebug

func (vm *VM) StackDebug() []types.Value

Debug methods for testing and verification

func (*VM) StackTop

func (vm *VM) StackTop() types.Value

StackTop returns the top element of the stack

type VMFactory

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

VMFactory creates VMs with different optimization levels

func DefaultOptimizedFactory

func DefaultOptimizedFactory() *VMFactory

DefaultOptimizedFactory returns a factory with all P1 optimizations enabled

func NewVMFactory

func NewVMFactory(memOpt, unionTypes, caching bool) *VMFactory

NewVMFactory creates a new VM factory with specified optimizations

func (*VMFactory) CreateVM

func (f *VMFactory) CreateVM(bytecode *Bytecode) *VM

CreateVM creates a VM with the configured optimizations

func (*VMFactory) CreateVMWithPool

func (f *VMFactory) CreateVMWithPool(bytecode *Bytecode) (*VM, func())

CreateVMWithPool creates a VM that uses resource pooling

func (*VMFactory) ReleaseVM

func (f *VMFactory) ReleaseVM(vm *VM)

ReleaseVM properly releases VM resources back to pools

type VMPool

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

VMPool provides object pooling for VM instances to reduce allocations

func NewVMPool

func NewVMPool() *VMPool

NewVMPool creates a new VM pool

func (*VMPool) Get

func (p *VMPool) Get() *VM

Get retrieves a VM from the pool

func (*VMPool) Put

func (p *VMPool) Put(vm *VM)

Put returns a VM to the pool after resetting it

type ValuePool

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

ValuePool provides object pooling for Value types to reduce allocations

func NewValuePool

func NewValuePool() *ValuePool

NewValuePool creates a new value pool with caching

func (*ValuePool) ClearCache

func (p *ValuePool) ClearCache()

ClearCache clears the value caches (for memory management)

func (*ValuePool) GetBool

func (p *ValuePool) GetBool(value bool) *types.BoolValue

GetBool gets a bool value (always cached)

func (*ValuePool) GetFloat

func (p *ValuePool) GetFloat(value float64) *types.FloatValue

GetFloat gets a float value from cache or creates new one - simplified for performance

func (*ValuePool) GetInt

func (p *ValuePool) GetInt(value int64) *types.IntValue

GetInt gets an int value from cache or creates new one - optimized for performance

func (*ValuePool) GetStats

func (p *ValuePool) GetStats() PoolStats

GetStats returns current pool statistics

func (*ValuePool) GetString

func (p *ValuePool) GetString(value string) *types.StringValue

GetString gets a string value from cache or creates new one - performance focused

func (*ValuePool) PutBool

func (p *ValuePool) PutBool(v *types.BoolValue)

PutBool returns a bool value to the pool

func (*ValuePool) PutFloat

func (p *ValuePool) PutFloat(v *types.FloatValue)

PutFloat returns a float value to the pool

func (*ValuePool) PutInt

func (p *ValuePool) PutInt(v *types.IntValue)

PutInt returns an int value to the pool (no-op for cached values)

func (*ValuePool) PutString

func (p *ValuePool) PutString(v *types.StringValue)

PutString returns a string value to the pool

type VariableLookupCache

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

VariableLookupCache accelerates variable resolution

func (*VariableLookupCache) CacheVariableIndex

func (vlc *VariableLookupCache) CacheVariableIndex(name string, index int)

CacheVariableIndex stores variable name -> index mapping

func (*VariableLookupCache) ClearVariableCache

func (vlc *VariableLookupCache) ClearVariableCache()

ClearVariableCache clears the variable cache

func (*VariableLookupCache) GetVariableIndex

func (vlc *VariableLookupCache) GetVariableIndex(name string) (int, bool)

GetVariableIndex retrieves cached variable index

Jump to

Keyboard shortcuts

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