leia

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 19, 2026 License: Apache-2.0 Imports: 29 Imported by: 0

README

Leia

Leia is a general-purpose scripting language designed to run standalone or inside Go applications. It combines a compact, Go-shaped syntax with dynamic values, modules, concurrency, an embeddable VM, and opt-in domain dialects.

func greet(name) {
    return "Hello, " .. name .. "!"
}

numbers := [1, 2, 3, 4, 5]
total := 0
for _, n := range ipairs(numbers) {
    total += n
}

print(greet("Leia"))
print("sum:", total)

Save the program as hello.leia, then run it with leia run hello.leia.

Getting Started

Leia v0.1.0 requires Go 1.25.12 or later when installed from source. Install the CLI and language server at the release tag:

go install github.com/never-labs/leia/cmd/leia@v0.1.0
go install github.com/never-labs/leia/cmd/leia-lsp@v0.1.0

Release archives contain both binaries and are verified against the published SHA256SUMS. Review the installer before running it, then install to a directory on your PATH:

curl -fsSLo /tmp/leia-install.sh https://raw.githubusercontent.com/never-labs/leia/v0.1.0/scripts/install.sh
less /tmp/leia-install.sh
bash /tmp/leia-install.sh --version v0.1.0 --bin-dir "$HOME/.local/bin"

Check the installation and run a one-line program:

leia version
leia eval 'print("hello from leia")'

See Getting started for repository examples, formatting, linting, testing, and project modules.

Language At A Glance

Leia provides dynamic values, lexical closures, arrays and tables, functions, multiple returns, errors, modules, coroutines, and Go-style goroutines and channels. The language specification is the normative syntax and semantics reference; the standard library index lists the modules available to scripts.

Tagged dialects let a host add domain syntax without changing the core grammar. Data-oriented libraries, scientific helpers, hot reload, and provider-backed AI workflows are available for applications that need them. Start with the core language and enable host-facing capabilities explicitly.

Embed In Go

The root Go package is the supported embedding API. A minimal trusted-local host looks like this:

package main

import leia "github.com/never-labs/leia"

func main() {
    vm := leia.New()
    if err := vm.Exec(`print("hello from embedded Leia")`); err != nil {
        panic(err)
    }
}

VM is mutable and is not safe for concurrent use. Use one VM per script instance or leia.Pool for concurrent hosts. Compile reusable programs once, but do not run the same compiled Program concurrently. The embedding guide covers host modules, values, cancellation, resource budgets, pooling, and hot reload.

Security

leia.New() is intended for trusted local code and is not a sandbox. For untrusted scripts, begin with SecuritySandbox(), add explicit resource budgets, and expose only narrowly scoped Go bindings:

vm := leia.New(
    leia.SecuritySandbox(),
    leia.WithMaxSteps(100_000),
    leia.WithMaxNativeCalls(1_000),
)

Treat filesystem, environment, network, process, dynamic evaluation, module loading, and host callbacks as capabilities owned by the embedding application. Do not put provider credentials in Leia source. Read the sandbox reference before running untrusted code, and report vulnerabilities privately as described in SECURITY.md.

Compatibility And Experimental Features

v0.1.0 is the first public release and remains pre-1.0. The spec-covered core language, documented standard-library APIs, CLI, module resolution, and root Go embedding API are the intended compatibility surface for this tag. Necessary pre-1.0 changes will be documented in release notes, but strict backward compatibility is not yet guaranteed.

The following remain experimental: AI providers and live-provider behavior, new or optional dialect extensions, JIT internals and availability, typed runtime kernels, and diagnostics not explicitly documented as stable. Programs must not depend on JIT compilation; the interpreter defines semantics and the bytecode VM and JIT must preserve them. See the platform policy and performance methodology. Benchmark comparisons, including LuaJIT references, apply only to the recorded workloads, hardware, versions, and execution modes; Leia makes no whole-language "LuaJIT-class" performance guarantee.

Platforms

The initial support target is the CLI, interpreter, and bytecode VM on macOS and Linux for amd64 and arm64. A combination is considered tested only when its release notes contain execution evidence. Windows amd64 and arm64 archives may be published as available artifacts, but Windows is not support-claimed for v0.1.0 without matching release evidence. Native JIT acceleration is limited to eligible ARM64 builds and remains experimental.

Run leia capabilities --json to inspect the modes and optional surfaces in a specific binary. The platform matrix is the authoritative support policy.

Documentation

Leia is licensed under the Apache License 2.0. Contributions are covered by CONTRIBUTING.md and the Code of Conduct.

Documentation

Overview

Package leia provides the public Go API for embedding the Leia scripting language.

A VM executes Leia source and compiled programs, exposes explicit Go-backed functions and modules, and can be configured with library, capability, sandbox, and resource-budget options. VM instances are mutable and are not safe for concurrent use; concurrent hosts should use separate VMs or Pool.

Hosts that execute untrusted scripts should begin with SecuritySandbox and grant back only the capabilities and bindings their application requires.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Encode

func Encode(v Value) (interface{}, error)

Encode converts a public Leia value back into its default Go representation.

func ValidModuleMode

func ValidModuleMode(mode ModuleMode) bool

ValidModuleMode reports whether mode is accepted by module-aware runtime configuration.

Types

type BudgetError

type BudgetError struct {
	Resource string
	Limit    int64
	Err      error
}

BudgetError reports exhaustion of a resource budget configured on a VM.

func (*BudgetError) Error

func (e *BudgetError) Error() string

func (*BudgetError) Unwrap

func (e *BudgetError) Unwrap() error

type CapabilityFlags

type CapabilityFlags uint64

CapabilityFlags controls host capabilities that are separate from selecting which standard-library tables exist.

