runtime

package
v0.60.0 Latest Latest
Warning

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

Go to latest
Published: Aug 24, 2026 License: MIT Imports: 42 Imported by: 0

Documentation

Overview

Package runtime implements the Vibescript execution engine — the Engine, Script, Execution, environment, memory accounting, module loader, and built-in registration. It is hidden from external embedders behind the vibes facade.

Index

Constants

View Source
const (
	ParamNormal      = ast.ParamNormal
	ParamKeyword     = ast.ParamKeyword
	ParamRest        = ast.ParamRest
	ParamKeywordRest = ast.ParamKeywordRest
)
View Source
const (
	TypeAny      = ast.TypeAny
	TypeInt      = ast.TypeInt
	TypeFloat    = ast.TypeFloat
	TypeNumber   = ast.TypeNumber
	TypeString   = ast.TypeString
	TypeBool     = ast.TypeBool
	TypeNil      = ast.TypeNil
	TypeDuration = ast.TypeDuration
	TypeTime     = ast.TypeTime
	TypeMoney    = ast.TypeMoney
	TypeArray    = ast.TypeArray
	TypeHash     = ast.TypeHash
	TypeRange    = ast.TypeRange
	TypeSymbol   = ast.TypeSymbol
	TypeFunction = ast.TypeFunction
	TypeShape    = ast.TypeShape
	TypeUnion    = ast.TypeUnion
	TypeEnum     = ast.TypeEnum
	TypeUnknown  = ast.TypeUnknown
)
View Source
const (
	KindNil       = value.KindNil
	KindBool      = value.KindBool
	KindInt       = value.KindInt
	KindFloat     = value.KindFloat
	KindString    = value.KindString
	KindArray     = value.KindArray
	KindHash      = value.KindHash
	KindFunction  = value.KindFunction
	KindBuiltin   = value.KindBuiltin
	KindMoney     = value.KindMoney
	KindDuration  = value.KindDuration
	KindTime      = value.KindTime
	KindSymbol    = value.KindSymbol
	KindObject    = value.KindObject
	KindRange     = value.KindRange
	KindBlock     = value.KindBlock
	KindEnum      = value.KindEnum
	KindEnumValue = value.KindEnumValue
	KindClass     = value.KindClass
	KindInstance  = value.KindInstance
	KindRegex     = value.KindRegex
	KindShape     = value.KindShape
)
View Source
const (
	ObjectTagNone         = value.ObjectTagNone
	ObjectTagRescuedError = value.ObjectTagRescuedError
	ObjectTagMatchData    = value.ObjectTagMatchData
)
View Source
const Unlimited = -1

Unlimited disables a quota when supplied as a Config quota value (StepQuota, MemoryQuotaBytes, or RecursionLimit). The runtime treats any non-positive quota as unbounded; Unlimited is the explicit spelling callers use to request that, distinct from a zero value, which selects the built-in default. Disabling RecursionLimit lets deep recursion grow the host Go stack until it overflows the process — no named quota profile does this; it is an at-your-own-risk escape hatch for trusted workloads.

Variables

View Source
var (
	ProfileLow    = QuotaProfile{Name: "low", StepQuota: 1_000_000, MemoryQuotaBytes: 16 << 20, RecursionLimit: 256}
	ProfileMedium = QuotaProfile{Name: "medium", StepQuota: 20_000_000, MemoryQuotaBytes: 128 << 20, RecursionLimit: 1_000}
	ProfileHigh   = QuotaProfile{Name: "high", StepQuota: 200_000_000, MemoryQuotaBytes: 512 << 20, RecursionLimit: 4_000}
	ProfileXHigh  = QuotaProfile{Name: "xhigh", StepQuota: Unlimited, MemoryQuotaBytes: Unlimited, RecursionLimit: 10_000}
)

The named quota profiles. Values are deliberately generous relative to the embedding-API defaults: the CLI, which selects these, runs the developer's own scripts and is not a sandbox.

Functions

func AssignDestructure added in v0.60.0

func AssignDestructure(target *DestructureTarget, value Value, assign func(Expression, Value) error) error

AssignDestructure applies Vibescript's destructuring assignment rules and invokes assign for each concrete leaf target. It is the host-facing entry point used by tools that walk destructuring targets without a sandboxed Execution (such as the REPL extracting bound names from a result); it never charges memory because those callers run outside a quota. Sandboxed evaluation goes through Execution.assignDestructure, which charges every fresh slot array (the right-hand-side snapshot and any named rest window) against the memory quota before it is allocated.

func MemberCompletionNames added in v0.50.0

func MemberCompletionNames() map[string][]string

MemberCompletionNames returns the builtin member-method names per receiver type, for editor tooling such as LSP completion. The slices are copies; callers may sort or mutate them freely. Each type's list includes the universal Object-level helpers (itself, nil?, eql?, equal?, tap, yield_self) and the introspection predicates (respond_to?, is_a?, kind_of?, instance_of?), which resolve on every value through resolveMember's fallback even though they live outside the per-kind dispatch switches.

func QuotaProfileNames added in v0.60.0

func QuotaProfileNames() []string

QuotaProfileNames returns the profile names in ascending order of generosity, for help text and error messages.

Types

type AliasStmt added in v0.60.0

type AliasStmt = ast.AliasStmt

type ArrayLiteral

type ArrayLiteral = ast.ArrayLiteral

type AssignStmt

type AssignStmt = ast.AssignStmt

type BinaryExpr

type BinaryExpr = ast.BinaryExpr

type Block

type Block struct {
	Params         []Param
	ImplicitParams []string
	Body           []Statement
	Env            *Env
	// contains filtered or unexported fields
}

Block represents a closure passed to a function at runtime. It stays in the vibes package because its fields reference parser AST and the runtime Env/Script types.

func BlockOf

func BlockOf(v Value) *Block

BlockOf returns the *Block stored in v, or nil.

func (*Block) ValueBlockMarker

func (*Block) ValueBlockMarker()

type BlockLiteral

type BlockLiteral = ast.BlockLiteral

type BoolLiteral

type BoolLiteral = ast.BoolLiteral

