evm

package
v0.4.14 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 24 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

EVM

Run Go plugins inside a Go application. Compile against the APIs you expose, link their implementations, then create a VM session. Swap linked programs when you activate a new plugin; existing sessions retain their program.

EVM supports sequential Go: structs, collections, closures, interfaces, concrete generic instances, range functions and defer/panic/recover. It excludes goroutines, channels, unsafe and arbitrary native imports. Source is limited to 1 MiB. Unsupported constructs fail compilation.

module, err := evmcompiler.Compile("bonus.go", `
func Bonus(points int64) int64 {
    if points < 1000 { return 0 }
    return points / 10
}`)
if err != nil { return err }
program, err := evm.Link(module)
if err != nil { return err }
vm := evm.New(program)
var out [1]values.Value
err = vm.Run(ctx, "Bonus", []values.Value{values.Int(1500)}, out[:])
if err != nil { return err }
bonus := out[0].AsInt() // 150

A linked program is immutable and shareable. A VM owns registers and globals; it is neither concurrent nor reentrant. Initialization runs once before the first entry. Later calls retain globals. Reset() clears session state and makes the next call initialize again. Execution failure invalidates the session until reset. Results are written only on success; host side effects are not rolled back by the VM.

Arguments/results use values.Value. Their types come from the entry signature. Keep program-local interfaces and function references with their program; repack them through the destination program's APIs when crossing that boundary.

Host APIs

Use evmbind for a Go API package:

module, err := evmcompiler.Compile("plugin.go", source, schema.Package())
if err != nil { return err }
program, err := evm.Link(module, schema.Bind(host))

schema.Package() supplies declarations; schema.Bind(host) supplies their implementations. Reuse the schema so nominal type identities match. Generated bindings call Go directly; reflection is the fallback. Native pointers retain their identity and mutations. The host must synchronize concurrent access.

Manual APIs use Package.Types, Functions and Methods; see binding declarations. Only supplied exports satisfy imports. A Call and its argument/result windows are borrowed for that callback. Read arguments before overwriting overlapping result slots; never retain the windows. Host callbacks must honor cancellation themselves.

A package may also supply Go Source. Its shared scalar types and methods can compile as guest code; see shared scalar source. PackageSource, PackagePaths and PackagesSource print the script-facing API for tooling or an agent writing a plugin.

Limits and errors

VM.Limits sets session limits. RunWithBudget sets invocation limits, including initialization. Zero fields select defaults or inherit the session limit. Budget.Duration and the context bound elapsed time cooperatively; native calls must return or observe cancellation. Instruction, depth, register, allocation and output limits cover VM execution. Allocation accounting is cumulative until reset and includes transient capacity; it is not live heap size. Native APIs remain responsible for their own work and allocations.

Script panics and language errors can be recovered by a direct deferred function. Uncaught errors retain source positions and unwrap their cause. Budget, cancellation, invalid-value and native callback errors are fatal and skip script defers. Native Go panics propagate after VM cleanup. The host owns rollback and resource cleanup.

Bytecode and native bindings are trusted implementation inputs. Link validates operands and layouts; it cannot prove arbitrary pointers safe. Accept script source through the compiler, not uploaded raw bytecode. EVM is not a process isolation boundary.

Standard library and output

Imports expose selected fmt, log, math, strings, strconv and errors APIs. Unlisted symbols fail type checking. Formatting supports flags, aggregates, custom formatting methods and wrapped errors. errors.As is not exposed. log has no process-exit or configuration APIs.

VM.Output func(string) error receives print/log output; nil uses Go's logger. Sink errors abort execution. Limits.OutputBytes defaults to 1 MiB and caps both a formatted value and total output per invocation, including initialization. Library callbacks share the VM's execution limits.

KVO records

Create a model package once:

models, err := evm.ModelPackage("m", schema)

A customer model exposes m.Customer and m.CustomerEdit. Selectors come from the model, including local and qualified aliases. The host supplies lookup, scan and save operations; model registration does not grant database access.

A cursor wrapper can call call.SetRecordResult(model, cursor.Record()). Immutable records travel as 16-byte pairs, including through any. Field reads use their shared representation metadata; they need no read-record arena or expiry check. Generated and reflected native records use the same script API. Use registered record methods to expose a Go helper as customer.PointBalance().

Mutable editors require evm.WithRecords(ctx) inside the transaction. Register an editor through scope.EditRecord; recover/check it through scope.MutableRecord in the save wrapper. Flush pending materialized collections before saving. Saving and committing remain host operations.

ToJSON() returns detached JSON-compatible data. It traverses records directly, preserves integer precision and invokes custom JSON/text marshalers at scalar leaves. It does not serialize and reparse the whole record. Program.JSONValue and Call.JSONValue convert VM any to an owned Go tree; numbers are json.Number. The call form charges the allocation budget. Their byte limit counts equivalent escaped JSON output. EncodeJSON writes actual JSON bytes.

Declaring borrowing effects

Host declarations can make ownership analysis more precise:

readEffects := &evm.OwnershipEffects{
    NoRetain: true, NoInvalidate: true,
    Borrowed: []evm.BorrowSource{{Result: 0, Domain: "db.tx", ScopeParameter: 1}},
}
endEffects := &evm.OwnershipEffects{
    NoRetain: true,
    Ends: []evm.ScopeEnd{{Domain: "db.tx", ScopeParameter: 1}},
}
writeEffects := &evm.OwnershipEffects{
    NoRetain: true,
    Callbacks: []evm.ScopedCallback{{Argument: 1, Domain: "db.tx"}},
}

Attach these to ExternalFunction.Ownership or ExternalMethod.Ownership. Results and callback arguments are zero-based; scope parameters are one-based, including a receiver, with zero meaning the enclosing scope. Only promise NoInvalidate when the operation cannot close or replace existing borrowed storage. A cursor advancing to another transaction must not promise it. NoRetain forbids keeping arguments beyond the synchronous call. Effects are part of the compiled binding contract: Link rejects mismatches.

Register another borrowable host type with values.NewOwnedType and its budgeted ownership callback. Immutable record types provide this automatically. Unknown calls conservatively retain arguments and invalidate live borrows. Simple read-only guest helpers are analyzed. Scope-local flat arrays, slices and maps remain borrowed when all aliases stay local and no call invalidates the scope. Other containers own their borrowed leaves when inserted; opaque borrowed types copy at acquisition. Function.OwnershipSites explains inserted operations. Scope matching treats all potentially aliased instances of a domain conservatively; nested callbacks remain safe through leaf copying.

Read-only KVO handles represent snapshots, not stable database identity. Owning a snapshot can change its representation/address; use an explicitly carried primary key for identity or map keys that must survive an ownership boundary. Explicit Go struct copies (copy := *row) allocate VM struct storage and own their payload; ordinary handle assignment and interface packing do not box. Returned strings are conservatively copied even when their originating record was already owned. Materialized collection fields own their contents.

Raw Go access and handwritten bytecode do not get compiler ownership analysis. Use kvo.Record.Own() before retaining encoded bytes beyond a transaction. Host effects must describe actual invalidation; no runtime lease or per-record transaction bookkeeping can repair an incorrect declaration.

Shared scalar source

A package can provide Source instead of native declarations. Its functions and methods compile as guest Go code. SharedTypes preserves a native scalar's type identity across host signatures and KVO fields:

idType := values.NewType("ids.ID", values.Raw)
ids := evm.Package{
    Path: "ids",
    Source: idsSource, // the same Go scalar/method source used by the host
    SharedTypes: []evm.SharedType{{
        Name: "ID", Native: reflect.TypeFor[ID](), Type: idType,
    }},
}

Register ids with the model package for compilation and linking. A KVO word whose native type is ID appears as ids.ID, including inside collections. Its methods work even when the script imports only the model package. Shared source must use supported EVM imports and cannot declare globals or init functions. The shared type's scalar kind must match its native declaration. Keep host-specific integrations in separate files; embed the shared source.

Internals and tests

Inside EVM covers values, instruction encoding, compilation, calling conventions, the evaluator and optimization. evmasm is the assembler for tests and diagnostics; bytecode has no persisted compatibility format. Benchmarks separate execution, compilation and database costs.

go test ./evm/... ./values/... ./nativebind/...
go run ./evm/EVMBook-rebuild.go

Documentation

Overview

Package evm implements a register VM for compiled Go programs. Its bytecode is trusted input, not a sandbox boundary or a persisted compatibility format.

Code generated by go generate. DO NOT EDIT.

Immutable KVO records travel as cells and borrow storage until the compiler inserts an ownership copy. Mutable editors remain bound to a RecordScope.

Index

Constants

View Source
const RecordListDirect uint8 = 1

RecordListDirect fuses a single adjacent len/index consumer with its property read. No list value escapes the instruction, so no VM temporary is needed.

View Source
const VMFieldBase = kvo.RuntimePropBase

VMFieldBase separates VM layout fields from persistent KVO property codes.

Variables

View Source
var (
	ErrSteps         = errors.New("instruction limit exceeded")
	ErrDepth         = errors.New("call depth limit exceeded")
	ErrRegisters     = errors.New("register limit exceeded")
	ErrDivideByZero  = errors.New("integer division by zero")
	ErrAllocations   = errors.New("allocation count limit exceeded")
	ErrAllocation    = errors.New("allocation budget exceeded")
	ErrNegativeShift = errors.New("negative shift amount")
	ErrInvalidState  = errors.New("VM session failed; call Reset before reuse")
	ErrNilFunction   = errors.New("call of nil function")
	ErrFunction      = errors.New("invalid function value")
	ErrReentry       = errors.New("VM is already running")
)
View Source
var (
	ErrNil    = errors.New("nil pointer dereference")
	ErrBounds = errors.New("index or slice bounds out of range")
	ErrNilMap = errors.New("assignment to nil map")
)
View Source
var ErrDeferStack = errors.New("defer stack is no longer active")
View Source
var ErrOutput = errors.New("output limit exceeded")
View Source
var ErrTypeAssertion = errors.New("interface conversion failed")
View Source
var JSONObjectType = values.NewType("map[string]interface{}", values.Pointer)

JSONObjectType is shared by native packages that exchange JSON objects.

Functions

func RecordScalarType

func RecordScalarType(t kvo.AnyType) *values.Type

RecordScalarType supplies the VM type for KVO leaves.

func RecordWordType

func RecordWordType(p kvo.PropImpl) *values.Type