const (
	CapModuleLoading    CapabilityFlags = 1 << iota // require() may load .leia files from the host filesystem
	CapFilesystemRead                               // script file APIs may read the host filesystem
	CapFilesystemWrite                              // script file APIs may mutate the host filesystem
	CapEnvironmentRead                              // script OS APIs may read host environment variables
	CapEnvironmentWrite                             // script OS APIs may mutate host environment variables

	// CapFilesystem enables both filesystem read and write access.
	CapFilesystem = CapFilesystemRead | CapFilesystemWrite

	// CapEnvironment enables both environment read and write access.
	CapEnvironment = CapEnvironmentRead | CapEnvironmentWrite

	// CapAll enables every host capability (default, for compatibility).
	CapAll = CapModuleLoading | CapFilesystem | CapEnvironment

	// CapSafe disables host-backed capabilities.
	CapSafe CapabilityFlags = 0
)

type CompileOption

type CompileOption func(*compileOptions)

CompileOption configures Compile.

func WithSourceName

func WithSourceName(name string) CompileOption

WithSourceName sets the source name used in diagnostics for a compiled string. CompileFile uses the path by default.

type DialectHandler

type DialectHandler func(body Value, options Value) ([]Value, error)

DialectHandler implements a host-provided tagged dialect.

The body is the tagged string or tagged block value. Options is nil when the call site did not provide an options table. Return one or more Leia values in the same style as ordinary host functions.

type DialectOptions

type DialectOptions struct {
	Aliases      []string
	Category     string
	Capabilities []string
	Block        DialectHandler
}

DialectOptions describes a host-provided dialect.

type Error

type Error struct {
	Kind    ErrorKind
	Message string
	Line    int
	Col     int
	File    string
	// Err holds the underlying cause, when one is available.
	Err error
	// Value holds the original Leia error value when Kind == ErrScript.
	// It may be a string, table, or any Leia value converted to interface{}.
	Value interface{}
}

Error is a structured error from Leia execution.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Is

func (e *Error) Is(target error) bool

func (*Error) Unwrap

func (e *Error) Unwrap() error

type ErrorKind

type ErrorKind string

ErrorKind identifies the phase of Leia execution that produced an error.

const (
	ErrLex     ErrorKind = "lex"
	ErrParse   ErrorKind = "parse"
	ErrRuntime ErrorKind = "runtime"
	ErrScript  ErrorKind = "script" // error() called from Leia
)

type ExitError

type ExitError struct {
	Code int
	Err  error
}

ExitError reports a script-requested process exit. Embedders can catch this error and decide whether to terminate the host process, map it to an HTTP status, or treat it as an ordinary script result.

func (*ExitError) Error

func (e *ExitError) Error() string

func (*ExitError) Unwrap

func (e *ExitError) Unwrap() error

type HostCallbackError

type HostCallbackError struct {
	Name string
	Err  error
}

HostCallbackError is returned through execution APIs when a registered Go callback returns a non-nil error.

func (*HostCallbackError) Error

func (e *HostCallbackError) Error() string

func (*HostCallbackError) Unwrap

func (e *HostCallbackError) Unwrap() error

type HostCallbackPanicError

type HostCallbackPanicError struct {
	Name  string
	Value interface{}
}

HostCallbackPanicError is returned through execution APIs when a registered Go callback panics. The panic is recovered and exposed without crashing the host process.

func (*HostCallbackPanicError) Error

func (e *HostCallbackPanicError) Error() string

type HotInstance

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

HotInstance is a loaded Leia file with a persistent VM. Reloading an instance keeps the VM and its existing non-function globals by default, so ordinary script state survives code replacement without an explicit migration hook. Running goroutines or externally saved old closures are not migrated.

func (*HotInstance) Call

func (inst *HotInstance) Call(name string, args ...interface{}) ([]interface{}, error)

Call calls a function on the persistent VM without rerunning top-level code.

func (*HotInstance) CallContext

func (inst *HotInstance) CallContext(ctx context.Context, name string, args ...interface{}) ([]interface{}, error)

CallContext is the context-aware form of Call.

func (*HotInstance) Generation

func (inst *HotInstance) Generation() uint64

Generation returns the current successfully applied generation.

func (*HotInstance) Handle

func (inst *HotInstance) Handle() *ModuleHandle

Handle returns the underlying latest-program handle.

func (*HotInstance) Reload

func (inst *HotInstance) Reload() error

Reload recompiles and applies the source file while preserving state.

func (*HotInstance) ReloadContext

func (inst *HotInstance) ReloadContext(ctx context.Context) error

ReloadContext is the context-aware form of Reload.

func (*HotInstance) ReloadIfChanged

func (inst *HotInstance) ReloadIfChanged() (ReloadResult, error)

ReloadIfChanged recompiles and applies the source file only when source bytes differ from this instance's currently applied generation.

func (*HotInstance) ReloadIfChangedContext

func (inst *HotInstance) ReloadIfChangedContext(ctx context.Context) (ReloadResult, error)

ReloadIfChangedContext is the context-aware form of ReloadIfChanged.

func (*HotInstance) VM

func (inst *HotInstance) VM() *VM

VM returns the persistent VM owned by this instance. Callers must not use it concurrently with HotInstance methods.

type HotLoader

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

HotLoader compiles Leia files into atomically swappable program handles.

It intentionally does not start a filesystem watcher. Embedding applications can call Reload from their own watcher, admin endpoint, or deployment hook. HotLoader does not register files into require(); it is a Go embedding API for managing the latest successfully compiled Program.

func NewHotLoader

func NewHotLoader(opts ...HotLoaderOption) *HotLoader

NewHotLoader creates a hot loader for Leia source files.

func (*HotLoader) Handle

func (loader *HotLoader) Handle(path string) (*ModuleHandle, bool)

Handle returns a previously loaded module handle.

func (*HotLoader) Load

func (loader *HotLoader) Load(path string) (*ModuleHandle, error)

Load compiles path and returns a handle. Repeated Load calls for the same path return the existing handle after reloading it.

func (*HotLoader) LoadContext

