eval

package
v0.14.3 Latest Latest
Warning

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

Go to latest
Published: May 2, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Builtins = make(map[string]*BuiltinFunc)

Builtins is the registry of built-in functions

Functions

func ArgTypeMismatch

func ArgTypeMismatch(builtin string, expected string, got string) error

ArgTypeMismatch creates a helpful error when an argument has the wrong type

Examples:

ArgTypeMismatch("_str_len", "string", "int")
→ "Runtime error in _str_len: expected string, got int"

ArgTypeMismatch("_list_concat", "list", "string")
→ "Runtime error in _list_concat: expected list, got string
   Hint: Use ++ for list concatenation, not string concatenation"

func EmptyListError

func EmptyListError(builtin string) error

EmptyListError creates an error for operations on empty lists

func IndexOutOfBounds

func IndexOutOfBounds(builtin string, index int, length int) error

IndexOutOfBounds creates an error for invalid list/string indexing

func InvalidOperation

func InvalidOperation(builtin string, reason string) error

InvalidOperation creates an error for operations that can't be performed

func MapKey

func MapKey(v Value) (string, error)

MapKey returns a canonical, collision-free string key for Go map lookup. Distinct from String() which is for display only. Supported key types: int, string, bool. Returns error for unsupported types.

func NewRuntimeError

func NewRuntimeError(code, message string, pos interface{}) error

NewRuntimeError creates a runtime error with structured information

Types

type ArrayValue

type ArrayValue struct {
	Elements []Value
}

ArrayValue represents an array with O(1) indexed access

func (*ArrayValue) Get

func (a *ArrayValue) Get(i int64) (Value, bool)

Get returns the element at index i, or nil if out of bounds

func (*ArrayValue) Set

func (a *ArrayValue) Set(i int64, v Value) *ArrayValue

Set returns a new array with the element at index i replaced

func (*ArrayValue) String

func (a *ArrayValue) String() string

func (*ArrayValue) Type

func (a *ArrayValue) Type() string

type BoolValue

type BoolValue struct {
	Value bool
}

BoolValue represents a boolean value

func (*BoolValue) String

func (b *BoolValue) String() string

func (*BoolValue) Type

func (b *BoolValue) Type() string

type BudgetEnforcer

type BudgetEnforcer interface {
	// WithBudgetLimits creates a new context with the given budget limits
	// Returns the new context that should be used for evaluation
	WithBudgetLimits(limits map[string]int) interface{}
}

BudgetEnforcer is implemented by effect contexts that support budget enforcement This interface avoids import cycles between eval and effects packages

type BuiltinError

type BuiltinError struct {
	Builtin  string // Name of the builtin that failed
	Expected string // Expected type(s)
	Got      string // Actual type received
	Hint     string // Helpful suggestion for fixing
}

BuiltinError represents a runtime error from a builtin function

func (*BuiltinError) Error

func (e *BuiltinError) Error() string

type BuiltinFunc

type BuiltinFunc struct {
	Name    string
	Impl    interface{} // The actual Go function
	NumArgs int         // Expected number of arguments
	IsPure  bool        // Whether the function is pure
}

BuiltinFunc represents a built-in function

type BuiltinFunction

type BuiltinFunction struct {
	Name string
	Fn   func(args []Value) (Value, error)
}

BuiltinFunction represents a built-in function

func (*BuiltinFunction) String

func (b *BuiltinFunction) String() string

func (*BuiltinFunction) Type

func (b *BuiltinFunction) Type() string

type BytesValue

type BytesValue struct {
	Value    []byte
	Filename string // original filename from upload (empty if not from upload)
	MimeType string // detected or declared MIME type (empty if unknown)
}

BytesValue represents raw binary data (e.g., file content, uploads).

func (*BytesValue) String

func (b *BytesValue) String() string

func (*BytesValue) Type

func (b *BytesValue) Type() string

type ConstructorClosure

type ConstructorClosure struct {
	TypeName string // The ADT name (e.g., "Option")
	CtorName string // Constructor name (e.g., "Some")
	Arity    int    // Number of fields expected
}

ConstructorClosure represents an ADT constructor that takes arguments When applied, it creates a TaggedValue with the provided fields. This is used in the test harness to inject constructor bindings.

func (*ConstructorClosure) Apply

func (c *ConstructorClosure) Apply(args []Value) (*TaggedValue, error)