RecordWordType maps a scalar KVO property to its script type.

func StandardLibraryPaths

func StandardLibraryPaths() []string

StandardLibrarySource supplies a virtual package to the compiler. Libraries have no globals; only reachable functions become part of a linked Program.

func StandardLibrarySource

func StandardLibrarySource(path string) (string, bool)

func ValidateDirectBindings

func ValidateDirectBindings(packages []Package) error

ValidateDirectBindings checks register conventions against the declared packages. A compiler schema may omit implementations until Link binds it to a host.

func ValidateShape

func ValidateShape(s *values.Shape) error

ValidateShape checks native declaration storage before the compiler builds Go types. It accepts recursive pointer graphs and rejects recursive value storage.

Types

type BorrowSource

type BorrowSource struct {
	Result         int
	Domain         string
	ScopeParameter int
}

BorrowSource declares a result whose storage is valid within a scope. ScopeParameter is zero for the enclosing scope, or the one-based argument index identifying it (including the receiver for methods). Domain names are binding-defined identities, e.g. "edb.transaction".

type Budget

type Budget struct {
	Steps, Allocations, AllocationBytes  uint64
	Duration                             time.Duration // soft wall-clock limit for the invocation
	HardDuration                         time.Duration
	HardAllocations, HardAllocationBytes uint64
	UnlimitedSteps                       bool
}

Budget applies to one RunWithBudget call, including first-use initialization. Zero fields inherit VM defaults. Allocation limits also obey the remaining session allowance configured by VM.Limits.

type BudgetScope

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

BudgetScope temporarily restricts the running invocation. A scope may span several external calls. Only the innermost scope can be closed.

func (*BudgetScope) BorrowRecords

func (s *BudgetScope) BorrowRecords(c *Call) *RecordScope

BorrowRecords opens a transaction-local record scope inside this budget.

func (*BudgetScope) End

func (s *BudgetScope) End(c *Call) error

End checks the section before restoring the parent limits. Call it before committing external effects. An exhausted scope also fails the invocation.

type Call

type Call struct {
	Context  context.Context
	Position SourcePosition
	R        []uint64
	P        []unsafe.Pointer
	// contains filtered or unexported fields
}

Call borrows an in-place argument/result window for this native call. Read parameters before overwriting result slots. Do not retain Call or its slices, and do not reenter this VM. Independent VMs may run concurrently.

func (*Call) AllocCells

func (c *Call) AllocCells(n uint64) (unsafe.Pointer, error)

func (*Call) Argument

func (c *Call) Argument(i int) values.Value

func (*Call) ChargeAllocation

func (c *Call) ChargeAllocation(bytes uint64) error

ChargeAllocation accounts for native result payloads retained by the VM.

func (*Call) EncodeJSON

func (c *Call) EncodeJSON(v values.Value, limit int) (json.RawMessage, error)

EncodeJSON encodes an any argument from this invocation.

func (*Call) EncodeJSONObject

func (c *Call) EncodeJSONObject(v values.Value, limit int) (json.RawMessage, error)

EncodeJSONObject encodes a statically typed map[string]any argument.

func (*Call) FlushRecord

func (c *Call) FlushRecord(editor *kvo.Editor) error

FlushRecord applies edits made through Go map and slice aliases before the external database saves this one row. Repeated saves see subsequent edits.

func (*Call) IncreaseCPUBudget

func (c *Call) IncreaseCPUBudget(ms uint64) error

IncreaseCPUBudget adds wall time to the current scope, capped by the host.

func (*Call) IncreaseMemBudget

func (c *Call) IncreaseMemBudget(bytes, allocs uint64) error

IncreaseMemBudget raises the invocation allowance without resetting usage.

func (*Call) Interface

func (c *Call) Interface(slot int) (*values.Type, values.Value, error)

Interface reads a native argument by ABI slot, preserving nil versus typed nil. Returned values and type identities belong to this Program.

func (*Call) JSONValue

func (c *Call) JSONValue(v values.Value, limit int) (any, error)

JSONValue also meters the materialized tree against this invocation's budget.

func (*Call) NarrowBudget

func (c *Call) NarrowBudget(steps uint64, duration time.Duration) *BudgetScope

NarrowBudget starts a scope at the current external call. Zero leaves that limit alone. All work still counts against the enclosing budgets.

func (*Call) NarrowCPUBudget

func (c *Call) NarrowCPUBudget(soft, hard time.Duration) *BudgetScope

NarrowCPUBudget starts an adjustable time scope. Enclosing limits still apply. Memory is charged to the invocation, including across transaction scopes.

func (*Call) Program

func (c *Call) Program() *Program

func (*Call) RecordValue

func (c *Call) RecordValue(model *kvo.Model, m kvo.Record) (values.Value, error)

RecordValue returns the immutable row cell without allocating a handle.

func (*Call) RunCallback

func (c *Call) RunCallback(v values.Value) (err error)

RunCallback runs a borrowed func() on the native call's goroutine. Its registers are separate so Go can keep using the original Call window. Globals, captured cells, transaction scopes and all budgets stay shared.

func (*Call) SetEditRecordResult

func (c *Call) SetEditRecordResult(model *kvo.Model, e *kvo.Editor) error

SetEditRecordResult returns a transaction-bound editor and meters its handle.