func (loader *HotLoader) LoadContext(ctx context.Context, path string) (*ModuleHandle, error)

LoadContext is the context-aware form of Load.

func (*HotLoader) LoadInstance

func (loader *HotLoader) LoadInstance(path string) (*HotInstance, error)

LoadInstance compiles path, creates a persistent VM, and runs the program once. Future Reload calls on the returned instance preserve existing non-function globals by default while replacing function definitions.

func (*HotLoader) LoadInstanceContext

func (loader *HotLoader) LoadInstanceContext(ctx context.Context, path string) (*HotInstance, error)

LoadInstanceContext is the context-aware form of LoadInstance.

func (*HotLoader) Reload

func (loader *HotLoader) Reload(path string) error

Reload recompiles path and atomically swaps the handle on success. If compilation fails, the previously installed program remains active.

func (*HotLoader) ReloadContext

func (loader *HotLoader) ReloadContext(ctx context.Context, path string) error

ReloadContext is the context-aware form of Reload.

func (*HotLoader) ReloadIfChanged

func (loader *HotLoader) ReloadIfChanged(path string) (ReloadResult, error)

ReloadIfChanged recompiles and publishes path only when its source bytes differ from the current handle generation. Unchanged files do not rerun top-level code and do not advance the generation counter.

func (*HotLoader) ReloadIfChangedContext

func (loader *HotLoader) ReloadIfChangedContext(ctx context.Context, path string) (ReloadResult, error)

ReloadIfChangedContext is the context-aware form of ReloadIfChanged.

type HotLoaderOption

type HotLoaderOption func(*HotLoader)

HotLoaderOption configures a HotLoader.

func WithHotLoaderCompileOptions

func WithHotLoaderCompileOptions(opts ...CompileOption) HotLoaderOption

WithHotLoaderCompileOptions applies compile options to each Load/Reload.

func WithHotLoaderVMOptions

func WithHotLoaderVMOptions(opts ...Option) HotLoaderOption

WithHotLoaderVMOptions applies VM options to HotInstance VMs created by this loader.

type Kind

type Kind string

Kind identifies the public kind of a Leia value.

const (
	KindNil       Kind = "nil"
	KindBool      Kind = "bool"
	KindInt       Kind = "int"
	KindFloat     Kind = "float"
	KindString    Kind = "string"
	KindTable     Kind = "table"
	KindFunction  Kind = "function"
	KindCoroutine Kind = "coroutine"
	KindChannel   Kind = "channel"
	KindUnknown   Kind = "unknown"
)

type LibFlags

type LibFlags uint64

LibFlags controls which standard libraries are loaded.

const (
	LibString    LibFlags = 1 << iota // string.*
	LibTable                          // table.*
	LibMath                           // math.*
	LibIO                             // io.*
	LibOS                             // os.*
	LibCoroutine                      // coroutine (built-in, always available)
	LibHTTP                           // http.* (server)
	LibJSON                           // json.*
	LibBase64                         // base64.*
	LibHash                           // hash.*
	LibFS                             // fs.*
	LibPath                           // path.*
	LibTime                           // time.*
	LibNet                            // net.* (HTTP client)
	LibVec                            // vec.* (2D/3D vectors)
	LibColor                          // color.*
	LibRegexp                         // regexp.*
	LibUTF8                           // utf8.*
	LibBit32                          // bit32.*
	LibBinary                         // binary.*
	LibBits                           // bits.*
	LibBytes                          // bytes.*
	LibCSV                            // csv.*
	LibURL                            // url.*
	LibUUID                           // uuid.*
	LibProcess                        // process.*
	LibScript                         // script.*
	LibDebug                          // debug.*
	LibTestkit                        // testkit.*
	LibMatrix                         // matrix.*
	LibRand                           // rand.*
	LibSort                           // sort.*
	LibEncoding                       // encoding.*
	LibCompress                       // compress.*
	LibCrypto                         // crypto.*
	LibContainer                      // container.*
	LibLog                            // log.*
	LibArray                          // array.* dense arrays
	LibSoA                            // soa.* structure-of-arrays
	LibLinalg                         // linalg.* scientific dense vector/matrix helpers
	LibStats                          // stats.* scientific reductions and resampling helpers
	LibODE                            // ode.* numeric integration helpers
	LibControl                        // control.* control-system helpers
	LibLLM                            // llm.* native model/tool integration
	LibDialect                        // dialect.* built-in language dialects
	LibDB                             // db.* built-in SQLite runtime

	// LibAll includes every library (default).
	LibAll = LibString | LibTable | LibMath | LibIO | LibOS | LibCoroutine |
		LibHTTP | LibJSON | LibBase64 | LibHash |
		LibFS | LibPath | LibTime | LibNet |
		LibVec | LibColor | LibRegexp | LibUTF8 | LibBit32 |
		LibBinary | LibBits | LibBytes | LibCSV | LibURL | LibUUID |
		LibProcess | LibScript | LibDebug | LibTestkit | LibMatrix |
		LibRand | LibSort | LibEncoding | LibCompress | LibCrypto |
		LibContainer | LibLog | LibArray | LibSoA | LibLinalg |
		LibStats | LibODE | LibControl | LibLLM | LibDialect | LibDB

	// LibSafe is a sandboxed subset with no I/O, network, or system access.
	LibSafe = LibString | LibTable | LibMath | LibCoroutine |
		LibJSON | LibBase64 | LibHash | LibVec | LibColor |
		LibRegexp | LibUTF8 | LibBit32 | LibBinary | LibBits |
		LibBytes | LibCSV | LibURL | LibUUID | LibMatrix |
		LibPath | LibTime | LibRand | LibSort | LibEncoding | LibCompress | LibCrypto |
		LibContainer | LibArray | LibSoA | LibLinalg | LibStats | LibODE | LibControl | LibDialect

	// LibApp is a convenient preset for application development (no GL).
	LibApp = LibString | LibTable | LibMath | LibIO | LibOS | LibCoroutine |
		LibJSON | LibBase64 | LibHash | LibFS | LibPath | LibTime | LibNet |
		LibRegexp | LibUTF8 | LibBit32 | LibBinary | LibBits |
		LibBytes | LibCSV | LibURL | LibUUID | LibProcess | LibScript |
		LibDebug | LibMatrix | LibRand | LibSort | LibEncoding |
		LibCompress | LibCrypto | LibContainer | LibLog | LibArray | LibSoA |
		LibLinalg | LibStats | LibODE | LibControl |
		LibLLM | LibDialect | LibDB

	// LibGame is a preset for game development (no I/O, includes vec/color).
	LibGame = LibString | LibTable | LibMath | LibCoroutine |
		LibVec | LibColor | LibJSON | LibBit32 | LibBits |
		LibTime | LibRand | LibArray | LibSoA | LibLinalg | LibStats | LibODE | LibControl
)