type BreakStmt

type BreakStmt = ast.BreakStmt

type Builtin

type Builtin struct {
	Name       string
	Fn         BuiltinFunc
	AutoInvoke bool

	// SignatureParams carries the published positional parameters of a typed
	// host builtin (NewTypedBuiltin) so argument evaluation applies the same
	// callable and typed expectations an annotated script function would.
	SignatureParams []Param
	// OptionsHashTarget receives a collapsed keyword options hash for builtin
	// wrappers around script functions (method, constructor, and function-call
	// alias callers).
	OptionsHashTarget *ScriptFunction

	// ReturnTypeTarget is the script function whose declared return type
	// governs this builtin's result. Only the wrappers that return their
	// function's value set it, so an absorbed break can be validated against
	// the right annotation.
	//
	// It is deliberately separate from OptionsHashTarget, which records the
	// function an options hash collapses into and is also set on a
	// constructor. A constructor runs initialize through
	// callFunctionIgnoringReturn and returns the instance, so initialize's
	// annotation is not the constructor's contract: reusing that field made
	// `C.new { break 7 }` fail against `def initialize() -> nil`.
	ReturnTypeTarget *ScriptFunction
	// CapturedValues holds runtime values the builtin's Fn closes over and keeps
	// alive for as long as the builtin is reachable. The memory estimator charges
	// their payloads so a stored bound builtin (for example `probe = big.eql?`,
	// which captures its receiver) cannot retain arbitrarily large structures
	// outside the runtime memory quota. Builtins that close over no runtime values
	// leave this nil and stay free, as before.
	CapturedValues []Value
	// BoundReceiver, when non-nil, marks a receiver-bound builtin (such as a bound
	// script method or eql?/equal? predicate) and exposes a two-phase clone. These
	// builtins read the value they were resolved from through a mutable cell, so a
	// plain clone of the Fn keeps using the pre-clone receiver. When
	// Script.Call host-clones a returned graph (or re-roots an inbound one) that
	// holds both a receiver and a predicate bound to it, the clone walk reserves an
	// empty clone, registers it, recurses to clone the receiver, then installs the
	// cloned receiver via this hook. Reserving before recursing keeps a receiver
	// graph that reaches the predicate bound to it (for example `[p, a]` where `a`
	// stores `p = a.eql?`) deduplicated to one clone, so a re-entering
	// `probe(clonedReceiver)` still reports identity. Builtins with no bound
	// receiver leave this nil.
	BoundReceiver *boundReceiverClone
	// Capability marks a builtin a capability adapter exposed for a single
	// Script.Call. Capability grants are per call: when a closure that captured
	// one (for example a `Hash.new { ... }` default proc copying a capability
	// into a local) escapes and re-enters a later call, the inbound rebinder
	// revokes the captured grant so a missing-key lookup cannot invoke a
	// capability the re-entering call never granted.
	Capability bool
	// contains filtered or unexported fields
}

Builtin represents a built-in function callable from Vibescript. It remains defined in the vibes package because BuiltinFunc references the runtime *Execution type.

func BuiltinOf

func BuiltinOf(v Value) *Builtin

BuiltinOf returns the *Builtin stored in v, or nil.

func (*Builtin) ValueBuiltinMarker

func (*Builtin) ValueBuiltinMarker()

type BuiltinFunc

type BuiltinFunc func(exec *Execution, receiver Value, args []Value, kwargs map[string]Value, block Value) (Value, error)

BuiltinFunc is the Go function signature for built-in Vibescript functions.

type CallExpr

type CallExpr = ast.CallExpr

type CallOptions

type CallOptions struct {
	Globals      map[string]Value
	Capabilities []CapabilityAdapter
	AllowRequire bool
	Keywords     map[string]Value
}

CallOptions configures globals, capabilities, and other settings for a script invocation.

type CapabilityAdapter

type CapabilityAdapter interface {
	Bind(binding CapabilityBinding) (map[string]Value, error)
}

CapabilityAdapter binds host capabilities into a script invocation.

func MustNewContextCapability

func MustNewContextCapability(name string, resolver ContextCapabilityResolver) CapabilityAdapter

MustNewContextCapability is the panicking variant of NewContextCapability.

func MustNewDBCapability

func MustNewDBCapability(name string, impl Database) CapabilityAdapter

MustNewDBCapability is the panicking variant of NewDBCapability.

func MustNewEventsCapability

func MustNewEventsCapability(name string, publisher EventPublisher) CapabilityAdapter

MustNewEventsCapability is the panicking variant of NewEventsCapability.

func MustNewJobQueueCapability

func MustNewJobQueueCapability(name string, impl JobQueue) CapabilityAdapter

MustNewJobQueueCapability is the panicking variant of NewJobQueueCapability.

func NewContextCapability

func NewContextCapability(name string, resolver ContextCapabilityResolver) (CapabilityAdapter, error)

NewContextCapability constructs a data-only context capability adapter that bridges a contextcap.Resolver into the runtime CapabilityAdapter interface. The vibes facade re-exports this entry point under the same name.

func NewDBCapability

func NewDBCapability(name string, impl Database) (CapabilityAdapter, error)

NewDBCapability constructs a database capability adapter bound to the provided script-facing name. The vibes facade re-exports this entry point under the same name.

func NewEventsCapability

func NewEventsCapability(name string, publisher EventPublisher) (CapabilityAdapter, error)

NewEventsCapability constructs a CapabilityAdapter that delegates to a *events.Capability. The vibes facade re-exports this entry point under the same name.

func NewJobQueueCapability

func NewJobQueueCapability(name string, impl JobQueue) (CapabilityAdapter, error)

NewJobQueueCapability constructs a CapabilityAdapter that delegates to a *jobqueue.Capability. It is the runtime-facing entry point used by the vibes facade.

type CapabilityBinding

type CapabilityBinding struct {
	Context context.Context
	Engine  *Engine
}

CapabilityBinding provides execution context for adapters during binding.

type CapabilityContractProvider

type CapabilityContractProvider interface {
	CapabilityContracts() map[string]CapabilityMethodContract
}