func (*Call) SetInterface

func (c *Call) SetInterface(slot int, t *values.Type, v values.Value) (err error)

SetInterface writes an interface result by ABI slot. Dynamic types must be declared in the wrapper's DynamicTypes (or used by source) before linking. Boxing and value copies are charged to this execution's allocation budget.

func (*Call) SetReadRecordResult

func (c *Call) SetReadRecordResult(model *kvo.Model, m row2.View) error

SetReadRecordResult returns one immutable KVO row from a host function. The compiler owns the payload when it escapes its borrowing boundary.

func (*Call) SetRecordResult

func (c *Call) SetRecordResult(model *kvo.Model, m kvo.Record) error

func (*Call) SetResult

func (c *Call) SetResult(i int, v values.Value)

func (*Call) SetValue

func (c *Call) SetValue(slot int, v values.Value)

SetValue writes a V pair into a result slot whose external type uses both banks.

func (*Call) Value

func (c *Call) Value(slot int) values.Value

Value reads a V pair. Access R-only and P-only arguments through their banks.

type CaptureSlot

type CaptureSlot struct {
	Type *values.Type
	Slot uint16
}

type Closure

type Closure struct {
	Function uint32
	Captures []Operand
}

type Conversion

type Conversion struct{ From, To NumericType }

type DeferKind

type DeferKind uint8
const (
	DeferDirect DeferKind = iota + 1
	DeferIndirect
	DeferInvoke
	DeferPanic
	DeferRecover
)

type DeferOp

type DeferOp struct {
	Kind          DeferKind
	Target        FunctionRef
	Function      Operand
	Signature     uint32
	Invoke        uint32
	Receiver      uint16 // Pair register captured by DeferInvoke.
	Args          []Operand
	ExternalStack bool
}

DeferOp describes values to capture now, then invoke when its owner exits. ExternalStack selects the Raw stack handle in the instruction's A operand.

type DirectBinding

type DirectBinding struct {
	Op   Opcode
	Call DirectFunc
	// Window also exposes the ordinary R/P argument window through Call.
	// Generated package functions use it for their leading *evm.Call.
	Window bool
	// contains filtered or unexported fields
}

DirectBinding binds a small external operation with zero or one result. Call receives arguments in declaration order, receiver first. Missing arguments are zero. Its value result is ignored for a void operation. Its error result reports VM or conversion failures. Fallible APIs use Native. Op alone is sufficient in the package supplied to the compiler. Methods may use a function opcode with their receiver as argument zero; this supports pair-valued receivers such as immutable KVO records.

func DirectUnary

func DirectUnary(fn func(uint64) uint64) DirectBinding

DirectUnary binds an infallible word-to-word operation through DirectBinding. Direct calls use a specialized instruction; indirect and deferred calls use the same declaration and ordinary ABI. The returned binding is immutable registration metadata. Use DirectBinding directly for Call/context access.

type DirectFunc

type DirectFunc func(*Call, values.Value, values.Value) (values.Value, error)

type DynamicMethod

type DynamicMethod struct {
	ID        string
	Signature Signature
	Variadic  bool
	Function  FunctionRef
}

type DynamicType

type DynamicType struct {
	Shape   *values.Shape
	Methods []DynamicMethod
}

DynamicType defines a concrete interface payload. Indexes belong to a Program.

type ExecutionError

type ExecutionError struct {
	Function string
	PC       int
	Position SourcePosition
	Err      error
}

ExecutionError retains the source location and wrapped host/VM error.

func (*ExecutionError) Error

func (e *ExecutionError) Error() string

func (*ExecutionError) Unwrap

func (e *ExecutionError) Unwrap() error

type ExtendedKind

type ExtendedKind uint8
const (
	ExtendedMakeInterface ExtendedKind = iota + 1
	ExtendedTypeAssert
	ExtendedFieldAddr
	ExtendedField
	ExtendedIndexAddr
	ExtendedIndex
	ExtendedSlice
	ExtendedMakeSlice
	ExtendedSliceToArray
	ExtendedMakeMap
	ExtendedLookup
	ExtendedMapUpdate
	ExtendedDelete
	ExtendedClear
	ExtendedLen
	ExtendedCap
	ExtendedAppend
	ExtendedCopy
	ExtendedRange
	ExtendedNext
	ExtendedConvert
	ExtendedEqual
	ExtendedComplex
	ExtendedReal
	ExtendedImag
	ExtendedComplexBinary
	ExtendedComplexNegate
	ExtendedMinMax
	ExtendedGetKey
	ExtendedSetKey
	ExtendedGetChildKey
	ExtendedPackedArray
	ExtendedPackedLoad
	ExtendedPackedStore
	ExtendedAddressLoad
	ExtendedAddressStore
	ExtendedFieldStore
	ExtendedNativeAlloc
	ExtendedOwn
	ExtendedRecordCopy
	ExtendedRecordList
	ExtendedRecordListLen
	ExtendedRecordListIndex
)

type ExtendedOp

type ExtendedOp struct {
	Record   *RecordType
	Kind     ExtendedKind
	Shape    *values.Shape
	Source   *values.Shape
	In, Out  []Operand
	Index    uint64
	ChildKey uint64 // leaf property for ExtendedGetChildKey
	Flags    uint8
	Packed   bool // Local slice/array backing uses the element's scalar bank.
	// contains filtered or unexported fields
}