type Module

type Module map[string]interface{}

Module is a Go-backed namespace exposed to Leia through require(name). Values use the same reflection conversion rules as RegisterFunc and Set.

func ModuleFrom

func ModuleFrom(source interface{}, opts ...ModuleFromOption) (Module, error)

ModuleFrom builds a require-able Module from a Go value. It is intended for service structs and third-party clients whose exported methods should be exposed to scripts without manually writing a Module literal.

type ModuleFromOption

type ModuleFromOption func(*moduleFromOptions)

ModuleFromOption configures ModuleFrom and RegisterModuleFrom.

func WithModuleExactNames

func WithModuleExactNames() ModuleFromOption

WithModuleExactNames keeps exported Go field and method names unchanged.

func WithModuleNameMapper

func WithModuleNameMapper(mapper func(string) string) ModuleFromOption

WithModuleNameMapper maps exported Go field and method names to script names. The default mapper lower-cases the first rune, so ToUpper becomes toUpper.

type ModuleHandle

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

ModuleHandle points to the latest compiled generation of one Leia file. Its atomic snapshot makes reload publication safe, but each Program must still be run according to Program's concurrency contract.

func (*ModuleHandle) Call

func (handle *ModuleHandle) Call(vm *VM, name string, args ...interface{}) ([]interface{}, error)

Call runs the latest generation and then calls a named function on vm. The top-level program is executed on every Call, so embedders that want to avoid replaying top-level side effects should call Run once on their own VM and then use VM.Call.

func (*ModuleHandle) CallContext

func (handle *ModuleHandle) CallContext(ctx context.Context, vm *VM, name string, args ...interface{}) ([]interface{}, error)

CallContext runs the latest generation and then calls a named function on vm. See Call for the top-level execution behavior.

func (*ModuleHandle) Generation

func (handle *ModuleHandle) Generation() uint64

Generation returns the current generation. It increments only after a successful Load or Reload.

func (*ModuleHandle) Path

func (handle *ModuleHandle) Path() string

Path returns the source path associated with this handle.

func (*ModuleHandle) Program

func (handle *ModuleHandle) Program() (*Program, bool)

Program returns the current compiled program.

func (*ModuleHandle) Run

func (handle *ModuleHandle) Run(vm *VM) error

Run executes the latest generation on vm.

func (*ModuleHandle) RunContext

func (handle *ModuleHandle) RunContext(ctx context.Context, vm *VM) error

RunContext executes the latest generation on vm.

type ModuleMode

type ModuleMode string

ModuleMode selects how module metadata is used when configuring runtime require() resolution from leia.mod.

const (
	// ModuleModeMod uses local replaces, vendor entries, and the module cache.
	ModuleModeMod ModuleMode = "mod"
	// ModuleModeReadonly is explicit non-mutating module mode. Runtime loading
	// remains offline and may use existing vendor/cache entries.
	ModuleModeReadonly ModuleMode = "readonly"
	// ModuleModeVendor restricts remote module resolution to vendor entries.
	ModuleModeVendor ModuleMode = "vendor"
)

type Option

type Option func(*vmOptions)

Option configures a VM instance.

func ModuleOptionsForScript

func ModuleOptionsForScript(script string) []Option

ModuleOptionsForScript discovers the nearest leia.mod for script and returns module-loading options derived from it. It intentionally does not fetch packages or mutate files.

func ModuleOptionsForScriptMode

func ModuleOptionsForScriptMode(script string, mode ModuleMode) []Option

ModuleOptionsForScriptMode is ModuleOptionsForScript with an explicit module mode. Readonly and mod modes use existing local vendor/cache entries without mutating module files or downloading. Vendor mode ignores the module cache.

func SecuritySandbox

func SecuritySandbox() Option

SecuritySandbox selects the production-oriented in-process sandbox baseline: safe standard libraries, no host-backed capabilities, and no JIT by default. Pair it with context deadlines and WithMaxSteps for concrete resource budgets.

func WithArgs

func WithArgs(script string, args ...string) Option

WithArgs sets the script entrypoint arguments. The global arg table follows Leia's Lua-compatible convention: arg[0] is script and arg[1..n] are args.

func WithCapabilities

func WithCapabilities(caps CapabilityFlags) Option

WithCapabilities sets which host capabilities are available to scripts. Default: CapAll. Use CapSafe with LibSafe for an in-process sandbox that has no script module loading and no filesystem-backed script APIs.

func WithDebugAccess

func WithDebugAccess(enabled bool) Option

WithDebugAccess controls script-side debug APIs. Internal debug frame accounting remains active for host diagnostics.

func WithDialect

func WithDialect(name string, handler DialectHandler, opts ...DialectOptions) Option

WithDialect registers a host-provided dialect for this VM.

Built-in dialect names cannot be overridden. The handler runs for tagged strings, explicit dialect.eval calls, and tagged blocks unless opts.Block is supplied.

func WithDynamicEval