Apply creates a TaggedValue from the provided arguments

func (*ConstructorClosure) String

func (c *ConstructorClosure) String() string

func (*ConstructorClosure) Type

func (c *ConstructorClosure) Type() string

type ContractChecker

type ContractChecker interface {
	CheckRequires(cond bool, msg, location string) error
	CheckEnsures(cond bool, msg, location string) error
	IsContractCheckingEnabled() bool
}

ContractChecker is an interface for checking contract violations via EffContext M-VERIFY-CONTRACTS: Used to integrate with the effects.ContractContext

type ContractSpec

type ContractSpec struct {
	Kind     string      // "requires" or "ensures"
	Expr     interface{} // The contract expression (ast.Expr or core.CoreExpr)
	Message  string      // Auto-generated message from source (e.g., "limit > 0")
	Location string      // Source location for error messages (e.g., "api.ail:15")
}

ContractSpec represents a requires/ensures contract for a function (M-VERIFY-CONTRACTS)

type CoreEvaluator

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

CoreEvaluator evaluates Core AST programs after dictionary elaboration

func NewCoreEvaluator

func NewCoreEvaluator() *CoreEvaluator

NewCoreEvaluator creates a new core evaluator without a registry (for REPL)

func NewCoreEvaluatorWithRegistry

func NewCoreEvaluatorWithRegistry(registry *types.DictionaryRegistry) *CoreEvaluator

NewCoreEvaluatorWithRegistry creates a new Core evaluator with dictionary support

func (*CoreEvaluator) AddDictionary

func (e *CoreEvaluator) AddDictionary(key string, dict core.DictValue)

AddDictionary adds a dictionary to the evaluator (for REPL)

func (*CoreEvaluator) CallFunction

func (e *CoreEvaluator) CallFunction(fn *FunctionValue, args []Value) (Value, error)

CallFunction calls a function value with the given arguments

This is a helper for invoking FunctionValues from outside the evaluator, such as from the module runtime when calling entrypoints.

Parameters:

  • fn: The function value to call
  • args: The arguments to pass to the function

Returns:

  • The result value from executing the function
  • An error if execution fails

func (*CoreEvaluator) CallValue

func (e *CoreEvaluator) CallValue(fn Value, arg Value) (Value, error)

CallValue calls a function value with a single argument. Unlike CallFunction, this accepts eval.Value to support both FunctionValue and BuiltinFunction. Used by M-STREAM-BIDI for invoking event handlers from Go code.

func (*CoreEvaluator) CallValueN

func (e *CoreEvaluator) CallValueN(fn Value, args []Value) (Value, error)

CallValueN calls a function value with multiple arguments. M-ITERATIVE-LIST: Used by iterative builtins (e.g., foldl) that need multi-arg callbacks.

func (*CoreEvaluator) Env

func (e *CoreEvaluator) Env() *Environment

Env returns the current environment (for module evaluation) This allows the runtime to add bindings so subsequent module-level declarations can reference earlier ones.

func (*CoreEvaluator) Eval

func (e *CoreEvaluator) Eval(expr core.CoreExpr) (Value, error)

Eval evaluates a single expression (simplified for REPL)

func (*CoreEvaluator) EvalCoreProgram

func (e *CoreEvaluator) EvalCoreProgram(prog *core.Program) (Value, error)

EvalCoreProgram evaluates a Core program

func (*CoreEvaluator) EvalLetRecBindings

func (e *CoreEvaluator) EvalLetRecBindings(letrec *core.LetRec) (map[string]Value, error)

EvalLetRecBindings evaluates a LetRec and returns its bindings without evaluating the body

This uses the same 3-phase RefCell algorithm as evalCoreLetRec to ensure proper recursion support in module code. The algorithm:

  1. Pre-allocate RefCell indirection cells for all bindings
  2. Evaluate RHS under recursive environment (lambdas safe, non-lambdas strict)
  3. Return initialized values from cells

This is called by the module runtime when loading module declarations.

func (*CoreEvaluator) Fork

func (e *CoreEvaluator) Fork() *CoreEvaluator

Fork creates a new evaluator for concurrent request handling. It shares read-only state (registry, config) but creates fresh per-request state (env, resolver, recursionDepth). This is the concurrency primitive: each HTTP request goroutine gets its own Fork.

func (*CoreEvaluator) GetEffContext

func (e *CoreEvaluator) GetEffContext() interface{}

