Documentation
¶
Index ¶
- Variables
- func BuiltinCompile(vm *VM) int
- func BuiltinDir(vm *VM) int
- func BuiltinEval(vm *VM) int
- func BuiltinExec(vm *VM) int
- func BuiltinGlobals(vm *VM) int
- func BuiltinLocals(vm *VM) int
- func BuiltinRepr(vm *VM) int
- func BuiltinVars(vm *VM) int
- func GetPendingBuiltins() map[string]GoFunction
- func IsBool(v Value) bool
- func IsCallable(v Value) bool
- func IsDict(v Value) bool
- func IsFloat(v Value) bool
- func IsInt(v Value) bool
- func IsList(v Value) bool
- func IsNone(v Value) bool
- func IsString(v Value) bool
- func IsTrue(v Value) bool
- func IsTuple(v Value) bool
- func IsUserData(v Value) bool
- func RegisterModule(name string, loader ModuleLoader)
- func RegisterPendingBuiltin(name string, fn GoFunction)
- func RegisterTypeMetatable(typeName string, mt *TypeMetatable)
- func ResetModules()
- func ResetPendingBuiltins()
- func ResetTypeMetatables()
- func ResolveRelativeImport(name string, level int, packageName string) (string, error)
- func ToGoValue(v Value) any
- type Block
- type BlockType
- type CancelledError
- type CodeFlags
- type CodeObject
- type ExceptStarState
- type Frame
- type GeneratorState
- type GenericAlias
- type GoFunction
- type Instruction
- type LineEntry
- type ModuleBuilder
- func (b *ModuleBuilder) Build() *PyModule
- func (b *ModuleBuilder) Const(name string, value Value) *ModuleBuilder
- func (b *ModuleBuilder) Doc(doc string) *ModuleBuilder
- func (b *ModuleBuilder) Func(name string, fn GoFunction) *ModuleBuilder
- func (b *ModuleBuilder) Method(name string, fn GoFunction) *ModuleBuilder
- func (b *ModuleBuilder) Register() *PyModule
- func (b *ModuleBuilder) SubModule(name string, submodule *PyModule) *ModuleBuilder
- func (b *ModuleBuilder) Type(typeName string, constructor GoFunction, methods map[string]GoFunction) *ModuleBuilder
- type ModuleLoader
- type Opcode
- type PyBool
- type PyBuiltinFunc
- type PyBytes
- type PyCell
- type PyClass
- type PyClassMethod
- type PyCode
- type PyComplex
- type PyCoroutine
- type PyDict
- func (d *PyDict) DictContains(key Value, vm *VM) bool
- func (d *PyDict) DictDelete(key Value, vm *VM) bool
- func (d *PyDict) DictGet(key Value, vm *VM) (Value, bool)
- func (d *PyDict) DictLen() int
- func (d *PyDict) DictSet(key, value Value, vm *VM)
- func (d *PyDict) Keys(vm *VM) []Value
- func (d *PyDict) String() string
- func (d *PyDict) Type() string
- type PyException
- type PyFloat
- type PyFrozenSet
- type PyFunction
- type PyGenerator
- type PyGoFunc
- type PyInstance
- type PyInt
- type PyIterator
- type PyList
- type PyMethod
- type PyModule
- type PyNone
- type PyNotImplementedType
- type PyObject
- type PyPanicError
- type PyProperty
- type PyRange
- type PySet
- type PySlice
- type PyStaticMethod
- type PyString
- type PySuper
- type PyTuple
- type PyUserData
- type TimeoutError
- type TracebackEntry
- type TypeMetatable
- type VM
- func (vm *VM) AllocatedBytes() int64
- func (vm *VM) ApplyPendingBuiltins()
- func (vm *VM) ArgError(n int, msg string)
- func (vm *VM) Call(callable Value, args []Value, kwargs map[string]Value) (Value, error)
- func (vm *VM) CallDunder(inst *PyInstance, name string, args ...Value) (Value, bool)
- func (vm *VM) CallDunderWithError(inst *PyInstance, name string, args ...Value) (Value, bool, error)
- func (vm *VM) CallFunction(fn *PyFunction, args []Value, kwargs map[string]Value) (Value, error)
- func (vm *VM) CheckBool(n int) bool
- func (vm *VM) CheckDict(n int) *PyDict
- func (vm *VM) CheckFloat(n int) float64
- func (vm *VM) CheckInt(n int) int64
- func (vm *VM) CheckList(n int) *PyList
- func (vm *VM) CheckString(n int) string
- func (vm *VM) CheckUserData(n int, typeName string) *PyUserData
- func (vm *VM) CompareOp(op Opcode, a, b Value) Value
- func (vm *VM) ComputeC3MRO(class *PyClass, bases []*PyClass) ([]*PyClass, error)
- func (vm *VM) CoroutineSend(coro *PyCoroutine, value Value) (Value, bool, error)
- func (vm *VM) CoroutineThrow(coro *PyCoroutine, excType, excValue Value) (Value, bool, error)
- func (vm *VM) DefaultClassCall(cls *PyClass, args []Value, kwargs map[string]Value) (Value, error)
- func (vm *VM) Equal(a, b Value) bool
- func (vm *VM) EvalInNamespace(code *CodeObject, globals, locals map[string]Value) (Value, error)
- func (vm *VM) Execute(code *CodeObject) (Value, error)
- func (vm *VM) ExecuteInModule(code *CodeObject, mod *PyModule) error
- func (vm *VM) ExecuteInNamespace(code *CodeObject, globals, locals map[string]Value) error
- func (vm *VM) ExecuteWithContext(ctx context.Context, code *CodeObject) (Value, error)
- func (vm *VM) ExecuteWithTimeout(timeout time.Duration, code *CodeObject) (Value, error)
- func (vm *VM) GeneratorClose(gen *PyGenerator) error
- func (vm *VM) GeneratorSend(gen *PyGenerator, value Value) (Value, bool, error)
- func (vm *VM) GeneratorThrow(gen *PyGenerator, excType, excValue Value) (Value, bool, error)
- func (vm *VM) Get(idx int) Value
- func (vm *VM) GetBuiltin(name string) Value
- func (vm *VM) GetGlobal(name string) Value
- func (vm *VM) GetIntIndex(v Value) (int64, error)
- func (vm *VM) GetModule(name string) (*PyModule, bool)
- func (vm *VM) GetTop() int
- func (vm *VM) GetTypeMetatable(typeName string) *TypeMetatable
- func (vm *VM) HashValue(v Value) uint64
- func (vm *VM) ImportModule(name string) (*PyModule, error)
- func (vm *VM) IsInstanceOf(inst *PyInstance, cls *PyClass) bool
- func (vm *VM) MaxCollectionSize() int64
- func (vm *VM) MaxMemoryBytes() int64
- func (vm *VM) MaxRecursionDepth() int64
- func (vm *VM) NewTypeMetatable(typeName string) *TypeMetatable
- func (vm *VM) NewUserDataWithMeta(v any, typeName string) *PyUserData
- func (vm *VM) OptionalBool(pos int, def bool) bool
- func (vm *VM) OptionalFloat(pos int, def float64) float64
- func (vm *VM) OptionalInt(pos int, def int64) int64
- func (vm *VM) OptionalString(pos int, def string) string
- func (vm *VM) Pop() Value
- func (vm *VM) Push(v Value)
- func (vm *VM) RaiseError(format string, args ...any)
- func (vm *VM) Register(name string, fn GoFunction)
- func (vm *VM) RegisterBuiltin(name string, fn GoFunction)
- func (vm *VM) RegisterFuncs(funcs map[string]GoFunction)
- func (vm *VM) RegisterModule(name string, loader ModuleLoader)
- func (vm *VM) RegisterModuleInstance(name string, module *PyModule)
- func (vm *VM) RegisterType(typeName string, constructor GoFunction, methods map[string]GoFunction)
- func (vm *VM) Repr(v Value) string
- func (vm *VM) RequireArgs(name string, min int) bool
- func (vm *VM) Run(code *CodeObject) (Value, error)
- func (vm *VM) SetBuiltin(name string, v Value)
- func (vm *VM) SetCheckInterval(n int64)
- func (vm *VM) SetGlobal(name string, v Value)
- func (vm *VM) SetMaxCollectionSize(n int64)
- func (vm *VM) SetMaxMemoryBytes(n int64)
- func (vm *VM) SetMaxRecursionDepth(n int64)
- func (vm *VM) SetTop(n int)
- func (vm *VM) ToBool(n int) bool
- func (vm *VM) ToFloat(n int) float64
- func (vm *VM) ToInt(n int) int64
- func (vm *VM) ToList(v Value) ([]Value, error)
- func (vm *VM) ToString(n int) string
- func (vm *VM) ToUserData(n int) *PyUserData
- func (vm *VM) TrackAlloc(n int64) error
- func (vm *VM) Truthy(v Value) bool
- func (vm *VM) TypeError(expected string, got Value)
- func (vm *VM) TypeNameOf(v Value) string
- type Value
Constants ¶
This section is empty.
Variables ¶
True and False are singleton boolean values
var CompileFunc func(source, filename, mode string) (*CodeObject, error)
CompileFunc is set by the rage package to provide compilation capability for exec/eval/compile builtins. This avoids import cycles between runtime and compiler packages.
var None = &PyNone{}
None is the singleton None value
var NotImplemented = &PyNotImplementedType{}
NotImplemented is the singleton NotImplemented value
var OpcodeNames = map[Opcode]string{}/* 180 elements not displayed */
OpcodeNames maps opcodes to their string names for debugging
Functions ¶
func BuiltinCompile ¶
BuiltinCompile implements compile(source, filename, mode)
func BuiltinEval ¶
BuiltinEval implements eval(expression, globals=None, locals=None)
func BuiltinExec ¶
BuiltinExec implements exec(code, globals=None, locals=None)
func GetPendingBuiltins ¶
func GetPendingBuiltins() map[string]GoFunction
GetPendingBuiltins returns all pending builtins (called by NewVM)
func IsTrue ¶
IsTrue returns whether a Python value is truthy (without needing a VM reference). This handles common cases; for instances with __bool__/__len__, use vm.Truthy instead.
func RegisterModule ¶
func RegisterModule(name string, loader ModuleLoader)
RegisterModule registers a module loader with the given name The loader will be called when the module is first imported
func RegisterPendingBuiltin ¶
func RegisterPendingBuiltin(name string, fn GoFunction)
RegisterPendingBuiltin registers a builtin to be added to new VMs. Use this from stdlib modules that need to add builtin functions.
func RegisterTypeMetatable ¶
func RegisterTypeMetatable(typeName string, mt *TypeMetatable)
RegisterTypeMetatable registers a type metatable globally (without VM instance)
func ResetModules ¶
func ResetModules()
ResetModules clears the loaded modules cache and related registries. This should be called before initializing a new State to ensure a clean slate (useful for testing and creating isolated states).
func ResetPendingBuiltins ¶
func ResetPendingBuiltins()
ResetPendingBuiltins clears the pending builtins registry (called by ResetModules)
func ResetTypeMetatables ¶
func ResetTypeMetatables()
ResetTypeMetatables clears the type metatable registry (called by ResetModules)
func ResolveRelativeImport ¶
ResolveRelativeImport resolves a relative import to an absolute module name. Parameters:
- name: the module name from the import statement (may be empty for "from . import x")
- level: number of dots (1 for ".", 2 for "..", etc.)
- packageName: the current package (__package__ or derived from __name__)
Returns the resolved absolute module name or an error.
Types ¶
type Block ¶
type Block struct {
Type BlockType
Handler int // Handler address
Level int // Stack level
ExcStackLevel int // excHandlerStack level at block setup time
}
Block represents a control flow block
type CancelledError ¶
type CancelledError struct{}
CancelledError is returned when script execution is cancelled via context
func (*CancelledError) Error ¶
func (e *CancelledError) Error() string
type CodeFlags ¶
type CodeFlags int
CodeFlags represents flags for code objects
const ( FlagOptimized CodeFlags = 1 << iota // Locals are optimized FlagNewLocals // Use new dict for locals FlagVarArgs // *args parameter FlagVarKeywords // **kwargs parameter FlagNested // Nested function FlagGenerator // Generator function FlagNoFree // No free variables FlagCoroutine // Coroutine function FlagIterableCoroutine // Iterable coroutine FlagAsyncGenerator // Async generator )
type CodeObject ¶
type CodeObject struct {
Name string // Function/class/module name
Filename string // Source filename
FirstLine int // First line number in source
Code []byte // Bytecode instructions
Constants []any // Constant pool
Names []string // Names used in code
VarNames []string // Local variable names
FreeVars []string // Free variables (closures)
CellVars []string // Variables captured in closures
ArgCount int // Number of positional arguments
KwOnlyArgCount int // Number of keyword-only arguments
Flags CodeFlags // Code flags
StackSize int // Maximum stack size needed
LineNoTab []LineEntry // Line number table
}
CodeObject represents compiled Python code
func (*CodeObject) CellOrFreeName ¶ added in v0.3.0
func (co *CodeObject) CellOrFreeName(idx int) string
CellOrFreeName returns the variable name for a cell/free index.
func (*CodeObject) Disassemble ¶
func (co *CodeObject) Disassemble() string
Disassemble returns a human-readable disassembly of the code object
func (*CodeObject) LineForOffset ¶
func (co *CodeObject) LineForOffset(offset int) int
LineForOffset returns the source line for a bytecode offset
type ExceptStarState ¶
type ExceptStarState struct {
Remaining []*PyException
Message string
IsBase bool
}
ExceptStarState tracks the remaining unmatched exceptions during except* handling
type Frame ¶
type Frame struct {
Code *CodeObject
IP int // Instruction pointer
Stack []Value // Operand stack (pre-allocated)
SP int // Stack pointer (index of next free slot)
Locals []Value // Local variables
Globals map[string]Value // Global variables
EnclosingGlobals map[string]Value // Enclosing globals (for class bodies)
Builtins map[string]Value // Built-in functions
Cells []*PyCell // Closure cells
BlockStack []Block // Block stack for try/except/finally
OrderedGlobalKeys []string // Insertion-ordered global names (for class bodies)
}
Frame represents a call frame
type GeneratorState ¶
type GeneratorState int
GeneratorState represents the state of a generator/coroutine
const ( GenCreated GeneratorState = iota // Generator created but not started GenRunning // Generator is currently executing GenSuspended // Generator is suspended at yield GenClosed // Generator has finished or was closed )
type GenericAlias ¶
type GenericAlias struct {
Origin Value // The original class/builtin (e.g., list, dict, or a PyClass)
Args []Value // The type arguments
}
GenericAlias represents a parameterized type like list[int] or dict[str, int]
func (*GenericAlias) String ¶
func (g *GenericAlias) String() string
func (*GenericAlias) Type ¶
func (g *GenericAlias) Type() string
type GoFunction ¶
GoFunction is the signature for Go functions callable from Python. Similar to gopher-lua's LGFunction. The function receives the VM and returns the number of values pushed onto the stack.
type Instruction ¶
type Instruction struct {
Op Opcode
Arg int // Argument value (if HasArg)
Line int // Source line number
Offset int // Byte offset in code
}
Instruction represents a single bytecode instruction with its argument
type ModuleBuilder ¶
type ModuleBuilder struct {
// contains filtered or unexported fields
}
ModuleBuilder provides a fluent API for building modules
func NewModuleBuilder ¶
func NewModuleBuilder(name string) *ModuleBuilder
NewModuleBuilder creates a new module builder
func (*ModuleBuilder) Build ¶
func (b *ModuleBuilder) Build() *PyModule
Build returns the constructed module
func (*ModuleBuilder) Const ¶
func (b *ModuleBuilder) Const(name string, value Value) *ModuleBuilder
Const adds a constant value to the module
func (*ModuleBuilder) Doc ¶
func (b *ModuleBuilder) Doc(doc string) *ModuleBuilder
Doc sets the module's docstring
func (*ModuleBuilder) Func ¶
func (b *ModuleBuilder) Func(name string, fn GoFunction) *ModuleBuilder
Func adds a Go function to the module
func (*ModuleBuilder) Method ¶
func (b *ModuleBuilder) Method(name string, fn GoFunction) *ModuleBuilder
Method is an alias for Func
func (*ModuleBuilder) Register ¶
func (b *ModuleBuilder) Register() *PyModule
Register builds and registers the module with the global registry
func (*ModuleBuilder) SubModule ¶
func (b *ModuleBuilder) SubModule(name string, submodule *PyModule) *ModuleBuilder
SubModule adds a submodule to the module
func (*ModuleBuilder) Type ¶
func (b *ModuleBuilder) Type(typeName string, constructor GoFunction, methods map[string]GoFunction) *ModuleBuilder
Type adds a type/class to the module with methods
type ModuleLoader ¶
ModuleLoader is a function that creates/loads a module
type Opcode ¶
type Opcode byte
Opcode represents a single bytecode instruction
const ( // Stack manipulation OpPop Opcode = iota // Pop top of stack OpDup // Duplicate top of stack OpDup2 // Duplicate top two stack items (for augmented subscript) OpRot2 // Swap top two stack items OpRot3 // Rotate top three stack items // Constants and variables OpLoadConst // Load constant from constants pool (arg: index) OpLoadName // Load variable by name (arg: name index) OpStoreName // Store to variable by name (arg: name index) OpDeleteName // Delete variable by name (arg: name index) OpLoadFast // Load local variable (arg: local index) OpStoreFast // Store to local variable (arg: local index) OpDeleteFast // Delete local variable (arg: local index) OpLoadGlobal // Load global variable (arg: name index) OpStoreGlobal // Store to global variable (arg: name index) OpDeleteGlobal // Delete global variable (arg: name index) OpLoadAttr // Load attribute (arg: name index) OpStoreAttr // Store attribute (arg: name index) OpDeleteAttr // Delete attribute (arg: name index) // Subscript operations OpBinarySubscr // a[b] -> push a[b] OpStoreSubscr // a[b] = c OpDeleteSubscr // del a[b] // Arithmetic operations OpUnaryPositive // +a OpUnaryNegative // -a OpUnaryNot // not a OpUnaryInvert // ~a OpBinaryAdd // a + b OpBinarySubtract // a - b OpBinaryMultiply // a * b OpBinaryDivide // a / b OpBinaryFloorDiv // a // b OpBinaryModulo // a % b OpBinaryPower // a ** b OpBinaryMatMul // a @ b OpBinaryLShift // a << b OpBinaryRShift // a >> b OpBinaryAnd // a & b OpBinaryOr // a | b OpBinaryXor // a ^ b // In-place operations OpInplaceAdd // a += b OpInplaceSubtract // a -= b OpInplaceMultiply // a *= b OpInplaceDivide // a /= b OpInplaceFloorDiv // a //= b OpInplaceModulo // a %= b OpInplacePower // a **= b OpInplaceMatMul // a @= b OpInplaceLShift // a <<= b OpInplaceRShift // a >>= b OpInplaceAnd // a &= b OpInplaceOr // a |= b OpInplaceXor // a ^= b // Comparison operations OpCompareEq // a == b OpCompareNe // a != b OpCompareLt // a < b OpCompareLe // a <= b OpCompareGt // a > b OpCompareGe // a >= b OpCompareIs // a is b OpCompareIsNot // a is not b OpCompareIn // a in b OpCompareNotIn // a not in b // Boolean operations OpJumpIfTrueOrPop // Jump if true, else pop (arg: offset) OpJumpIfFalseOrPop // Jump if false, else pop (arg: offset) // Control flow OpJump // Unconditional jump (arg: offset) OpJumpIfTrue // Jump if top is true (arg: offset) OpJumpIfFalse // Jump if top is false (arg: offset) OpPopJumpIfTrue // Pop and jump if true (arg: offset) OpPopJumpIfFalse // Pop and jump if false (arg: offset) OpContinueLoop // Continue through finally blocks (arg: loop target offset) // Iteration OpGetIter // Get iterator from iterable OpForIter // Get next from iterator or jump (arg: offset) // Function operations OpMakeFunction // Create function object (arg: flags) OpCall // Call function (arg: arg count) OpCallKw // Call function with keyword args (arg: arg count) OpCallEx // Call function with *args/**kwargs unpacking (arg: flags, 1=has **kwargs) OpReturn // Return from function // Class operations OpLoadBuildClass // Load __build_class__ OpLoadMethod // Load method for call optimization OpCallMethod // Call method (arg: arg count) // Collection building OpBuildTuple // Build tuple (arg: count) OpBuildList // Build list (arg: count) OpBuildSet // Build set (arg: count) OpBuildMap // Build dict (arg: count of key-value pairs) OpBuildString // Build string from parts (arg: count) // Unpacking OpUnpackSequence // Unpack sequence (arg: count) OpUnpackEx // Unpack with star (arg: counts before/after) // List/set/dict comprehensions OpListAppend // Append to list for comprehension OpSetAdd // Add to set for comprehension OpMapAdd // Add to map for comprehension // Import operations OpImportName // Import module (arg: name index) OpImportFrom // Import from module (arg: name index) OpImportStar // Import * from module // Exception handling OpSetupExcept // Setup exception handler (arg: handler offset) OpSetupFinally // Setup finally handler (arg: handler offset) OpPopExcept // Pop exception handler from block stack OpPopBlock // Pop top block from block stack (for normal finally entry) OpEndFinally // End finally block OpRaiseVarargs // Raise exception (arg: count 0-3) OpExceptionMatch // Check if exception matches type for except clause OpClearException // Clear current exception state (for handler entry) OpPopExceptHandler // Pop excHandlerStack entry (end of handler body) // Exception groups (except*) OpSetupExceptStar // Setup except* handler (arg: handler offset) OpExceptStarMatch // Match exception group against type: stack [eg, type] → [eg, subgroup_or_None] OpExceptStarReraise // Re-raise unmatched exceptions from except* block // With statement OpSetupWith // Setup with statement (arg: cleanup offset) OpWithCleanup // Cleanup with statement // Assertion OpAssert // Assert with optional message // Closure operations OpLoadClosure // Load closure variable OpStoreClosure // Store to closure variable OpLoadDeref // Load from cell OpStoreDeref // Store to cell OpDeleteDeref // Delete cell variable (set to nil) OpMakeCell // Create cell for variable // Misc OpNop // No operation OpPrintExpr // Print expression result (REPL) OpLoadLocals // Load locals dict // Generator operations OpYieldValue // Yield value from generator, suspend execution OpYieldFrom // Delegate to sub-iterator (yield from) OpGenStart // Generator frame initialization marker // Coroutine operations OpGetAwaitable // Get awaitable from object (__await__) OpGetAIter // Get async iterator (__aiter__) OpGetANext // Get next from async iterator (__anext__) // Pattern matching operations (match statement) OpMatchSequence // Match sequence pattern (arg: expected length, or -1 for variable with star) OpMatchMapping // Match mapping pattern (arg: number of keys) OpMatchClass // Match class pattern (arg: number of positional attrs) OpMatchKeys // Check if mapping has required keys (keys on stack) OpCopyDict // Copy dict for **rest in mapping pattern OpGetLen // Get length of sequence (non-consuming for pattern match) OpMatchStar // Handle starred pattern in sequence (arg: minLength) OpExtractStar // Extract star slice (arg: beforeStar << 8 | afterStar) // Specialized LOAD_FAST for common indices (no arg needed) OpLoadFast0 // Load local variable 0 OpLoadFast1 // Load local variable 1 OpLoadFast2 // Load local variable 2 OpLoadFast3 // Load local variable 3 // Specialized STORE_FAST for common indices (no arg needed) OpStoreFast0 // Store to local variable 0 OpStoreFast1 // Store to local variable 1 OpStoreFast2 // Store to local variable 2 OpStoreFast3 // Store to local variable 3 // Specialized constant loading (no arg needed) OpLoadNone // Load None OpLoadTrue // Load True OpLoadFalse // Load False OpLoadZero // Load integer 0 OpLoadOne // Load integer 1 // Specialized arithmetic (no arg needed) OpIncrementFast // Increment local by 1 (arg: local index) - has arg! OpDecrementFast // Decrement local by 1 (arg: local index) - has arg! OpNegateFast // Negate local in place (arg: local index) - for sign = -sign OpAddConstFast // Add constant to local (arg: packed local index + const index) OpAccumulateFast // Add TOS to local (arg: local index) - for x = x + expr // Superinstructions - combined operations OpLoadFastLoadFast // Load two locals (arg: packed indices) OpLoadFastLoadConst // Load local then const (arg: packed indices) OpStoreFastLoadFast // Store then load (arg: packed indices) OpBinaryAddInt // Add two ints (optimized path) OpBinarySubtractInt // Subtract two ints (optimized path) OpBinaryMultiplyInt // Multiply two ints (optimized path) OpBinaryDivideFloat // True division (always returns float) OpBinaryAddFloat // Float addition OpCompareLtInt // Compare less than for ints OpCompareLeInt // Compare less than or equal for ints OpCompareGtInt // Compare greater than for ints OpCompareGeInt // Compare greater than or equal for ints OpCompareEqInt // Compare equal for ints OpCompareNeInt // Compare not equal for ints // Empty collection loading (no arg needed) OpLoadEmptyList // Load empty list [] OpLoadEmptyTuple // Load empty tuple () OpLoadEmptyDict // Load empty dict {} // Combined compare and jump (superinstructions) OpCompareLtJump // Compare < and jump if false (arg: offset) OpCompareLeJump // Compare <= and jump if false (arg: offset) OpCompareGtJump // Compare > and jump if false (arg: offset) OpCompareGeJump // Compare >= and jump if false (arg: offset) OpCompareEqJump // Compare == and jump if false (arg: offset) OpCompareNeJump // Compare != and jump if false (arg: offset) // Compare two locals and jump (ultra-optimized loop conditions) // arg format: low 4 bits = local1, next 4 bits = local2, remaining = jump offset >> 4 OpCompareLtLocalJump // local1 < local2, jump if false // Inline builtins (no function call overhead) OpLenList // len(list) - inline OpLenString // len(string) - inline OpLenTuple // len(tuple) - inline OpLenDict // len(dict) - inline OpLenGeneric // len() - generic but optimized path // More superinstructions OpLoadConstLoadFast // Load const then local (arg: packed indices) OpLoadGlobalLoadFast // Load global then local (arg: packed indices) // Annotations OpSetupAnnotations // Ensure __annotations__ dict exists in current namespace )
type PyBuiltinFunc ¶
type PyBuiltinFunc struct {
Name string
Fn func(args []Value, kwargs map[string]Value) (Value, error)
Bound bool // true when self is already captured (bound method wrapper)
}
PyBuiltinFunc represents a built-in function
func (*PyBuiltinFunc) String ¶
func (b *PyBuiltinFunc) String() string
func (*PyBuiltinFunc) Type ¶
func (b *PyBuiltinFunc) Type() string
type PyBytes ¶
type PyBytes struct {
Value []byte
}
PyBytes represents Python bytes
type PyClass ¶
type PyClass struct {
Name string
Bases []*PyClass
Dict map[string]Value
Mro []*PyClass // Method Resolution Order
IsABC bool // True if class uses ABC abstract method checking
RegisteredSubclasses []*PyClass // Virtual subclasses registered via ABC.register()
Metaclass *PyClass // Custom metaclass (if any)
Slots []string // nil means no __slots__ (dict allowed); non-nil restricts instance attrs
}
PyClass represents a Python class
type PyClassMethod ¶
type PyClassMethod struct {
Func Value
}
PyClassMethod wraps a function to bind class as first argument
func (*PyClassMethod) String ¶
func (c *PyClassMethod) String() string
func (*PyClassMethod) Type ¶
func (c *PyClassMethod) Type() string
type PyCode ¶
type PyCode struct {
Code *CodeObject
}
PyCode wraps a CodeObject for Python access via compile()
type PyComplex ¶
PyComplex represents a Python complex number
func MakeComplex ¶
MakeComplex creates a PyComplex value
func NewComplex ¶
NewComplex creates a Python complex from two Go float64s (real, imag)
type PyCoroutine ¶
type PyCoroutine struct {
Frame *Frame // Suspended frame state
Code *CodeObject // The coroutine's code object
Name string // Coroutine function name
State GeneratorState // Current state (reuses generator states)
YieldValue Value // Value to send into coroutine on resume
}
PyCoroutine represents a Python coroutine object (async def)
func (*PyCoroutine) String ¶
func (c *PyCoroutine) String() string
func (*PyCoroutine) Type ¶
func (c *PyCoroutine) Type() string
type PyDict ¶
type PyDict struct {
Items map[Value]Value // Legacy field for compatibility
// contains filtered or unexported fields
}
PyDict represents a Python dictionary with hash-based lookups
func (*PyDict) DictContains ¶
DictContains checks if a key exists using hash-based lookup
func (*PyDict) DictDelete ¶
DictDelete removes a key using hash-based lookup
type PyException ¶
type PyException struct {
ExcType *PyClass // Exception class (e.g., ValueError, TypeError)
TypeName string // Exception type name (used when ExcType is nil)
Args *PyTuple // Exception arguments
Message string // String representation
Cause *PyException // __cause__ for chained exceptions (raise X from Y)
Context *PyException // __context__ for implicit chaining
SuppressContext bool // __suppress_context__ - set True when __cause__ is assigned
Traceback []TracebackEntry // Traceback frames
Instance *PyInstance // non-nil for ExceptionGroup instances
Notes *PyList // __notes__ list (nil until add_note is called)
}
PyException represents a Python exception
func (*PyException) Error ¶
func (e *PyException) Error() string
func (*PyException) String ¶
func (e *PyException) String() string
func (*PyException) Type ¶
func (e *PyException) Type() string
type PyFrozenSet ¶
type PyFrozenSet struct {
Items map[Value]struct{} // Legacy field for compatibility
// contains filtered or unexported fields
}
PyFrozenSet represents an immutable Python frozenset
func (*PyFrozenSet) FrozenSetAdd ¶
func (s *PyFrozenSet) FrozenSetAdd(value Value, vm *VM)
FrozenSetAdd adds a value to the frozenset (used during construction)
func (*PyFrozenSet) FrozenSetContains ¶
func (s *PyFrozenSet) FrozenSetContains(value Value, vm *VM) bool
FrozenSetContains checks if a value exists using hash-based lookup
func (*PyFrozenSet) FrozenSetLen ¶
func (s *PyFrozenSet) FrozenSetLen() int
FrozenSetLen returns the number of items
func (*PyFrozenSet) String ¶
func (s *PyFrozenSet) String() string
func (*PyFrozenSet) Type ¶
func (s *PyFrozenSet) Type() string
type PyFunction ¶
type PyFunction struct {
Code *CodeObject
Globals map[string]Value
Defaults *PyTuple
KwDefaults map[string]Value // Keyword-only argument defaults
Closure []*PyCell
Name string
IsAbstract bool // Set by @abstractmethod decorator
Dict map[string]Value // Custom attributes (e.g. func._name)
}
PyFunction represents a Python function
func (*PyFunction) String ¶
func (f *PyFunction) String() string
func (*PyFunction) Type ¶
func (f *PyFunction) Type() string
type PyGenerator ¶
type PyGenerator struct {
Frame *Frame // Suspended frame state
Code *CodeObject // The generator's code object
Name string // Generator function name
State GeneratorState // Current state
YieldValue Value // Value to send into generator on resume
// Saved VM exception state (isolated per-generator)
SavedCurrentException *PyException
SavedLastException *PyException
SavedExcHandlerStack []*PyException
SavedPendingReturn Value
SavedHasPendingReturn bool
SavedPendingJump int
SavedHasPendingJump bool
}
PyGenerator represents a Python generator object
func (*PyGenerator) String ¶
func (g *PyGenerator) String() string
func (*PyGenerator) Type ¶
func (g *PyGenerator) Type() string
type PyGoFunc ¶
type PyGoFunc struct {
Name string
Fn GoFunction
}
PyGoFunc wraps a Go function for use in Python
func NewGoFunction ¶
func NewGoFunction(name string, fn GoFunction) *PyGoFunc
NewGoFunction creates a Python-callable function from a Go function
type PyInstance ¶
type PyInstance struct {
Class *PyClass
Dict map[string]Value // nil when class defines __slots__
Slots map[string]Value // non-nil when class defines __slots__
}
PyInstance represents an instance of a class
func (*PyInstance) String ¶
func (i *PyInstance) String() string
func (*PyInstance) Type ¶
func (i *PyInstance) Type() string
type PyInt ¶
PyInt represents a Python integer
func MakeBigInt ¶
MakeBigInt returns a PyInt from a big.Int value
func (*PyInt) BigIntValue ¶
BigIntValue returns the big.Int representation of this integer
type PyIterator ¶
type PyIterator struct {
Items []Value
Index int
Source *PyList // Optional: if set, Items is dynamically read from Source.Items (for live mutation visibility)
}
PyIterator wraps an iterator
func (*PyIterator) String ¶
func (i *PyIterator) String() string
func (*PyIterator) Type ¶
func (i *PyIterator) Type() string
type PyList ¶
type PyList struct {
Items []Value
}
PyList represents a Python list
type PyMethod ¶
type PyMethod struct {
Func *PyFunction
Instance Value
}
PyMethod represents a bound method
type PyModule ¶
type PyModule struct {
Name string
Dict map[string]Value // Module namespace (__dict__)
Doc string // __doc__
Package string // __package__
Loader Value // __loader__
Spec Value // __spec__
}
PyModule represents a Python module
type PyNotImplementedType ¶
type PyNotImplementedType struct{}
PyNotImplementedType represents Python's NotImplemented singleton
func (*PyNotImplementedType) String ¶
func (n *PyNotImplementedType) String() string
func (*PyNotImplementedType) Type ¶
func (n *PyNotImplementedType) Type() string
type PyPanicError ¶
type PyPanicError struct {
ExcType string // Exception type name (e.g., "TypeError", "ValueError")
Message string // Error message
}
PyPanicError is used to propagate Python exceptions through Go panics. This type is caught by the VM's recover and converted to a proper PyException.
func (*PyPanicError) Error ¶
func (e *PyPanicError) Error() string
type PyProperty ¶
PyProperty represents a Python property descriptor
func (*PyProperty) String ¶
func (p *PyProperty) String() string
func (*PyProperty) Type ¶
func (p *PyProperty) Type() string
type PyRange ¶
type PyRange struct {
Start, Stop, Step int64
}
PyRange represents a range object
type PySet ¶
type PySet struct {
Items map[Value]struct{} // Legacy field for compatibility
// contains filtered or unexported fields
}
PySet represents a Python set with hash-based lookups
func (*PySet) SetContains ¶
SetContains checks if a value exists using hash-based lookup
type PySlice ¶
type PySlice struct {
Start Value // Can be nil (None) or int
Stop Value // Can be nil (None) or int
Step Value // Can be nil (None) or int
}
PySlice represents a slice object for slicing sequences
type PyStaticMethod ¶
type PyStaticMethod struct {
Func Value
}
PyStaticMethod wraps a function to prevent binding
func (*PyStaticMethod) String ¶
func (s *PyStaticMethod) String() string
func (*PyStaticMethod) Type ¶
func (s *PyStaticMethod) Type() string
type PyString ¶
type PyString struct {
Value string
}
PyString represents a Python string
func InternString ¶
InternString returns an interned PyString for short strings This allows pointer comparison for equality in many cases
type PySuper ¶
type PySuper struct {
ThisClass *PyClass // The class where super() was called (__class__)
Instance Value // The instance (self) or class
StartIdx int // Index in MRO to start searching from (after ThisClass)
}
PySuper represents Python's super() proxy object
type PyTuple ¶
type PyTuple struct {
Items []Value
}
PyTuple represents a Python tuple
type PyUserData ¶
PyUserData wraps arbitrary Go values for use in Python. Similar to gopher-lua's LUserData.
func NewUserData ¶
func NewUserData(v any) *PyUserData
NewUserData creates a new userdata wrapping a Go value
func (*PyUserData) String ¶
func (u *PyUserData) String() string
func (*PyUserData) Type ¶
func (u *PyUserData) Type() string
type TimeoutError ¶
TimeoutError is returned when script execution exceeds the time limit
func (*TimeoutError) Error ¶
func (e *TimeoutError) Error() string
type TracebackEntry ¶
TracebackEntry represents a single frame in a traceback
type TypeMetatable ¶
type TypeMetatable struct {
Name string
Methods map[string]GoFunction
Properties map[string]GoFunction // Getters that are called automatically (like Python @property)
}
TypeMetatable holds methods and properties for a user-defined type
func GetRegisteredTypeMetatable ¶
func GetRegisteredTypeMetatable(typeName string) *TypeMetatable
GetRegisteredTypeMetatable retrieves a type metatable globally (without VM instance)
func (*TypeMetatable) SetMethod ¶
func (mt *TypeMetatable) SetMethod(name string, fn GoFunction)
SetMethod sets a method on a type metatable
func (*TypeMetatable) SetMethods ¶
func (mt *TypeMetatable) SetMethods(methods map[string]GoFunction)
SetMethods sets multiple methods on a type metatable
type VM ¶
type VM struct {
Globals map[string]Value
// Filesystem module imports
SearchPaths []string // Directories to search for .py modules
FileImporter func(filename string) (*CodeObject, error) // Callback to compile a .py file (avoids circular dep)
// contains filtered or unexported fields
}
VM is the Python virtual machine
func (*VM) AllocatedBytes ¶ added in v0.3.0
AllocatedBytes returns the approximate number of bytes currently tracked.
func (*VM) ApplyPendingBuiltins ¶
func (vm *VM) ApplyPendingBuiltins()
ApplyPendingBuiltins applies any pending builtins to an existing VM. This is useful when enabling modules after VM creation.
func (*VM) Call ¶
Call calls a Python callable with the given arguments This is the exported version of the internal call method
func (*VM) CallDunder ¶
CallDunder looks up and calls a dunder method on a PyInstance via MRO. Returns (result, found). If found is false, no method was found. Panics with RaiseError on call errors (matching GoFunction conventions).
func (*VM) CallDunderWithError ¶
func (vm *VM) CallDunderWithError(inst *PyInstance, name string, args ...Value) (Value, bool, error)
CallDunderWithError looks up and calls a dunder method on a PyInstance via MRO. Returns (result, found, error) - for use in PyBuiltinFunc where errors are returned.
func (*VM) CallFunction ¶
CallFunction calls a PyFunction with the given arguments.
func (*VM) CheckFloat ¶
CheckFloat gets argument n as float64, raises error if not convertible
func (*VM) CheckString ¶
CheckString gets argument n as string, raises error if not a string
func (*VM) CheckUserData ¶
func (vm *VM) CheckUserData(n int, typeName string) *PyUserData
CheckUserData gets argument n as userdata, checking the metatable name
func (*VM) ComputeC3MRO ¶
ComputeC3MRO computes the Method Resolution Order using C3 linearization algorithm. This properly handles multiple inheritance and detects inconsistent hierarchies.
func (*VM) CoroutineSend ¶
CoroutineSend resumes a coroutine with a value (same as generator but for coroutines)
func (*VM) CoroutineThrow ¶
CoroutineThrow throws an exception into a coroutine
func (*VM) DefaultClassCall ¶ added in v0.3.0
DefaultClassCall calls the default class instantiation logic (abstract check → __new__ → __init__).
func (*VM) EvalInNamespace ¶
EvalInNamespace evaluates code and returns the result
func (*VM) Execute ¶
func (vm *VM) Execute(code *CodeObject) (Value, error)
Execute runs bytecode and returns the result
func (*VM) ExecuteInModule ¶
func (vm *VM) ExecuteInModule(code *CodeObject, mod *PyModule) error
ExecuteInModule runs bytecode with a module's dict as the global namespace. This is used to populate a module's namespace when registering Python modules.
func (*VM) ExecuteInNamespace ¶
func (vm *VM) ExecuteInNamespace(code *CodeObject, globals, locals map[string]Value) error
ExecuteInNamespace executes code with custom globals/locals
func (*VM) ExecuteWithContext ¶
ExecuteWithContext runs bytecode with a context for cancellation/timeout support. The context is checked periodically during execution (see SetCheckInterval). Returns CancelledError if the context is cancelled, or TimeoutError if it times out.
func (*VM) ExecuteWithTimeout ¶
ExecuteWithTimeout runs bytecode with a time limit. Returns TimeoutError if the script exceeds the specified duration.
func (*VM) GeneratorClose ¶
func (vm *VM) GeneratorClose(gen *PyGenerator) error
GeneratorClose closes a generator
func (*VM) GeneratorSend ¶
GeneratorSend resumes a generator with a value and returns the next yielded value Returns (value, done, error) where done is true if the generator finished
func (*VM) GeneratorThrow ¶
GeneratorThrow throws an exception into a generator
func (*VM) Get ¶
Get returns the value at the given stack index (1-based, like Lua) Negative indices count from top
func (*VM) GetIntIndex ¶
GetIntIndex exports getIntIndex for use by stdlib packages.
func (*VM) GetTypeMetatable ¶
func (vm *VM) GetTypeMetatable(typeName string) *TypeMetatable
GetTypeMetatable retrieves a registered type metatable
func (*VM) ImportModule ¶
ImportModule imports a module by name
func (*VM) IsInstanceOf ¶
func (vm *VM) IsInstanceOf(inst *PyInstance, cls *PyClass) bool
IsInstanceOf checks if an instance is an instance of a class (including subclasses via MRO).
func (*VM) MaxCollectionSize ¶ added in v0.3.0
MaxCollectionSize returns the current collection size limit. 0 means unlimited.
func (*VM) MaxMemoryBytes ¶ added in v0.3.0
MaxMemoryBytes returns the current memory limit. 0 means unlimited.
func (*VM) MaxRecursionDepth ¶ added in v0.3.0
MaxRecursionDepth returns the current maximum recursion depth. 0 means unlimited.
func (*VM) NewTypeMetatable ¶
func (vm *VM) NewTypeMetatable(typeName string) *TypeMetatable
NewTypeMetatable creates a new type metatable
func (*VM) NewUserDataWithMeta ¶
func (vm *VM) NewUserDataWithMeta(v any, typeName string) *PyUserData
NewUserDataWithMeta creates userdata with a metatable attached
func (*VM) OptionalBool ¶
OptionalBool returns the bool at stack position pos if present and not None, otherwise returns def.
func (*VM) OptionalFloat ¶
OptionalFloat returns the float at stack position pos if present and not None, otherwise returns def.
func (*VM) OptionalInt ¶
OptionalInt returns the int at stack position pos if present and not None, otherwise returns def.
func (*VM) OptionalString ¶
OptionalString returns the string at stack position pos if present and not None, otherwise returns def.
func (*VM) RaiseError ¶
RaiseError raises a Python-style error. The format string can optionally start with an exception type prefix like "ValueError: ".
func (*VM) Register ¶
func (vm *VM) Register(name string, fn GoFunction)
Register registers a Go function as a global
func (*VM) RegisterBuiltin ¶
func (vm *VM) RegisterBuiltin(name string, fn GoFunction)
RegisterBuiltin registers a Go function as a builtin
func (*VM) RegisterFuncs ¶
func (vm *VM) RegisterFuncs(funcs map[string]GoFunction)
RegisterFuncs registers multiple functions at once
func (*VM) RegisterModule ¶
func (vm *VM) RegisterModule(name string, loader ModuleLoader)
RegisterModule registers a module loader on the VM
func (*VM) RegisterModuleInstance ¶
RegisterModuleInstance directly registers a pre-built module
func (*VM) RegisterType ¶
func (vm *VM) RegisterType(typeName string, constructor GoFunction, methods map[string]GoFunction)
RegisterType is a convenience function to register a Go type with methods Usage:
vm.RegisterType("person", map[string]GoFunction{
"new": newPerson,
"name": personGetName,
"set_name": personSetName,
})
func (*VM) RequireArgs ¶
RequireArgs checks that at least min arguments were passed. If not, it raises a TypeError with the function name and returns false. Usage:
if !vm.RequireArgs("loads", 1) { return 0 }
func (*VM) SetBuiltin ¶
SetBuiltin registers a builtin function
func (*VM) SetCheckInterval ¶
SetCheckInterval sets how often the VM checks for timeout/cancellation. Lower values are more responsive but have more overhead. Default is 1000 instructions.
func (*VM) SetMaxCollectionSize ¶ added in v0.3.0
SetMaxCollectionSize sets the maximum number of elements in a single collection. 0 means unlimited.
func (*VM) SetMaxMemoryBytes ¶ added in v0.3.0
SetMaxMemoryBytes sets the approximate memory limit in bytes. 0 means unlimited.
func (*VM) SetMaxRecursionDepth ¶ added in v0.3.0
SetMaxRecursionDepth sets the maximum call stack depth. 0 means unlimited.
func (*VM) ToList ¶
ToList converts a Python iterable to a Go slice of Values (exported wrapper). Handles lists, tuples, strings, ranges, sets, dicts, iterators, generators, etc.
func (*VM) ToUserData ¶
func (vm *VM) ToUserData(n int) *PyUserData
ToUserData gets argument n as userdata
func (*VM) TrackAlloc ¶ added in v0.3.0
TrackAlloc is the exported wrapper of trackAlloc for stdlib use.
func (*VM) TypeNameOf ¶
TypeNameOf returns the Python type name for a value.
Source Files
¶
- api.go
- attr_collections.go
- attr_format.go
- attr_numeric.go
- attr_objects.go
- attr_string.go
- attributes.go
- builtins.go
- builtins_classes.go
- builtins_exceptions.go
- builtins_functions.go
- builtins_reflection.go
- builtins_types.go
- calls.go
- conversions.go
- exceptions.go
- generators.go
- generators_dispatch.go
- items.go
- iteration.go
- module.go
- opcode.go
- operations.go
- operations_arithmetic.go
- operations_compare.go
- operations_format.go
- types.go
- types_callable.go
- types_collections.go
- vm.go
- vm_dispatch.go