func WithDynamicEval(enabled bool) Option

WithDynamicEval controls script-side string compilation APIs such as load(), loadstring(), script.compile(), and script.eval(). It does not affect host-side Compile/Exec calls.

func WithEnvironment

func WithEnvironment(enabled bool) Option

WithEnvironment controls script-side host environment variable APIs. It enables or disables both read and write access.

func WithEnvironmentAllowlist

func WithEnvironmentAllowlist(names ...string) Option

WithEnvironmentAllowlist restricts script-side environment APIs to the named variables. Passing no names allows no variables; omit this option to keep the default unrestricted behavior when environment access is otherwise enabled.

func WithEnvironmentRead

func WithEnvironmentRead(enabled bool) Option

WithEnvironmentRead controls script-side environment variable reads. This gates APIs such as os.getenv, os.environ, and os.expand.

func WithEnvironmentWrite

func WithEnvironmentWrite(enabled bool) Option

WithEnvironmentWrite controls script-side environment variable writes. This gates APIs such as os.setenv and os.unsetenv.

func WithFilesystem

func WithFilesystem(enabled bool) Option

WithFilesystem controls filesystem-backed script APIs such as fs, dofile, and loadfile. It enables or disables both filesystem read and write access. It does not affect host-side ExecFile/CompileFile calls.

func WithFilesystemRead

func WithFilesystemRead(enabled bool) Option

WithFilesystemRead controls script-side filesystem read access. This gates APIs such as fs.readfile, fs.stat, fs.readdir, dofile, and loadfile.

func WithFilesystemRoot

func WithFilesystemRoot(root string) Option

WithFilesystemRoot confines fs module paths and script-side file loading to root. Relative script paths are resolved inside root. An empty root leaves filesystem paths unrestricted.

func WithFilesystemWrite

func WithFilesystemWrite(enabled bool) Option

WithFilesystemWrite controls script-side filesystem write access. This gates APIs such as fs.writefile, fs.remove, fs.rename, fs.mkdir, fs.chdir, and fs.tempfile.

func WithGoImports

func WithGoImports(imports map[string]any) Option

WithGoImports registers an explicit allowlist of Go-backed modules that scripts may load with require("go:..."). The values are converted with the same rules as ModuleFrom, so pass concrete modules or host values; this does not dynamically load Go packages by import path.

func WithJIT

func WithJIT() Option

WithJIT enables the ARM64 JIT compiler (implies bytecode VM). Only available on darwin/arm64 (Apple Silicon).

func WithLLMProvider

func WithLLMProvider(provider llm.Provider) Option

WithLLMProvider installs the provider used by llm.turn. A nil provider makes llm.turn return a provider error.

func WithLLMProviderFactory

func WithLLMProviderFactory(factory llm.ProviderFactory) Option

WithLLMProviderFactory installs a constructor for script-declared models {} provider configs. Host-injected providers still take precedence for ordinary llm.turn calls; this hook is used when no provider is otherwise configured.

func WithLLMRecorder

func WithLLMRecorder(sink llm.RecordSink) Option

WithLLMRecorder records provider turns after execution. It is intended for reproducible tests and offline agent evaluation. Recorder entries include the request/result protocol shape, so hosts should store them according to their own prompt-retention policy.

func WithLLMReplay

func WithLLMReplay(records []llm.Record) Option

WithLLMReplay installs a deterministic sequential provider backed by records produced by WithLLMRecorder. Each incoming request is checked against the next recorded request before the recorded result or error is returned.

func WithLLMTrace

func WithLLMTrace(sink llm.TraceSink) Option

WithLLMTrace installs a host-side metadata trace sink for llm.turn/react. Events intentionally omit prompt text and tool result values by default.

func WithLibs

func WithLibs(libs LibFlags) Option

WithLibs sets which standard libraries are available. Default: LibAll

func WithMaxCallDepth

func WithMaxCallDepth(max int64) Option

WithMaxCallDepth limits active script/native function call depth. A non-positive value uses the runtime default.

When a call-depth limit is set, JIT execution is disabled so native code cannot bypass frame-depth checkpoints.

func WithMaxChannelCapacity

func WithMaxChannelCapacity(max int64) Option

WithMaxChannelCapacity limits the buffer capacity accepted by make(chan, n). Unbuffered channels are still allowed. A non-positive value disables the limit.

When a channel-capacity limit is set, JIT execution is disabled so native code cannot bypass channel-creation checkpoints.

func WithMaxFilesystemReadBytes

func WithMaxFilesystemReadBytes(max int64) Option

WithMaxFilesystemReadBytes limits bytes read into memory by fs.readfile() and fs.copy(). It does not limit host-side CompileFile/ExecFile calls or script source loading, which is controlled by WithMaxModuleBytes.

When a filesystem-read limit is set, JIT execution is disabled so native code cannot bypass filesystem checks.

func WithMaxFilesystemWriteBytes

func WithMaxFilesystemWriteBytes(max int64) Option

WithMaxFilesystemWriteBytes limits bytes written by fs.writefile(), fs.appendfile(), and fs.copy().

When a filesystem-write limit is set, JIT execution is disabled so native code cannot bypass filesystem checks.

func WithMaxGoroutines

func WithMaxGoroutines(max int64) Option

WithMaxGoroutines limits active goroutines started by script go statements. A non-positive value disables the limit.

When a goroutine limit is set, JIT execution is disabled so native code cannot bypass task-creation checkpoints.

func WithMaxHostResultBytes

func WithMaxHostResultBytes(max int64) Option

WithMaxHostResultBytes limits string bytes returned from a single native Go call, including standard-library functions and registered host callbacks. A non-positive value disables the limit.

When a host-result limit is set, JIT execution is disabled so native code cannot bypass result materialization checks.

func WithMaxModuleBytes

func WithMaxModuleBytes(max int64) Option