CapabilityContractProvider exposes per-method contracts for capability adapters. Contract keys must match builtin method names exposed to scripts (for example "jobs.enqueue").

type CapabilityMethodContract

type CapabilityMethodContract struct {
	ValidateArgs   func(args []Value, kwargs map[string]Value, block Value) error
	ValidateReturn func(result Value) error
}

CapabilityMethodContract validates capability method calls at the boundary. These contracts run before and after a capability builtin executes.

ValidateReturn always runs after the builtin returns. The only exception is runtime-internal: a first-party builtin that has already validated and isolated its result records that fact through an unexported per-call proof on the Execution (markValidatedCapabilityReturn), which the dispatcher consumes to avoid validating the same value twice. Adapters outside this package cannot record that proof, so a host-supplied contract can never skip its declared return validation.

type CaseExpr

type CaseExpr = ast.CaseExpr

type CaseWhenClause

type CaseWhenClause = ast.CaseWhenClause

type CheckWarning added in v0.60.0

type CheckWarning struct {
	Function string
	Pos      Position
	Message  string
	// Source is the file path of the required module the warning originates
	// in; empty for warnings in the checked script itself.
	Source string
}

CheckWarning describes a statically checkable contract issue.

type ClassDef

type ClassDef struct {
	Name         string
	IsModule     bool
	Methods      map[string]*ScriptFunction
	ClassMethods map[string]*ScriptFunction
	ClassVars    map[string]Value
	// NestedModules lists the short names of module declarations nested in
	// this definition's body. The compiled definitions are registered under
	// the qualified name (Name + "::" + short) and linked into ClassVars per
	// call so Outer::Inner resolves like any other scoped constant.
	NestedModules []string
	Body          []Statement
	// contains filtered or unexported fields
}

ClassDef represents a user-defined class or module with its methods and class-level state. Module declarations (`module Name ... end`) compile to a ClassDef with IsModule set: a module is a namespace, so ClassMethods holds its `def self.` functions (`Billing.code`) and ClassVars its constants (`Billing::LIMIT`), while Methods stays empty. Modules cannot be instantiated, and their members are reachable only through the module's own name.

func ClassOf

func ClassOf(v Value) *ClassDef

ClassOf returns the *ClassDef stored in v, or nil if v is not a class value. It is the typed companion to v.Class(), which returns the value.ClassPayload interface for cycle-free reach from outside vibes.

func (*ClassDef) ValueClassMarker

func (*ClassDef) ValueClassMarker()

type ClassStmt

type ClassStmt = ast.ClassStmt

type ClassVarExpr

type ClassVarExpr = ast.ClassVarExpr

type ConditionalExpr added in v0.60.0

type ConditionalExpr = ast.ConditionalExpr

type Config

type Config struct {
	StepQuota        int
	MemoryQuotaBytes int
	StrictEffects    bool
	RecursionLimit   int
	ModulePaths      []string
	ModuleAllowList  []string
	ModuleDenyList   []string
	RandomReader     io.Reader
	RandomReadFunc   func(context.Context, []byte) (int, error)
	OutputWriter     io.Writer
	ErrorWriter      io.Writer
	MaxCachedModules int
	MaxSourceBytes   int

	// DevMode enables development-time module reloading. When true, every
	// require revalidates its cached module against the source file's
	// mtime+size and recompiles it when the file changed, and require
	// misses are re-resolved from disk instead of being negatively cached.
	// The zero value (false) keeps production behavior: modules compile
	// once and are served from cache until ClearModuleCache. DevMode is
	// not intended for production: each require costs a stat, and a
	// reload is not atomic across concurrently running Calls (each
	// in-flight Call keeps the module version it first required).
	DevMode bool
}

Config controls interpreter execution bounds and enforcement modes.

type ContextCapabilityResolver

type ContextCapabilityResolver = contextcap.Resolver

ContextCapabilityResolver is an internal alias for contextcap.Resolver so runtime code (and tests) can keep using the short name that matches the public vibes facade.

type DBEachRequest

type DBEachRequest = db.DBEachRequest

Internal aliases for db capability types so runtime code (and tests) can keep referring to short names that match the public vibes facade.

type DBFindRequest

type DBFindRequest = db.DBFindRequest

Internal aliases for db capability types so runtime code (and tests) can keep referring to short names that match the public vibes facade.

type DBQueryRequest

type DBQueryRequest = db.DBQueryRequest

Internal aliases for db capability types so runtime code (and tests) can keep referring to short names that match the public vibes facade.

type DBSumRequest

type DBSumRequest = db.DBSumRequest

Internal aliases for db capability types so runtime code (and tests) can keep referring to short names that match the public vibes facade.

type DBUpdateRequest

type DBUpdateRequest = db.DBUpdateRequest

Internal aliases for db capability types so runtime code (and tests) can keep referring to short names that match the public vibes facade.

type Database

type Database = db.Database

Internal aliases for db capability types so runtime code (and tests) can keep referring to short names that match the public vibes facade.

type DatabaseReader

type DatabaseReader = db.DatabaseReader

Internal aliases for db capability types so runtime code (and tests) can keep referring to short names that match the public vibes facade.

type DatabaseWriter

type DatabaseWriter = db.DatabaseWriter

Internal aliases for db capability types so runtime code (and tests) can keep referring to short names that match the public vibes facade.

type DestructureElement added in v0.60.0

type DestructureElement = ast.DestructureElement

type DestructureTarget added in v0.60.0

type DestructureTarget = ast.DestructureTarget

type Duration

type Duration = value.Duration

Internal aliases for the value package types so runtime code can keep referring to short names (Value, Money, KindInt, NewNil, etc.) without repeating the value. prefix everywhere. These mirror the public re-exports in vibes/value_alias.go and exist purely to keep the runtime sources readable after the move out of package vibes.

type Engine

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

Engine executes Vibescript programs with deterministic limits.

func MustNewEngine

func MustNewEngine(cfg Config) *Engine

MustNewEngine constructs an Engine or panics if the config is invalid.

func NewEngine

