Help us shape the future of Go! Take the 2026 Go Developer Survey

value

package
v0.38.0 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package value defines Kukel's runtime values and the semantics of the operators on them. The compiler uses the same operations for constant folding as the VM uses at run time.

Index

Constants

View Source
const (
	TypeError     = "TypeError"
	ZeroDivision  = "ZeroDivisionError"
	RangeError    = "RangeError"
	ArgumentError = "ArgumentError"
	StackOverflow = "StackOverflowError"
	IOError       = "IOError"
	MemberError   = "MemberError"
	ValueError    = "ValueError"
	InternalError = "InternalError"
)

Runtime error kinds.

Variables

View Source
var (
	NilValue = Value{}
	True     = Value{/* contains filtered or unexported fields */}
	False    = Value{/* contains filtered or unexported fields */}
)

Functions

func ArgumentRange added in v0.31.0

func ArgumentRange(min, max int) string

ArgumentRange gives a range of numbers of arguments in words, for messages: "1 to 3 arguments", "at most 1 argument".

func Arguments added in v0.27.0

func Arguments(n int) string

Arguments gives a number of arguments in words, for messages: "1 argument", "2 arguments".

func Compare

func Compare(op CmpOp, a, b Value) (bool, error)

Compare applies a relational operator: numbers with numbers, strings with strings (byte order); other combinations are type errors. Any comparison with NaN is false.

func Equal

func Equal(a, b Value) bool

Equal reports whether a == b: numbers by value (1 == 1.0), strings by bytes, nil and booleans by value, everything else by identity. Values of different kinds are never equal (except int and float).

func FormatFloat

func FormatFloat(f float64) string

FormatFloat formats f as the shortest text that reads back as f, always with a "." or an exponent so that it does not look like an int.

func Len

func Len(v Value) (int, error)

Len returns the length of a string (in bytes), vector or map.

func Quote

func Quote(s string) string

Quote writes s as a Kukel string literal.

func SetIndex

func SetIndex(x, i, v Value) error

SetIndex does x[i] = v for a vector (an existing index) or a map.

func SetMember

func SetMember(p Value, name string, v Value) error

SetMember does p->name = v; name must be a data member.

Types

type ArithOp

type ArithOp uint8

ArithOp is a binary arithmetic or bitwise operator.

const (
	Add ArithOp = iota
	Sub
	Mul
	Div
	Mod
	BitAnd
	BitOr
	BitXor
	Shl
	Shr
)

func (ArithOp) String

func (op ArithOp) String() string

type BoundMethodObj

type BoundMethodObj struct {
	Recv   Value
	Method *MethodObj
}

BoundMethodObj is a method together with the object it was taken from (the value of p->m without a call).

type BuiltinObj

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

BuiltinObj is a function implemented in Go. It returns an error message (a runtime error) or a result. args is a view of the VM's stack, valid only during the call: copy values out of it, never keep the slice.

type CellObj

type CellObj struct {
	V Value
}

CellObj holds a captured variable, shared by the frame that declared it and the closures that captured it.

type ClassObj

type ClassObj struct {
	Name        string
	Base        *ClassObj
	FieldNames  []string              // instance data members, inherited ones first
	FieldIndex  map[string]int        // name -> slot in ObjectObj.Fields
	Methods     map[string]*MethodObj // own and inherited member functions (overrides resolved)
	Statics     []Value               // the class's own static data members
	StaticNames []string              // their names
	Ctor        *MethodObj            // C::C, else the nearest base class's constructor, or nil

	// Native classes (written in Go) only: Native is set, and Show is how
	// str() shows an object (a native class has no data members).
	Native bool
	Show   func(o *ObjectObj) string
}

ClassObj is a class at run time.

func (*ClassObj) IsSubclassOf

func (c *ClassObj) IsSubclassOf(k *ClassObj) bool

IsSubclassOf reports whether c is k or derives from k.

type ClosureObj

type ClosureObj struct {
	Fn    Named
	Cells []*CellObj
	This  *ObjectObj // nil outside member functions
}

ClosureObj is a function literal's value: the function, the cells of the variables it captured, and the this of the member function it was made in.

type CmpOp

type CmpOp uint8

CmpOp is a relational operator.

const (
	Less CmpOp = iota
	LessEq
	Greater
	GreaterEq
)

func (CmpOp) String

func (op CmpOp) String() string

type Env