GetEffContext returns the current effect context

Returns nil if no effect context has been set.

func (*CoreEvaluator) GetEnvironmentBindings

func (e *CoreEvaluator) GetEnvironmentBindings() map[string]Value

GetEnvironmentBindings returns all bindings in the current environment

func (*CoreEvaluator) SetCoreTypeInfo

func (e *CoreEvaluator) SetCoreTypeInfo(cti types.CoreTypeInfo)

SetCoreTypeInfo sets the type info for looking up effect budgets on closures

When set, the evaluator will extract effect budgets from function types and populate EffectBudgets on FunctionValues during closure creation.

func (*CoreEvaluator) SetDictionaryRegistry

func (e *CoreEvaluator) SetDictionaryRegistry(reg *types.DictionaryRegistry)

SetDictionaryRegistry replaces the dictionary registry. M-DX19: Used to inject derived type class instances from the pipeline.

func (*CoreEvaluator) SetEffContext

func (e *CoreEvaluator) SetEffContext(ctx interface{})

SetEffContext sets the effect context for this evaluator

The effect context provides capability grants for effect operations. It uses interface{} to avoid import cycles with the effects package.

Parameters:

  • ctx: The effect context (should be *effects.EffContext)

Example:

evaluator.SetEffContext(effCtx)

func (*CoreEvaluator) SetEnv

func (e *CoreEvaluator) SetEnv(env *Environment)

SetEnv replaces the evaluator's current environment. Used by ModuleRuntime to isolate per-module scopes (M-MODULE-SCOPE).

func (*CoreEvaluator) SetExperimentalBinopShim

func (e *CoreEvaluator) SetExperimentalBinopShim(enabled bool)

SetExperimentalBinopShim enables the experimental operator shim

func (*CoreEvaluator) SetGlobalResolver

func (e *CoreEvaluator) SetGlobalResolver(resolver GlobalResolver)

SetGlobalResolver sets the resolver for global references

func (*CoreEvaluator) SetMaxRecursionDepth

func (e *CoreEvaluator) SetMaxRecursionDepth(max int)

SetMaxRecursionDepth sets the maximum allowed recursion depth

func (*CoreEvaluator) SetResolver

func (e *CoreEvaluator) SetResolver(resolver GlobalResolver)

SetResolver sets the resolver for global references

type Environment

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

Environment represents a variable environment. Thread-safe: concurrent reads are protected by RWMutex to support serve-api's per-request evaluator forking, where module-level environments are shared (read) across goroutines while per-request environments are written to by individual goroutines.

func NewEnvironment

func NewEnvironment() *Environment

NewEnvironment creates a new environment

func (*Environment) Clone

func (e *Environment) Clone() *Environment

Clone creates a shallow copy of the environment (copies values map, shares parent)

func (*Environment) Extend

func (e *Environment) Extend(name string, value Value) *Environment

Extend creates a new child environment with a binding

func (*Environment) Get

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

Get gets a value from the environment

func (*Environment) GetAllBindings

func (e *Environment) GetAllBindings() map[string]Value

GetAllBindings returns all bindings in this environment and its parents

func (*Environment) NewChildEnvironment

func (e *Environment) NewChildEnvironment() *Environment

NewChildEnvironment creates a child environment

func (*Environment) Set

func (e *Environment) Set(name string, value Value)

Set sets a value in the environment

type ErrorValue

type ErrorValue struct {
	Message string
}

ErrorValue represents an error value

func (*ErrorValue) String

func (e *ErrorValue) String() string

func (*ErrorValue) Type

func (e *ErrorValue) Type() string

type EvalExitCode

type EvalExitCode struct {
	Code int
}

EvalExitCode is a sentinel panic value used by the exit() builtin. When panicked with this value, the runtime catches it and calls os.Exit(Code). This approach lets the evaluator unwind cleanly, flushing traces and telemetry.

type FallbackResolver

type FallbackResolver struct {
	Primary   GlobalResolver // Caller's resolver (builtins, effects)
	Secondary GlobalResolver // Function's defining resolver (constructors, module scope)
}

FallbackResolver tries the primary resolver first, then falls back to the secondary resolver. Used by M-DX-XPKG-RESOLVE to combine the caller's resolver (for builtins/effect context) with the function's defining resolver (for constructors and module-specific lookups that the caller's resolver can't see).

