evm

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: 0BSD Imports: 31 Imported by: ? 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

Safe, fast embedded Go. Compile Go source at run time and run it right inside your Go application—on your own structs, slices, and maps, within execution budgets you control.

EVM pairs an optimizing Go compiler with a register-based virtual machine. Scripts call your host functions and methods directly, either through generated bindings with zero reflection or through reflection with no build step. Because EVM shares memory and garbage collection with your host process, scripts read and mutate your real Go data with no serialization at the boundary.

This repository brings three pieces together:

  • EVM — a compiler, VM, host-binding generator, and standard library for running a safe, sequential subset of Go inside your app.
  • GoX — typed HTML templates that put markup inside real Go functions, compiled and live-reloaded through EVM.
  • KVO — typed data records with fast binary encodings (Fast2 / Compact2) and one unified API across Go structs, encoded rows, scripts, and templates.

A plugin looks like ordinary Go, using your application's own types and methods:

func OnOrder(c *shop.Customer, o *shop.Order, now time.Time) string {
	points := o.Cents / 100 * shop.PointsPerDollar
	if slices.ContainsFunc(o.Items, isGift) {
		points *= 2
	}
	// ...
	c.AddPoints(points, "order "+o.ID)
	// ...
}

The host compiles that source against the packages it chooses to expose, links it once with default limits, resolves the entry point and typed codecs, and runs it on a pooled VM with live Go pointers:

module := must(evmcompiler.Compile("bonus.go", pluginSource, packages...))
limits := evm.Limits{Steps: 1_000_000, Duration: time.Second}
program := must(evm.LinkOptions{DefaultLimits: &limits}.Link(module, packages...))
customerCodec := evmbind.Codec[*Customer](shopSchema)
orderCodec := evmbind.Codec[*Order](shopSchema)
onOrder := must(program.LookupFunction("OnOrder", &evm.Signature{Params: []*values.Type{customerCodec.Type(), orderCodec.Type(), values.TimeType}, Results: []*values.Type{values.StringType}}))
// ...
vm := program.AcquireVM(context.Background())
defer vm.Release()
slots := [4]values.Value{customerCodec.Pack(ada), orderCodec.Pack(order), values.NativeTime(now)}
ensure(vm.Run(onOrder, slots[:]))
fmt.Fprintln(out, slots[3].AsString())

Whether you are running a plugin, rendering a GoX template, or working with KVO records, the lifecycle is always the same five steps (walked through in Basic usage below):

  1. Write your application in plain Go—no framework lock-in or special base types.
  2. Expose selected packages. evmbind.New reads your package's own .go source and turns its exports into a script-facing API.
  3. Compile plugin or template source against those packages; type mismatches and missing fields fail here, before anything runs.
  4. Link once into an immutable, concurrency-safe *evm.Program with default limits, then resolve callables and typed codecs.
  5. Acquire a VM and run on your live Go values, as many times as you need, under explicit execution budgets.

Requires Go 1.27+.

go get github.com/andreyvit/evm

Why EVM?

  • Customize per account with code, not tangled configuration. Generic config-driven engines accumulate complex internals where dozens of edge cases (95% of them irrelevant to any one account) interact in brittle ways. Writing and validating simple Go for one account's exact rules is far simpler than maintaining one generic engine for every account. That unlocks deeper customization, much higher-quality AI-generated code, and a tiny blast radius (a single account instead of every account)—opening the door to lights-out, no-human-required parts of your codebase.
  • Per-account versioning and staged rollouts. Run different versions of even your own built-in logic for different accounts, rolling out changes gradually without littering the host binary with feature flags.
  • Iterate faster than server deploys. Templates, reports, emails, and ad-hoc data queries can be edited, compiled, and swapped at run time without redeploying the host binary.
  • No second language, no serialization tax. Plugins are Go and operate on your actual *Customer pointers, slices, and maps. Call c.AddPoints(...) directly—no JSON marshaling, no shadow data model.
  • Type-checked before a single instruction runs. Every plugin is compiled against your real host API. A typo in a field name or a wrong argument type is caught at compile time.
  • Strict capability control. A script can import only the packages you hand it. There are no goroutines, no unsafe, and no filesystem, network, or process access unless you explicitly expose it.
  • Runaway scripts stop cleanly. Every invocation runs inside explicit budgets for instruction steps, allocations, wall-clock duration, call depth, and output bytes.
  • Built for the request path. EVM compiles to typed register bytecode over unboxed 64-bit words, dispatches small host calls straight from registers through generated wrappers, and allocates zero bytes on warm calls beyond what the script itself allocates. Across five benchmark workloads (November 2026), EVM ran 6–15Ă— faster than Yaegi and 3–12Ă— faster than GopherLua, landing between 1.4Ă— faster and 1.9Ă— slower than C Lua 5.5 (LuaJIT with tracing remained 1.4–13Ă— ahead). GoX rendered six application templates in 27–40% less time than cached html/template. See the dated benchmarks for hardware, inputs, and commands.
  • Ideal for AI-generated plugins and ad-hoc queries. Print your exposed Go declarations with evmcompiler.PackageSource, let an agent or operator write a rule or query script, and let the compiler verify it before it ever runs—no new endpoints or deploys required.

Security model: EVM controls what APIs a script can call and how many resources it can spend, not OS-level process isolation. See Trust.

Want to see how the VM works under the hood? Read Inside EVM—a complete book covering values, KVO data modeling, register windows, bytecode, the compiler, the evaluator, optimizations, and GoX lowering.

At a glance

  • EVM: Sequential Go 1.23 (structs, slices, maps, strings, closures, interfaces, generics, range-over-func, defer/panic/recover, package globals, init, multi-file packages); no goroutines, channels, or unsafe. Source-driven host bindings with reflection or generated direct wrappers, shared Go memory, curated standard library, per-call budgets, source-mapped errors, coverage, and disassembly.
  • GoX: HTML inside Go functions, components as typed functions, typed callback slots, automatic contextual escaping (html/template rules), implicit and optional arguments, formatting pipelines, HTML/text/CSS output, concurrent renders, gox fmt / gox check, and editor support.
  • KVO: Schema-defined records with stable numeric property codes, one typed API across Go structs, Fast2, Compact2, MessagePack, and decoded memory, zero-decode field reads, batched editors, and first-class script and template integration.

How EVM Go differs from standard Go

EVM runs sequential Go 1.23 with 64-bit int/uint sizes, and 95% of what you write works identically to ordinary Go. The deliberate differences fall into five areas:

  • No guest concurrency or unsafe (share-nothing by default): Goroutines, channels, select, unsafe, and cgo are rejected at compile time. Instead, EVM follows a PHP-style share-nothing model: one immutable *evm.Program is shared across goroutines, each request leases a pooled single-goroutine *evm.VM, and package globals start fresh on every outermost vm.Run. For callbacks invoked concurrently across VMs, host APIs declare registration parameters as *evm.ConcurrentFunctionOf[S] so the compiler checks captured state at statically visible calls and evmbind enforces the proof at the native boundary, while evmruntime/concurrency (in evmstd.Packages()) provides a synchronized concurrency.Cache (see Concurrency model; plain *evm.FunctionOf[S] callbacks remain unchecked). Slice lengths and capacities fit in 32 bits, and single-file scripts may omit the package clause.
  • Host-defined virtual packages: Scripts can import only host-supplied packages plus EVM's curated standard library (no filesystem, network, or env). Host package variables (Package.Values) are read-only and unaddressable. Script package globals start fresh and run init() on each outermost vm.Run.
  • KVO records & editors: Model types (*m.Customer) expose local and qualified property selectors (c.points_earned / c.customer_points_earned) that are read-only; edits go through *m.CustomerEdit (with collection writes flushed on save), encoded records never decode implicitly (call NativeCopy()), and local list ranges avoid allocating a slice.
  • Automatic ownership copies for borrowed data: Transaction-scoped KVO records and //evm:borrow-bytes slices are copied automatically by the compiler when they escape, cross an invalidating call, or (for borrowed bytes) are mutated.
  • Fatal budget & cancellation traps: defer/recover() catches script panics and Go language errors (ErrNil, ErrBounds, etc.), whereas budget exhaustion, cancellation, and host callback errors abort immediately without running script defers.

For the complete breakdown—including hidden host fields, concrete host generics, and VM-bound closures—see Inside EVM §6.10: How EVM Go differs from standard Go.

Basic usage

1. EVM: run a Go plugin

Start with a plugin written in ordinary Go. It imports your application as package shop:

package plugin

import (
	"fmt"
	"shop"
	"slices"
	"strings"
	"time"
)

// OnOrder awards points for an order and returns a line for the log.
func OnOrder(c *shop.Customer, o *shop.Order, now time.Time) string {
	points := o.Cents / 100 * shop.PointsPerDollar
	if slices.ContainsFunc(o.Items, isGift) {
		points *= 2
	}
	if now.Sub(c.Joined) >= 365*24*time.Hour {
		points += 50 // loyalty bonus after a year
	}
	c.AddPoints(points, "order "+o.ID)

	for _, tier := range []string{"gold", "silver"} {
		if c.Points >= shop.TierThreshold(tier) {
			c.Tier = tier
			break
		}
	}
	return fmt.Sprintf("%s: +%d points, %d total, %s", o.ID, points, c.Points, c.Tier)
}

func isGift(item shop.Item) bool { return strings.HasPrefix(item.SKU, "GIFT-") }

The host application is plain Go with no knowledge of EVM:

// PointsPerDollar is the base earning rate.
const PointsPerDollar = 10

type Customer struct {
	Name    string
	Tier    string
	Points  int64
	Joined  time.Time
	History []string
}