WithMaxModuleBytes limits bytes read by script-side module/file loading APIs such as require(), dofile(), loadfile(), and script.loadFile(). It does not limit host-side CompileFile/ExecFile calls. A non-positive value disables the limit.

When a module-byte limit is set, JIT execution is disabled so native code cannot bypass file-loading checks.

func WithMaxModuleDepth

func WithMaxModuleDepth(max int64) Option

WithMaxModuleDepth limits nested filesystem-backed require() calls. Built-in standard-library modules and already loaded package entries do not consume this budget. A non-positive value disables the limit.

When a module-depth limit is set, JIT execution is disabled so native code cannot bypass file-loading checks.

func WithMaxNativeCalls

func WithMaxNativeCalls(max int64) Option

WithMaxNativeCalls limits calls from script into native Go functions, including standard-library functions and registered host callbacks. A non-positive value disables the limit.

When a native-call limit is set, JIT execution is disabled so native code cannot bypass host-call budget checkpoints.

func WithMaxSteps

func WithMaxSteps(max int64) Option

WithMaxSteps limits interpreter statements or bytecode instructions executed by one Exec/Run. A non-positive value disables the limit.

When a step limit is set, JIT execution is disabled so native code cannot bypass the budget checkpoints.

func WithModuleCache

func WithModuleCache(root string) Option

WithModuleCache enables read-only module resolution from a module cache populated by leia mod download. It never downloads modules at runtime.

func WithModuleCollection

func WithModuleCollection(name, root string) Option

WithModuleCollection maps a require collection prefix to a filesystem root. require("vendor:pkg.util") resolves as ROOT/pkg/util.leia. This mirrors Odin's collection-style package roots while keeping Leia module loading explicit.

func WithModuleLoading

func WithModuleLoading(enabled bool) Option

WithModuleLoading controls whether require() may load .leia files from the host filesystem. Requiring enabled built-in standard libraries is still allowed, because that is controlled by WithLibs.

func WithModuleMode

func WithModuleMode(mode ModuleMode) Option

WithModuleMode records the module resolution mode used by module-aware runtime setup. Vendor mode filters non-vendor cache entries before require() resolution.

func WithModuleReplace

func WithModuleReplace(path, root string) Option

WithModuleReplace maps a module path prefix to a local filesystem root. require("example.com/lib/foo") resolves as ROOT/foo.leia when the prefix is example.com/lib. This is the runtime side of leia.mod replace directives.

func WithNetworkAccess

func WithNetworkAccess(enabled bool) Option

WithNetworkAccess controls host-backed network APIs in net and http.

func WithPrint

func WithPrint(fn func(args ...interface{})) Option

WithPrint overrides the print() function (useful to capture output in tests/games).

func WithProcessExecution

func WithProcessExecution(enabled bool) Option

WithProcessExecution controls process.run(), process.exec(), and process.which(). process.shell() has a separate switch.

func WithProcessShell

func WithProcessShell(enabled bool) Option

WithProcessShell controls process.shell().

func WithRequirePath

func WithRequirePath(path string) Option

WithRequirePath sets the base directory for require() module loading.

func WithSandbox

func WithSandbox() Option

WithSandbox selects the safe standard library set and disables host filesystem-backed capabilities.

func WithSecurity

func WithSecurity(policy SecurityPolicy) Option

WithSecurity applies a grouped security policy. It is equivalent to applying the corresponding fine-grained options, but gives embedders one place to construct and audit production limits.

func WithTestkitAccess

func WithTestkitAccess(enabled bool) Option

WithTestkitAccess controls script-side testkit diagnostics.

func WithTracing

func WithTracing() Option

WithTracing is an alias for WithJIT (kept for backward compatibility). The JIT compiler now includes both method-level and trace-level compilation.

func WithVM

func WithVM() Option

WithVM enables the bytecode VM instead of the default tree-walking interpreter.

type Pool

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

Pool manages a pool of VM instances for concurrent use. Typical use in a game server: one VM per goroutine/request.

func NewPool

func NewPool(max int, init func() *VM) *Pool

NewPool creates a VM pool. init is called to create each new VM instance. max is the maximum number of idle VMs to keep (0 = unlimited).

NewPool preserves VM state between Get/Put calls. Use NewPoolWithReset when pooled VMs must be explicitly cleaned before reuse.

func NewPoolWithReset

func NewPoolWithReset(max int, init func() *VM, reset PoolResetFunc) *Pool

NewPoolWithReset creates a VM pool that calls reset before storing VMs.

The reset hook can call vm.Reset() to clear globals and module state, or return false to discard a VM that should not be reused. Passing nil preserves NewPool behavior.

func (*Pool) Do

func (p *Pool) Do(fn func(*VM) error) error

Do acquires a VM, calls fn, then returns it to the pool.

func (*Pool) Get

func (p *Pool) Get() *VM

Get acquires a VM from the pool (creates one if none available).

func (*Pool) Put

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

Put returns a VM to the pool.

func (*Pool) Size

func (p *Pool) Size() int

Size returns the number of idle VMs in the pool.

type PoolResetFunc

type PoolResetFunc func(*VM) bool

PoolResetFunc is called by Put before a VM is returned to the idle pool. Return false to discard the VM instead of pooling it.

type Program

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

Program is a compiled Leia source unit.

Program hides parser, AST, bytecode, and JIT details from embedding callers. It may cache VM/JIT state while running, so callers should not run the same Program concurrently.

func Compile

func Compile(src string, opts ...CompileOption) (*Program, error)

Compile parses a Leia source string into a reusable Program.

func CompileContext

func CompileContext(ctx context.Context, src string, opts ...CompileOption) (*Program, error)

CompileContext is like Compile, but returns ctx.Err() if the context is already cancelled before or after parsing. It does not yet preempt parser work in the middle of a single parse.

func CompileFile

func CompileFile(path string, opts ...CompileOption) (*Program, error)

CompileFile reads and parses a Leia file into a reusable Program.

