vm

package
v1.2.2 Latest Latest
Warning

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

Go to latest
Published: Mar 15, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package vm provides the virtual machine (evaluator) for the English programming language.

The vm package is split into multiple files for better organization:

  • values.go: Value types (Value, FunctionValue, ReturnValue, BreakValue, RuntimeError)
  • environment.go: Environment struct and methods for scope management
  • evaluator.go: Evaluator struct and all eval* methods
  • operations.go: Arithmetic and comparison operations
  • conversions.go: Type conversion functions
  • helpers.go: Helper utilities

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Compare

func Compare(op string, left, right Value) (bool, error)

Compare evaluates a comparison expression and returns a boolean. Strict rules:

  • "is equal to" / "is not equal to": any two values of the SAME type
  • ordering operators: numbers only

func Equals

func Equals(left, right Value) bool

Equals performs a same-type equality check (no type coercion).

func GetType

func GetType(v Value) *types.TypeInfo

GetType returns a *types.TypeInfo describing a runtime value.

func NewRuntimeError

func NewRuntimeError(message string) error

NewRuntimeError creates a RuntimeError with a default stdlib call-stack frame.

func ToBool

func ToBool(v Value) (bool, error)

ToBool converts a Value to bool for use in conditions. With strict typing, ONLY actual boolean values are accepted. Truthy/falsy coercion of numbers and strings is not permitted.

func ToNumber

func ToNumber(v Value) (float64, error)

ToNumber attempts to convert a Value to float64. Only float64 and integer types are accepted — no implicit string→number coercion. Callers that need explicit string→number conversion must use "cast to number".

func ToString

func ToString(v Value) string

ToString converts any Value to its textual representation. This is used for display (Print/Write) and explicit "cast to text". It is NOT called automatically during arithmetic or comparisons.

Types

type ArrayValue

type ArrayValue = types.ArrayValue

ArrayValue is re-exported from vm/types for convenience within vm/.

type BreakValue

type BreakValue struct{}

BreakValue signals a loop break.

type BuiltinFunc

type BuiltinFunc func(name string, args []Value) (Value, error)

BuiltinFunc is the signature for the injected standard-library evaluator. It is called whenever a built-in function (Body == nil) is invoked.

type ContinueValue

type ContinueValue struct{}

ContinueValue signals a loop continue.

type Environment

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

Environment represents a lexical scope: variables, constants, functions, and structs.

func NewEnvironment

func NewEnvironment() *Environment

NewEnvironment creates a new root environment.

func (*Environment) Define

func (e *Environment) Define(name string, value Value, isConstant bool) error

Define declares a new variable in the current scope, inferring its type from value.

func (*Environment) DefineErrorType

func (e *Environment) DefineErrorType(name, parent string)

DefineErrorType registers a custom error type in the root environment. parent is the parent type name; pass "" for a root error type.

func (*Environment) DefineFunction

func (e *Environment) DefineFunction(name string, fn *FunctionValue)

DefineFunction registers a function in the current scope.

func (*Environment) DefineStruct

func (e *Environment) DefineStruct(name string, def *StructDefinition)

DefineStruct registers a struct definition in the current scope.

func (*Environment) DefineTyped

func (e *Environment) DefineTyped(name string, typeName string, value Value, isConstant bool) error

DefineTyped declares a new variable with an explicit type annotation. The type annotation is enforced: the initial value (if any) must match the declared type, and all subsequent assignments must also match.

func (*Environment) Get

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

Get retrieves a variable value, searching up the scope chain.

func (*Environment) GetAllFunctions

func (e *Environment) GetAllFunctions() map[string]*FunctionValue

GetAllFunctions returns a shallow copy of functions in this scope only.

func (*Environment) GetAllVariables

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

GetAllVariables returns a shallow copy of variables in this scope only.

func (*Environment) GetFunction

func (e *Environment) GetFunction(name string) (*FunctionValue, bool)

GetFunction retrieves a function searching up the scope chain.

func (*Environment) GetStruct

func (e *Environment) GetStruct(name string) (*StructDefinition, bool)

GetStruct retrieves a struct definition searching up the scope chain.

func (*Environment) GetVarType

func (e *Environment) GetVarType(name string) (types.TypeKind, bool)

GetVarType returns the declared TypeKind of a variable in the scope chain.

func (*Environment) IsConstant

func (e *Environment) IsConstant(name string) bool

IsConstant returns whether a variable is a constant (searches up the chain).

func (*Environment) IsKnownErrorType

func (e *Environment) IsKnownErrorType(name string) bool

IsKnownErrorType reports whether name is a registered custom error type.

func (*Environment) IsSubtypeOf

func (e *Environment) IsSubtypeOf(childType, parentType string) bool

IsSubtypeOf reports whether childType is the same as parentType or inherits from it. It walks the parent chain of childType until it either finds parentType or exhausts all ancestors.

func (*Environment) NewChild

func (e *Environment) NewChild() *Environment

NewChild creates a child scope that inherits from this environment.

func (*Environment) Set

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

Set assigns a new value to an existing variable, enforcing the declared type.

Assigning nothing (nil) is always permitted — it acts as a typed null.

