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 ¶
- func Encode(v Value) (interface{}, error)
- func ValidModuleMode(mode ModuleMode) bool
- type BudgetError
- type CapabilityFlags
- type CompileOption
- type DialectHandler
- type DialectOptions
- type Error
- type ErrorKind
- type ExitError
- type HostCallbackError
- type HostCallbackPanicError
- type HotInstance
- func (inst *HotInstance) Call(name string, args ...interface{}) ([]interface{}, error)
- func (inst *HotInstance) CallContext(ctx context.Context, name string, args ...interface{}) ([]interface{}, error)
- func (inst *HotInstance) Generation() uint64
- func (inst *HotInstance) Handle() *ModuleHandle
- func (inst *HotInstance) Reload() error
- func (inst *HotInstance) ReloadContext(ctx context.Context) error
- func (inst *HotInstance) ReloadIfChanged() (ReloadResult, error)
- func (inst *HotInstance) ReloadIfChangedContext(ctx context.Context) (ReloadResult, error)
- func (inst *HotInstance) VM() *VM
- type HotLoader
- func (loader *HotLoader) Handle(path string) (*ModuleHandle, bool)
- func (loader *HotLoader) Load(path string) (*ModuleHandle, error)
- func (loader *HotLoader) LoadContext(ctx context.Context, path string) (*ModuleHandle, error)
- func (loader *HotLoader) LoadInstance(path string) (*HotInstance, error)
- func (loader *HotLoader) LoadInstanceContext(ctx context.Context, path string) (*HotInstance, error)
- func (loader *HotLoader) Reload(path string) error
- func (loader *HotLoader) ReloadContext(ctx context.Context, path string) error
- func (loader *HotLoader) ReloadIfChanged(path string) (ReloadResult, error)
- func (loader *HotLoader) ReloadIfChangedContext(ctx context.Context, path string) (ReloadResult, error)
- type HotLoaderOption
- type Kind
- type LibFlags
- type Module
- type ModuleFromOption
- type ModuleHandle
- func (handle *ModuleHandle) Call(vm *VM, name string, args ...interface{}) ([]interface{}, error)
- func (handle *ModuleHandle) CallContext(ctx context.Context, vm *VM, name string, args ...interface{}) ([]interface{}, error)
- func (handle *ModuleHandle) Generation() uint64
- func (handle *ModuleHandle) Path() string
- func (handle *ModuleHandle) Program() (*Program, bool)
- func (handle *ModuleHandle) Run(vm *VM) error
- func (handle *ModuleHandle) RunContext(ctx context.Context, vm *VM) error
- type ModuleMode
- type Option
- func ModuleOptionsForScript(script string) []Option
- func ModuleOptionsForScriptMode(script string, mode ModuleMode) []Option
- func SecuritySandbox() Option
- func WithArgs(script string, args ...string) Option
- func WithCapabilities(caps CapabilityFlags) Option
- func WithDebugAccess(enabled bool) Option
- func WithDialect(name string, handler DialectHandler, opts ...DialectOptions) Option
- func WithDynamicEval(enabled bool) Option
- func WithEnvironment(enabled bool) Option
- func WithEnvironmentAllowlist(names ...string) Option
- func WithEnvironmentRead(enabled bool) Option
- func WithEnvironmentWrite(enabled bool) Option
- func WithFilesystem(enabled bool) Option
- func WithFilesystemRead(enabled bool) Option
- func WithFilesystemRoot(root string) Option
- func WithFilesystemWrite(enabled bool) Option
- func WithGoImports(imports map[string]any) Option
- func WithJIT() Option
- func WithLLMProvider(provider llm.Provider) Option
- func WithLLMProviderFactory(factory llm.ProviderFactory) Option
- func WithLLMRecorder(sink llm.RecordSink) Option
- func WithLLMReplay(records []llm.Record) Option
- func WithLLMTrace(sink llm.TraceSink) Option
- func WithLibs(libs LibFlags) Option
- func WithMaxCallDepth(max int64) Option
- func WithMaxChannelCapacity(max int64) Option
- func WithMaxFilesystemReadBytes(max int64) Option
- func WithMaxFilesystemWriteBytes(max int64) Option
- func WithMaxGoroutines(max int64) Option
- func WithMaxHostResultBytes(max int64) Option
- func WithMaxModuleBytes(max int64) Option
- func WithMaxModuleDepth(max int64) Option
- func WithMaxNativeCalls(max int64) Option
- func WithMaxSteps(max int64) Option
- func WithModuleCache(root string) Option
- func WithModuleCollection(name, root string) Option
- func WithModuleLoading(enabled bool) Option
- func WithModuleMode(mode ModuleMode) Option
- func WithModuleReplace(path, root string) Option
- func WithNetworkAccess(enabled bool) Option
- func WithPrint(fn func(args ...interface{})) Option
- func WithProcessExecution(enabled bool) Option
- func WithProcessShell(enabled bool) Option
- func WithRequirePath(path string) Option
- func WithSandbox() Option
- func WithSecurity(policy SecurityPolicy) Option
- func WithTestkitAccess(enabled bool) Option
- func WithTracing() Option
- func WithVM() Option
- type Pool
- type PoolResetFunc
- type Program
- func Compile(src string, opts ...CompileOption) (*Program, error)
- func CompileContext(ctx context.Context, src string, opts ...CompileOption) (*Program, error)
- func CompileFile(path string, opts ...CompileOption) (*Program, error)
- func CompileFileContext(ctx context.Context, path string, opts ...CompileOption) (*Program, error)
- type ReloadResult
- type SecurityPolicy
- type VM
- func (vm *VM) BindMethod(className, methodName string, fn interface{}) error
- func (vm *VM) BindStruct(name string, proto interface{}) error
- func (vm *VM) BindStructWithConstructor(name string, proto interface{}, ctor interface{}) error
- func (vm *VM) Call(name string, args ...interface{}) ([]interface{}, error)
- func (vm *VM) CallContext(ctx context.Context, name string, args ...interface{}) ([]interface{}, error)
- func (vm *VM) CallPublicValue(fn Value, args ...Value) ([]Value, error)
- func (vm *VM) CallValue(fn interface{}, args ...interface{}) ([]interface{}, error)
- func (vm *VM) CallValueContext(ctx context.Context, fn interface{}, args ...interface{}) ([]interface{}, error)
- func (vm *VM) Exec(src string) error
- func (vm *VM) ExecContext(ctx context.Context, src string) error
- func (vm *VM) ExecFile(path string) error
- func (vm *VM) ExecFileContext(ctx context.Context, path string) error
- func (vm *VM) Get(name string) (interface{}, error)
- func (vm *VM) GetPublicValue(name string) Value
- func (vm *VM) RegisterFunc(name string, fn interface{}) error
- func (vm *VM) RegisterModule(name string, members Module) error
- func (vm *VM) RegisterModuleFrom(name string, source interface{}, opts ...ModuleFromOption) error
- func (vm *VM) RegisterTable(name string, members map[string]interface{}) error
- func (vm *VM) Reset()
- func (vm *VM) Run(prog *Program) error
- func (vm *VM) RunContext(ctx context.Context, prog *Program) error
- func (vm *VM) Set(name string, val interface{}) error
- func (vm *VM) SetArgs(script string, args []string)
- func (vm *VM) SetPublicValue(name string, val Value)
- type Value
- func (v Value) Bool() bool
- func (v *Value) Decode(src interface{}) error
- func (v Value) Encode() (interface{}, error)
- func (v Value) Float() float64
- func (v Value) Int() int64
- func (v Value) IsNil() bool
- func (v Value) Kind() Kind
- func (v Value) String() string
- func (v Value) To(target reflect.Type) (reflect.Value, error)
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ValidModuleMode ¶
func ValidModuleMode(mode ModuleMode) bool
ValidModuleMode reports whether mode is accepted by module-aware runtime configuration.
Types ¶
type BudgetError ¶
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 ¶
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.
type ErrorKind ¶
type ErrorKind string
ErrorKind identifies the phase of Leia execution that produced an error.
type ExitError ¶
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.
type HostCallbackError ¶
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 ¶
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 ¶
Reload recompiles path and atomically swaps the handle on success. If compilation fails, the previously installed program remains active.
func (*HotLoader) ReloadContext ¶
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 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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
WithEnvironment controls script-side host environment variable APIs. It enables or disables both read and write access.
func WithEnvironmentAllowlist ¶
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 ¶
WithEnvironmentRead controls script-side environment variable reads. This gates APIs such as os.getenv, os.environ, and os.expand.
func WithEnvironmentWrite ¶
WithEnvironmentWrite controls script-side environment variable writes. This gates APIs such as os.setenv and os.unsetenv.
func WithFilesystem ¶
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 ¶
WithFilesystemRead controls script-side filesystem read access. This gates APIs such as fs.readfile, fs.stat, fs.readdir, dofile, and loadfile.
func WithFilesystemRoot ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
WithLLMTrace installs a host-side metadata trace sink for llm.turn/react. Events intentionally omit prompt text and tool result values by default.
func WithMaxCallDepth ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
WithModuleCache enables read-only module resolution from a module cache populated by leia mod download. It never downloads modules at runtime.
func WithModuleCollection ¶
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 ¶
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 ¶
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 ¶
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 ¶
WithProcessExecution controls process.run(), process.exec(), and process.which(). process.shell() has a separate switch.
func WithProcessShell ¶
WithProcessShell controls process.shell().
func WithRequirePath ¶
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 ¶
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.
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 ¶
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.
type PoolResetFunc ¶
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 ¶
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 ¶
CompileFileContext is like CompileFile, but returns ctx.Err() if the context is already cancelled before or after file parsing.
func (*Program) SourceName ¶
SourceName returns the diagnostic source name attached to the Program.
type ReloadResult ¶
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 (*VM) BindMethod ¶
BindMethod adds a method to an already-registered struct class.
func (*VM) BindStruct ¶
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 ¶
BindStructWithConstructor is like BindStruct but uses a custom constructor function. The constructor is called when Leia calls Name.new(args...).
func (*VM) Call ¶
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 ¶
CallPublicValue calls a function held as a public Value.
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) ExecContext ¶
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) ExecFileContext ¶
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) GetPublicValue ¶
GetPublicValue gets a global as a public Value.
func (*VM) RegisterFunc ¶
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 ¶
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 ¶
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) RunContext ¶
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) SetArgs ¶
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 ¶
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 Decode ¶
Decode converts a Go value into a public Leia value using the existing reflection conversion rules.
func MustDecode ¶
func MustDecode(v interface{}) Value
MustDecode is like Decode but panics on error.
func (Value) Float ¶
Float returns the value as a float64. Int values are converted to float64; other non-float values return 0.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
benchmarks
|
|
|
cmd/layout_bench
command
|
|
|
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
|
|
|
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. |