ExtendedOp is an immutable bytecode operand descriptor, not an executable callback. BC selects it for operations needing more than three operands.

type ExternalConstant

type ExternalConstant struct {
	// Untyped preserves exact Go constants until the consuming expression supplies a type.
	Untyped constant.Value
	Rune    bool
	Name    string
	Type    *values.Type
	Value   values.Value
}

type ExternalFunction

type ExternalFunction struct {
	Ownership *OwnershipEffects
	// ParamNames preserves declaration names for source frontends such as GoX.
	ParamNames []string
	Direct     DirectBinding
	// On exposes a receiver-free operation as pkg.Record.Operation(args).
	On *RecordType

	Variadic bool
	// DynamicTypes declares concrete interface results produced by this wrapper.
	DynamicTypes []*values.Type
	Name         string
	Signature    Signature
	Call         Native
	// contains filtered or unexported fields
}

func BindStandardFunction

func BindStandardFunction(path, name string, signature Signature) (*ExternalFunction, bool)

BindStandardFunction binds a compiler-checked virtual library primitive. Signatures come from the virtual package, never from reflected Go functions.

func (*ExternalFunction) LinkName

func (f *ExternalFunction) LinkName() string

LinkName identifies the function in imports and disassembly.

type ExternalMethod

type ExternalMethod struct {
	Ownership    *OwnershipEffects
	Direct       DirectBinding
	Name         string
	Receiver     *values.Type
	Signature    Signature
	Variadic     bool
	Call         Native
	DynamicTypes []*values.Type
}

ExternalMethod has a receiver-free source signature. Its native ABI prepends Receiver to the argument list, reserving incoming V0 via ParameterLayout.

type Function

type Function struct {
	// OwnershipSites describes compiler-emitted clone locations before linking.
	OwnershipSites []OwnershipSite
	// LocalRecordReads marks instructions whose result cannot outlive its next execution in this frame.
	LocalRecordReads map[int]bool
	Method           bool // The first parameter is the receiver.
	// RecoverPC is a bytecode PC plus one; zero means no recovery continuation.
	RecoverPC uint32
	// RecoverTransparent marks compiler-generated receiver forwarding wrappers.
	RecoverTransparent bool
	Captures           []CaptureSlot
	Internal           bool // Generated functions are callable by bytecode only.
	Name               string
	Position           SourcePosition
	Signature          Signature
	// RCount/PCount cover this function's parameters, results and locals.
	// Outgoing arguments/results follow them and are sized by the linker.
	RCount, PCount int
	Code           []Instruction
	// Lines is optional; when present it has one source line per instruction.
	Lines     []int
	Positions []SourcePosition
}

type FunctionRef

type FunctionRef struct {
	Native bool
	Index  uint32
}

FunctionRef selects a linked code or host function. Function values store its module-local index plus one in R, with zero reserved for nil.

type Import

type Import struct {
	Ownership     *OwnershipEffects
	Receiver      *values.Type
	Package, Name string
	Signature     Signature
}

type Instruction

type Instruction uint64

Instruction is one 64-bit word with its opcode in the low 16 bits. Most opcodes have three 16-bit operands. ABCD12 uses four 12-bit operands. WithBC combines B and C into 32 bits. Branches use a signed displacement from the following instruction. Constants live in separate pools.

func ABC

func ABC(op Opcode, a, b, c uint16) Instruction

func ABCD12

func ABCD12(op Opcode, a, b, c, d uint16) Instruction

ABCD12 packs four 12-bit operands above the ordinary opcode.

func WithBC

func WithBC(op Opcode, a uint16, bc uint32) Instruction

func (Instruction) A

func (i Instruction) A() uint16

func (Instruction) ABCD12

func (i Instruction) ABCD12() (a, b, c, d uint16)

func (Instruction) B

func (i Instruction) B() uint16

func (Instruction) BC

func (i Instruction) BC() uint32

func (Instruction) C

func (i Instruction) C() uint16

func (Instruction) Op

func (i Instruction) Op() Opcode

func (Instruction) SignedD12

func (i Instruction) SignedD12() int

type Invoke

type Invoke struct {
	InterfaceName string // Qualified static interface name for listings.
	Method        values.Method
}

type JSONTypes

type JSONTypes struct{ Boolean, Integer, Unsigned, Float, String, Array, Object uint32 }

JSONTypes identifies the concrete types a KVO JSON value can produce.

type Layout

type Layout struct {
	Slots          []uint16
	RCount, PCount int
}

Layout allocates V pairs first, then independent R and P slots. Slots retains source order, so a wrapper can derive its ABI once during registration.

func LayoutOf

func LayoutOf(types []*values.Type) (Layout, error)

func ParameterLayout

func ParameterLayout(params []*values.Type, method bool) (Layout, error)

ParameterLayout reserves incoming V0 for a method's receiver. The explicit arguments use the ordinary packed layout starting at R1 and P1.

type Limits

type Limits struct {
	Steps                 uint64 // one per dispatched bytecode instruction
	Allocations           uint64
	AllocationBytes       uint64
	OutputBytes           uint64
	Depth, RSlots, PSlots int
}

type Module