type Env interface {
	Stdout() io.Writer
	Stderr() io.Writer
	Stdin() *bufio.Reader
	// Call calls a Kukel function (or built-in) and returns its result.
	Call(fn Value, args []Value) (Value, error)
	// Rand is the program's random number source (seed sets it).
	Rand() *rand.Rand
	// Started is when the program started (for clock).
	Started() time.Time
	// Local returns the value stored under key for this interpreter,
	// storing init() first if there is none: per-program state of a
	// native module (such as its event loop).
	Local(key any, init func() any) any
	// Thrown returns the value a Kukel exception carries, when err (from
	// Call) is one that a try could catch; not for exit() or fatal errors.
	Thrown(err error) (Value, bool)
	// Done is closed when the program is cancelled (nil if it cannot be);
	// a Go function that waits should also wait for it and then return
	// Err().
	Done() <-chan struct{}
	Err() error
}

Env is what built-in functions get from the VM.

type Error

type Error struct {
	Kind string
	Msg  string
}

Error is a runtime error raised by an operation. Kind names the class of error; it becomes the "kind" field of the Error object the VM throws.

func Errorf

func Errorf(kind, format string, args ...any) *Error

Errorf returns a runtime error of the given kind.

func (*Error) Error

func (e *Error) Error() string

type ExitError

type ExitError struct{ Code int }

ExitError is returned by the exit built-in: the program stops at once with this exit code (try cannot catch it; finally blocks do not run).

func (*ExitError) Error

func (e *ExitError) Error() string

type IteratorObj

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

IteratorObj is the state of a for-each loop.

type Kind

type Kind uint8

Kind is the type of a value.

const (
	Nil Kind = iota
	Bool
	Int
	Float
	String
	Vector
	Map
	Function
	Builtin
	Class
	Object
	BoundMethod
	Closure  // a function literal with its captured variables
	Iterator // internal: the state of a for-each loop
	Internal // internal: a Go value the VM keeps in a slot (a pending exception)
	Cell     // internal: a captured variable
)

func (Kind) String

func (k Kind) String() string

String returns the name typeof() reports for k.

type MapObj

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

MapObj is the shared, mutable storage of a map. It keeps the insertion order of its keys.

func NewMap

func NewMap() *MapObj

func (*MapObj) Delete

func (m *MapObj) Delete(k Value) (bool, error)

Delete removes k and reports whether it was a key.

func (*MapObj) Each

func (m *MapObj) Each(f func(k, v Value))

Each calls f for each key and value in insertion order.

func (*MapObj) Get

func (m *MapObj) Get(k Value) (v Value, ok bool, err error)

Get returns the value for k; ok is false when k is not a key.

func (*MapObj) Keys

func (m *MapObj) Keys() []Value

Keys returns the keys in insertion order.

func (*MapObj) Len

func (m *MapObj) Len() int

Len returns the number of keys.

func (*MapObj) Set

func (m *MapObj) Set(k, v Value) error

Set sets the value for k. An existing equal key keeps its place (and its original form: m[1.0] = x after m[1] = y keeps the key 1).

type MethodObj

type MethodObj struct {
	Name   string
	Class  *ClassObj // the class that declares it
	Static bool
	Fn     Named // the compiled function; nil if declared but not defined

	// A member function of a native class: Native for an instance member
	// function or constructor, Builtin for a static one (a plain function).
	Native  NativeMethod
	Builtin *BuiltinObj
}

MethodObj is a member function of a class.

func Method

func Method(p Value, name string) (*MethodObj, error)

Method finds the member function p->name(...) calls.

func (*MethodObj) Defined added in v0.2.0

func (m *MethodObj) Defined() bool

Defined reports whether m has code (a declared member function may not).

func (*MethodObj) FullName

func (m *MethodObj) FullName() string

FullName is "Class::name".

type Named

type Named interface {
	Name() string
}

Named is implemented by function objects.

type NativeMethod added in v0.2.0

type NativeMethod func(env Env, this *ObjectObj, args []Value) (Value, error)

NativeMethod is an instance member function (or constructor) written in Go; a static one is a plain built-in (MethodObj.Builtin).

type ObjectObj

type ObjectObj struct {
	Class  *ClassObj
	Fields []Value
	Native any // data the VM attaches (the stack trace of a thrown Error)
	State  any // the Go value inside an object of a native class
}

ObjectObj is an instance of a class.

type Value

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

Value is a Kukel value. It is a small tagged struct, so that numbers do not allocate: num holds the bits of a Bool, Int or Float, obj the payload of the other kinds (*VectorObj, a function object, *BuiltinObj, ...). A String holds its length in num and its bytes in obj: a *byte to the first byte (a pointer fits in an interface without an allocation), or the *strBuf of a string made by concatenation. The zero Value is nil.

func Arith

func Arith(op ArithOp, a, b Value) (Value, error)

Arith applies a binary arithmetic or bitwise operator.