func (*FallbackResolver) ResolveValue

func (f *FallbackResolver) ResolveValue(ref core.GlobalRef) (Value, error)

ResolveValue tries Primary first, then Secondary on failure.

type FloatValue

type FloatValue struct {
	Value float64
}

FloatValue represents a floating-point value

func (*FloatValue) String

func (f *FloatValue) String() string

func (*FloatValue) Type

func (f *FloatValue) Type() string

type FunctionValue

type FunctionValue struct {
	Params           []string
	Body             interface{} // Can be ast.Expr, core.CoreExpr, or typedast.TypedNode
	Env              *Environment
	Resolver         GlobalResolver  // M-DX-XPKG-RESOLVE: resolver from defining module (for cross-package calls)
	Typed            bool            // Whether Body is typed
	EffectBudgets    map[string]int  // Budget max limits per effect (from @limit annotation)
	EffectMinBudgets map[string]int  // Budget min limits per effect (from @min annotation, M-DX25 M4)
	Preconditions    []*ContractSpec // requires blocks (M-VERIFY-CONTRACTS)
	Postconditions   []*ContractSpec // ensures blocks (M-VERIFY-CONTRACTS)
}

FunctionValue represents a function value

func (*FunctionValue) String

func (f *FunctionValue) String() string

func (*FunctionValue) Type

func (f *FunctionValue) Type() string

type GlobalResolver

type GlobalResolver interface {
	ResolveValue(ref core.GlobalRef) (Value, error)
}

GlobalResolver resolves global references to values

type IndirectValue

type IndirectValue struct {
	Cell *RefCell
}

IndirectValue defers to the cell at read-time Environment bindings point to IndirectValue during LetRec evaluation

func (*IndirectValue) Force

func (iv *IndirectValue) Force() (Value, error)

Force resolves the indirection, checking for initialization and cycles

func (*IndirectValue) String

func (iv *IndirectValue) String() string

func (*IndirectValue) Type

func (iv *IndirectValue) Type() string

type IntValue

type IntValue struct {
	Value int
}

IntValue represents an integer value

func (*IntValue) String

func (i *IntValue) String() string

func (*IntValue) Type

func (i *IntValue) Type() string

type ListValue

type ListValue struct {
	Elements []Value
}

ListValue represents a list of values

func (*ListValue) String

func (l *ListValue) String() string

func (*ListValue) Type

func (l *ListValue) Type() string

type MapEntry

type MapEntry struct {
	Key   Value
	Value Value
}

MapEntry stores the original key and value for a map entry

type MapValue

type MapValue struct {
	Entries map[string]*MapEntry // canonical key -> entry
}

MapValue represents an immutable hash map with O(1) lookup (copy-on-write)

func (*MapValue) Insert

func (m *MapValue) Insert(key, val Value) (*MapValue, error)

Insert returns a new map with the key-value pair added/updated. O(n) copy-on-write.

func (*MapValue) Lookup

func (m *MapValue) Lookup(key Value) (Value, bool)

Lookup returns the value for a key, or (nil, false) if not found. O(1).

func (*MapValue) Remove

func (m *MapValue) Remove(key Value) *MapValue

Remove returns a new map without the given key. O(n) copy-on-write.

func (*MapValue) Size

func (m *MapValue) Size() int

Size returns the number of entries. O(1).

func (*MapValue) String

func (m *MapValue) String() string

func (*MapValue) Type

func (m *MapValue) Type() string

type MinBudgetEnforcer

type MinBudgetEnforcer interface {
	// SetMinBudgets sets minimum usage requirements on the context's budget
	SetMinBudgets(minLimits map[string]int)
}

MinBudgetEnforcer is implemented by effect contexts that support minimum budget requirements M-DX25 M4: Minimum budgets ensure effects were actually exercised.

type MinimumChecker

type MinimumChecker interface {
	// CheckMinimums verifies all minimum requirements are met
	// Returns nil if all minimums satisfied, error otherwise
	CheckMinimums(position string) error
}

MinimumChecker is implemented by effect contexts that can verify minimum usage M-DX25 M4: Called on scope exit to ensure effects were exercised.

type RecordValue

type RecordValue struct {
	Fields map[string]Value
}

RecordValue represents a record (struct) value

func (*RecordValue) String

func (r *RecordValue) String() string

func (*RecordValue) Type

func (r *RecordValue) Type() string

type RefCell