type Module struct {
	JSONTypes JSONTypes
	// NoOptimization disables optional linker rewrites. The compiler sets this for debug modules.
	NoOptimization bool
	// StrictCallWindows promises that callers only observe declared results after a script call.
	StrictCallWindows bool
	// Sources holds original text keyed by source-position filename for optional disassembly comments.
	Sources      map[string]string
	Defers       []DeferOp
	Types        []DynamicType // concrete interface types indexed by R; slot zero, if present, must be empty
	Invokes      []Invoke
	FunctionRefs []FunctionRef
	Closures     []Closure
	Signatures   []Signature
	Functions    []Function
	Imports      []Import
	Words        []uint64
	Strings      []string
	Conversions  []Conversion
	Shapes       []*values.Shape
	ExtendedOps  []ExtendedOp
	Globals      []*values.Shape
	Init         string
}

func (*Module) Disassemble

func (m *Module) Disassemble() string

Disassemble lists all functions in compiled module order, with source lines and decoded operands.

func (*Module) DisassembleFunction

func (m *Module) DisassembleFunction(index int) string

DisassembleFunction lists the function at the given module index.

type NamedFunction

type NamedFunction struct {
	Name      string
	Signature Signature
}

NamedFunction identifies a public, noncapturing guest function. It contains no VM state and may be retained by a host registration after the call returns.

type Native

type Native func(*Call) error

type NumericKind

type NumericKind uint8
const (
	NumericSigned NumericKind = iota + 1
	NumericUnsigned
	NumericFloat
)

type NumericType

type NumericType struct {
	Kind NumericKind
	Bits uint8
}

type Opcode

type Opcode uint16
const (
	OpConst Opcode = iota + 1
	OpString
	OpMoveR
	OpMoveP
	OpMoveV
	OpClearP
	OpAddI64
	OpSubI64
	OpMulI64
	OpDivI64
	OpDivU64
	OpRemI64
	OpRemU64
	OpAddF64
	OpSubF64
	OpMulF64
	OpDivF64
	OpAnd
	OpOr
	OpXor
	OpShl
	OpShrI64
	OpShrU64
	OpEqR
	OpEqP
	OpLtI64
	OpLtU64
	OpEqF64
	OpLtF64
	OpJump
	OpJz
	OpJnz
	OpCallFunc
	OpCallHost
	OpReturn

	OpConvert
	OpCheckShift
	OpAddF32
	OpSubF32
	OpMulF32
	OpDivF32
	OpEqF32
	OpLtF32
	OpConcatStr
	OpEqStr
	OpLtStr
	OpAlloc
	OpLoad
	OpStore
	OpExtended
	OpGlobal
	OpFunction
	OpClosure
	OpCallVirt
	OpCallIndirect
	OpCheckNil
	OpDeferStack
	OpDefer
	OpRunDefers
	OpPanic
	OpRecover
	OpLoopLtI64
	OpCallHostRR
	OpCallHostRP
	OpJNil
	OpJNotNil
	OpLoadIndexR
	OpStoreIndexR
	OpLeI64
	OpLeU64
	OpMulAddF64
	OpAddMulF64
	OpSubAddF64
	OpLoopAddLtI64
	OpLoopAddLeI64
	OpAddImmI64
	OpLoopLeI64

	// Direct external calls. Each suffix names its explicit arguments, then its result.
	OpCallHostU
	OpCallHostS
	OpCallHostP
	OpCallHostUU
	OpCallHostUS
	OpCallHostUP
	OpCallHostSU
	OpCallHostSS
	OpCallHostSP
	OpCallHostPU
	OpCallHostPS
	OpCallHostPP
	OpCallHostUUU
	OpCallHostUUS
	OpCallHostUUP
	OpCallHostUSU
	OpCallHostUSS
	OpCallHostUSP
	OpCallHostUPU
	OpCallHostUPS
	OpCallHostUPP
	OpCallHostSUU
	OpCallHostSUS
	OpCallHostSUP
	OpCallHostSSU
	OpCallHostSSS
	OpCallHostSSP
	OpCallHostSPU
	OpCallHostSPS
	OpCallHostSPP
	OpCallHostPUU
	OpCallHostPUS
	OpCallHostPUP
	OpCallHostPSU
	OpCallHostPSS
	OpCallHostPSP
	OpCallHostPPU
	OpCallHostPPS
	OpCallHostPPP
	OpCallHostMethodU
	OpCallHostMethodS
	OpCallHostMethodP
	OpCallHostMethodUU
	OpCallHostMethodUS
	OpCallHostMethodUP
	OpCallHostMethodSU
	OpCallHostMethodSS
	OpCallHostMethodSP
	OpCallHostMethodPU
	OpCallHostMethodPS
	OpCallHostMethodPP
	OpLoadIndexByte
	OpStoreIndexByte
	OpLoadIndexWord
	OpStoreIndexWord
	OpLoadIndexPtr
	OpStoreIndexPtr

	// Side-effecting direct calls; V means no result. A and B are read-only.
	OpCallHostV
	OpCallHostUV
	OpCallHostSV
	OpCallHostPV
	OpCallHostUUV
	OpCallHostUSV
	OpCallHostUPV
	OpCallHostSUV
	OpCallHostSSV
	OpCallHostSPV
	OpCallHostPUV
	OpCallHostPSV
	OpCallHostPPV
	OpCallHostMethodV
	OpCallHostMethodUV
	OpCallHostMethodSV
	OpCallHostMethodPV
)