func CompileFileContext

func CompileFileContext(ctx context.Context, path string, opts ...CompileOption) (*Program, error)

CompileFileContext is like CompileFile, but returns ctx.Err() if the context is already cancelled before or after file parsing.

func (*Program) SourceName

func (p *Program) SourceName() string

SourceName returns the diagnostic source name attached to the Program.

type ReloadResult

type ReloadResult struct {
	Changed    bool
	Generation uint64
}

ReloadResult describes whether a reload published or applied new source.

type SecurityPolicy

type SecurityPolicy struct {
	Libs                    LibFlags
	Capabilities            CapabilityFlags
	CapabilitiesSet         bool
	MaxSteps                int64
	MaxNativeCalls          int64
	MaxCallDepth            int64
	MaxGoroutines           int64
	MaxChannelCapacity      int64
	MaxHostResultBytes      int64
	MaxModuleBytes          int64
	MaxModuleDepth          int64
	MaxFilesystemReadBytes  int64
	MaxFilesystemWriteBytes int64
	EnvironmentAllowlist    []string
	DisableDynamicEval      bool
	DisableNetworkAccess    bool
	DisableDebugAccess      bool
	DisableTestkitAccess    bool
	DisableProcessExecution bool
	DisableProcessShell     bool
	DisableJIT              bool
	DisableModuleLoading    bool
}

SecurityPolicy groups production sandbox controls behind one auditable embedding option. Zero-valued fields keep existing defaults.

type VM

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

VM is a Leia virtual machine instance. A VM is NOT goroutine-safe; use Pool for concurrent access.

func New

func New(opts ...Option) *VM

New creates a new Leia VM with the given options.

func (*VM) BindMethod

func (vm *VM) BindMethod(className, methodName string, fn interface{}) error

BindMethod adds a method to an already-registered struct class.

func (*VM) BindStruct

func (vm *VM) BindStruct(name string, proto interface{}) error

BindStruct registers a Go struct type as a Leia class. proto should be a zero value or example of the struct (e.g. Vec2{} or &Vec2{}).

This creates a Leia global named `name` with a .new() constructor and field/method access via metatable.

Example:

type Vec2 struct{ X, Y float64 }
func (v Vec2) Length() float64 { return math.Sqrt(v.X*v.X + v.Y*v.Y) }

vm.BindStruct("Vec2", Vec2{})

// In Leia:
v := Vec2.new(3, 4)
print(v.Length())  // 5
print(v.X)         // 3
v.X = 10

func (*VM) BindStructWithConstructor

func (vm *VM) BindStructWithConstructor(name string, proto interface{}, ctor interface{}) error

BindStructWithConstructor is like BindStruct but uses a custom constructor function. The constructor is called when Leia calls Name.new(args...).

func (*VM) Call

func (vm *VM) Call(name string, args ...interface{}) ([]interface{}, error)

Call calls a named Leia function with Go arguments and returns Go values. Args and return values are automatically converted via reflection.

func (*VM) CallContext

func (vm *VM) CallContext(ctx context.Context, name string, args ...interface{}) ([]interface{}, error)

CallContext calls a named Leia function with Go arguments and returns Go values.

Context cancellation is checked before starting, after completion, and at VM execution checkpoints while the call is running.

func (*VM) CallPublicValue

func (vm *VM) CallPublicValue(fn Value, args ...Value) ([]Value, error)

CallPublicValue calls a function held as a public Value.

func (*VM) CallValue

func (vm *VM) CallValue(fn interface{}, args ...interface{}) ([]interface{}, error)

CallValue calls a Leia function value (obtained via Get) with Go arguments.

func (*VM) CallValueContext

func (vm *VM) CallValueContext(ctx context.Context, fn interface{}, args ...interface{}) ([]interface{}, error)

CallValueContext calls a Leia function value with Go arguments.

Context cancellation is checked before starting, after completion, and at VM execution checkpoints while the call is running.

func (*VM) Exec

func (vm *VM) Exec(src string) error

Exec compiles and executes a Leia source string.

func (*VM) ExecContext

func (vm *VM) ExecContext(ctx context.Context, src string) error

ExecContext compiles and executes a Leia source string.

Context cancellation is checked before starting and after completion. Runtime preemption for long-running scripts is a separate sandbox/resource-control feature and is not implied by this method.

func (*VM) ExecFile

func (vm *VM) ExecFile(path string) error

ExecFile reads and executes a Leia source file.

func (*VM) ExecFileContext

func (vm *VM) ExecFileContext(ctx context.Context, path string) error

ExecFileContext reads and executes a Leia source file.

Context cancellation is checked before starting and after completion. Runtime preemption for long-running scripts is a separate sandbox/resource-control feature and is not implied by this method.

func (*VM) Get

func (vm *VM) Get(name string) (interface{}, error)

Get gets a global variable as a Go interface{} (auto-converted).

func (*VM) GetPublicValue

func (vm *VM) GetPublicValue(name string) Value

GetPublicValue gets a global as a public Value.

func (*VM) RegisterFunc

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

RegisterFunc registers a Go function as a Leia global. fn must be a func type. Args/returns are auto-converted via reflection.

Example:

vm.RegisterFunc("distance", func(x1, y1, x2, y2 float64) float64 {
    dx, dy := x2-x1, y2-y1
    return math.Sqrt(dx*dx + dy*dy)
})

func (*VM) RegisterModule

func (vm *VM) RegisterModule(name string, members Module) error

RegisterModule registers a Go-backed module for require(name).

Go-backed host modules are explicit embedding capabilities: this API exposes only the names the embedding application registers. Built-in stdlib modules and filesystem-loaded .leia modules keep their existing controls. Registered host modules remain available when filesystem module loading is disabled, which makes them suitable for sandboxed embeddings that need a narrow Go API surface.

Example:

vm.RegisterModule("go/strings", leia.Module{
    "upper": strings.ToUpper,
    "trim":  strings.TrimSpace,
})