func NewEngine(cfg Config) (*Engine, error)

NewEngine constructs an Engine with sane defaults and registers built-ins.

func (*Engine) Builtins

func (e *Engine) Builtins() map[string]Value

Builtins returns a copy of the registered builtin map.

func (*Engine) ClearModuleCache

func (e *Engine) ClearModuleCache() int

ClearModuleCache drops all cached modules and returns the number of entries removed. Long-running hosts can call this between script runs to force fresh module reloads.

func (*Engine) Compile

func (e *Engine) Compile(source string) (*Script, error)

func (*Engine) CompileSnippet added in v0.60.0

func (e *Engine) CompileSnippet(source, entrypoint string) (*Script, error)

CompileSnippet compiles source as an inline snippet. Top-level declarations remain top-level, while executable top-level statements are moved into a synthetic entrypoint function so callers can invoke the snippet through the same Script.Call contract as ordinary scripts.

func (*Engine) ConfigSummary

func (e *Engine) ConfigSummary() string

ConfigSummary provides a human-readable description of the interpreter limits.

func (*Engine) Execute

func (e *Engine) Execute(ctx context.Context, script string) error

Execute compiles the provided source ensuring it is valid under current config.

func (*Engine) MaxSourceBytes added in v0.60.0

func (e *Engine) MaxSourceBytes() int

MaxSourceBytes reports the effective source-size limit, in bytes, applied before parsing. The value reflects the configured limit after defaults are resolved, so callers can reject oversized inputs before reading them.

func (*Engine) RegisterBuiltin

func (e *Engine) RegisterBuiltin(name string, fn BuiltinFunc)

RegisterBuiltin registers a callable global available to scripts.

func (*Engine) RegisterBuiltinWithSignature added in v0.60.0

func (e *Engine) RegisterBuiltinWithSignature(name string, fn BuiltinFunc, sig Signature) error

RegisterBuiltinWithSignature registers a callable global that publishes an opt-in static contract: the checker validates known arguments and infers the declared result, and the same contract is enforced at runtime. When the name replaces a core builtin, the published signature supersedes the core contract; registering with RegisterBuiltin instead keeps the callable fully dynamic.

func (*Engine) RegisterZeroArgBuiltin

func (e *Engine) RegisterZeroArgBuiltin(name string, fn BuiltinFunc)

RegisterZeroArgBuiltin registers a builtin that can be invoked without arguments or parentheses.

type EnumDef

type EnumDef struct {
	Name         string
	Members      map[string]*EnumValueDef
	MembersByKey map[string]*EnumValueDef
	Order        []string
	// contains filtered or unexported fields
}

EnumDef represents a user-defined enumeration with named members.

func EnumOf

func EnumOf(v Value) *EnumDef

EnumOf returns the *EnumDef stored in v, or nil.

func (*EnumDef) ValueEnumMarker

func (*EnumDef) ValueEnumMarker()

type EnumMemberStmt

type EnumMemberStmt = ast.EnumMemberStmt

type EnumStmt

type EnumStmt = ast.EnumStmt

type EnumValueDef

type EnumValueDef struct {
	Enum   *EnumDef
	Name   string
	Symbol string
	Index  int
}

EnumValueDef represents a single member within an EnumDef.

func EnumValueOf

func EnumValueOf(v Value) *EnumValueDef

EnumValueOf returns the *EnumValueDef stored in v, or nil.

func (*EnumValueDef) ValueEnumValueMarker

func (*EnumValueDef) ValueEnumValueMarker()

type Env

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

Env represents a lexical scope that maps variable names to values.

Bindings live in two stores: inline holds small normal script scopes without a map allocation, values holds larger normal script scopes, and statics holds bindings whose deep size never changes after definition (builtins, per-call function clones). Statics are stored separately so memory-quota estimation can account for them in O(1) through the staticBytes counter instead of re-walking every binding on each check -- the root env's builtin set dominated estimation cost otherwise.

func (*Env) Assign

func (e *Env) Assign(name string, val Value) bool

Assign updates an existing variable in the nearest enclosing scope. Names not bound anywhere are defined in the outermost mutable scope, and names found in a frozen scope rebind in the nearest mutable scope below it, so engine-shared bindings are never written.

func (*Env) CloneShallow

func (e *Env) CloneShallow() *Env

CloneShallow returns a copy of the environment with the same parent and a shallow copy of its bindings.

func (*Env) Define

func (e *Env) Define(name string, val Value)

Define binds a new variable in the current scope.

func (*Env) DefineStatic added in v0.40.0

func (e *Env) DefineStatic(name string, val Value)

DefineStatic binds a variable whose deep size is fixed at definition time, keeping it out of the per-check estimation walk.

func (*Env) Get

func (e *Env) Get(name string) (Value, bool)

Get looks up a variable by name, traversing parent scopes if needed.

func (*Env) PredeclareAssignmentLocal added in v0.60.0

func (e *Env) PredeclareAssignmentLocal(name string)

func (*Env) PredeclareLocal added in v0.60.0

func (e *Env) PredeclareLocal(name string)

type EqualityContext added in v0.60.0

type EqualityContext = value.EqualityContext

Internal aliases for the value package types so runtime code can keep referring to short names (Value, Money, KindInt, NewNil, etc.) without repeating the value. prefix everywhere. These mirror the public re-exports in vibes/value_alias.go and exist purely to keep the runtime sources readable after the move out of package vibes.

type EventPublishRequest

type EventPublishRequest = events.PublishRequest

Internal aliases for events capability types so runtime code (and tests) can keep referring to short names that match the public vibes facade.

type EventPublisher

type EventPublisher = events.Publisher

Internal aliases for events capability types so runtime code (and tests) can keep referring to short names that match the public vibes facade.

type Execution

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

Execution holds the runtime state for a single script evaluation.

func (*Execution) CallBlock

func (exec *Execution) CallBlock(block Value, args []Value) (Value, error)

CallBlock invokes a block value with the provided arguments. This is the public entry point for capability adapters that need to call user-supplied blocks (e.g. db.each, db.tx).