func HostCallOpcode

func HostCallOpcode(method bool, args []values.Repr, result values.Repr) Opcode

HostCallOpcode selects a direct instruction from its explicit argument and result banks. Pair means string; Pointer means a true pointer or a record token. A zero result selects a void operation.

func UnaryHostOpcode

func UnaryHostOpcode(sig Signature) Opcode

UnaryHostOpcode selects the fused argument move, external call and result move.

func (Opcode) HostRegisters

func (op Opcode) HostRegisters() (a, b byte, ok bool)

HostRegisters supplies the disassembly and assembler prefixes. When a tied operand crosses R/P, print the result bank, except that a string always prints V.

func (Opcode) String

func (op Opcode) String() string

func (Opcode) TiedHostArgument

func (op Opcode) TiedHostArgument() (int, bool)

TiedHostArgument returns the source argument that must occupy A, counting the receiver as argument zero. Void calls read A without overwriting it.

type Operand

type Operand struct {
	Slot uint16
	Repr values.Repr
}

type OwnershipEffects

type OwnershipEffects struct {
	NoRetain     bool
	NoInvalidate bool
	Borrowed     []BorrowSource
	Ends         []ScopeEnd
	Callbacks    []ScopedCallback
}

OwnershipEffects describes host behavior for compiler ownership analysis. A nil declaration is conservative: the call may retain arguments and end scopes. Ends lists specific invalidations; NoInvalidate forbids all of them. Borrowed results must support ownership copying. Unknown aliasing may cause acquisition-time copying, reported in Function.OwnershipSites.

func (*OwnershipEffects) Clone

func (e *OwnershipEffects) Clone() *OwnershipEffects

func (*OwnershipEffects) Equal

func (e *OwnershipEffects) Equal(other *OwnershipEffects) bool

func (*OwnershipEffects) Validate

func (e *OwnershipEffects) Validate(sig Signature) error

type OwnershipSite

type OwnershipSite struct {
	PC     int
	Reason string
}

type Package

type Package struct {
	Source      string
	SharedTypes []SharedType
	Records     []*RecordType
	// EntryTypes are native concrete types that may enter in interface arguments to Run.
	EntryTypes []*values.Type
	Types      []TypeDecl
	Methods    []ExternalMethod
	Path       string
	Functions  []ExternalFunction
	Constants  []ExternalConstant
}

func ModelPackage

func ModelPackage(path string, schemas ...*kvo.Schema) (Package, error)

ModelPackage declares read and edit handles for every entity in a completed KVO schema. Register once and share its type identities across compilations. Database operations are supplied separately by the host.

func TimePackage

func TimePackage() Package

TimePackage exposes the database's timestamp cell as time.Time. It is linked automatically, so record fields and host methods share the same nominal type.

func (*Package) OwnsMethodReceiver

func (p *Package) OwnsMethodReceiver(t *values.Type) bool

OwnsMethodReceiver reports whether t is a named concrete type declared by p, or an explicitly declared pointer to one.

func (*Package) Record

func (p *Package) Record(model *kvo.Model, mutable bool) *RecordType

Record returns the package's handle for the given model and access mode.

type PanicError

type PanicError struct {
	Type  *values.Type
	Value values.Value
	// contains filtered or unexported fields
}

PanicError exposes the concrete value of an uncaught explicit Go panic. Type is external metadata; Value is the unboxed payload belonging to this Program.

func (*PanicError) Error

func (e *PanicError) Error() string

type Program

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

Program is an immutable linked snapshot. Registration and symbol lookup stay outside the execution loop. Independent VMs may share a Program if its native wrappers support concurrent use.

func Link(m *Module, packages ...Package) (*Program, error)

func (*Program) DisassembleFloatLoops

func (p *Program) DisassembleFloatLoops() string

DisassembleFloatLoops lists the private execution plans chosen by Link. The module's source listing and instruction PCs remain valid.

func (*Program) EncodeJSON

func (p *Program) EncodeJSON(ctx context.Context, v values.Value, limit int) (json.RawMessage, error)

EncodeJSON encodes a script's any value. Objects have string keys. Arrays and slices are JSON arrays. The byte limit also bounds expansion of shared subtrees. Unsupported types and cycles fail without exposing VM pointers.

func (*Program) InterfaceType

func (p *Program) InterfaceType(v values.Value) *values.Type

func (*Program) JSONValue

func (p *Program) JSONValue(ctx context.Context, v values.Value, limit int) (any, error)

JSONValue projects a script's any value directly into an owned Go JSON tree. Numbers are json.Number, preserving the encoder's exact spelling and precision. The limit is the equivalent JSON byte length, including escaped strings.

func (*Program) NamedFunction

func (p *Program) NamedFunction(v values.Value) (*NamedFunction, error)

NamedFunction resolves a function passed through an interface. Captures, methods and native functions cannot become independently callable entries.

func (*Program) PackInterface

func (p *Program) PackInterface(t *values.Type, v values.Value) (values.Value, error)

PackInterface prepares a host input. The caller owns allocation limits and snapshots aggregate values before passing them here. Native results should use Call.SetInterface, which charges the active VM budget.