func (*VM) RegisterModuleFrom

func (vm *VM) RegisterModuleFrom(name string, source interface{}, opts ...ModuleFromOption) error

RegisterModuleFrom exposes exported fields and methods from source as a Go-backed module. It is a convenience wrapper around ModuleFrom followed by RegisterModule.

func (*VM) RegisterTable

func (vm *VM) RegisterTable(name string, members map[string]interface{}) error

RegisterTable registers a table of Go functions as a global namespace.

Example:

vm.RegisterTable("vec", map[string]interface{}{
    "dot":   func(ax,ay,bx,by float64) float64 { return ax*bx + ay*by },
    "cross": func(ax,ay,bx,by float64) float64 { return ax*by - ay*bx },
})

func (*VM) Reset

func (vm *VM) Reset()

Reset clears all script-created VM state and reinitializes the VM with the same options used by New.

Reset discards globals, loaded module cache, bytecode VM/JIT state, script directory changes made by executed programs, and registered Go bindings added after construction. Options such as WithLibs, WithRequirePath, WithPrint, WithMaxSteps, WithVM, and WithJIT are preserved.

Reset is explicit: Pool does not call it unless a reset hook is configured. Like the rest of VM, Reset is not goroutine-safe.

func (*VM) Run

func (vm *VM) Run(prog *Program) error

Run executes a previously compiled Program.

func (*VM) RunContext

func (vm *VM) RunContext(ctx context.Context, prog *Program) error

RunContext executes a previously compiled Program.

Context cancellation is checked before starting and after completion. Runtime preemption for long-running scripts is a separate sandbox/resource-control feature and is not implied by this method.

func (*VM) Set

func (vm *VM) Set(name string, val interface{}) error

Set sets a global variable to a Go value (auto-converted).

func (*VM) SetArgs

func (vm *VM) SetArgs(script string, args []string)

SetArgs updates the script entrypoint arguments on an existing VM. The global arg table follows Leia's Lua-compatible convention: arg[0] is script and arg[1..n] are args.

func (*VM) SetPublicValue

func (vm *VM) SetPublicValue(name string, val Value)

SetPublicValue sets a global to a public Value.

type Value

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

Value is the public representation of a Leia value.

It intentionally hides the internal runtime value layout. Existing APIs that still accept interface{} can also accept Value directly.

func Bool

func Bool(v bool) Value

Bool constructs a boolean Leia value.

func Decode

func Decode(v interface{}) (Value, error)

Decode converts a Go value into a public Leia value using the existing reflection conversion rules.

func Float

func Float(v float64) Value

Float constructs a floating-point Leia value.

func Int

func Int(v int64) Value

Int constructs an integer Leia value.

func MustDecode

func MustDecode(v interface{}) Value

MustDecode is like Decode but panics on error.

func Nil

func Nil() Value

Nil constructs a nil Leia value.

func String

func String(v string) Value

String constructs a string Leia value.

func (Value) Bool

func (v Value) Bool() bool

Bool returns the value as a bool. Non-bool values return false.

func (*Value) Decode

func (v *Value) Decode(src interface{}) error

Decode stores the Go value converted with the existing reflection rules.

func (Value) Encode

func (v Value) Encode() (interface{}, error)

Encode converts the value back into its default Go representation.

func (Value) Float

func (v Value) Float() float64

Float returns the value as a float64. Int values are converted to float64; other non-float values return 0.

func (Value) Int

func (v Value) Int() int64

Int returns the value as an int64. Non-int values return 0.

func (Value) IsNil

func (v Value) IsNil() bool

IsNil reports whether the value is nil.

func (Value) Kind

func (v Value) Kind() Kind

Kind returns the value kind.

func (Value) String

func (v Value) String() string

String returns the value's string form.

func (Value) To

func (v Value) To(target reflect.Type) (reflect.Value, error)

To stores the value in target using the existing conversion rules.

Directories

Path Synopsis
benchmarks
cmd
leia command
leia-lsp command
examples
embedding
Package embedding contains executable examples for embedding Leia in Go.
Package embedding contains executable examples for embedding Leia in Go.
game_engine command
internal
ast
jit
Package jit provides the low-level native-code substrate used by the VM and higher-level JIT compilers.
Package jit provides the low-level native-code substrate used by the VM and higher-level JIT compilers.
methodjit
Package methodjit implements the method JIT compiler pipeline.
Package methodjit implements the method JIT compiler pipeline.
modfile
Package modfile parses and formats Leia module manifests.
Package modfile parses and formats Leia module manifests.
modpkg
Package modpkg implements local Leia module maintenance.
Package modpkg implements local Leia module maintenance.
nanbox
Package nanbox implements NaN-boxed 8-byte Values for Leia Season 2.
Package nanbox implements NaN-boxed 8-byte Values for Leia Season 2.
runtime
Package runtime implements the tree-walking runtime for Leia.
Package runtime implements the tree-walking runtime for Leia.
stdlib/catalog
Package catalog describes the public standard-library surface without depending on runtime values or module constructors.
Package catalog describes the public standard-library surface without depending on runtime values or module constructors.
stdlib/lib/data
Package data provides Leia's runtime-independent columnar data foundation.
Package data provides Leia's runtime-independent columnar data foundation.
support/modresolve
Package modresolve contains shared require() path resolution rules.
Package modresolve contains shared require() path resolution rules.
support/source
Package source provides shared source-file discovery and syntax checks for Leia tooling.
Package source provides shared source-file discovery and syntax checks for Leia tooling.
tooling/format
Package format provides shared Leia source formatting for CLI and editor tooling.
Package format provides shared Leia source formatting for CLI and editor tooling.
vm
feedback.go implements per-instruction type feedback collection for the Method JIT.
feedback.go implements per-instruction type feedback collection for the Method JIT.
llm

Jump to

Keyboard shortcuts

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