type RefCell struct {
	Val      Value // The actual value (once initialized)
	Init     bool  // Has the value been set?
	Visiting bool  // Currently being evaluated? (for cycle detection)
}

RefCell allows self/mutual recursion via indirection Used in LetRec evaluation for function-first semantics (OCaml/Haskell style)

type ScopeCharger

type ScopeCharger interface {
	// PopScopeAndChargeCaller charges the caller context with declared semantic budgets
	// Called when restoring old context after function evaluation
	PopScopeAndChargeCaller()
}

ScopeCharger is implemented by effect contexts that support scoped budget charging M-DX25: When a scoped function returns, the caller is charged the callee's declared budget

type SimpleEvaluator

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

SimpleEvaluator for basic testing

func New

func New() *SimpleEvaluator

New creates a new evaluator with built-in functions (for compatibility)

func NewSimple

func NewSimple() *SimpleEvaluator

NewSimple creates a simple evaluator

func (*SimpleEvaluator) EvalProgram

func (e *SimpleEvaluator) EvalProgram(program *ast.Program) (Value, error)

EvalProgram evaluates a program

type StringValue

type StringValue struct {
	Value string
}

StringValue represents a string value

func (*StringValue) String

func (s *StringValue) String() string

func (*StringValue) Type

func (s *StringValue) Type() string

type TaggedValue

type TaggedValue struct {
	ModulePath string  // Module where type is defined (e.g., "std/option") - prevents ambiguity
	TypeName   string  // The ADT name (e.g., "Option")
	CtorName   string  // Constructor name (e.g., "Some", "None")
	Fields     []Value // Constructor field values
}

TaggedValue represents an ADT constructor at runtime

func (*TaggedValue) String

func (t *TaggedValue) String() string

func (*TaggedValue) Type

func (t *TaggedValue) Type() string

type TraceCollector

type TraceCollector struct {
	Entries []TraceEntry
	Enabled bool
}

TraceCollector collects execution traces for training data

type TraceEntry

type TraceEntry struct {
	CallSiteID  uint64
	FnID        uint64
	FnScheme    *types.Scheme
	CallEffects *types.Row
	Inputs      []string
	Output      string
	Seed        *int64
	VirtualTime bool
	Timestamp   int64
}

TraceEntry represents a single trace entry

type TraceRecorder

type TraceRecorder interface {
	HasTraceCollector() bool
	RecordFunctionEnter(name string, args []string)
	RecordFunctionExit(name string, result string)
}

TraceRecorder is implemented by effect contexts that support semantic trace collection. M-TRACE-EXPORT: Used to record function calls during AILANG program execution.

type TupleValue

type TupleValue struct {
	Elements []Value
}

TupleValue represents a tuple of values

func (*TupleValue) String

func (t *TupleValue) String() string

func (*TupleValue) Type

func (t *TupleValue) Type() string

type TypedEvaluator

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

TypedEvaluator evaluates TypedAST programs

func NewTypedEvaluator

func NewTypedEvaluator(trace bool, seed int, virtualTime bool) *TypedEvaluator

NewTypedEvaluator creates a new typed evaluator

func NewTypedEvaluatorWithEnv

func NewTypedEvaluatorWithEnv(env *Environment, trace bool, seed int, virtualTime bool) *TypedEvaluator

NewTypedEvaluatorWithEnv creates evaluator with existing environment

func (*TypedEvaluator) EvalTypedProgram

func (e *TypedEvaluator) EvalTypedProgram(prog *typedast.TypedProgram) (Value, error)

EvalTypedProgram evaluates a typed program

type UnitValue

type UnitValue struct{}

UnitValue represents the unit value ()

func (*UnitValue) String

func (u *UnitValue) String() string

func (*UnitValue) Type

func (u *UnitValue) Type() string

type Value

type Value interface {
	Type() string
	String() string
}

Value represents a runtime value in AILANG

func CallBuiltin

func CallBuiltin(name string, args []Value) (Value, error)

CallBuiltin calls a builtin function with the given arguments

DEPRECATED: This function is no longer used for effect-based builtins (IO, FS). Effect-based builtins now route through internal/runtime/builtins.go and the effect system for capability checking. This function is kept for backward compatibility with non-effect builtins and for internal validation.

For effect-based operations, use runtime.ModuleRuntime with EffContext instead.

Jump to

Keyboard shortcuts

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