Documentation
¶
Overview ¶
Package goscript is the core of goscript, the scripting language of the Weakpixel engine: a small, dynamically typed language with Go syntax, compiled to bytecode and run on a register VM.
A script file is valid Go syntax without a package clause and without imports. It holds top-level var, const, struct type and func declarations; parameters and variables need no types, and a type, where written, is checked at run time. Lists and dicts are written list{1, 2} and dict{"k": v}:
const limit = 100
var calls = 0
func fib(n) {
calls++
if n < 2 {
return n
}
return fib(n-1) + fib(n-2)
}
Use it in three steps: Compile turns source into an immutable Program, VM.Load instantiates a Module (its globals) and runs the top-level initializers, and Module.Func looks up a function to call with Func.Call. Calls, arithmetic, loops, recursion and access to existing lists, dicts and structs allocate nothing once the VM's register file has grown to the deepest call; that is the point of the package, so it can run inside a game tick. Options.Budget stops a runaway script.
The host decides what scripts can reach: it registers functions (Env.Func, called with a Call that aliases the VM's registers) and value types (Env.Type: inline types such as a vector kept in 64 bits, or heap types wrapping a Go pointer) in an Env passed to Compile. Host functions may call script functions back. See the package example.
The package depends on the standard library only (go/parser parses the source) and knows nothing about the engine; the engine integration lives elsewhere. A VM, and every Module and Func loaded into it, is meant for one goroutine, like the engine's World.
Design and status: doc/design/goscript.md.
Example ¶
A host registers functions and types in an Env, compiles a script against it and calls the script's functions.
package main
import (
"errors"
"fmt"
"math"
"os"
"github.com/weakpixel/engine/goscript"
)
// point is an inline host type: two float32 packed into the 64 bits of a
// Value, so making and adding points never allocates.
var point = &goscript.Type{Name: "Point", Inline: true}
func makePoint(x, y float32) goscript.Value {
return point.Make(uint64(math.Float32bits(x)) | uint64(math.Float32bits(y))<<32)
}
func pointXY(v goscript.Value) (x, y float32) {
bits, _ := point.Bits(v)
return math.Float32frombits(uint32(bits)), math.Float32frombits(uint32(bits >> 32))
}
func init() {
point.Fields = map[string]goscript.Field{
"X": {Get: func(_ *goscript.VM, v goscript.Value) (goscript.Value, error) {
x, _ := pointXY(v)
return goscript.Float(float64(x)), nil
}},
}
point.Binary = func(op goscript.Op, a, b goscript.Value) (goscript.Value, error) {
if _, ok := point.Bits(b); !ok || op != goscript.OpAdd {
return goscript.Value{}, fmt.Errorf("operator %s not defined on Point and %s", op, b.Kind())
}
ax, ay := pointXY(a)
bx, by := pointXY(b)
return makePoint(ax+bx, ay+by), nil
}
point.String = func(v goscript.Value) string {
x, y := pointXY(v)
return fmt.Sprintf("Point(%g, %g)", x, y)
}
}
// A host registers functions and types in an Env, compiles a script
// against it and calls the script's functions.
func main() {
env := goscript.NewEnv()
env.Type(point)
env.Func("geo.Pt", func(c *goscript.Call) error {
x, err := c.Float(0)
if err != nil {
return err
}
y, err := c.Float(1)
if err != nil {
return err
}
c.Return(makePoint(float32(x), float32(y)))
return nil
})
env.Func("log", func(c *goscript.Call) error {
if len(c.Args()) == 0 {
return errors.New("log needs an argument")
}
fmt.Println("log:", c.Arg(0))
return nil
})
src := `
type Body struct { Pos, Vel Point }
func step(b *Body) { b.Pos = b.Pos + b.Vel }
func run(n) {
b := &Body{Pos: geo.Pt(0, 0), Vel: geo.Pt(1, 2)}
for range n {
step(b)
}
log(b.Pos)
return b.Pos.X
}
`
prog, err := goscript.Compile("body.gs", []byte(src), env)
if err != nil {
fmt.Println(err)
return
}
m, err := goscript.New(goscript.Options{Output: os.Stdout, Budget: 1_000_000}).Load(prog)
if err != nil {
fmt.Println(err)
return
}
results := make([]goscript.Value, 1)
if _, err := m.Func("run").Call([]goscript.Value{goscript.Int(3)}, results); err != nil {
fmt.Println(err)
return
}
fmt.Println(results[0])
}
Output: log: Point(3, 6) 3
Index ¶
- func Equal(a, b Value) bool
- func HostPointer[T any](t *Type, v Value) (*T, bool)
- type Call
- type Dict
- type Env
- type Error
- type Field
- type Func
- type Kind
- type List
- type Module
- type Op
- type Options
- type Param
- type Program
- type RuntimeError
- type Struct
- type TraceEntry
- type Type
- type VM
- type Value
- func (v Value) AsBool() (b, ok bool)
- func (v Value) AsDict() (*Dict, bool)
- func (v Value) AsFloat() (float64, bool)
- func (v Value) AsFunc() (*Func, bool)
- func (v Value) AsInt() (int64, bool)
- func (v Value) AsList() (*List, bool)
- func (v Value) AsString() (string, bool)
- func (v Value) IsNil() bool
- func (v Value) Kind() Kind
- func (v Value) Number() (float64, bool)
- func (v Value) String() string
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type Call ¶
type Call struct {
// contains filtered or unexported fields
}
Call is one call of a host function. The VM reuses Calls: do not keep a *Call, or the slice from Args, after the function returns.
func (*Call) Int ¶
Int returns argument i as an int, or an error naming the function and the argument when it is missing or not an int.
func (*Call) Return ¶
Return sets the results; it replaces earlier ones. It panics past eight results.
type Dict ¶
type Dict struct {
// contains filtered or unexported fields
}
Dict is a script dict: keys to values, iterated in insertion order so that scripts and replays are deterministic. Scripts write dict{"k": v} and share dicts by reference.
Keys are bools, ints, floats, strings, inline host values and heap objects (by identity). A float key with an integral value is the same key as that int, matching 1 == 1.0.
func (*Dict) Get ¶
Get returns the value for key and whether the key is present. A key that cannot be a dict key is reported as absent.
type Env ¶
type Env struct {
// contains filtered or unexported fields
}
Env is what the host offers scripts: functions, grouped in namespaces by dotted names, and value types. Compile resolves every name of a script against it, so a misspelled host name is a compile error. Build an Env before compiling and do not change it while a Program compiled with it is loaded.
func (*Env) FieldType ¶
FieldType registers t for field and method access only: values of t that host functions or fields return work in scripts, but scripts cannot name t (no annotation, literal or type value), so its name only appears in messages and need not be unique. Use it for the struct types nested in a host type's fields. Dotted field names make groups as for Env.Type.
func (*Env) Func ¶
Func registers fn under name: "clamp" is called as clamp(x), and "sound.Play" as sound.Play(key), which makes sound a namespace. It panics when name is not an identifier or two joined by a dot, when it is already registered, or when it collides with a namespace.
func (*Env) Global ¶
Global registers a read-only global: scripts read name as v, call its methods and read its fields (world.Spawn(...), world.game.Settings). It panics when name is not an identifier or is already a host function, type, global or namespace.
func (*Env) Type ¶
Type registers t, making its name usable in type annotations and, as a value, in expressions (TypeOf reads it back). A dotted name such as "gfx.Transform" puts the type in namespace gfx, like a dotted function. A field whose name is dotted, such as "gfx.Transform", makes its first part a reserved group: the compiler reads x.gfx.Transform as that one field, and a script may not declare a variable, parameter or struct field named gfx.
It panics when t's name or a field name is not an identifier or ns.Name, when the name is already registered here or collides with a namespace, or when the process has more than 8191 host types.
type Error ¶
Error is a compile error: a problem in the script's source, at a position of the original file.
type Field ¶
type Field struct {
// Get returns the field of v.
Get func(vm *VM, v Value) (Value, error)
// Set returns v with the field set to x: a new value for an inline
// type, the same pointer after storing for a heap type. Nil makes the
// field read-only.
Set func(vm *VM, v, x Value) (Value, error)
}
Field is a field of a host Type. The hooks get the VM running the script, so a host that keeps state per VM (VM.SetHost) can reach it; they must not call script functions. An error stops the script with a runtime error at the access.
type Func ¶
type Func struct {
// contains filtered or unexported fields
}
Func is a function value: a script function of a Module, a closure, or a host function registered with Env.Func.
func (*Func) Call ¶
Call runs f with args and copies its results into results. It returns how many results f returned; results beyond len(results) are dropped, and entries past the returned count are left as they were. args and results stay owned by the caller and are not retained, so a call allocates nothing once the VM's register file is large enough.
A script error is returned as a *RuntimeError and leaves the VM usable. A wrong number of arguments is such an error too.
Call may be used from inside a host function (Call.VM): the call runs on top of the running one and shares its instruction budget.
Call panics when f is nil.
type Kind ¶
type Kind uint8
Kind is the dynamic type of a Value.
type List ¶
type List struct {
// contains filtered or unexported fields
}
List is a script list: an ordered, growable sequence of values. Scripts write list{1, 2} and share lists by reference. A host may create lists, read them and change them, from the goroutine that runs the VM.
func (*List) Append ¶
Append adds items at the end; it allocates only when the list grows past its capacity.
type Module ¶
type Module struct {
// contains filtered or unexported fields
}
Module is a Program loaded into a VM: the program's code with its own globals. Loading the same Program twice gives two independent Modules.
func (*Module) CopyParams ¶
CopyParams copies the current values of the script's parameters into dst, in the order of Program.Params, and returns dst; dst must have room for them. After VM.Load these are the defaults the initializers set.
Panics with "goscript: CopyParams: want <n> values" when len(dst) is not the number of parameters.
func (*Module) Func ¶
Func returns the top-level function name, or nil when the script declares no function by that name.
func (*Module) Global ¶
Global returns the current value of the top-level var or func name, and false when the script declares no such global.
func (*Module) SetGlobal ¶
SetGlobal sets the top-level var name and reports whether the script declares it. Functions cannot be replaced.
func (*Module) SwapParams ¶
SwapParams exchanges the values of the script's parameters with vals, in the order of Program.Params: afterwards the parameters hold what vals held, and vals holds their previous values. Calling it twice restores both. It allocates nothing.
A host running one Module for many objects keeps a slice per object and swaps it in before calling into the script and out after it, so code reading a parameter sees the object's value and writes to it stay with the object. Closures called later see whatever slice is swapped in then.
Panics with "goscript: SwapParams: want <n> values" when len(vals) is not the number of parameters.
type Op ¶
type Op uint8
Op is an arithmetic operator handed to Type.Binary.
The operators a host type can implement.
type Options ¶
type Options struct {
// Output receives what the builtin print writes. Nil means io.Discard.
Output io.Writer
// MaxCallDepth bounds nested script calls; a deeper call is a runtime
// error ("stack overflow"). Zero means 1000.
MaxCallDepth int
// Budget bounds the work of one call from the host: every loop
// iteration (backward jump) and every call uses one unit, and a call
// that runs out stops with a runtime error ("budget exhausted"), so a
// runaway loop cannot freeze the game. Calls a host function makes
// from inside a call share its budget. Zero means unlimited.
Budget int64
}
Options configures a VM.
type Param ¶
type Param struct {
// Name is the var's name.
Name string
// Type is the var's type annotation as written ("float", "Vec2"),
// or "" when it has none.
Type string
// Comment is the text of the var's doc and line comments, without the
// comment markers, doc comment first, one line per comment line. The
// host reads its own markers from it.
Comment string
// Pos is where the var is declared.
Pos token.Position
// contains filtered or unexported fields
}
Param is an exported top-level var of a script: a value the host may set per use of the script. A host that runs one script for many objects (an engine running the same behavior on many entities) keeps a value slice per object and swaps it in around each call with Module.SwapParams, so the script reads its parameters as ordinary globals.
type Program ¶
type Program struct {
// contains filtered or unexported fields
}
Program is a compiled script. It is immutable and may be loaded into any number of VMs (VM.Load); each load gets its own globals.
func Compile ¶
Compile parses and compiles a script against env, the host's functions and types (nil for none). name is used in positions ("name:line:col") and errors. All problems the compiler finds are returned together as one error (errors.Join of *Error values).
type RuntimeError ¶
type RuntimeError struct {
// Pos is where the failing instruction came from.
Pos token.Position
Msg string
// Trace lists the active calls when the error happened, innermost
// first; Trace[0].Pos == Pos.
Trace []TraceEntry
}
RuntimeError is an error a script raised while running: an operation on the wrong kinds, an integer division by zero, a call with the wrong number of arguments, a stack overflow. The VM unwinds the failed call and stays usable.
func (*RuntimeError) Error ¶
func (e *RuntimeError) Error() string
type Struct ¶
type Struct struct {
// contains filtered or unexported fields
}
Struct is a script struct value. Structs are references: T{} and &T{} both make one, and assignment shares it.
type TraceEntry ¶
TraceEntry is one call of a RuntimeError's trace.
type Type ¶
type Type struct {
// Name is how scripts write the type in annotations and how errors
// name it. It must be a Go identifier.
Name string
// Inline selects the 64-bit inline representation ([Type.Make],
// [Type.Bits]); otherwise values are pointers ([HostValue]).
Inline bool
// Fields are read as v.Name and written as v.Name = x.
Fields map[string]Field
// Methods are called as v.Name(args); the receiver is argument 0.
Methods map[string]func(*Call) error
// Binary implements the arithmetic operators where one operand has
// this type (the other may be any value, as in v * 2). It returns an
// error for an operand it does not support.
Binary func(op Op, a, b Value) (Value, error)
// Equal replaces bitwise (inline) or pointer (heap) equality.
Equal func(a, b Value) bool
// String formats a value for print; nil prints the type's name.
String func(v Value) string
// New makes a value from a composite literal, T{A: 1, B: x}. The call's
// arguments are the literal's field names (as strings) and values,
// alternating, in source order; the compiler has checked that every
// name is a field of the type. Nil makes literals of the type a compile
// error. It may allocate: a literal makes a value.
New func(c *Call) error
// Range and Next make the values rangeable: for k, v := range x. Range,
// if set, returns the starting state of a loop over v (otherwise it is
// nil); Next is called with v and a pointer to the state before every
// step and returns the step's key and value, or ok false when the loop
// is done. The VM keeps the state in a register, so a loop whose hooks
// do not allocate allocates nothing. A loop left with break or return
// gets no further call. Nil Next makes ranging over the type an error.
// Like the Field hooks, they get the VM and must not call scripts.
Range func(vm *VM, v Value) (state Value, err error)
Next func(vm *VM, v Value, state *Value) (key, value Value, ok bool, err error)
// contains filtered or unexported fields
}
Type is a value type defined by the host, such as a vector, a color or a handle to a Go object. Register it with Env.Type before compiling a script that names it.
An inline type keeps its whole value in 64 bits (two float32, a packed color): making, copying and passing its values never allocates. A heap type points at a Go value of the host (HostValue, HostPointer).
The hooks are optional. They run on the VM's goroutine and must not keep the Values of a Call beyond it.
func HostTypeOf ¶
HostTypeOf returns the host type of v and true when v is a host value (inline or heap).
func TypeOf ¶
TypeOf returns the host type that v names and true when v is a type name used as a value, such as gfx.Sprite in world.Remove(e, gfx.Sprite).
func (*Type) Deref ¶
Deref returns the pointer and the extra bits of v and true when v is a value of the heap type t (made by Ref or HostValue).
func (*Type) Make ¶
Make returns an inline value of t with the given bits. It panics when t is not inline or not registered with an Env.
func (*Type) Ref ¶
Ref returns a value of the heap type t pointing at p, with 32 bits of host data carried in the value itself, so a host can check it on every access without a lookup (a generation, an epoch). p must point into memory the garbage collector knows (a Go allocation, possibly into the middle of it). A nil p gives nil. It panics like HostValue.
Use it instead of HostValue when the values point into memory the host owns as raw bytes, such as a field of a struct held by reference.
type VM ¶
type VM struct {
// contains filtered or unexported fields
}
VM runs compiled scripts. It owns one register file and one frame stack, shared by every Module loaded into it. Both grow (by doubling) only when a call goes deeper than any call before, so steady-state calls allocate nothing.
A VM is not safe for concurrent use: use it, and its Modules and Funcs, from one goroutine.
func (*VM) Load ¶
Load instantiates prog in vm: it allocates the globals, then runs the top-level var initializers (in dependency order) and the init functions (in source order). An error is the first initializer's *RuntimeError; the Module is not returned then.
type Value ¶
type Value struct {
// contains filtered or unexported fields
}
Value is one script value. It is two machine words, so it is copied, stored in registers and passed to and from the host without allocating.
Layout (why: a single NaN-boxed uint64 would hide pointers from Go's garbage collector, so the pointer gets its own word):
- nil: p == nil, u == 0. The zero Value is nil.
- bool, int, float, builtin: p points at the kind's entry of scalarTags (a static sentinel, so the GC ignores it) and u holds the bits.
- string: p is the string's data pointer (or emptyString for ""), u the length. u's top bit is clear.
- inline host values: p points at the type's entry of hostTags, u holds the bits the host chose (a float32 vector, a packed color).
- heap objects (functions, lists, dicts, structs, cells, host objects): p points at the object, u is heapTag | kind, plus for host objects the host type's index in bits 8 to 23 and 32 bits of host data in bits 24 to 55 (see Type.Ref).
Kind tells them apart in this order: p == nil, p inside scalarTags, p inside hostTags, u's top bit; what is left is a string.
func HostValue ¶
HostValue returns p as a value of the heap type t. A nil p gives nil. It panics when t is inline or not registered with an Env.
func String ¶
String returns a string Value. It does not copy s: the Value keeps s's bytes alive, which is safe because Go strings are immutable.
func (Value) AsFloat ¶
AsFloat returns v's float and true, or 0 and false when v is not a float. An int is not converted; use Value.Number for either.
func (Value) AsFunc ¶
AsFunc returns v's function and true when v is a script or host function value (not a builtin).
func (Value) AsInt ¶
AsInt returns v's int and true, or 0 and false when v is not an int. A float is not converted.
func (Value) AsString ¶
AsString returns v's string and true, or "" and false when v is not a string. It does not copy.