type Evaluator

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

Evaluator executes the AST

func NewEvaluator

func NewEvaluator(env *Environment, builtinFn BuiltinFunc) *Evaluator

NewEvaluator creates a new evaluator with the given environment and optional builtin function.

func (*Evaluator) Eval

func (ev *Evaluator) Eval(node interface{}) (Value, error)

Eval evaluates an AST node

type FieldDefinition

type FieldDefinition struct {
	Name         string
	TypeInfo     *types.TypeInfo
	DefaultValue Value
}

FieldDefinition describes a single field in a struct.

type FunctionValue

type FunctionValue struct {
	Name       string
	Parameters []string
	Body       []ast.Statement
	Closure    *Environment
}

FunctionValue represents a user-defined function. It lives in vm/ (not vm/types/) because it holds a *Environment closure.

func (*FunctionValue) String

func (f *FunctionValue) String() string

type LookupTableValue

type LookupTableValue = types.LookupTableValue

LookupTableValue is re-exported from vm/types for convenience within vm/.

type ReferenceValue

type ReferenceValue struct {
	Name string
	Env  *Environment
}

ReferenceValue holds a reference to a named variable in a specific environment. Lives in vm/ because it references *Environment.

type ReturnValue

type ReturnValue struct{ Value Value }

ReturnValue wraps a function's return payload.

type RuntimeError

type RuntimeError struct {
	Message   string
	CallStack []string
	Line      int // source line where the error occurred (0 = unknown)
}

RuntimeError is a non-catchable interpreter error with an optional call stack.

func (*RuntimeError) Error

func (e *RuntimeError) Error() string

func (*RuntimeError) RuntimeCallStack

func (e *RuntimeError) RuntimeCallStack() []string

RuntimeCallStack implements the stacktraces.RuntimeError interface and returns the full call-stack slice (most-recent frame first).

func (*RuntimeError) RuntimeLine

func (e *RuntimeError) RuntimeLine() int

RuntimeLine implements the stacktraces.RuntimeError interface and returns the source line where the error occurred (0 = unknown).

func (*RuntimeError) RuntimeMessage

func (e *RuntimeError) RuntimeMessage() string

RuntimeMessage implements the stacktraces.RuntimeError interface and returns the human-readable error message without call-stack details.

type StructDefinition

type StructDefinition struct {
	Name       string
	Fields     map[string]*FieldDefinition
	Methods    map[string]*FunctionValue
	FieldOrder []string // preserves declaration order
}

StructDefinition describes a struct type declared in source code. It lives in vm/ (not vm/types/) because Methods references *FunctionValue.

type StructInstance

type StructInstance struct {
	Definition *StructDefinition
	Fields     map[string]Value
}

StructInstance is a runtime instance of a StructDefinition.

type TypeChecker

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

TypeChecker performs static type analysis on an AST before execution.

type TypeError

type TypeError struct {
	Line    int
	Message string
	// File is the source file in which the error occurred.
	// It is empty for errors in the main (top-level) file and populated for
	// errors detected inside imported files.
	File string
}

TypeError represents a compile-time type error.

func Check

func Check(program *ast.Program, predefines ...string) []*TypeError

Check runs the type checker on a program and returns all type errors found. Provide the names of any stdlib-predefined variables via predefines so the checker can report redeclarations as compile-time errors.

func (*TypeError) CompileFile

func (te *TypeError) CompileFile() string

CompileFile implements stacktraces.CompileFileError.

func (*TypeError) CompileLine

func (te *TypeError) CompileLine() int

CompileLine implements stacktraces.CompileError.

func (*TypeError) CompileMessage

func (te *TypeError) CompileMessage() string

CompileMessage implements stacktraces.CompileError.

func (*TypeError) Error

func (te *TypeError) Error() string

type Value

type Value = interface{}

Value is the universal runtime value interface for the English language. Every evaluated expression produces a Value.

func Add

func Add(left, right Value) (Value, error)

Add adds two values. Strict rules:

  • number + number → number (arithmetic)
  • text + text → text (concatenation)
  • array + array → array (concatenation, same element type required)
  • any other combination is a TypeError

func CastValue

func CastValue(v Value, target types.TypeKind) (Value, error)

CastValue performs an explicit "cast to" conversion. For complex types that need the full ToString (arrays, lookup tables), it delegates to the vm-level ToString before calling types.Cast.

func Divide

func Divide(left, right Value) (Value, error)

Divide divides two numbers. Division by zero is an error.

func Modulo

func Modulo(left, right Value) (Value, error)

Modulo computes the integer remainder of two numbers.

func Multiply

func Multiply(left, right Value) (Value, error)

Multiply multiplies two numbers.

func Subtract

func Subtract(left, right Value) (Value, error)

Subtract subtracts two numbers.

Directories

Path Synopsis
Package types defines the English language's type system: the TypeKind enum, composite value types (array, lookup table), type metadata, key serialisation, explicit casting, and error helpers.
Package types defines the English language's type system: the TypeKind enum, composite value types (array, lookup table), type metadata, key serialisation, explicit casting, and error helpers.

Jump to

Keyboard shortcuts

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