It is a host boundary: the arguments come from Go code that may retain their backing, and the return value is script state the host must not hold live, so both directions cross as independent values (#1210) unless the invoking builtin declared itself non-retaining. Native builtins drive blocks through the internal paths and pay none of this.

func (*Execution) Context

func (exec *Execution) Context() context.Context

Context returns the execution's bound context. Capability adapters that have been carved into sibling packages (vibes/capability/...) rely on it to forward cancellation and request-scoped values to host callbacks without reaching into unexported runtime fields.

func (*Execution) Step

func (exec *Execution) Step() error

Step accounts for one interpreter step against quota and memory limits and returns the deadline error when the script's context has been canceled. Capability adapters call it inside per-row loops so long-running host callbacks honor the same budget as in-script work.

type ExprStmt

type ExprStmt = ast.ExprStmt

type Expression

type Expression = ast.Expression

type FloatLiteral

type FloatLiteral = ast.FloatLiteral

type ForStmt

type ForStmt = ast.ForStmt

type FunctionStmt

type FunctionStmt = ast.FunctionStmt

type HashEntry added in v0.60.0

type HashEntry = value.HashEntry

Internal aliases for the value package types so runtime code can keep referring to short names (Value, Money, KindInt, NewNil, etc.) without repeating the value. prefix everywhere. These mirror the public re-exports in vibes/value_alias.go and exist purely to keep the runtime sources readable after the move out of package vibes.

type HashLiteral

type HashLiteral = ast.HashLiteral

type HashPair

type HashPair = ast.HashPair

type Identifier

type Identifier = ast.Identifier

type IfExpr added in v0.60.0

type IfExpr = ast.IfExpr

type IfExprBranch added in v0.60.0

type IfExprBranch = ast.IfExprBranch

type IfStmt

type IfStmt = ast.IfStmt

type IndexExpr

type IndexExpr = ast.IndexExpr

type Instance

type Instance struct {
	Class *ClassDef
	Ivars map[string]Value
}

Instance represents a runtime instance of a ClassDef with its own instance variables.

func InstanceOf

func InstanceOf(v Value) *Instance

InstanceOf returns the *Instance stored in v, or nil.

func (*Instance) ValueInstanceMarker

func (*Instance) ValueInstanceMarker()

type IntegerLiteral

type IntegerLiteral = ast.IntegerLiteral

type InterpolatedString

type InterpolatedString = ast.InterpolatedString

type InterpolatedSymbol added in v0.60.0

type InterpolatedSymbol = ast.InterpolatedSymbol

type IvarExpr

type IvarExpr = ast.IvarExpr

type JobQueue

type JobQueue = jobqueue.JobQueue

Internal aliases for jobqueue capability types so runtime code (and tests) can keep referring to short names that match the public vibes facade.

type JobQueueEnqueueOptions

type JobQueueEnqueueOptions = jobqueue.JobQueueEnqueueOptions

Internal aliases for jobqueue capability types so runtime code (and tests) can keep referring to short names that match the public vibes facade.

type JobQueueJob

type JobQueueJob = jobqueue.JobQueueJob

Internal aliases for jobqueue capability types so runtime code (and tests) can keep referring to short names that match the public vibes facade.

type JobQueueRetryRequest

type JobQueueRetryRequest = jobqueue.JobQueueRetryRequest

Internal aliases for jobqueue capability types so runtime code (and tests) can keep referring to short names that match the public vibes facade.

type JobQueueWithRetry

type JobQueueWithRetry = jobqueue.JobQueueWithRetry

Internal aliases for jobqueue capability types so runtime code (and tests) can keep referring to short names that match the public vibes facade.

type KeywordArg

type KeywordArg = ast.KeywordArg

type MemberContract added in v0.60.0

type MemberContract struct {
	// Receiver is the runtime receiver kind providing the member, or
	// "universal" for the Object-level fallback helpers every value
	// answers.
	Receiver string
	// Name is the canonical member name; Aliases resolve to the same
	// builtin under the same contract.
	Name    string
	Aliases []string
	// Params describes the positional parameters; Variadic reports an
	// unbounded tail beyond them.
	Params   []MemberParam
	Variadic bool
	// TakesBlock reports whether the member consumes a block argument.
	TakesBlock bool
	// AutoInvoke reports whether a bare member read invokes the builtin.
	AutoInvoke bool
	// ValueMember reports a member exposed as a direct value rather than
	// a callable: reading it yields Result and calling it is not part of
	// the contract.
	ValueMember bool
	// Result is the rendered invariant result type; empty when unknown.
	Result string
	// Effect is the member's declared receiver effect: "pure",
	// "mutates-receiver", or "unknown".
	Effect string
	// MutatesReceiver reports whether a call may modify the receiver in
	// place.
	//
	// Deprecated: use Effect, which also distinguishes pure members from
	// unclassified ones.
	MutatesReceiver bool
}

MemberContract is the exported view of one registered builtin member contract, for editor tooling such as LSP completion.

func MemberContracts added in v0.60.0

func MemberContracts() []MemberContract

MemberContracts returns the registered builtin member contracts for editor tooling, ordered by receiver kind, then name, with the universal contracts last. The returned slices are copies; callers may mutate them freely.

type MemberExpr

type MemberExpr = ast.MemberExpr

type MemberParam added in v0.60.0

type MemberParam struct {
	// Name is the display name used in rendered signatures.
	Name string
	// Type is the rendered parameter type; empty when undeclared.
	Type string
	// Optional reports whether the call may omit the parameter.
	Optional bool
}

MemberParam is one positional parameter of an exported member contract.

type Money

type Money = value.Money

Internal aliases for the value package types so runtime code can keep referring to short names (Value, Money, KindInt, NewNil, etc.) without repeating the value. prefix everywhere. These mirror the public re-exports in vibes/value_alias.go and exist purely to keep the runtime sources readable after the move out of package vibes.

type NextStmt

type NextStmt = ast.NextStmt

type NilLiteral

type NilLiteral = ast.NilLiteral

type Node

type Node = ast.Node

type ObjectTag added in v0.60.0

type ObjectTag = value.ObjectTag

ObjectTag records what an attribute bag is, for the few bags the runtime builds to stand for something specific.

type Param

type Param = ast.Param

type ParamKind added in v0.60.0

type ParamKind = ast.ParamKind

type ParseIssue added in v0.50.0

type ParseIssue struct {
	Pos     Position
	End     Position
	Message string
}

ParseIssue is one structured parse failure extracted from a Compile error. Pos is the 1-indexed position where the issue starts; End is the exclusive end of the offending token, or the zero Position when the parser could not determine a span. Message carries the bare error text without the position prefix or rendered code frame.

func ParseIssues added in v0.50.0

func ParseIssues(err error) []ParseIssue

ParseIssues extracts the structured parse failures carried by a Compile error, in source order. It returns nil for nil errors and for errors that carry no parse positions (such as size-limit or duplicate top-level name failures).

type Position

type Position = source.Position

Position is an internal alias for source.Position so runtime code can use the short name. AST and other internal aliases below mirror the vibes facade re-exports.

type Program

type Program = ast.Program

type PropertyDecl

type PropertyDecl = ast.PropertyDecl

type QuotaProfile added in v0.60.0

type QuotaProfile struct {
	Name             string
	StepQuota        int
	MemoryQuotaBytes int
	RecursionLimit   int
}

QuotaProfile is a named bundle of the execution quotas: step, memory, and recursion. Profiles let a host or the CLI select a coherent budget by name instead of tuning each quota independently. A profile's quota values use the same conventions as Config: a positive value is an explicit limit and Unlimited disables that quota.

The ladder runs low -> medium -> high -> xhigh. The lower rungs model a constrained embedded sandbox budget; xhigh means "run it like a normal interpreter" — unlimited steps and memory. No profile leaves recursion uncapped, deliberately: the interpreter recurses on the host Go stack, so an unbounded recursion would crash the process with an uncatchable stack overflow instead of a clean "recursion depth exceeded" error. Every profile therefore keeps a finite recursion cap, high enough to be irrelevant to any real program yet low enough to fail cleanly on runaway recursion.

func QuotaProfileByName added in v0.60.0

func QuotaProfileByName(name string) (QuotaProfile, bool)

QuotaProfileByName returns the profile with the given name, matched case-insensitively, and reports whether one was found.

func (QuotaProfile) ApplyTo added in v0.60.0

func (p QuotaProfile) ApplyTo(cfg *Config)

ApplyTo sets every quota field on cfg from the profile, leaving all other Config fields untouched. Callers layer explicit per-quota overrides on top after applying a profile. A quota added to QuotaProfile must be copied here too, or an embedder selecting a profile silently keeps the Config default for it; TestQuotaProfileApplyTo enforces that.

type RaiseStmt

type RaiseStmt = ast.RaiseStmt

type Range

type Range = value.Range

Internal aliases for the value package types so runtime code can keep referring to short names (Value, Money, KindInt, NewNil, etc.) without repeating the value. prefix everywhere. These mirror the public re-exports in vibes/value_alias.go and exist purely to keep the runtime sources readable after the move out of package vibes.

type RangeExpr

type RangeExpr = ast.RangeExpr

type RegexLiteral added in v0.60.0

type RegexLiteral = ast.RegexLiteral

type RescueClause added in v0.60.0

type RescueClause = ast.RescueClause

type RescueExpr added in v0.60.0

type RescueExpr = ast.RescueExpr

type RetryStmt added in v0.60.0

type RetryStmt = ast.RetryStmt

type ReturnStmt

type ReturnStmt = ast.ReturnStmt

type RuntimeError

type RuntimeError struct {
	Type      string
	Message   string
	CodeFrame string
	Frames    []StackFrame
}

RuntimeError represents a Vibescript runtime error with a call stack and source context.

func (*RuntimeError) Error

func (re *RuntimeError) Error() string

Error returns the error message with a code frame and formatted stack trace.

func (*RuntimeError) Unwrap

func (re *RuntimeError) Unwrap() error

Unwrap returns nil to satisfy the error unwrapping interface. RuntimeError is a terminal error that wraps the original error message but not the error itself.

type ScopeExpr

type ScopeExpr = ast.ScopeExpr

type Script

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

Script represents a parsed Vibescript module ready for execution.

func CompileSnippetWithProgram added in v0.60.0

func CompileSnippetWithProgram(e *Engine, source, entrypoint string) (*Script, *ast.Program, []error, error)

CompileSnippetWithProgram compiles source as an inline snippet and returns the parsed program from the same parser pass. The returned program reflects the user's source; only the compiled script receives the synthetic entrypoint.

func CompileWithProgram added in v0.60.0

func CompileWithProgram(e *Engine, source string) (*Script, *ast.Program, []error, error)

CompileWithProgram compiles source and returns the parsed program from the same parser pass. It is intended for internal tooling paths that need both diagnostics and navigation data without reparsing clean source.

func (*Script) Call

func (s *Script) Call(ctx context.Context, name string, args []Value, opts CallOptions) (Value, error)

func (*Script) CheckOrderIndependentWarnings added in v0.60.0

func (s *Script) CheckOrderIndependentWarnings() []CheckWarning

CheckOrderIndependentWarnings returns the whole-script check warnings that hold regardless of which function runs first or what state earlier calls established: undefined value/function names and typed block parameters contradicted by literal receivers. Hosts that check functions outside any entrypoint execution order use it where state-sensitive warnings (for example a type annotation that resolves only after a require in the entrypoint runs) would misfire.

The pass checks against empty CallOptions, so hosts that inject Globals or Capabilities should prefer CheckWarningsWithOptions with their real options: free names that only those options bind are reported here.

func (*Script) CheckWarnings added in v0.60.0

func (s *Script) CheckWarnings() []CheckWarning

CheckWarnings returns statically checkable contract issues for the compiled script. It reports only facts that are known from the AST and compiled script metadata; dynamic calls remain runtime-checked.

func (*Script) CheckWarningsForCall added in v0.60.0

func (s *Script) CheckWarningsForCall(name string, args []Value, opts CallOptions) []CheckWarning

CheckWarningsForCall returns statically checkable contract issues for a single function call, including host-supplied arguments and keywords.

func (*Script) CheckWarningsForFunction added in v0.60.0

func (s *Script) CheckWarningsForFunction(name string) []CheckWarning

CheckWarningsForFunction returns statically checkable contract issues for the execution path of a single function call.

func (*Script) CheckWarningsForFunctionWithOptions added in v0.60.0

func (s *Script) CheckWarningsForFunctionWithOptions(name string, opts CallOptions) []CheckWarning

CheckWarningsForFunctionWithOptions returns statically checkable contract issues for a single function call using the same host globals that Call would receive.

func (*Script) CheckWarningsWithOptions added in v0.60.0

func (s *Script) CheckWarningsWithOptions(opts CallOptions) []CheckWarning

CheckWarningsWithOptions returns statically checkable contract issues using the same host globals that a later Call would receive.

func (*Script) CheckedCall added in v0.60.0

func (s *Script) CheckedCall(ctx context.Context, name string, args []Value, opts CallOptions) (Value, []CheckWarning, error)

CheckedCall statically checks the exact call — the same function, argument values, and options a Call would receive — and executes it only when the checker reports no diagnostics. The returned warnings are the static gate: when non-empty, the script did not run and the error is nil. A nil warning slice with a non-nil error is a runtime failure from the executed call.

Both phases receive identical inputs: the static phase resolves the same host globals and capability surfaces that the call binds, so a script cannot pass the gate under one contract and execute under another. Capability adapters are bound in each phase with the same adapters and options; adapters are expected to expose the same surface on every bind.

The ordinary Call API stays gradual: CheckedCall is the opt-in gate for deployment pipelines and untrusted-script boundaries where a provable contradiction should block execution entirely.

func (*Script) Classes

func (s *Script) Classes() []*ClassDef

Classes returns compiled classes in deterministic name order.

func (*Script) Enums

func (s *Script) Enums() []*EnumDef

Enums returns compiled enums in deterministic name order.

func (*Script) Function

func (s *Script) Function(name string) (*ScriptFunction, bool)

Function looks up a compiled function by name.

func (*Script) Functions

func (s *Script) Functions() []*ScriptFunction

Functions returns compiled functions in deterministic name order.

type ScriptFunction

type ScriptFunction struct {
	Name         string
	Params       []Param
	ReturnTy     *TypeExpr
	Body         []Statement
	Pos          Position
	Env          *Env
	Exported     bool
	Private      bool
	Protected    bool
	Accessor     functionAccessorKind
	AccessorName string
	// contains filtered or unexported fields
}

ScriptFunction represents a user-defined function within a Vibescript module.

func FunctionOf

func FunctionOf(v Value) *ScriptFunction

FunctionOf returns the *ScriptFunction stored in v, or nil.

func (*ScriptFunction) ValueFunctionMarker

func (*ScriptFunction) ValueFunctionMarker()

type Signature added in v0.60.0

type Signature struct {
	// Params declares the positional parameters in order. Optional
	// parameters must trail the required ones.
	Params []SignatureParam
	// Result is the invariant result type spelling; empty keeps the result
	// unknown to the checker.
	Result string
	// AcceptsBlock permits a literal or forwarded block argument. The block
	// is passed through to the builtin unvalidated.
	AcceptsBlock bool
}

Signature is the opt-in static contract a host callable publishes to the checker. Type spellings use the script annotation grammar ("int", "array<string>", "{ name: string }", "money | nil"); an empty spelling leaves that slot unknown. A published signature is also enforced at runtime, so the checker and the boundary can never disagree.

type SignatureParam added in v0.60.0

type SignatureParam struct {
	// Name labels the parameter in diagnostics.
	Name string
	// Type is the annotation spelling validated at the boundary; empty
	// leaves the parameter unknown.
	Type string
	// Optional marks a parameter the caller may omit.
	Optional bool
}

SignatureParam declares one positional parameter of a host callable.

type SplatArg added in v0.60.0

type SplatArg = ast.SplatArg

type StackFrame

type StackFrame struct {
	Function string
	Pos      Position
	// Source is the module path for module-backed frames. It is empty for
	// root scripts compiled directly by an embedder.
	Source string
}

StackFrame represents a single entry in a runtime error's call stack.

type Statement

type Statement = ast.Statement

type StringExpr

type StringExpr = ast.StringExpr

type StringLiteral

type StringLiteral = ast.StringLiteral

type StringPart

type StringPart = ast.StringPart

type StringText

type StringText = ast.StringText

type SymbolLiteral

type SymbolLiteral = ast.SymbolLiteral

type Token

type Token = ast.Token

type TokenType

type TokenType = ast.TokenType

type TryStmt

type TryStmt = ast.TryStmt

type TypeExpr

type TypeExpr = ast.TypeExpr

type TypeKind

type TypeKind = ast.TypeKind

type TypeLiteral added in v0.60.0

type TypeLiteral = ast.TypeLiteral

type UnaryExpr

type UnaryExpr = ast.UnaryExpr

type UntilStmt

type UntilStmt = ast.UntilStmt

type Value

type Value = value.Value

Internal aliases for the value package types so runtime code can keep referring to short names (Value, Money, KindInt, NewNil, etc.) without repeating the value. prefix everywhere. These mirror the public re-exports in vibes/value_alias.go and exist purely to keep the runtime sources readable after the move out of package vibes.

func DeclareNonMutating added in v0.60.0

func DeclareNonMutating(v Value) Value

DeclareNonMutating records a builtin's promise that no invocation of it writes to any container reachable from its receiver, arguments, keyword arguments, block, or from any execution's roots, and returns it. Allocating a container and filling it in is not such a write; the promise covers only state something else can already reach.

This is a safety promise, not a performance hint. The runtime stops invalidating its memoized memory-estimator walk around calls to a builtin that makes it, so a declaration that is not true leaves an execution's memory accounting missing whatever the builtin changed, and the execution then allocates past its configured MemoryQuotaBytes. Declare nothing and the builtin keeps today's conservative behavior, which is slower and correct.

The promise is between an embedder and itself. A host builtin already runs arbitrary Go in the embedding process and can allocate without bound today, so declaring grants no capability a host did not have, and script code can neither read the declaration nor reach it. What it does do is disable a backstop the host is then responsible for honoring.

func DeclareNonRetaining added in v0.60.0

func DeclareNonRetaining(v Value) Value

DeclareNonRetaining records a builtin's promise that no invocation of it stores, anywhere that outlives the invocation, a reference to any Value it receives or returns, or to any container reachable from one, and returns it. Package-level variables, adapter fields, closure captures, channels, caches and anything handed to another goroutine all count as outliving it, and keeping a container reached through an argument counts as keeping the argument.

Host-driven dispatch consults this promise: a builtin that has not made it has its collection inputs and result published, so a later script write copies instead of mutating a wrapper the host retained.

It is stated as a safety promise rather than a hint because of what it will mean once consulted: an execution calling a builtin that makes it keeps accounting for memory on its own, so an untrue declaration would let a container the host kept be mutated later without that execution observing it, and its quota would then admit allocations it should have refused.

It is a separate promise from DeclareNonMutating and neither implies the other.

func MarkHostBuiltin added in v0.60.0

func MarkHostBuiltin(v Value) Value

MarkHostBuiltin marks a builtin as one whose Go body the runtime did not write, and returns it. The vibes facade applies it to every builtin it hands a host, which is the only way a host can make one: internal/runtime is not importable from outside this module's own packages.

Marking at construction rather than where a builtin is published is what makes it complete. Registration and capability binding only see the callables reachable at that moment, so one a host produces later -- a factory'"'"'s result, a capability method returning a callable, a builtin returning a builtin -- stayed unmarked, and dispatch gave its frame no claim over the arrays it walks. A block calling pop inside such a frame cleared a slot it had not reached, and walking [1, 2, 3] yielded 1, 2, nil.

func NewArray

func NewArray(a []Value) Value

NewArray returns an array Value.

func NewAutoBuiltin

func NewAutoBuiltin(name string, fn BuiltinFunc) Value

NewAutoBuiltin returns a builtin function Value that auto-invokes without parentheses.

func NewBlock

func NewBlock(params []Param, body []Statement, env *Env) Value

NewBlock returns a block (closure) Value.

func NewBool

func NewBool(b bool) Value

NewBool returns a boolean Value.

func NewBuiltin

func NewBuiltin(name string, fn BuiltinFunc) Value

NewBuiltin returns a builtin function Value.

func NewCapturingBuiltin added in v0.60.0

func NewCapturingBuiltin(name string, fn BuiltinFunc, captured ...Value) Value

NewCapturingBuiltin returns a builtin function Value whose Fn closes over the given runtime values. The captured values are recorded on the builtin so the memory estimator charges their payloads while the builtin is reachable, keeping closures such as a bound predicate's receiver inside the memory quota.

func NewClass

func NewClass(def *ClassDef) Value

NewClass returns a class definition Value.

func NewDuration

func NewDuration(d Duration) Value

NewDuration returns a duration Value.

func NewEnum

func NewEnum(def *EnumDef) Value

NewEnum returns an enum definition Value.

func NewEnumValue

func NewEnumValue(def *EnumValueDef) Value

NewEnumValue returns an enum member Value.

func NewFloat

func NewFloat(f float64) Value

NewFloat returns a floating-point Value.

func NewFunction

func NewFunction(fn *ScriptFunction) Value

NewFunction returns a script-defined function Value.

func NewHash

func NewHash(h map[string]Value) Value

NewHash returns a hash (map) Value.

func NewHashWithCapacity added in v0.60.0

func NewHashWithCapacity(capacity int) Value

NewHashWithCapacity returns an empty hash pre-sized for capacity entries.

func NewInstance

func NewInstance(inst *Instance) Value

NewInstance returns a class instance Value.

func NewInt

func NewInt(i int64) Value

NewInt returns an integer Value.

func NewMoney

func NewMoney(m Money) Value

NewMoney returns a money Value.

func NewNil

func NewNil() Value

NewNil returns a nil Value.

func NewObject

func NewObject(attrs map[string]Value) Value

NewObject returns an object Value with the given attributes.

func NewRange

func NewRange(r Range) Value

NewRange returns a range Value.

func NewRegex added in v0.60.0

func NewRegex(r value.Regex) Value

NewRegex returns a regex Value.

func NewShape added in v0.60.0

func NewShape(ty *TypeExpr) Value

NewShape returns a first-class shape value wrapping an annotation type (ADR-004 expression-position shape literals). The payload is the shared, immutable *TypeExpr from the AST.

func NewString

func NewString(s string) Value

NewString returns a string Value.

func NewSymbol

func NewSymbol(name string) Value

NewSymbol returns a symbol Value.

func NewTaggedObject added in v0.60.0

func NewTaggedObject(attrs map[string]Value, tag ObjectTag, stringForm string) Value

NewTaggedObject returns an attribute bag carrying provenance and the string form it publishes, fixed at construction so mutating the entries cannot change what it renders.

func NewTime

func NewTime(t time.Time) Value

NewTime returns a time Value.

func NewTypedBuiltin added in v0.60.0

func NewTypedBuiltin(name string, fn BuiltinFunc, sig Signature) (Value, error)

NewTypedBuiltin builds a host builtin Value that publishes sig to the checker and validates calls against it at runtime. Keyword arguments are rejected: signatures describe positional contracts only. The returned value can be registered as an engine builtin, passed as a call-option global, or exposed as a capability method.

type ValueKind

type ValueKind = value.ValueKind

Internal aliases for the value package types so runtime code can keep referring to short names (Value, Money, KindInt, NewNil, etc.) without repeating the value. prefix everywhere. These mirror the public re-exports in vibes/value_alias.go and exist purely to keep the runtime sources readable after the move out of package vibes.

type WhileStmt

type WhileStmt = ast.WhileStmt

type YieldExpr

type YieldExpr = ast.YieldExpr

Jump to

Keyboard shortcuts

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