Integers wrap around (two's complement); an int combined with a float gives a float; int / int truncates toward zero; / and % by integer 0 are errors; + also concatenates two strings. Bitwise operators and shifts take ints only; a shift count must be in 0..63; >> is an arithmetic shift.

func BitNot

func BitNot(v Value) (Value, error)

BitNot returns ~v.

func Concat added in v0.8.0

func Concat(a, b Value) Value

Concat returns the string a + b.

func Detached added in v0.8.0

func Detached(v Value) Value

Detached returns v, with a string's bytes no longer shared with a buffer that its interpreter can still append to: for a value that goes to another goroutine.

func IncDec

func IncDec(v Value, delta int64) (Value, error)

IncDec adds delta (1 or -1) to a number, for ++ and --.

func Index

func Index(x, i Value) (Value, error)

Index returns x[i]: an element of a vector, the byte (an int) of a string, or the value of a map key (nil for a missing key).

func MakeBool

func MakeBool(b bool) Value

func MakeBoundMethod

func MakeBoundMethod(recv Value, m *MethodObj) Value

func MakeBuiltin

func MakeBuiltin(b *BuiltinObj) Value

func MakeClass

func MakeClass(c *ClassObj) Value

func MakeClosure

func MakeClosure(c *ClosureObj) Value

func MakeFloat

func MakeFloat(f float64) Value

func MakeFunction

func MakeFunction(f Named) Value

MakeFunction wraps a function object (a *bytecode.Function); Named gives its name for printing.

func MakeInt

func MakeInt(i int64) Value

func MakeInternal

func MakeInternal(x any) Value

MakeInternal wraps a Go value that only the VM uses.

func MakeMap

func MakeMap(m *MapObj) Value

func MakeString

func MakeString(s string) Value

func MakeVector

func MakeVector(elems []Value) Value

func Member

func Member(p Value, name string, function func(Named) Value) (Value, error)

Member returns the value of p->name: a data member, or else a method (bound to p; a static method gives its plain function).

func Neg

func Neg(v Value) (Value, error)

Neg returns -v.

func NewCell

func NewCell(v Value) Value

func NewIterator

func NewIterator(x Value) (Value, error)

NewIterator starts iterating over a vector, map or string.

func NewObject

func NewObject(c *ClassObj) Value

NewObject makes an object of class c with all data members nil.

func ObjectValue

func ObjectValue(o *ObjectObj) Value

ObjectValue is the value of an existing object.

func (Value) AsBool

func (v Value) AsBool() bool

func (Value) AsBoundMethod

func (v Value) AsBoundMethod() *BoundMethodObj

func (Value) AsBuiltin

func (v Value) AsBuiltin() *BuiltinObj

func (Value) AsCell

func (v Value) AsCell() *CellObj

func (Value) AsClass

func (v Value) AsClass() *ClassObj

func (Value) AsClosure

func (v Value) AsClosure() *ClosureObj

func (Value) AsFloat

func (v Value) AsFloat() float64

func (Value) AsInt

func (v Value) AsInt() int64

func (Value) AsMap

func (v Value) AsMap() *MapObj

func (Value) AsObject

func (v Value) AsObject() *ObjectObj

func (Value) AsString

func (v Value) AsString() string

func (Value) AsVector

func (v Value) AsVector() *VectorObj

func (Value) IntValue added in v0.8.0

func (v Value) IntValue() (int64, bool)

IntValue gives the int that v equals (Equal): an int, or a float with an integral value in the int range.

func (Value) IsCallable

func (v Value) IsCallable() bool

IsCallable reports whether v can be called: a function, function literal, bound method or built-in.

func (Value) IsNil

func (v Value) IsNil() bool

func (Value) Kind

func (v Value) Kind() Kind

func (Value) Next

func (v Value) Next() (first, second Value, ok bool)

Next returns the next pair: (element index, element) for a vector, (key, value) for a map, (byte index, byte) for a string. ok is false at the end. A vector is walked while the index is below its current length; map keys deleted during the loop are skipped.

func (Value) Obj

func (v Value) Obj() any

Obj returns the payload of a Function value (or any other object).

func (Value) OneNameGetsKey

func (v Value) OneNameGetsKey() bool

OneNameGetsKey reports what a for-each loop with one name gets from Next: the first value (the key) for a map, the second (the element or byte) otherwise.

func (Value) Repr

func (v Value) Repr() string

Repr returns v as it appears inside a container: strings are quoted.

func (Value) String

func (v Value) String() string

String returns the text print() and str() produce for v.

func (Value) Truthy

func (v Value) Truthy() bool

Truthy reports whether v counts as true: nil, false, 0 and 0.0 are false, everything else is true.

type VectorObj

type VectorObj struct {
	Elems []Value
}

VectorObj is the shared, mutable storage of a vector.

Jump to

Keyboard shortcuts

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