func (*Program) PointerInterface

func (p *Program) PointerInterface(t *values.Type, ptr unsafe.Pointer) (values.Value, error)

PointerInterface packs a trusted native pointer for an interface argument to Run. The type must be registered by the host and linked into this particular program.

func (*Program) Shape

func (p *Program) Shape(t *values.Type) *values.Shape

Shape returns immutable linked storage metadata for a host adapter.

func (*Program) UnpackInterface

func (p *Program) UnpackInterface(v values.Value) (*values.Shape, values.Value, error)

UnpackInterface reads a program-local interface payload for a host adapter.

type RecordScope

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

func WithRecords

func WithRecords(ctx context.Context) (context.Context, *RecordScope)

WithRecords binds mutable editors to one transaction. Close the scope before ending the transaction. Immutable reads do not need a scope.

func (*RecordScope) Close

func (s *RecordScope) Close()

func (*RecordScope) Edit

func (s *RecordScope) Edit(model *kvo.Model, m *row2.Editor) values.Value

func (*RecordScope) EditRecord

func (s *RecordScope) EditRecord(model *kvo.Model, m *kvo.Editor) values.Value

func (*RecordScope) Mutable

func (s *RecordScope) Mutable(v values.Value, model *kvo.Model) (*row2.Editor, error)

func (*RecordScope) MutableRecord

func (s *RecordScope) MutableRecord(v values.Value, model *kvo.Model) (*kvo.Editor, error)

func (*RecordScope) Read

func (s *RecordScope) Read(model *kvo.Model, m row2.View) values.Value

func (*RecordScope) ReadRecord

func (s *RecordScope) ReadRecord(model *kvo.Model, m kvo.Record) values.Value

type RecordType

type RecordType struct {
	// SchemaView exposes the properties supported by the current KVO codec.
	SchemaView bool
	Name       string
	Model      *kvo.Model
	Mutable    bool
	Pointer    *values.Type // guest *Model: Pair for immutable cells, Pointer for editors
}

func NewRecordType

func NewRecordType(name string, model *kvo.Model, mutable bool) *RecordType

type ScopeEnd

type ScopeEnd struct {
	Domain         string
	ScopeParameter int
}

type ScopedCallback

type ScopedCallback struct {
	Argument int
	Domain   string
}

ScopedCallback is invoked synchronously inside a newly established scope; the host closes that scope after the callback returns or unwinds.

type SharedType

type SharedType struct {
	Name   string
	Native reflect.Type
	Type   *values.Type
}

SharedType maps a host scalar to a type declared in Package.Source. Its methods are compiled from that same source.

type Signature

type Signature struct{ Params, Results []*values.Type }

type SourcePosition

type SourcePosition struct {
	File         string
	Line, Column int
}

type TypeDecl

type TypeDecl struct {
	// ScalarBase distinguishes Go int from int64 when their storage shapes match.
	ScalarBase *values.Type
	Name       string
	Shape      *values.Shape
}

TypeDecl exposes a named type, or an unnamed support type when Name is empty. Shape is declarative storage; native wrappers use the same cells as VM code.

type VM

type VM struct {
	// Output receives fmt/log/debug output. Nil uses the normal Go logger.
	Output func(string) error

	Limits Limits
	// contains filtered or unexported fields
}

VM owns reusable execution storage. It is neither concurrent nor reentrant. Zero limit fields select defaults; positive fields override them.

func New

func New(p *Program) *VM

func (*VM) Reset

func (vm *VM) Reset() error

Reset discards session globals and initialization state, and releases retained pointers. A failed or interrupted session must be reset before it can run again.

func (*VM) Run

func (vm *VM) Run(ctx context.Context, entry string, args, results []values.Value) error

Run writes results only on success. Value types are the entry signature's types, supplied externally; callers must honor them. Reusing a VM and output storage avoids allocations after growth. Native panics propagate to the host.

func (*VM) RunWithBudget

func (vm *VM) RunWithBudget(ctx context.Context, entry string, args, results []values.Value, call Budget) error

RunWithBudget bounds this invocation without changing defaults for later calls. Cancel the supplied context to interrupt an active invocation.

Directories

Path Synopsis
bench
internal/mathwork
Package mathwork holds the independent numeric workloads.
Package mathwork holds the independent numeric workloads.
internal/optwork
Package optwork holds workloads compiled by both Go and EVM.
Package optwork holds workloads compiled by both Go and EVM.
internal/workload
Package workload contains shared fixtures for the EVM and Lua benchmarks.
Package workload contains shared fixtures for the EVM and Lua benchmarks.
Package evmasm assembles textual EVM code without a Go compiler.
Package evmasm assembles textual EVM code without a Go compiler.
Package evmbind builds a reusable EVM host schema from Go declarations.
Package evmbind builds a reusable EVM host schema from Go declarations.
cmd/evmbind command
Command evmbind generates a package of native wrappers for an EVM API.
Command evmbind generates a package of native wrappers for an EVM API.
internal/methodfixture
Code generated by kvo.
Code generated by kvo.
Package evmcompiler compiles sequential Go 1.23 to EVM bytecode.
Package evmcompiler compiles sequential Go 1.23 to EVM bytecode.
log
internal
genstdlib command

Jump to

Keyboard shortcuts

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