// AddPoints credits the customer and records why.
func (c *Customer) AddPoints(points int64, reason string) {
	c.Points += points
	c.History = append(c.History, reason)
}
// ...
// TierThreshold returns the points a customer needs to hold a tier.
func TierThreshold(tier string) int64 {

The host embeds both sources, binds its own package, compiles and links the plugin once, then calls it for each order:

// The host's own source tells the compiler what package "shop" declares.
//
//go:embed shop.go
var shopSource embed.FS

// The underscore keeps the go tool from building the plugin as host code.
//
//go:embed _plugin/bonus.go
var pluginSource string
// ...
// Bind the host package. Every exported type, method, function and
// constant in shop.go becomes visible. Go cannot look functions or types
// up by name, so the options supply the functions, plus the types that
// no function, method or field leads to.
shopSchema := must(evmbind.New("shop", shopSource, evmbind.Options{
	Functions: map[string]any{"TierThreshold": TierThreshold},
	Types:     []reflect.Type{reflect.TypeFor[Customer](), reflect.TypeFor[Order]()},
}))
// What a plugin can import: the host package and the standard packages.
packages := append(evmstd.Packages(), shopSchema.Bind(nil))

// Compile and link once. A linked program is immutable and can be shared.
module := must(evmcompiler.Compile("bonus.go", pluginSource, packages...))
limits := evm.Limits{Steps: 1_000_000, Duration: time.Second}
program := must(evm.LinkOptions{DefaultLimits: &limits}.Link(module, packages...))
customerCodec := evmbind.Codec[*Customer](shopSchema)
orderCodec := evmbind.Codec[*Order](shopSchema)
onOrder := must(program.LookupFunction("OnOrder", &evm.Signature{Params: []*values.Type{customerCodec.Type(), orderCodec.Type(), values.TimeType}, Results: []*values.Type{values.StringType}}))

ada := &Customer{Name: "Ada", Tier: "basic", Joined: time.Date(2024, 1, 15, 0, 0, 0, 0, time.UTC)}
now := time.Date(2025, 3, 1, 0, 0, 0, 0, time.UTC)
for _, order := range []*Order{
	{ID: "A-1", Cents: 4200, Items: []Item{{SKU: "MUG-1", Qty: 2}}},
	{ID: "A-2", Cents: 9900, Items: []Item{{SKU: "GIFT-CARD", Qty: 1}}},
	{ID: "A-3", Cents: 1500, Items: []Item{{SKU: "LMP-3", Qty: 1}}},
} {
	func() {
		vm := program.AcquireVM(context.Background())
		defer vm.Release()
		slots := [4]values.Value{customerCodec.Pack(ada), orderCodec.Pack(order), values.NativeTime(now)}
		ensure(vm.Run(onOrder, slots[:]))
		fmt.Fprintln(out, slots[3].AsString())
	}()
}
fmt.Fprintln(out, ada.Name, "has", ada.Points, "points after", ada.History)

go run ./examples/evm-basic prints:

A-1: +470 points, 470 total, basic
A-2: +2030 points, 2500 total, gold
A-3: +200 points, 2700 total, gold
Ada has 2700 points after [order A-1 order A-2 order A-3]

What to notice in this example:

  • Single source of truth: evmbind.New reads shop.go directly (declarations, parameter names, and doc comments) without executing it, so there is no separate IDL to keep in sync. shopSchema.Bind(nil) pairs those declarations with their runtime implementations.
  • Safe compilation and checked lookup: Compile errors return evmcompiler.Diagnostics with file, line, and column; importing an unexposed package fails compilation. program.LookupFunction resolves OnOrder once after linking and checks every parameter and result type in order.
  • Programs, pooled VMs, and fresh globals: A linked *evm.Program is immutable, holds default limits (LinkOptions.DefaultLimits), and is shared across goroutines. Each caller leases a single-goroutine *evm.VM with program.AcquireVM(ctx) and returns its cleared buffers to the shared pool with defer vm.Release(). Every outermost vm.Run starts with fresh package globals and runs package init(), then clears globals and buffers on exit—so ada.Points and ada.History persist on the host *Customer rather than in guest globals.
  • Live Go pointers and stack slots: evmbind.Codec[*Customer](shopSchema) resolves the bound Go type once. Pack passes the live Go address (zero copy, preserving pointer identity and typed nil), so c.AddPoints and c.Tier = tier mutate ada in place. Arguments and results travel in one stack-allocated [4]values.Value array—three arguments in slots 0..2, one result in slot 3 (written only on success). Because values.Value carries no runtime type tag, callers must pack each argument slot according to its parameter type in the checked signature. (must and ensure are small panic helpers at the bottom of main.go.)

To cover a batch of calls with one shared budget instead of one budget per order, acquire one VM, call vm.SetBudget, and reuse a stack-allocated slot array across the loop:

match := must(program.LookupFunction("Match", &evm.Signature{
	Params:  []*values.Type{values.Int64, values.Float64, values.BoolType, values.StringType},
	Results: []*values.Type{values.Int64, values.BoolType},
}))
limits := evm.Limits{Steps: 50_000_000, Duration: 2 * time.Second}
vm := program.AcquireVM(ctx)
defer vm.Release()
vm.SetBudget(limits)
var slots [6]values.Value
var total int64
for _, row := range rows {
	slots[0] = values.Int(row.Cents)
	slots[1] = values.Float(row.Rate)
	slots[2] = values.Bool(row.VIP)
	slots[3] = values.String(row.Tag)
	if err := vm.Run(match, slots[:]); err != nil {
		return 0, err
	}
	if slots[5].AsBool() {
		total += slots[4].AsInt()
	}
}

Both budget lifetimes follow the same rules: AcquireVM(ctx) starts from the program's default limits, successive vm.Run calls spend that allowance, and vm.SetBudget(limits) starts a fresh allowance and deadline while the VM is idle. Omitting LinkOptions.DefaultLimits (nil) selects EVM's finite defaults; an explicit empty &evm.Limits{} or vm.SetBudget(evm.Limits{}) disables quotas while keeping structural bounds (Depth, RSlots, PSlots) and context cancellation. Each outermost vm.Run still gets fresh globals and runs init().

2. GoX: render a typed HTML template

A GoX template is an ordinary Go function taking *gox.Builder with HTML markup right inside the body. Here is the main page from examples/gox-basic:

package views

import (
	"app"

	"github.com/andreyvit/evm/gox"
)

func Page(b *gox.Builder, store *app.Store, user *app.User, cart *app.Cart, q string) {
	<Layout title={store.Name}>
		<slot-styles>
			<style>.out { opacity: .5 }</style>
		</slot-styles>
		<slot-content>
			<Header user={user} cart={cart} />
			<form><input name="q" value={q} placeholder="Search"></form>
			<ProductList q={q} />
			<CartSummary cart={cart} />
		</slot-content>
	</Layout>
}

// Callers do not pass store. *app.Store is an implicit type, so Header and
// ProductList receive the store of whichever component calls them.
func Header(b *gox.Builder, store *app.Store, user *app.User, cart *app.Cart) {
	<header>
		<h1>
			"Welcome to "
			store.Name
		</h1>
		<span class="avatar" title={user.Email}>user.Initials()</span>
		" "
		user.Name
		if user.Admin {
			" (admin)"
		}
		", member since "
		user.Joined | app.FormatDate
		" — "
		app.Pluralize(cart.Count(), "item", "items")
		" in cart"
	</header>
}

The layout takes its content as slots:

//gox:arg styles optional
func Layout(b *gox.Builder, title string, styles func(), content func()) {
	<html>
		<head>
			<title>title</title>
			<style>.tag { font-size: 12px }</style>
			if styles != nil {
				styles()
			}
		</head>
		<body>content()</body>
	</html>
}

A product row mixes markup, Go control flow and a helper:

func ProductRow(b *gox.Builder, store *app.Store, p *app.Product) {
	<li class="product {stockClass(p)}">
		<a href={p.URL()}>p.Name</a>
		" "
		p.Price | app.FormatMoney
		if !p.InStock() {
			<em>" sold out"</em>
		}
		for _, tag := range p.Tags {
			" "
			<span class="tag">
				"#"
				tag
			</span>
		}
		<small>
			" seen "
			p.Viewed() | strconv.Itoa
			"Ă—"
		</small>
	</li>
}

func stockClass(p *app.Product) string {
	if p.InStock() {
		return "in"
	}
	return "out"
}

The host exposes its application package to templates, as it does for a plugin, and adds GoX options:

// Go cannot look functions or types up by name, so the options supply
// the functions, plus the types that no function, method or field
// leads to.
app := must(evmbind.New("app", appSource, evmbind.Options{
	Functions: map[string]any{
		"Pluralize":   Pluralize,
		"Discount":    Discount,
		"FormatMoney": FormatMoney,
		"FormatDate":  FormatDate,
	},
	Types: []reflect.Type{
		reflect.TypeFor[Store](),
		reflect.TypeFor[User](),
		reflect.TypeFor[Cart](),
	},
}))
return &Env{
	Schema:   app,
	Packages: []evm.Package{app.Bind(nil)},
	Options: gox.Options{
		// A component that declares a *app.Store parameter receives
		// its caller's store without being passed it.
		// FormatMoney takes the store the same way, so a template
		// writes price | app.FormatMoney.
		ImplicitTypes: []string{"*app.Store"},
	},
}

Then it compiles and links once, and renders for each request:

env := NewEnv()

// Compile and link once. "Page" names the function Render runs. A linked
// program is immutable and renders concurrently.
tmpl := must(env.Options.CompileFiles("Page", Views, env.Packages...))
page := must(tmpl.Link(env.Packages...))
storeCodec := evmbind.Codec[*Store](env.Schema)
userCodec := evmbind.Codec[*User](env.Schema)
cartCodec := evmbind.Codec[*Cart](env.Schema)

user := &User{Name: "Ada Lovelace", Email: "ada@example.com", Admin: true, Joined: time.Date(2025, 3, 1, 0, 0, 0, 0, time.UTC)}
cart := &Cart{Coupon: "SPRING", Lines: []CartLine{
	{Product: TheStore.Products[0], Qty: 2},
	{Product: TheStore.Products[2], Qty: 1},
}}
args := [4]values.Value{storeCodec.Pack(TheStore), userCodec.Pack(user), cartCodec.Pack(cart)}
for _, query := range []string{"", "lamp"} {
	args[3] = values.String(query)
	html := must(page.Render(context.Background(), args[:], gox.RenderOptions{Strict: true}))
	fmt.Fprintln(out, html)
}

go run ./examples/gox-basic prints the page twice, once per query.

What to notice:

  • Go + markup together: Inside an element, quoted strings and expressions render, while if, for, and variables are ordinary Go. Each file imports the packages it uses, and gox fmt adds missing imports automatically.
  • Typed components and slots: <Header user={user} cart={cart} /> calls Header with type-checked arguments. Slots are func() parameters—<slot-content> fills content, and //gox:arg styles optional lets callers omit styles.
  • Implicit context: Nobody passes store to Header because *app.Store is in ImplicitTypes and flows automatically from the caller's scope.
  • Explicit formatting, automatic escaping: Text positions accept only strings and trusted content, so p.Price | app.FormatMoney explicitly formats the price (filling store implicitly). Every value is escaped for its exact context (Wool Blanket <XL> renders as Wool Blanket &lt;XL&gt;).
  • Live updates & strict mode: Strict: true turns nil-pointer output diagnostics into render errors. Recompiling a template at run time is just compiling and linking the updated source—see render_test.go.
3. KVO: read and edit typed records

KVO cleanly separates what a record means, how it is stored, and who reads it:

  • A schema holds properties and models.
  • A property pairs a stable numeric code, a name (like customer:points_earned), and a type into a typed handle such as kvo.NewSignedProp[int64](...).
  • A model lists the properties belonging to one record type.
  • A record (kvo.Record) is a 16-byte handle viewing data in place, with no decoded copy.
  • A binding connects a model to a Go struct type and constructs records.

One kvo.Record API works identically across all four representations:

Representation Record from Reads and edits
Go struct binding.Record(reflect.ValueOf(ptr)) Read and write the struct's fields
Fast2 or Compact2 row binding.Encoded(row2.Open(bytes)) Read fields from the bytes; an edit builds a new row
MessagePack row binding.MessagePack(bytes) Scan the encoded map by msgpack names; an edit rewrites the changed path
Decoded memory record.Fastest() on a row whose model has no Go struct Read indexed, owned values

Fast2 and Compact2 are the current row formats. Fast2 favors access speed, Compact2 size, and a Fast2 row can hold Compact2 children. MessagePack and Fast1 are supported legacy formats; kvo/codec/fast1 has its own API.

The same Get, Edit and script field access work on every representation. Code that takes a kvo.Record does not know which one it has.

This repository has no database. A database such as edb stores the rows and hands out records. A model also serves values that are never stored: a script takes a Go struct as a typed record the same way.

The example

The model, with a Go struct for it:

// Customer is the Go struct form of a customer. A kvo tag binds a field to a
// property by name; a msgpack tag names its key in MessagePack rows.
type Customer struct {
	Name     string    `kvo:"name" msgpack:"name"`
	Tags     []string  `kvo:"tags" msgpack:"tags"`
	Earned   int64     `kvo:"points_earned" msgpack:"points_earned"`
	Redeemed int64     `kvo:"points_redeemed" msgpack:"points_redeemed"`
	Joined   time.Time `kvo:"joined" msgpack:"joined"`
}

// Declare each property once, with a stable code and a type. A model lists
// the properties of one record type. Build all of this at startup.
var (
	Schema       = kvo.NewSchema()
	CustomerType = kvo.NewEntityType(Schema, "customer", reflect.TypeFor[Customer]())

	Customer_Name = kvo.NewStringProp[string](Schema, 1, "customer:name", kvo.TMachineString)
	Customer_Tags = kvo.NewListProp(Schema, 2, "customer:tags",
		kvo.ListOf(kvo.TMachineString), values.StringCodec[string]())
	Customer_Earned   = kvo.NewSignedProp[int64](Schema, 3, "customer:points_earned", kvo.TInt64)
	Customer_Redeemed = kvo.NewSignedProp[int64](Schema, 4, "customer:points_redeemed", kvo.TInt64)
	Customer_Joined   = kvo.NewTimeProp(Schema, 5, "customer:joined")

	CustomerModel = kvo.NewModel(Schema, CustomerType, func(b *kvo.ModelBuilder) {
		b.Prop(Customer_Name)
		b.Prop(Customer_Tags)
		b.Prop(Customer_Earned)
		b.Prop(Customer_Redeemed)
		b.Prop(Customer_Joined)
	})

	// Customers makes records of the model from structs and from rows.
	Customers = kvo.Bind(reflect.TypeFor[Customer](), CustomerModel)
)

// PointBalance takes a record in any representation. Scripts call it as a
// method: customer.PointBalance().
func PointBalance(c kvo.Record) int64 {
	return c.Get(Customer_Earned) - c.Get(Customer_Redeemed)
}

Go code makes three records, one per representation, then reads and edits them the same way:

// One customer per representation. A database would hand out the two
// encoded rows; here the binding encodes them from structs.
ada := &Customer{Name: "Ada", Tags: []string{"vip"}, Earned: 1250, Redeemed: 250, Joined: date(2024, 1, 15)}
bob := &Customer{Name: "Bob", Tags: []string{"newsletter"}, Earned: 300, Redeemed: 100, Joined: date(2025, 2, 1)}
cyd := &Customer{Name: "Cyd", Earned: 80, Joined: date(2025, 2, 20)}
bobRow := Customers.Encode(nil, reflect.ValueOf(bob).Elem(), row2.Fast2)
cydRow := msgpack.Encode(nil, reflect.ValueOf(cyd))

// A record is a 16-byte handle that views the struct or the row's bytes
// in place. Opening a row decodes nothing.
records := []kvo.Record{
	Customers.Record(reflect.ValueOf(ada)),
	Customers.Encoded(row2.Open(bobRow)),
	Customers.MessagePack(cydRow),
}

// Go reads typed properties the same way from every representation.
for _, c := range records {
	name := c.Get(Customer_Name)     // string
	tags := c.Get(Customer_Tags)     // kvo.List[string]
	joined := c.Get(Customer_Joined) // time.Time
	fmt.Fprintf(out, "%s: %d points, %d tags, joined %s\n", name, PointBalance(c), tags.Len(), joined.Format(time.DateOnly))
}

// Go edits through an editor. Editing a struct writes to the struct.
// Editing a row builds a new row and leaves the old bytes alone.
for i, c := range records {
	edit := c.Edit()
	edit.Set(Customer_Earned, edit.Get(Customer_Earned)+100)
	edit.List(Customer_Tags).AddUnique("welcomed")
	records[i] = edit.Record()
}

A script sees the schema as package m. A model is a type, a property is a field, and an editor is the Edit type:

package rules

import (
	"fmt"
	"m"
	"time"
)

// Describe reads a customer. Package m comes from the KVO schema: each model
// is a type and each property is a field. The same code runs on a Go struct
// and on an encoded row.
func Describe(c *m.Customer, now time.Time) string {
	status := "member"
	for _, tag := range c.tags {
		if tag == "vip" {
			status = "VIP"
		}
	}
	days := int(now.Sub(c.joined).Hours() / 24)
	return fmt.Sprintf("%s: %s for %d days, %d points", c.name, status, days, c.PointBalance())
}

// Redeem edits a customer. The host decides what an edit means: here it
// writes to the Go struct or builds a new row.
func Redeem(c *m.CustomerEdit, points int64) bool {
	if points <= 0 || points > c.points_earned-c.points_redeemed {
		return false
	}
	c.points_redeemed += points
	return true
}

The host builds package m from the schema, compiles the script once and runs it on the same three records:

// Scripts see the schema as package "m": type m.Customer with a field
// per property. PointBalance becomes a method of it.
models := must(evm.ModelPackage("m", Schema))
ensure(evmbind.RegisterMethods(&models, []evmbind.Method{
	evmbind.RecordMethod(CustomerModel, "PointBalance", PointBalance, evmbind.BorrowOnly),
}, evmbind.MethodOptions{}))
packages := append(evmstd.Packages(), models)

// Compile and link once.
module := must(evmcompiler.Compile("rules.go", rulesSource, packages...))
limits := evm.Limits{Steps: 100_000, Duration: time.Second}
program := must(evm.LinkOptions{DefaultLimits: &limits}.Link(module, packages...))
describe := must(program.LookupFunction("Describe", &evm.Signature{Params: []*values.Type{models.Record(CustomerModel, false).Pointer, values.TimeType}, Results: []*values.Type{values.StringType}}))
redeem := must(program.LookupFunction("Redeem", &evm.Signature{Params: []*values.Type{models.Record(CustomerModel, true).Pointer, values.Int64}, Results: []*values.Type{values.BoolType}}))
ctx, scope := evm.WithRecords(context.Background())
defer scope.Close()
vm := program.AcquireVM(ctx)
defer vm.Release()
// The script reads the same records. Nothing is converted or copied.
now := date(2025, 3, 1)
for _, c := range records {
	slots := [3]values.Value{c.Value(), values.NativeTime(now)}
	ensure(vm.Run(describe, slots[:]))
	fmt.Fprintln(out, slots[2].AsString())
}

// The script edits through the host's editors. They live in a record
// scope, which a host opens for the length of a transaction.

for i, c := range records {
	edit := c.Edit()
	slots := [3]values.Value{scope.EditRecord(CustomerModel, edit), values.Int(250)}
	ensure(vm.Run(redeem, slots[:]))
	records[i] = edit.Record()
	fmt.Fprintf(out, "%s redeems 250: %v, balance %d\n", c.Get(Customer_Name), slots[2].AsBool(), PointBalance(records[i]))
}
fmt.Fprintf(out, "Ada's struct: %d redeemed\n", ada.Redeemed)

go run ./examples/kvo-basic prints:

Ada: 1000 points, 1 tags, joined 2024-01-15
Bob: 200 points, 1 tags, joined 2025-02-01
Cyd: 80 points, 0 tags, joined 2025-02-20
Ada's struct: 1350 earned, tags [vip welcomed]
Bob's old row: 300 earned; new row: 400 earned, tags [newsletter welcomed]
Ada: VIP for 411 days, 1100 points
Bob: member for 28 days, 300 points
Cyd: member for 9 days, 180 points
Ada redeems 250: true, balance 850
Bob redeems 250: true, balance 50
Cyd redeems 250: false, balance 180
Ada's struct: 500 redeemed

What to notice:

  • Typed, unboxed reads: c.Get(Customer_Earned) returns an int64 directly—the property handle carries the Go type.
  • Local names: Property customer:points_earned uses the local name points_earned in struct tags and script selectors.
  • Representation-agnostic code: Describe ran unchanged on a Go struct, a Fast2 row, and a MessagePack row, and PointBalance works both as a Go function and as c.PointBalance() in scripts.
  • Safe edits: Editing ada mutated the struct in place, while editing bob left bobRow untouched and returned a new row from edit.Record(). Read-only records need no scope; script editors live inside an evm.WithRecords scope. Persistence and lookup always stay in your host application.

Advanced usage

A quick map of every capability across EVM, GoX, and KVO. Follow the linked guides for complete contracts and edge cases.

EVM

Deep dives: host contracts · evmbind guide · hand-written bindings · values representation · standard packages

Compile
  • Single file or full package: evmcompiler.Compile(filename, source, packages...) compiles one file (the package clause is optional); evmcompiler.CompileFiles(map[string]string{...}, packages...) compiles a multi-file package. Scripts support Go 1.23 features including generics and range over integers and functions.
  • Diagnostics: Compile errors return evmcompiler.Diagnostics, where each Diagnostic carries a Position and Message.
  • Safety limits: Total source is capped at evmcompiler.MaxSourceSize (1 MiB). Nesting is capped at 32 type levels (MaxTypeNesting), 500 expression levels (MaxExprNesting; a+b+c is 2), 100 statement levels (MaxStmtNesting; each else if counts), and 32 nested function literals (MaxFuncNesting). Constant string expressions are capped at 1 MiB (MaxConstStringSize). Package-wide branching is bounded by MaxBranchWeight (~4,000 sequential ifs, a 2,300-case switch, or a 450-case switch assigning distinct locals); split large functions or packages if you hit it.
  • Reuse environments for many scripts: evmcompiler.NewEnvironment(packages...) type-checks your host packages once. Subsequent Compile and CompileFiles calls check only the script itself. Environments are immutable and safe for concurrent use. (Unlike the package-list functions, NewEnvironment fails eagerly if any package cannot be imported.)
  • Debugging & tooling: Pass evmcompiler.Options{NoOptimization: true} to keep unoptimized bytecode, call module.Disassemble() to inspect it, or build test modules with evmasm.Assemble(source). For static analysis tools, use Analyze, AnalyzeFiles, SourceImporter, and CheckLimits.
  • Generate API docs for humans or agents: evmcompiler.PackageSource, PackagesSource, and PackagePaths print the exact Go declarations scripts see. Customize per-function comment lines with evmcompiler.DeclarationOptions{Annotations: fn}.
  • Link once, share everywhere: evm.Link(module, packages...) or evm.LinkOptions{DefaultLimits: &limits}.Link(module, packages...) returns an immutable *evm.Program (evm.LinkWithHostData attaches host metadata read via program.HostData()). DefaultLimits is copied at link time.
  • Shared link environments: evm.NewLinkEnvironment(packages...) or evm.LinkOptions{DefaultLimits: &limits}.NewEnvironment(packages...) validates and binds host packages once so linking many modules stays fast. Calling env.NewLinkEnvironment(packages...) on an evmcompiler.Environment shares linked host shapes, bound native methods, and all-native method tables across every program compiled from that environment (do not mutate those shared tables).
  • Resolve functions once: program.LookupFunction(name, want) resolves an entry point to a two-word evm.Callable (shared target plus optional captures). A non-nil *evm.Signature checks exact parameter and result type identity in order; nil accepts any signature; &evm.Signature{} requires func(). Validate retained callables with fn.CheckSignature(want).
  • Acquire a VM and run: vm := program.AcquireVM(ctx) leases a pooled, single-goroutine *evm.VM with a fresh budget from the program's default limits; defer vm.Release() clears references and returns its buffers to the shared pool. Execute with vm.Run(fn, slots) where slots holds arguments followed by one slot per result (nil for func()). Each slot is an untyped values.Value: callers must pack every argument slot with the constructor or codec matching its parameter type in the checked signature. Each outermost vm.Run starts with fresh package globals and runs package init(), clearing globals and buffers on return. Results are written only on success.
  • Dynamic interface dispatch: vm.LookupMethod(ifaceVal, name, sig) resolves a concrete interface method on its runtime receiver to a bound evm.Callable, invoked with the same vm.Run.
  • Program isolation: Interface values, callables, and type IDs belong to one linked program—foreign callables fail before execution, and values crossing programs must be repacked.
Host packages from source
  • Automatic binding: evmbind.New("shop", source, evmbind.Options{...}) reads your package's .go source and exposes its exports. Pass schema.Package() to Compile and schema.Bind(host) to Link.
  • Functions, receivers, and variables:
    • Options.Functions binds package functions by Go value.
    • Options.Host binds them as methods on a host receiver (taking a leading *evm.VM), supplied at link time via schema.Bind(host).
    • Options.Values exposes read-only package variables.
  • Shaping the API: Use Options.Types for extra root types, Options.Omit to exclude symbols ("Secret", "User.Token"), Options.Only or Options.Selective to pick a subset from a large package, Options.Methods / Fields / OmitFields to filter members, and Options.TypeNames to rename types for scripts.
  • Cross-package sharing & generics: Share types across schemas with Options.Imports (evmstd.Imports() supplies time.Duration, *url.URL, etc.). Bind concrete generic structs with Options.Instances and generic functions with Options.GenericFunctions.
  • Typed codecs, interfaces & guest storage:
    • Resolve a bound Go type once with evmbind.Codec[T](schema): Type() supplies its *values.Type for LookupFunction, Pack/Unpack convert ordinary bound native struct pointers without reflection or copying (preserving pointer identity and typed nil), and PackIn/UnpackIn run metered conversions on an active *evm.VM for slices, maps, structs, and other bound types.
    • Register concrete interface implementations with Options.Implementations (evmbind.Pointer[Tx]()), and pack/unpack them across the Go boundary with schema.PackInterface(program, ptr) / schema.UnpackInterface(program, v) (preserving typed nils). program.PackInterface / program.UnpackInterface wrap and unwrap already-packed EVM values.
    • Build and inspect guest-only structs, arrays, slices, and maps with vm.PackAggregate / vm.UnpackAggregate and vm.PackMap / vm.UnpackMap.
    • Schemas enforce their declared types and static-only policy—there is no runtime registration of arbitrary unregistered Go types through any.
  • No source available? evmbind.Discover("app", evmbind.Discovery{...}) binds functions and reachable types purely by reflection (no parameter names or doc comments; add constants via Discovery.Constants). Combine multiple package fragments for one import path with evm.MergePackages.
Generated native bindings

By default, host calls go through reflection. Generated bindings compile direct Go wrappers into your host binary so calls and field accesses avoid reflection.

  • Generate: Run go run github.com/andreyvit/evm/evmbind/cmd/evmbind -dir ../api -path demo -native example.org/project/api -package apibindings -o bindings_gen.go for a full package, or call evmbind.Generate(...) from Go with the same options as evmbind.New. Regenerate whenever bound declarations change.
  • Wire up: Pass Options.Static: &apibindings.Bindings. evmbind.Automatic (default) uses generated wrappers when their source fingerprint matches and falls back to reflection otherwise; evmbind.StaticOnly panics on missing or stale wrappers. Check schema.UsesStatic() to see which path is active, and use -tags evmreflect to exclude generated code while refactoring.
  • Fast paths: Small calls (functions with ≤2 args or pointer methods with ≤1 arg, returning ≤1 word/string/pointer) use direct register instructions. Generated field accessors also accelerate KVO via schema.NativeFields and binding.WithNativeSchema(schema). Use evmbind.GenerateMethods for record methods.
Hand-written packages
  • Build an evm.Package directly with Types, Functions, Methods, Constants, Values, and Aliases (evm.TypeAlias).
  • Implement evm.ExternalFunction / ExternalMethod with Call (func(*evm.VM) error, using vm.CallArgument and vm.SetCallResult) or Direct (evm.DirectUnary / evm.DirectBinding) for zero-window register calls.
  • Declare types from values.Shape (values.NewStructShape, values.NewPointerShape), add custom field conversions with TypeDecl.NativeCodec, expose package variables via evm.ExternalValue, and list interface entry types in Package.EntryTypes.
  • Never retain the borrowed *evm.VM or its argument window after returning, and check vm.Context for cancellation inside long host calls.
Values across the boundary
  • Values vs. storage cells: Every host-boundary value is a 16-byte values.Value (R uint64, P unsafe.Pointer) whose type comes from the signature or codec; callers are responsible for matching each argument slot to its declared parameter type. A slot is an indexed position in the call slice or register bank; a storage cell is an addressable values.Value in VM backing storage (register-only scalars need no cell).
  • Direct & shared: Scalars, strings, and named scalars convert directly (values.Int, values.Float, values.Bool, values.String). Bound structs pass by value; pointers keep their Go address via evmbind.Codec[*T] so host and script share one object. Slices and maps of bound types keep their Go backing storage (PackIn/UnpackIn); guest-only aggregates use vm.PackAggregate / vm.UnpackAggregate and vm.PackMap / vm.UnpackMap.
  • time.Time: One type on both sides. values.NativeTime(t) preserves location and monotonic reading; values.Time(t) stores a UTC instant.
  • any, error, and host interfaces: any carries registered native Go values with their types (never arbitrary unregistered Go types); script-only values arrive in Go as *evm.GuestValue and round-trip intact. Built-in error crosses both ways with its identity; open vm.OpenCallbackScope(limits) to keep script-defined error methods and exported Go func wrappers callable after vm.Run or vm.Release until scope.Close(), with a fresh per-call budget of limits. EVM does not synthesize runtime Go proxies for arbitrary interfaces—use a precompiled Go adapter backed by vm.LookupMethod (see embedding guide).
Functions and callbacks
  • Accepting and validating callables: Use *evm.FunctionOf[func(int) int] (or *evm.FunctionOf[any] for host-checked registrations; both alias evm.Callable) for retained callables that run on one VM at a time or under host serialization. For registration parameters whose callbacks may run concurrently across pooled VMs, declare *evm.ConcurrentFunctionOf[S] (S = non-variadic function signature or any, also aliasing evm.Callable): the compiler verifies captures/receiver at statically visible calls, and evmbind enforces fn.CheckConcurrentUse() at the native boundary. Retain a function value with program.Callable(v) and verify untyped registrations with fn.CheckSignature(want). A retained Callable keeps its receiver/captures and owning *evm.Program alive across runs.
  • Calling back mid-call: vm.Run(cb, slots) runs on the same *evm.VM whether invoked at the top level (including a native root) or synchronously from inside a host binding (sharing the goroutine, globals, remaining budget, cancellation, and active record scopes). Top-level calls use the VM's own registers directly; only re-entry from an active native call (including a native root calling vm.Run) swaps in a separate pooled register/frame segment so the outer binding's R/P windows stay stable even if the callback grows registers, restoring outer state on errors, panics, and budget failure. For interface methods, resolve with vm.LookupMethod and call vm.Run. Wrap errors with vm.CallbackError or vm.PanicCallback to keep guest recover() working.
  • Later invocations & concurrency: Invoke a retained Callable later by acquiring a fresh VM from fn.Program().AcquireVM(ctx). Captures stay shared while package globals start fresh—plain *evm.FunctionOf[S] callbacks are not checked by the compiler, and EVM does not synchronize concurrent guest writes to shared captures or native pointers. Use *evm.ConcurrentFunctionOf[S] on concurrent registration parameters plus concurrency.Cache (see Concurrency model), or synchronize concurrent access on the host side.
  • Passing Go closures to scripts: Cache evm.NewNativeFunctionType(sig) and create script-callable closures with vm.NativeFunction (metered during a call) or program.NativeFunction (for Run inputs).
Concurrency model (share-nothing by default)

EVM uses a PHP-style share-nothing model for host concurrency:

  • Immutable program, pooled per-goroutine VMs: Compile and link once into a shared *evm.Program. Any number of Go goroutines can run it concurrently by leasing pooled single-goroutine *evm.VMs (program.AcquireVM(ctx) / defer vm.Release()). Scripts themselves have no goroutines, channels, or locks.
  • Fresh globals per outermost vm.Run: Every outermost vm.Run allocates fresh package globals, runs package init(), and clears globals and buffers on exit. Concurrent requests cannot step on each other's package variables.
  • Caveat — shared captures, mutable receivers, and native pointers: The one place script state can outlive a single run is a retained evm.Callable (or exported Go adapter) that captures variables or binds a guest struct receiver (for example, an integration struct initialized once at plugin load time), plus any shared native Go pointers passed in by the host. If the host invokes that callable concurrently across multiple VMs, those captured cells and receiver fields are shared, and EVM does not synchronize concurrent guest mutations to them. Plain *evm.FunctionOf[S] callbacks remain unchecked; without *evm.ConcurrentFunctionOf[S], the host must require stateless top-level functions (!fn.HasCaptures()), keep captured/receiver state read-only after setup, or serialize calls on the host side.
  • Host-declared *evm.ConcurrentFunctionOf[S] verification: Declare a concurrent registration parameter as *evm.ConcurrentFunctionOf[S] (S = non-variadic function signature or any, e.g. AddAdminHandler(path, method string, handler *evm.ConcurrentFunctionOf[func(HandlerContext) any], ...)). Plugins pass c.Handle or a closure directly—no wrapper call is needed. evmbind records the parameter index in Package.ConcurrentCallbackParams, tells the compiler to verify statically visible calls before optimization, and enforces fn.CheckConcurrentUse() at the native boundary (nil passes through for optional callbacks). For capturing callbacks the binding also checks the registration site with vm.CheckConcurrentBorrow(i). Hand-written host bindings must check both. Verification accepts nil, plain top-level functions, and statically known closures/bound methods whose captures and receiver are used read-only (allowing len/cap, static guest helpers, *concurrency.Cache methods, and synchronous nested closures including GetOrLoad loaders), while rejecting writes, aliases stored in guest storage, and captured or indirect guest calls. The host answers for native code: a callback can call native functions and methods with tracked state and return tracked values to the host. Three guards remain: a pointer to a plain shared variable or field (&c.n) cannot go to native code, a guest type behind a native interface is still checked as guest code, and a callback cannot use the object it is registered on (ctx in ctx.AddHandler(...)). Dynamic callback expressions fail compilation. Limitations: calling the registration function indirectly (e.g. add := ctx.AddAdminHandler; add(...)) is not statically visible, so evmbind rejects unverified capturing callbacks at run time. Taking a method or closure for a concurrent registration also borrows its receiver and captures. The builder can read them afterwards. Writes through tracked aliases fail compilation, including after a branch that might register the callback. Go code holding its own pointer still needs to synchronize. See Concurrent callbacks and caches for allowed and forbidden plugin examples.
  • Shared concurrency.Cache[K, V]: Synchronized cache for concurrent callbacks (NewCache, Get, Set, GetOrLoad, InvalidateIfCurrent, and versioned Entry[V], exposed by evmruntime/concurrency in evmstd.Packages() and evmstd.ConcurrencyPackages()). Guest GetOrLoad omits ctx because the VM supplies vm.Context, while native Go (github.com/andreyvit/evm/evmruntime/concurrency) takes ctx explicitly:
    • Guest: (*Cache[K, V]).GetOrLoad(key K, fetch func() (V, time.Time, error)) (Entry[V], error)
    • Native Go: (*Cache[K, V]).GetOrLoad(ctx context.Context, key K, load func() (V, time.Time, error)) (Entry[V], error)
    • Behavior and limits: Holds at most 1,024 entries (evicts one arbitrary entry when full); zero time.Time does not expire while past/present expiry is not stored and expired entries drop on Get; InvalidateIfCurrent deletes only if the publication version matches; single-flight GetOrLoad lets waiters cancel independently via ctx, releases waiters to retry on loader error or panic, and prevents an older loader from overwriting a concurrent Set. Guest caches must be created with NewCache (zero value panics; native Go zero value is ready to use, do not copy after first use), accept only bool/integer/string (plus guest structs/arrays of those) as keys, and scalars or guest structs/arrays of those scalars as values (values also admit floats). Native Go accepts any reflexive comparable key and any value. Guest caches reject nested GetOrLoad misses on the same VM (concurrency: nested cache load would block). See Concurrent callbacks and caches.
Limits and budgets
  • Program defaults & VM leases: Set default limits at link time via LinkOptions.DefaultLimits (copied before publishing the program). Omitting DefaultLimits (nil) selects finite defaults (1M steps, 1M allocations, 64 MiB allocation bytes, 1 MiB output bytes, plus structural bounds: depth 1,024 and 1M R/P slots). An explicit empty &evm.Limits{} or vm.SetBudget(evm.Limits{}) disables quotas while keeping structural bounds and context cancellation; Limits.UnlimitedSteps lifts only the step cap.
  • Shared vs. fresh allowances: AcquireVM(ctx) starts a fresh allowance and deadline from the program's defaults; successive vm.Run calls and synchronous nested callbacks share it. Call vm.SetBudget(limits) while the VM is idle to start a fresh allowance and deadline (for a batch or between outermost runs). Parallel VMs spend independently.
  • Stretchable ceilings & narrowing: Set HardDuration, HardAllocations, or HardAllocationBytes so host calls (vm.IncreaseCPUBudget, vm.IncreaseMemBudget) or scripts (evmruntime.IncreaseCPUBudget, IncreaseMemBudget) can request extra headroom. Narrow limits for a sub-step with vm.NarrowBudget / vm.NarrowCPUBudget until scope.End(vm).
  • Accounting: Work is charged on every exit including failure, and an exhausted meter stays exhausted until vm.SetBudget or a fresh AcquireVM. Allocation limits are cumulative over the budget's lifetime, not live heap size. Host functions run outside VM meters unless they call vm.ChargeAllocation(bytes).
  • Limit errors: evm.ErrSteps, ErrDepth, ErrRegisters, ErrAllocations, ErrAllocation, ErrOutput, and ctx.Err() for timeouts and cancellation.
Errors and panics

Each leased VM has its own budget. Concurrent VMs share the Go heap, and native functions can allocate outside VM accounting. If the host must survive a worker running out of memory, run guest compilation and execution in a separate process with an OS memory limit.

  • Execution errors: Failures return *evm.ExecutionError{Function, PC, Position, Err} which unwraps cleanly for errors.Is (evm.ErrNil, ErrBounds, ErrNilMap, ErrDivideByZero, ErrNegativeShift, ErrTypeAssertion, ErrNilFunction). Uncaught panic(v) wraps *evm.PanicError.
  • Recovery vs. fatal: Scripts catch their own panics and language errors with defer/recover(). Budget exhaustion, cancellation, invalid values, and native callback errors are fatal and skip script defers.
  • VM state after failure: Every outermost vm.Run cleans up its globals, record scopes, and register buffers on exit—whether it succeeds or fails—and preserves caller result slots on failure. Spent budget stays charged (an exhausted meter stays exhausted until vm.SetBudget or a new AcquireVM), and host side effects are never rolled back. Foreign callables and wrong slot counts fail before entering guest code.
  • Host panics & manual errors: Panics inside evmbind functions become fatal VM errors with source positions; panics in hand-written Call callbacks propagate after VM cleanup. Move errors manually with vm.SetError, vm.ErrorValue, and vm.NativeError.
Standard packages and output
  • Built into the VM: errors, fmt, log, math, strconv, strings, evmruntime, evmruntime/log, and basic time.Time are always available.
  • Standard library (evmstd.Packages()): Adds bytes, cmp, encoding/base64, encoding/hex, encoding/json (validation/reformatting only), evmruntime/concurrency, html, iter, maps, math/bits, net/url, path, path/filepath, regexp, slices, sort, time, unicode, unicode/utf8, and unicode/utf16 (included automatically by GoX). Nothing touches disk, network, or env (time.Now is exposed; time.Local and LoadLocation are not). See evmstd/API.md for the generated Go standard library inventory; evmruntime/concurrency is documented in Concurrency model and Concurrent callbacks and caches.
  • Metering & extending: cmp, iter, maps, slices, and sort compile from script source and are metered; the rest call Go outside VM meters. bytes.Replace, bytes.ReplaceAll, bytes.Join, and bytes.Repeat charge their output size against the VM allocation budget before allocating (bytes.Repeat keeps its 16 MiB cap). The six regexp.Regexp ReplaceAll methods—literal (ReplaceAllLiteral, ReplaceAllLiteralString), capture expansion (ReplaceAll, ReplaceAllString), and callback (ReplaceAllFunc, ReplaceAllStringFunc)—charge their output against the VM allocation budget. A host package at path "time" merges with the built-in time package. List paths with evm.StandardLibraryPaths() and evmstd.Paths().
  • Output: Set vm.Output = func(s string) error to capture print, fmt.Print, and log (nil writes to Go's logger; capped at Limits.OutputBytes, default 1 MiB).
JSON, ownership, shared source, and coverage
  • JSON: Convert script any to Go trees (json.Number) with program.JSONValue / vm.JSONValue, encode JSON bytes with EncodeJSON / EncodeJSONObject, or call record.ToJSON() inside a script.
  • Ownership of borrowed data: The compiler automatically copies borrowed values (like transaction-scoped records) when they escape. Refine analysis with ExternalFunction.Ownership (&evm.OwnershipEffects{...}) or evmbind.BorrowOnly / NoRetain / NoInvalidate on record methods, register custom borrowable types with values.NewOwnedType, and inspect inserted copies via function.OwnershipSites.
  • Shared Go source: Supply guest-compiled Go via evm.Package{Path: "ids", Source: source} and unify host/KVO/script scalar identity with Package.SharedTypes. Bodyless declarations bind to ExternalFunction / ExternalMethod (generics via Instantiate), and TypeDecl{SourceName, TypeArgs} maps source types to native shapes. A small struct can share its type the same way and keep each copy in one cell (values.CellStruct); Package.ValueModels then reads stored sub-objects as that struct, on any row, without allocation on encoded and Go-backed rows.
  • Coverage: Attach evm.NewCoverage(program) via vm.SetCoverage(cov) (one collector per concurrent run, combined with Merge). Read line-level coverage via Lines() and per-instruction counts via Instructions().
Performance
Trust
  • Bytecode and bindings are trusted inputs: always compile script source rather than accepting raw uploaded bytecode.
  • Link validates operands and layouts, but cannot prove arbitrary pointers safe. EVM is a sandbox for API surface and budgets, not a process isolation boundary.
GoX

Full reference: the GoX guide · Inside EVM Chapter 11: GoX typed HTML templates.

Markup & escaping
  • Go + HTML: Write markup anywhere inside a function taking *gox.Builder. Tags separate statements; inside elements, "text" and expressions render, while assignments and control flow do not (_ = f() discards a result). Source indentation emits nothing—put spaces in strings. Use <>...</> for fragments, and parenthesize < comparisons (if (a < b)). return, break, and continue automatically close elements they exit.
  • Attributes & embedded JS/CSS: Static (class="card"), interpolated (href="/customers/{id}"), or dynamic (value={expr}). False boolean HTML attributes (disabled={off}) are omitted; others (aria-*) print false. Inside <script> and <style>, insert escaped Go data with {=expr}. Field selectors also accept JSON names and snake_case (p.app_ids for AppIDs).
  • Typed output & pipelines: Text positions accept only strings, trusted content, and gox.Content (never silently formatting numbers). Pipe values through formatters: v | f → f(v), v | f(a) → f(a, v), v | f(_, a) → f(v, a). Attributes accept strings and integers (plus bool as whole values; byte/rune are rejected as ambiguous); CSS accepts strings, integers, and floats; JS accepts JSON-compatible values.
  • Contextual escaping & nil guards: Uses Go's html/template escaping rules per context. Mark trusted values with gox.HTML, CSS, JS, JSStr, URL, Srcset, HTMLAttr, or gox.Content (gox.Text / gox.TrustedHTML). Nil pointers in output expressions report via RenderOptions.Report and skip that output (or fail under Strict: true).
Components, compiling, and tooling
  • Components & slots: Any function (<Button label="Save" />), selector (<ui.Button>), function value (<chosen />), or local closure is a component. func(...) parameters are typed slots (<slot-footer> fills footer; direct children fill body, and slots can take parameters like row func(item Item)). Self-closing calls returning a value can be assigned (content := <Translate key={key} />).
  • Implicit, optional, map, and ambient inputs: Mark parameters with //gox:arg name implicit (or Options.ImplicitTypes; *gox.Builder and *evmruntime.Ambient are always implicit), optional (plus gox.Optional[T] when presence matters), legacyName="...", or ambient="key". Build maps inline with extras:key={v}, extras:{k}={v}, extras:attrs:type="email", and override ambient context with ambient:color="blue".
  • Imperative helpers: Modify the open tag with b.Class, b.Attr, b.AttrOrOmit, b.Data, emit raw markup with b.Open/Close/Text/HTML, and compose class strings with gox.ClassList.
  • Compile, link, render: gox.Compile, CompileSources, and CompileFiles (plus gox.Options{ImplicitTypes, Format, ParseFrontmatter, AllowMissingPackage, Environment} for HTML, text, or CSS). Link once to a concurrent *gox.Program (or share host packages and DefaultLimits with gox.NewEnvironment / gox.LinkOptions.NewEnvironment), and render with RenderNative / RenderFuncNative (Go values), Render / RenderFunc (values.Value), or RenderFunction / RenderFunctionInCall (script callables; a delayed render acquires a fresh VM lease while retaining the callable's captures). Output caps at 16 MiB by default; failed renders emit nothing.
  • Host integration & metadata: Share GoX types via gox.Schema(), TrustedContentSchema(), and AmbientSchema(), store renderers in *evm.FunctionOf[func(*gox.Builder)], inspect parameters (ParametersFor), files & --- frontmatter (Files, Frontmatter, SplitFrontmatter), static/dynamic CSS classes for Tailwind safelists (Classes, DynamicClasses), and printed declarations (gox.PackageSource).
  • CLI & editors: go install ./cmd/gox provides gox fmt (formats and adds missing imports) and gox check (syntax check); Go APIs are FormatSource, CheckSyntax, and Preprocess (inspect GeneratedSources). Enforces gox.MaxTagNesting (100) and evmcompiler limits, supports GoX-mapped RenderOptions.Coverage, and includes editor support for Zed, Vim, Neovim, VS Code, TextMate, Sublime Text, and Helix.

GoX renders on the server with no client-side runtime and does not yet generate standalone native Go (GeneratedSources is for inspection).

KVO

Deep dives: KVO overview · reading & editing guide · records in scripts · Inside EVM Chapter 3: Data modeling with KVO

Declare
  • Schema & models: Build kvo.NewSchema(), kvo.NewEntityType(schema, "customer", goTypes...), and kvo.NewModel(schema, entityType, func(b *kvo.ModelBuilder) { ... }) once during startup (never per request). Property codes are permanent identities—never renumber or reuse them; duplicate codes or names panic.
  • Properties: Scalars (NewSignedProp[T], NewUnsignedProp[T], NewStringProp[T], NewBoolProp[T], NewFloat32Prop[T], NewFloat64Prop[T], NewBytesProp[T], NewTimeProp, NewLegacyTimeProp, NewScalarProp), lists (NewListProp), maps (NewMapProp, NewJSONMapProp, NewNestedMapCodec), nested records (NewRecordProp, NewRecordListProp, NewRecordMapProp), and untyped/runtime properties (NewProp, NewValueProp, schema.MustPropByCode, Bind…Prop).
  • Model options & struct mapping: Configure properties with kvo.Compact, PresenceIsSignificant (uses kvo.Optional[T]), PrimaryKey, PropName, embedded structs (b.Inline + kvo:",inline"), and script names (b.SetRowName). Map struct fields via kvo:"name" / kvo:"-" tags, or without tags via model.RegisterNativeType(goType, codeToFieldMap).
Represent, read, edit, and lifetimes
  • Representations: kvo.Bind(goType, model) (full struct) or kvo.Project(goType, model, fields) (subset/custom map) produce records over Go structs (binding.Record), Fast2/Compact2 rows (binding.Encoded(row2.Open(bytes)), row2.Trusted, kvo.Encoded(view).WithModel(model)), or MessagePack rows (binding.MessagePack). Encode with binding.Encode(..., row2.Fast2|Compact2) or msgpack.Encode; decode/validate with Decode, TryDecodeRecord, Validate. Mix layouts in one row with kvo.Compact.
  • Decode once & generated fields: Call record.Fastest() to decode once for repeated reads (Fast() keeps Fast2 as-is), NativePointer() / Native() to get the Go struct pointer, and WithGenerated / WithNativeSchema to remove reflection from struct field access.
  • Read: record.Get(prop) / prop.Get(record) return Go types directly (kvo.List[T], kvo.Map[K, V], kvo.Record, kvo.RecordList). Check presence with Missing() / Has(code), read untyped via GetValue, GetOwnedString, Child, ListValue, or export JSON via record.ToJSON. Operations panic on error; Try… variants return errors.
  • Edit: edit := record.Edit() supports Set, Get, Delete, edit.List(p) (Append, AddUnique, Remove, RemoveAt, Set, Clear), edit.Map(p) (Set, Delete, Clear, Lookup, SetNull), child editors (Edit, New, EditOrCreate, kvo.EditMap), and Record() / Snapshot() / MessagePack() / Changes(). Struct/memory editors write through immediately; row editors batch changes and leave source bytes untouched (MessagePack preserves unknown fields).
  • Lifetimes: Views borrow their bytes. Call record.Own() to keep data past its source, record.Clone() for an independent copy to edit, list.OwnedSlice() to copy strings too, and recordList.CloneSlice() to clone each element.
Records in scripts and templates
  • Model packages: evm.ModelPackage("m", schema) exposes m.Customer (read) and m.CustomerEdit (edit) to both scripts and GoX templates, with local (c.points_earned) and qualified (c.customer_points_earned) field selectors, zero-slice for _, tag := range c.tags iteration, and c.ToJSON().
  • Passing & editing: Pass read-only records as record.Value() to vm.Run (or kvo.Record / bound struct pointers to RenderNative), and return them from host functions via vm.SetRecordResult / RecordValue (vm.Record reads them). Open a scope with evm.WithRecords(ctx) for editors (scope.EditRecord, scope.MutableRecord, vm.SetEditRecordResult, and vm.FlushRecord before saving).
  • Methods & native storage: Expose Go helpers as model methods with evmbind.RecordMethod, RegisterMethods, and GenerateMethods; pass model structs through host APIs with evmbind.Options.Models and Mutable; add row.NativeCopy() via RecordType.NativeAllocation + evm.RegisterNativeCopies. The compiler automatically copies records that escape their scope.

Packages

Package layers, from examples at the top to values at the bottom

Each package imports only packages below it. evm imports kvo for record support; kvo, nativebind and values never import the VM, so a host can use the data model without it. kvo/codec/fast1 sits above kvo because it imports kvo; the other two codecs sit below because kvo imports them.

Package Imports
examples/* evm, evmbind, evmcompiler, evmstd, gox, kvo, kvo/codec/msgpack, kvo/codec/row2, values
gox evm, evmbind, evmcompiler, evmruntime, evmstd, values
evmstd evm, evmbind, evmruntime/concurrency, values
evmbind evm, evmcompiler, kvo, nativebind, values
evmcompiler evm, kvo, nativebind, values
evmasm evm, values
evm kvo, kvo/codec/row2, nativebind, values
kvo/codec/fast1 kvo
kvo kvo/codec/msgpack, kvo/codec/row2, nativebind, values
kvo/codec/row2, kvo/codec/msgpack values
nativebind values
values, evmruntime, evmruntime/concurrency nothing

Documentation

Guide What it covers
Embedding EVM Programs, VM leases, codecs, guest aggregates, synchronous callbacks, budgets, errors, borrowing effects, shared source, and coverage
evmbind Binding Go packages from source, generated wrappers, reflection discovery, and explicit record methods
Hand-written bindings Manual evm.Package declarations, DirectBinding, Go-backed record storage, and binding benchmarks
Standard packages Complete inventory of every standard library symbol exposed to scripts (and why omitted ones are excluded)
GoX guide Template syntax, contextual escaping, components, slots, implicit arguments, ambient context, tooling, and troubleshooting
GoX editor support Syntax highlighting for Zed, Vim, Neovim, VS Code, TextMate, Sublime Text, and Helix
KVO overview & Access guide Models, typed properties, lists, maps, child editors, decoding strategies, MessagePack edits, JSON, and lifetimes
Shared values Two-word Value representation, interface header layouts, and VM aggregate storage
Inside EVM (book) Full internals walkthrough: values, bytecode, compiler, evaluator, optimizer, and GoX lowering
Benchmarks How to run the suites and links to all dated measurement reports

Internals and tests

Inside EVM walks through the entire machine from Go source to register execution—values, instruction encoding, compilation, calling conventions, the host boundary, the evaluator, optimization, and GoX lowering. Bytecode has no persisted compatibility format. Benchmarks measure execution, compilation, and database costs separately.

go test ./...
go run ./examples/evm-basic
go run ./examples/gox-basic
go run ./examples/kvo-basic
go run ./EVMBook-rebuild.go
go test ./bench -run '^$' -bench . -benchmem
go test ./kvo -run '^$' -bench 'Benchmark(AccessStrategy|DecodedAccess|TypedList)$' -benchmem
go test ./gox -run '^$' -bench BenchmarkApplication -benchmem

README_test.go verifies that every code excerpt in this file stays byte-for-byte in sync with examples/.

License

Copyright (c) 2026 Andrey Tarantsov. Published under the Zero-Clause BSD license.

Documentation ¶

Overview ¶

Code generated by go generate; DO NOT EDIT.

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 handles retain their editor and materialized field values.

Index ¶

Constants ¶

View Source
const FieldValueCopy uint8 = 1

FieldValueCopy distinguishes a value read from a fused address load.

View Source
const MethodImportBase = 1 << 31

MethodImportBase is the Index of the reference to Module.MethodImports[0].

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 RecordValueReceiver uint8 = 2

RecordValueReceiver reads a property from an immutable row value snapshot.

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("invalid VM state")
	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 AnySliceType = values.NewType("[]any", values.Pair)

AnySliceType is the shared VM slice identity for native packages exchanging []any.

View Source
var ByteSliceType = values.NewOwnedType("[]uint8", values.Pair, func(v values.Value, _ values.OwnershipBudget) (values.Value, error) {
	return v, v.OwnBytes()
})

ByteSliceType is the shared VM slice identity for native packages exchanging []byte.

View Source
var ErrCallbackExpired = errors.New("callback scope has expired")
View Source
var ErrCallbackInactive = errors.New("callback requires an active native call on its originating VM")
View Source
var ErrCallbackScopeOpen = errors.New("callback scope already open")
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 ErrorSliceType = values.NewType("[]error", values.Pair)

ErrorSliceType is shared by native error methods and guest interfaces.

View Source
var JSONObjectType = values.NewType("map[string]any", values.Pointer)

JSONObjectType is shared by native packages that exchange JSON objects.

View Source
var NativeAnyCodec = &NativeValueCodec{
	Decode: func(c *VM, v values.Value) (values.Value, error) { return c.AnyValue(*(*any)(v.P)) },
	Encode: func(c *VM, v values.Value) (values.Value, error) {
		x, err := c.NativeAny(v)
		if err != nil {
			return values.Value{}, err
		}
		if err := c.ChargeAllocation(uint64(unsafe.Sizeof(x))); err != nil {
			return values.Value{}, err
		}
		return values.Value{P: unsafe.Pointer(&x)}, nil
	},
}

NativeAnyCodec is shared by all host packages exposing ordinary any fields. NativeLayout supplies the address of a Go interface, not its ABI words.

View Source
var NativeErrorCodec = &NativeValueCodec{
	Decode: func(c *VM, v values.Value) (values.Value, error) { return c.ErrorValue(*(*error)(v.P)) },
	Encode: func(c *VM, v values.Value) (values.Value, error) {
		result, err := c.NativeError(v)
		if err != nil {
			return values.Value{}, err
		}
		if err := c.ChargeAllocation(uint64(unsafe.Sizeof(result))); err != nil {
			return values.Value{}, err
		}
		return values.Value{P: unsafe.Pointer(&result)}, nil
	},
}

NativeErrorCodec stores native error interfaces using their Go layout.

Functions ¶

func ModelValueShape ¶

func ModelValueShape(row *RecordType) *values.Shape

ModelValueShape describes the opaque value cells used by native bindings. The compiler resolves the row identity to its own model property layout.

func NativeModelPointerLayout ¶

func NativeModelPointerLayout(model *kvo.Model, typ reflect.Type) *values.NativeLayout

NativeModelPointerLayout exposes native pointer slots through the model's row API. Stores require matching native backing; decoding is explicit.

func NativeModelValueLayout ¶

func NativeModelValueLayout(model *kvo.Model, typ reflect.Type) *values.NativeLayout

NativeModelValueLayout uses ordinary native struct snapshots for row values.

func NativeMutableRecord ¶

func NativeMutableRecord(v values.Value, model *kvo.Model) (kvo.Record, error)

NativeMutableRecord accepts only native-backed editable rows. An editor handle may have pending changes and must not be silently unwrapped into a Go pointer.

func NativeMutableRecordValue ¶

func NativeMutableRecordValue(model *kvo.Model, r kvo.Record) (values.Value, error)

NativeMutableRecordValue exposes the live native pointer as an editable row. Encoded records require explicit conversion before entering this boundary.

func PreserveCallbackPanic ¶

func PreserveCallbackPanic(value any) error

PreserveCallbackPanic returns an in-flight callback panic unchanged. Wrapped or replaced native panics must not recover the original guest value.

func RecordScalarType ¶

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

RecordScalarType supplies the VM type for KVO leaves.

func RecordValue ¶

func RecordValue(v values.Value, model *kvo.Model) (kvo.Record, error)

RecordValue reads an immutable row or its explicit value copy.

func RecordWordType ¶

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

RecordWordType maps a scalar KVO property to its script type.

func RegisterNativeCopies ¶

func RegisterNativeCopies(pkg *Package)

RegisterNativeCopies exposes NativeCopy on immutable rows with a selected native allocation type. Call after choosing allocations and before sharing or compiling the package. Encoded rows decode explicitly; native rows use ordinary shallow struct copies. No conversion changes the original record.

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.

func ValueModels ¶

func ValueModels(packages []Package) (map[*kvo.Model]*ValueModel, error)

ValueModels validates the value model declarations of packages and returns them by model. Compilers use it to type properties.

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 = Limits

Budget is an alias for Limits retained for existing host configuration.

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 *VM) *RecordScope

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

func (*BudgetScope) End ¶

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

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

type Callable ¶

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

Callable retains a linked function and its optional captures or bound receiver. Copies share the same captures. The zero value is a nil function.

func (Callable) AcceptsBorrowedBytes ¶

func (f Callable) AcceptsBorrowedBytes(domain string) bool

AcceptsBorrowedBytes reports whether the compiler tracks byte arguments from domain.

func (Callable) CheckConcurrentUse ¶

func (f Callable) CheckConcurrentUse() error

CheckConcurrentUse lets a host require capture verification at registration. Plain guest functions have no captures. A host that accepts bytecode directly must trust its producer, as it does for other compiler metadata.

func (Callable) CheckSignature ¶

func (f Callable) CheckSignature(want Signature) error

func (Callable) HasCaptures ¶

func (f Callable) HasCaptures() bool

func (Callable) Name ¶

func (f Callable) Name() string

func (Callable) Program ¶

func (f Callable) Program() *Program

func (Callable) Signature ¶

func (f Callable) Signature() Signature

func (*Callable) Value ¶

func (f *Callable) Value(p *Program, signature Signature) (values.Value, error)

type CallbackScope ¶

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

CallbackScope gives native Go adapters access to guest callbacks. The host must serialize its use. An implicit scope expires when the owner releases the VM.

func (*CallbackScope) Close ¶

func (s *CallbackScope) Close() error

Close ends the host callback lifetime. Previously exported functions and errors remain values, but invoking their script methods fails after Close.

func (*CallbackScope) WithCall ¶

func (s *CallbackScope) WithCall(fn func(*VM) error) error

WithCall borrows the active VM from a binding. An explicitly opened scope also accepts calls outside an active host binding, running each call on a fresh VM lease with its configured per-call budget.

type CaptureSlot ¶

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

type Closure ¶

type Closure struct {
	Function uint32
	Captures []Operand
}

type ConcurrentFunctionOf ¶

type ConcurrentFunctionOf[S any] = Callable

ConcurrentFunctionOf marks a host parameter for a retained callback that may run concurrently. The compiler verifies its receiver and captures at the call site.

type Conversion ¶

type Conversion struct{ From, To NumericType }

type Coverage ¶

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

Coverage collects one linked program's instruction and branch counts. Use a separate collector per concurrent execution and Merge after completion.

func NewCoverage ¶

func NewCoverage(p *Program) *Coverage

func (*Coverage) Instructions ¶

func (c *Coverage) Instructions() []InstructionCoverage

Instructions returns a snapshot, including instructions never executed.

func (*Coverage) Lines ¶

func (c *Coverage) Lines() []LineCoverage

func (*Coverage) Merge ¶

func (c *Coverage) Merge(other *Coverage) error

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.VM.
	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(*VM, 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
	ExtendedNativeAddress
)

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 {
	// Instantiate binds a generic source declaration for concrete type arguments.
	// The returned binding must have a concrete signature and no Instantiate hook.
	Instantiate func([]*values.Type) (ExternalFunction, error)
	Ownership   *OwnershipEffects
	// ParamNames preserves declaration names for source frontends such as GoX.
	ParamNames []string
	// Doc preserves declaration comments for source frontends.
	Doc    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 {
	// Instantiate returns a receiver-free signature for a generic source method.
	// Ownership parameter indexes include the receiver at zero.
	Instantiate  func([]*values.Type) (ExternalFunction, error)
	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.

func (ExternalMethod) Binding ¶

func (m ExternalMethod) Binding() ExternalFunction

Binding returns the native ABI declaration, including its receiver.

type ExternalValue ¶

type ExternalValue struct {
	Name string
	Type *values.Type
	Read Native
}

ExternalValue exposes a host-owned package value. Scripts may copy the value and use its methods, but cannot assign or take the address of its binding. Read must not invalidate borrowed records or change transaction scopes.

func (ExternalValue) LinkName ¶

func (v ExternalValue) LinkName() string

type Function ¶

type Function struct {
	// CapturesVerifiedForConcurrency reports whether the compiler verified use of the
	// bound receiver and closure captures for concurrent calls.
	CapturesVerifiedForConcurrency bool
	// ConcurrentBorrowCalls lists instructions whose registration arguments
	// were checked for post-borrow writes by the compiler.
	ConcurrentBorrowCalls map[int][]int
	// CallbackByteDomains lists the borrow domains tracked for []byte parameters.
	CallbackByteDomains []string
	// 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 is optional too, and takes precedence over Lines. Without
	// either, every instruction has the zero position.
	Positions []SourcePosition
}

type FunctionOf ¶

type FunctionOf[S any] = Callable

FunctionOf annotates a retained callable in a binding declaration. S is the required function signature. Use any for host-checked registrations.

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. Runtime native closures use a separate tagged value and retain their owning program.

A native reference indexes Module.Imports. One at or above MethodImportBase names Module.MethodImports instead; only the method tables of Module.Types hold such references.

func MethodImportRef ¶

func MethodImportRef(index int) FunctionRef

MethodImportRef refers to Module.MethodImports[index].

func (FunctionRef) MethodImport ¶

func (r FunctionRef) MethodImport() (int, bool)

MethodImport returns the index into Module.MethodImports that the reference names, and whether it names one.

type GuestValue ¶

type GuestValue struct {
	Program *Program
	Value   values.Value
}

GuestValue retains a guest-only value with its owning program. Returning it to that program preserves its type and reference identity without JSON.

func (*GuestValue) MarshalJSON ¶

func (g *GuestValue) MarshalJSON() ([]byte, error)

MarshalJSON serializes a retained guest value at a native JSON output boundary. It uses the same supported types and cycle checks as explicit VM JSON encoding.

func (*GuestValue) String ¶

func (g *GuestValue) String() string

String formats retained JSON-shaped values at native text output boundaries. Unsupported values produce a diagnostic rather than exposing VM handles.

type HostShapes ¶

type HostShapes struct {
	Table []*values.Shape
	// Set has bit i%64 of word i/64 set for each Table[i] the module lists.
	Set []uint64
	// After is the number of leading Module.Shapes that the selection
	// follows in the order of the listing; see Module.ListedShapes.
	After int
}

HostShapes selects shapes from a table that the modules of one compile environment share: the shapes of the host types a module's source can reach, a few thousand on a large host. The module does not own the table and must not change it.

type Import ¶

type Import struct {
	TypeArgs      []*values.Type
	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 InstructionCoverage ¶

type InstructionCoverage struct {
	Function        string
	PC              int
	Position        SourcePosition
	Count           uint64
	Taken, NotTaken uint64
	Branch          bool
}

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 {
	UnlimitedSteps                       bool
	Duration, HardDuration               time.Duration
	HardAllocations, HardAllocationBytes uint64
	Steps                                uint64 // one per dispatched bytecode instruction
	Allocations                          uint64
	AllocationBytes                      uint64
	OutputBytes                          uint64
	Depth, RSlots, PSlots                int
}

type LineCoverage ¶

type LineCoverage struct {
	File                                       string
	Line                                       int
	Instructions, Executed, Branches, Outcomes int
}

LineCoverage summarizes executable instructions at an original source line. A partially covered line was entered but contains unexecuted instructions or a conditional jump whose outcomes were not both observed.

func (LineCoverage) Covered ¶

func (l LineCoverage) Covered() bool

type LinkEnvironment ¶

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

LinkEnvironment is a set of bound host packages prepared for linking many modules.

NewLinkEnvironment validates the packages and resolves their bindings once. Each link then does only the work its module needs, and the programs share what the packages alone determine. A LinkEnvironment never changes after NewLinkEnvironment returns and is safe for concurrent use.

The packages must not change while the environment or its programs are in use.

func NewLinkEnvironment ¶

func NewLinkEnvironment(packages ...Package) (*LinkEnvironment, error)

NewLinkEnvironment validates and binds the packages. It fails where every link against them would fail.

func (e *LinkEnvironment) Link(m *Module) (*Program, error)

Link binds a module to the packages. It does not run it.

func (*LinkEnvironment) LinkWithHostData ¶

func (e *LinkEnvironment) LinkWithHostData(m *Module, hostData any) (*Program, error)

LinkWithHostData links like Link and retains host-owned metadata for the lifetime of the program; see LinkWithHostData.

func (*LinkEnvironment) Packages ¶

func (e *LinkEnvironment) Packages() []Package

Packages returns the packages the environment was built from, including the built-in time package.

type LinkOptions ¶

type LinkOptions struct {
	// DefaultLimits supplies the initial budget for each VM. Nil selects the
	// built-in limits. An explicit empty Limits disables the optional quotas.
	DefaultLimits *Limits
	// Shapes lists storage shapes that the modules to link name: usually
	// every shape of the compile environment that produces the modules. The
	// environment snapshots them once and its programs share the snapshots.
	// A program snapshots for itself any other shape its module names.
	// The shapes must not change while the environment is in use.
	Shapes []*values.Shape
	// Methods lists the method tables that the modules to link share, one
	// for each compile environment that produces them. The environment
	// binds them once and its programs share the result. A program binds
	// for itself the method tables of any other module.
	Methods []MethodTables
}

LinkOptions configures a prepared link environment.

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

Link links one module using these options.

func (LinkOptions) NewEnvironment ¶

func (o LinkOptions) NewEnvironment(packages ...Package) (*LinkEnvironment, error)

NewEnvironment prepares the packages for linking; see NewLinkEnvironment.

type MethodTables ¶

type MethodTables struct {
	Imports []Import
	Types   []DynamicType
}

MethodTables are the method tables that the modules of one compile environment share: the list every such module has as its MethodImports, and the host types whose methods name nothing but that list. A module that lists one of the types has the same Methods slice as here.

A link environment prepared with the tables binds them once, and its programs share the result. Nothing may change them afterwards.

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 lists the natives that instructions, function references and
	// defers name by index, and any native a method table names here.
	Imports []Import
	// MethodImports lists native methods for the method tables of Types
	// alone; see FunctionRef. A link binds those the tables name, so the
	// list may hold more. Modules compiled through one environment share
	// one list and the method tables of host types that name nothing else:
	// the module does not own them and they must not change.
	MethodImports []Import
	Words         []uint64
	Strings       []string
	Conversions   []Conversion
	// Shapes lists the shapes instructions index, then others the program
	// must know by type.
	Shapes []*values.Shape
	// HostShapes lists more shapes for the program to know by type.
	HostShapes  HostShapes
	ExtendedOps []ExtendedOp
	Globals     []*values.Shape
	Init        string
	// SourceBranches is reporting metadata keyed by function name, then instruction PC.
	SourceBranches map[string]map[int]SourceBranch
}

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.

func (*Module) ListedShapes ¶

func (m *Module) ListedShapes() iter.Seq[*values.Shape]

ListedShapes yields every shape the module lists, in the order a link takes them: a type with several shapes resolves to the first. The selection of HostShapes follows the first HostShapes.After of Shapes.

type Native ¶

type Native func(*VM) error

type NativeFunctionType ¶

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

NativeFunctionType caches the signature and register layout of runtime native functions. Build it once with the bindings and reuse it across invocations.

func NewNativeFunctionType ¶

func NewNativeFunctionType(signature Signature) (*NativeFunctionType, error)

type NativeSliceDecl ¶

type NativeSliceDecl struct {
	Layout, Element *values.NativeLayout
}

type NativeValueCodec ¶

type NativeValueCodec struct {
	Decode func(*VM, values.Value) (values.Value, error)
	Encode func(*VM, values.Value) (values.Value, error)
}

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. NativeValueCodec translates between native field values and VM values. Conversions may inspect the current program and charge allocations. They must not retain Call or change its argument/result window.

func NativeInterfaceCodec ¶

func NativeInterfaceCodec(t reflect.Type) *NativeValueCodec

NativeInterfaceCodec bridges a native method-interface slot without changing the concrete object's storage. Guest-only implementations cannot inhabit a Go interface; values must have a native type implementing the interface.

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
	// CallbackBytes is the domain of borrowed []byte arguments passed to guest callbacks.
	CallbackBytes string
}

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 {
	// ConcurrentCallbackParams lists the zero-based indexes of callback parameters
	// the host may invoke concurrently. Keys are function names or Receiver.Method.
	ConcurrentCallbackParams map[string][]int
	// ConcurrentInterfaceParams identifies retained interface arguments by the same convention.
	ConcurrentInterfaceParams map[string][]int
	// StructValues optionally chooses compact storage for source-defined generic
	// structs. A nil result retains ordinary storage. Callbacks run at compile time.
	StructValues map[string]func(string, []*values.Shape) *values.CellStruct
	SourceFiles  []SourceFile
	Aliases      []TypeAlias
	Source       string
	SharedTypes  []SharedType
	Records      []*RecordType
	// ValueModels expose sub-objects of KVO models as struct values that this
	// package declares.
	ValueModels []ValueModel
	// 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
	Values     []ExternalValue
}

func MergePackages ¶

func MergePackages(packages ...Package) ([]Package, error)

MergePackages combines packages that share a path into one, keeping the order of first appearance. Compile and Link accept each path once; hosts that build one script package from several bindings merge them first. Declarations are concatenated; at most one fragment of a path may carry Source, and StructValues names must not repeat.

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 time.Time and its native storage. It is linked automatically, so record fields and host methods share the same nominal type.

func WithTimePackage ¶

func WithTimePackage(packages []Package) ([]Package, error)

WithTimePackage puts the built-in time package first. A supplied package with path "time" extends it: its declarations join the built-in ones, so a host can add types, functions and further Time methods.

func WithoutRecords ¶

func WithoutRecords(p Package, models ...*kvo.Model) Package

WithoutRecords returns p without the row types of the given models and without their methods. A host uses it for value models: scripts read those sub-objects as struct values and never as rows.

func (Package) HasSource ¶

func (p Package) HasSource() bool

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.

func (Package) Sources ¶

func (p Package) Sources() []SourceFile

Sources returns files in declaration order without sharing the input slice. Source, when set, precedes SourceFiles and is named after the package path.

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

func (*PanicError) Unwrap ¶

func (e *PanicError) Unwrap() error

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 LinkWithHostData ¶

func LinkWithHostData(m *Module, hostData any, packages ...Package) (*Program, error)

LinkWithHostData retains host-owned metadata for the lifetime of the linked program. There is no setter; derived runtimes can retain their compiled data without a separate program registry.

func (*Program) AcquireVM ¶

func (p *Program) AcquireVM(ctx context.Context) *VM

AcquireVM leases a VM for this program and starts its default budget.

func (*Program) AssertValue ¶

func (p *Program) AssertValue(v values.Value, target *values.Type) (values.Value, bool, error)

AssertValue performs a Go type assertion on a program-local interface value. Concrete targets return their payload; interface targets retain the interface. It neither converts nor copies the underlying value.

func (*Program) Callable ¶

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

Callable retains an argument whose declared guest type is a function.

func (*Program) DefaultLimits ¶

func (p *Program) DefaultLimits() Limits

DefaultLimits returns the program's default per-VM execution limits.

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) HostData ¶

func (p *Program) HostData() any

HostData returns the value supplied when linking. EVM does not interpret it. The linker owns this value and must publish any mutable contents safely.

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) LookupFunction ¶

func (p *Program) LookupFunction(name string, want *Signature) (Callable, error)

LookupFunction resolves a named entry and checks its full signature when want is non-nil.

func (*Program) NativeFunction ¶

func (p *Program) NativeFunction(typ *NativeFunctionType, fn Native) (values.Value, error)

NativeFunction prepares a host-owned callable for an argument to Run. The caller owns allocation accounting for this input. Calls from the VM share its active execution limits; host code must honor cancellation and meter any work or result allocations it performs. Use VM.NativeFunction for values created during a VM invocation so the holder allocation is metered.

func (*Program) NativeFunctionData ¶

func (p *Program) NativeFunctionData(v values.Value) any

NativeFunctionData returns metadata attached to a native callable from this program. Guest callables and native functions without metadata return nil.

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, or nil for a type the module does not reach.

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 shares editor caches and local child slots during a call. Closing it releases those caches without invalidating held row handles.

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 {
	// NativeAllocation selects the native struct storage for guest-created
	// collections of this row. Nil keeps generic record storage.
	NativeAllocation reflect.Type

	// SchemaView exposes the properties supported by the current KVO codec.
	SchemaView bool
	Name       string
	Model      *kvo.Model
	Mutable    bool
	Value      *values.Type // guest Model value, distinct from its read handle
	Pointer    *values.Type // guest *Model: Pair for immutable cells and editable rows
}

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 sources. Its methods are compiled from that same source.

type Signature ¶

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

type SourceBranch ¶

type SourceBranch struct {
	PC       int
	Inverted bool
}

SourceBranch associates duplicated machine tests with one source condition. PC identifies its canonical instruction; Inverted reverses jump outcomes.

type SourceFile ¶

type SourceFile struct{ Name, Text string }

SourceFile is one Go source file in a virtual package. Imports are file-local.

type SourcePosition ¶

type SourcePosition struct {
	File         string
	Line, Column int
}

type TypeAlias ¶

type TypeAlias struct {
	Name   string
	Target *values.Type
}

TypeAlias gives an existing type another source name without new storage or runtime identity. The target must be declared in the same environment.

type TypeDecl ¶

type TypeDecl struct {
	// NativeSlice describes a host representation without changing guest storage.
	NativeSlice *NativeSliceDecl
	TypeArgs    []*values.Type
	// SourceName identifies a type declared in package sources. TypeArgs
	// instantiates it using existing native type identities.
	SourceName  string
	NativeCodec *NativeValueCodec
	// ScalarBase distinguishes Go int from int64 when their storage shapes match.
	ScalarBase *values.Type
	Name       string
	Shape      *values.Shape
}

type VM ¶

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

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

A VM executes one program on one goroutine. A Go binding may call Run again synchronously.

func (*VM) AllocCells ¶

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

func (*VM) AllocatedBytes ¶

func (vm *VM) AllocatedBytes() uint64

AllocatedBytes reports allocation charges since acquisition or SetBudget.

func (*VM) AnyValue ¶

func (c *VM) AnyValue(x any) (values.Value, error)

AnyValue converts native Go data into a guest interface. Native reference values retain their backing storage; guest handles must belong to this program.

func (*VM) BorrowBytes ¶

func (c *VM) BorrowBytes(data []byte) (values.Value, error)

BorrowBytes returns a transaction-scoped []byte. Declare the result in OwnershipEffects.Borrowed. Writes and escapes detach all its aliases.

func (*VM) CallArgument ¶

func (vm *VM) CallArgument(i int) values.Value

CallArgument reads an argument in the current Go binding.

func (*VM) CallbackError ¶

func (c *VM) CallbackError(err error) error

CallbackError preserves an in-flight guest panic across a native callback. Execution failures retain their trap behavior.

func (*VM) CallbackScope ¶

func (vm *VM) CallbackScope() *CallbackScope

CallbackScope returns the scope used by guest callbacks exported from this VM.

func (*VM) ChargeAllocation ¶

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

ChargeAllocation accounts for native result payloads retained by the VM.

func (*VM) CheckConcurrentBorrow ¶

func (vm *VM) CheckConcurrentBorrow(parameter int) error

CheckConcurrentBorrow checks the guest registration site. Checking only the method body would let an indirect registration reuse a proof from a different receiver without checking later writes to this one.

func (*VM) Coverage ¶

func (c *VM) Coverage() *Coverage

Coverage returns the enclosing invocation collector, or nil when disabled.

func (*VM) EncodeJSON ¶

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

EncodeJSON encodes an any argument from this invocation.

func (*VM) EncodeJSONObject ¶

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

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

func (*VM) ErrorValue ¶

func (c *VM) ErrorValue(err error) (values.Value, error)

ErrorValue preserves a native error's identity and optional error methods.

func (*VM) FlushMutableRecord ¶

func (c *VM) FlushMutableRecord(v values.Value, model *kvo.Model) error

FlushMutableRecord applies alias edits retained by this row handle.

func (*VM) FlushRecord ¶

func (c *VM) 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 (*VM) IncreaseCPUBudget ¶

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

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

func (*VM) IncreaseMemBudget ¶

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

IncreaseMemBudget raises the invocation allowance without resetting usage.

func (*VM) Interface ¶

func (c *VM) 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 (*VM) JSONValue ¶

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

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

func (*VM) JSONValueWithSize ¶

func (c *VM) JSONValueWithSize(v values.Value, limit int) (any, int, error)

JSONValueWithSize materializes an any value and reports its equivalent JSON byte length. Streaming output consumers can share one limit across values without serializing the materialized tree a second time.

func (*VM) LoadNative ¶

func (c *VM) LoadNative(s *values.Shape, p unsafe.Pointer) (values.Value, error)

LoadNative copies a value from its declared native layout into VM registers. The caller keeps p alive for the call; reference fields retain their targets.

func (*VM) LookupMethod ¶

func (vm *VM) LookupMethod(value values.Value, name string, signature Signature) (Callable, error)

LookupMethod resolves a method on this receiver and checks its receiver-free signature.

func (*VM) MutableRecord ¶

func (c *VM) MutableRecord(v values.Value, model *kvo.Model) (*kvo.Editor, any, error)

MutableRecord resolves the native editor and backing without a session lookup.

func (*VM) NarrowBudget ¶

func (c *VM) 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 (*VM) NarrowCPUBudget ¶

func (c *VM) 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 (*VM) NativeAny ¶

func (c *VM) NativeAny(v values.Value) (any, error)

NativeAny converts a guest interface to native Go. Registered native types keep their Go types and backing storage. Model row pointers return their live native pointer, or a kvo.Record for encoded data; native-backed row values return Go value copies. Guest-only types retain a handle.

func (*VM) NativeArguments ¶

func (c *VM) NativeArguments(params []*values.Type, args []any) ([]values.Value, error)

NativeArguments converts ordinary Go values into arguments for parameters of the given types: scalars, strings, time values, pointers to bound native structs, registered interface implementations and guest values. A Go slice or map converts when a linked package binds its type. A values.Value passes through unchanged. Native references keep their backing storage. A value whose Go type does not correspond to its parameter type is an error; there are no implicit numeric conversions. Conversion charges this call's allocation budget, and the results are valid for this program only.

func (*VM) NativeError ¶

func (c *VM) NativeError(value values.Value) (error, error)

NativeError converts an error argument while preserving its identity. The second result reports conversion failure, not the argument's value.

func (*VM) NativeFunction ¶

func (c *VM) NativeFunction(typ *NativeFunctionType, fn Native) (values.Value, error)

NativeFunction binds a native closure to the current program. The closure may retain owned host state, and may borrow the VM only while the binding runs. Guest calls and nested VM.Run calls share the active execution budget. Host code remains responsible for validating captured transaction lifetimes.

func (*VM) NativeFunctionWithData ¶

func (c *VM) NativeFunctionWithData(typ *NativeFunctionType, fn Native, data any) (values.Value, error)

NativeFunctionWithData retains immutable host metadata with a callable. Bindings use it to preserve the original native function across round trips.

func (*VM) NativeSlice ¶

func (c *VM) NativeSlice(layout, element *values.NativeLayout, data unsafe.Pointer, length, capacity uint32) (values.Value, error)

NativeSlice retains native backing without changing the logical slice shape.

func (*VM) OpenCallbackScope ¶

func (vm *VM) OpenCallbackScope(limits Limits) (*CallbackScope, error)

OpenCallbackScope keeps exported Go adapters callable until Close. Each callback invoked outside an active host binding—whether the originating VM is idle or already released—runs on a fresh VM lease with the same program and Go context and a fresh per-call budget of limits (zero quotas are unlimited, matching VM.SetBudget; pass program.DefaultLimits() to reuse the program's default policy).

func (*VM) PackAggregate ¶

func (vm *VM) PackAggregate(t *values.Type, members ...values.Value) (values.Value, error)

PackAggregate builds a guest struct, array, or slice from values in declaration or index order. Each input must match its declared field or element type.

func (*VM) PackMap ¶

func (vm *VM) PackMap(t *values.Type, items ...values.Value) (values.Value, error)

PackMap builds a guest map from alternating keys and values.

func (*VM) PanicCallback ¶

func (c *VM) PanicCallback(err error)

PanicCallback propagates callback execution failure through a native function whose Go signature cannot return that failure. VM native dispatch recovers it.

func (*VM) Program ¶

func (c *VM) Program() *Program

func (*VM) Record ¶

func (c *VM) Record(v values.Value, model *kvo.Model) (kvo.Record, error)

Record reads a guest immutable row, including an explicit value copy. The returned record retains its existing native representation and lifetime. Both a nil row pointer and a zero row value have missing record contents. Callers needing pointer identity must also inspect the original argument.

func (*VM) RecordValue ¶

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

RecordValue returns the immutable row cell without allocating a handle.

func (*VM) Release ¶

func (vm *VM) Release()

Release returns this VM's cleared buffers to the shared pool.

func (*VM) Run ¶

func (vm *VM) Run(fn Callable, slots []values.Value) error

Run calls a resolved function. Slots hold the arguments followed by room for its results.

func (*VM) SetBackedEditRecordResult ¶

func (c *VM) SetBackedEditRecordResult(model *kvo.Model, e *kvo.Editor, backing any) error

SetBackedEditRecordResult keeps the native backing with the virtual row.

func (*VM) SetBudget ¶

func (vm *VM) SetBudget(l Limits)

SetBudget starts a new allowance. Zero quotas are unlimited.

func (*VM) SetCallResult ¶

func (c *VM) SetCallResult(i int, v values.Value)

SetCallResult writes a result in the current Go binding.

func (*VM) SetCoverage ¶

func (vm *VM) SetCoverage(c *Coverage) error

SetCoverage changes instrumentation between runs. Nil disables collection.

func (*VM) SetEditRecordResult ¶

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

SetEditRecordResult returns a mutable KVO row with the editor's native lifetime.

func (*VM) SetError ¶

func (c *VM) SetError(result int, err error) error

SetError writes an error result by result index, rather than ABI slot.

func (*VM) SetInterface ¶

func (c *VM) 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 (*VM) SetReadRecordResult ¶

func (c *VM) 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 (*VM) SetRecordResult ¶

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

func (*VM) SetValue ¶

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

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

func (*VM) SliceElement ¶

func (c *VM) SliceElement(s *values.Shape, v values.Value, index uint64) (values.Value, error)

SliceElement reads an element using the linked native or VM storage layout. Host callbacks must use their parameter shape rather than assume VM cells.

func (*VM) StoreNative ¶

func (c *VM) StoreNative(s *values.Shape, p unsafe.Pointer, v values.Value) error

StoreNative copies a VM value into caller-owned storage of the declared layout.

func (*VM) TypedInterfaceValue ¶

func (c *VM) TypedInterfaceValue(x any) (values.Value, error)

TypedInterfaceValue preserves the concrete identity promised by a typed native interface. AnyValue separately preserves native error adaptation.

func (*VM) UnpackAggregate ¶

func (vm *VM) UnpackAggregate(t *values.Type, v values.Value) ([]values.Value, error)

UnpackAggregate returns guest struct fields in declaration order, or array or slice elements in index order. Nested values keep their EVM representation.

func (*VM) UnpackMap ¶

func (vm *VM) UnpackMap(t *values.Type, v values.Value) ([]values.Value, error)

UnpackMap returns alternating keys and values from a guest map.

func (*VM) Value ¶

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

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

type ValueModel ¶

type ValueModel struct {
	Model *kvo.Model
	Type  *values.Type
	// Props are the property codes of the struct's two fields, in field order.
	Props [2]uint64
}

ValueModel exposes the sub-objects of a KVO model as values of a struct type that the same package declares. A property of that model then reads as the struct, by value, on any read-only row, encoded or backed by a Go struct: the VM packs the two stored words into the struct's cell. Nothing is decoded into a Go struct and nothing is allocated, so the struct's methods, compiled from package source, run on stored data directly. A missing sub-object reads as the zero value.

The struct must keep its value copies in one cell (values.CellStruct), and each of its two fields must be a scalar property that fits one word. Editable rows do not expose such a property yet.

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.
cmd
gox command
Command gox checks syntax and formats GoX source files.
Command gox checks syntax and formats GoX source files.
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/appfixture
Package appfixture is an ordinary Go package whose own source is bound whole.
Package appfixture is an ordinary Go package whose own source is bound whole.
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.
concurrency
Package concurrency provides state that parallel callbacks can safely share.
Package concurrency provides state that parallel callbacks can safely share.
log
Package evmstd offers general-purpose Go standard packages to scripts, beyond the few the VM implements itself.
Package evmstd offers general-purpose Go standard packages to scripts, beyond the few the VM implements itself.
internal/cachecore
Package cachecore binds the guest cache to its host-owned storage.
Package cachecore binds the guest cache to its host-owned storage.
Package evmtest provides named-entry fixtures for compiler and binding tests.
Package evmtest provides named-entry fixtures for compiler and binding tests.
examples
evm-basic command
Command evm-basic runs a plugin written in Go inside a Go program.
Command evm-basic runs a plugin written in Go inside a Go program.
evm-basic/_plugin
A plugin: ordinary Go that the host compiles and runs inside EVM.
A plugin: ordinary Go that the host compiles and runs inside EVM.
gox-basic command
Command gox-basic renders a page with GoX templates that use an ordinary Go application directly: its types, methods, package functions and constants.
Command gox-basic renders a page with GoX templates that use an ordinary Go application directly: its types, methods, package functions and constants.
kvo-basic command
Command kvo-basic reads and edits the same records from Go and from a script, whether a record is a Go struct or an encoded row.
Command kvo-basic reads and edits the same records from Go and from a script, whether a record is a Go struct or an encoded row.
kvo-basic/_script
A script: ordinary Go that the host compiles and runs inside EVM.
A script: ordinary Go that the host compiles and runs inside EVM.
gox
Package gox compiles GoX templates into typed EVM functions.
Package gox compiles GoX templates into typed EVM functions.
internal
coveragegen command
Command coveragegen derives the instrumented interpreter from execute.
Command coveragegen derives the instrumented interpreter from execute.
genstd command
Command genstd generates the declarations and bindings of the standard packages that evmstd binds natively, and the API report listing what each offered standard package exposes and what it leaves out, with the reason.
Command genstd generates the declarations and bindings of the standard packages that evmstd binds natively, and the API report listing what each offered standard package exposes and what it leaves out, with the reason.
genstdlib command
inlinerow
Code generated by kvo.
Code generated by kvo.
inlinerow/gen command
naming
Package naming defines identifier spelling rules for EVM frontends.
Package naming defines identifier spelling rules for EVM frontends.
statrow
Code generated by kvo.
Code generated by kvo.
statrow/gen command
valuebench
Code generated by kvo.
Code generated by kvo.
valuebench/gen command
kvo
Package kvo defines logical models, typed properties, and record access and editing over MessagePack, Fast2, Compact2, native Go structs, and decoded memory.
Package kvo defines logical models, typed properties, and record access and editing over MessagePack, Fast2, Compact2, native Go structs, and decoded memory.
codec/fast1
Package fast1 implements the original KVO word-map storage format.
Package fast1 implements the original KVO word-map storage format.
codec/msgpack
Package msgpack implements EDB's MessagePack struct encoding.
Package msgpack implements EDB's MessagePack struct encoding.
codec/row2
Package row2 reads and writes the Fast2 and Compact2 KVO row formats.
Package row2 reads and writes the Fast2 and Compact2 KVO row formats.
Package nativebind selects native bindings once, when a schema is built.
Package nativebind selects native bindings once, when a schema is built.
internal/fixture
Code generated by nativebind.
Code generated by nativebind.
Package values defines two-word values shared by KVO adapters and EVM.
Package values defines two-word values shared by KVO adapters and EVM.

Jump to

Keyboard shortcuts

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