vm

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 33 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Internals

Provides some basic knowledge needed to be productive with embedding this language.

Scoping

Understanding this is crucial to knowing how variables are resolved.

{
    // the prelude: the builtin types such as `string`, `number` and `error`, plus what the host adds.
    // visible to all packages implicitly (no `imports` needed).
    // cannot be reassigned by the user.

    {
        // package-statics.
        // visible only to the current package.
        // e.g. `package xyz imports("time")`.
        // will make `time` available in the current `xyz` package.
        // cannot be reassigned by the user.

        {
            // package-globals.
            // visible in the current package and, through its name, to importers.
            // e.g. `isWorldFlat := false`.
            // can be reassigned if prefixed with `var`.
            // initialized in source order when the package loads; functions and classes are hoisted.

            {
                // package-closures.
                // visible to the current closure and other nested closures.
                // can be reassigned.
            }
        }
    }
}

At each layer, you can shadow symbols in the previous scope.

Example

The evie package wraps all of this in an Engine; this is the same thing on the vm level.

package main

import (
	"context"
	"fmt"

	"github.com/hxkhan/evie/diag"
	"github.com/hxkhan/evie/std/io"
	"github.com/hxkhan/evie/std/time"
	"github.com/hxkhan/evie/vm"
)

func main() {
	// the prelude: visible to every package without an import
	prelude := vm.NewPackage("prelude")
	prelude.Set("pi", vm.BoxNumber(3.14159))

	// packages that scripts import by name, e.g. `package foo imports("io")`
	resolver := func(name string) (*vm.Package, error) {
		switch name {
		case "io":
			return io.Construct(), nil
		case "time":
			return time.Construct(), nil
		}
		return nil, fmt.Errorf("package '%v' not found", name)
	}

	evm := vm.New(vm.Options{Prelude: prelude, Resolver: resolver})
	defer evm.Wait() // let tasks the script started finish

	_, err := evm.EvalSource(context.Background(), diag.NewSource("main.ev", []byte(`package main imports("io", "time")

	fn add(a, b) {
		io.println("add called in the evie world")
		time.wait(pi * 10)
		return a + b
	}`)))
	if err != nil {
		panic(err)
	}

	// the convenient call: Go arguments are boxed, a fiber is borrowed
	result, err := evm.Call("main.add", 3, 2)
	if err != nil {
		panic(err)
	}
	fmt.Println(result)

	// the explicit call: a looked-up value and evie values
	add, ok := evm.Lookup("main.add")
	if !ok {
		panic("main.add not found")
	}
	result, err = add.Call(vm.BoxNumber(3), vm.BoxNumber(2))
	if err != nil {
		panic(err)
	}
	fmt.Println(result)
}

Compiler fast paths

The compiler turns each AST node into a Go closure. A few rules keep the hot paths fast; check go build -gcflags=-m=1 ./vm and the benchmark suite when touching them.

  • Operands that need no evaluation. evaluate returns an operand: a Value for a constant, a local for a stack slot, a pkgGlobal for a package binding, or nil. Emitters specialise on these, so x + 1 reads the slot and adds the constant without calling another closure.
  • Generated operator matrix. Go only inlines Value.sub and its siblings when they are called directly from the closure (add, mod and Equals are too big to inline, so for +, %, == and != the closures handle numbers themselves); dispatching through a table of functions costs 10% to 40% on numeric loops. So ops_gen.go spells out every operator for every operand shape, including compound assignments and comparisons used as conditions, which compare numbers without boxing a bool. It is written by gen_ops.go; edit the generator and run go generate ./vm, never the output.
  • Frames spelled out. Go will not inline a frame-setup helper, and calling one costs 5% to 17% on call-heavy code, so the call protocol is written out in each entry point (emitCall, userFn.invoke, invokeMethod). Arity checks are inlinable through precomputed minimum and maximum counts.
  • Per-site method cache. A member call remembers the class type it last saw and the method it resolved to, so a monomorphic call site skips the lookup.
  • The general path must agree. Every fast path has a general version that Options.DisableInlining (-inline=false) forces. go test runs the root package's suite a second time that way (TestWithoutFastPaths), so a fast path that changes a result, or a general path that has stopped working, fails the tests. Only argument counts differ by design: they are checked while compiling only when the callee is known.
  • Stopping costs one compare. Every loop iteration and every call compares the instance's stop signal with the value the fiber saw last (fiber.signaled, inlined). The signal changes only when some run of the instance is asked to stop, so the slow path that looks at the fiber's own stopper runs once per stop request. Tasks inherit their parent's stopper; awaits, waiter callbacks and blocking natives wake on its context.
  • Code layout moves numbers. The same code emitted in a different order has shifted float loops by 7% either way. Run an A/B at least twice and judge by the suite's geometric mean, not one benchmark.

Documentation

Index

Constants

View Source
const (
	KindError      = "error"      // the default, for errors without a more specific kind
	KindType       = "type"       // a value of the wrong type, a call with the wrong arguments, a constant assigned
	KindValue      = "value"      // the right type but a value that cannot be used, as in number("two")
	KindRange      = "range"      // an index outside an array, string or buffer
	KindMember     = "member"     // a field, key, method or package member that does not exist
	KindNotFound   = "notFound"   // a file or directory that does not exist
	KindExists     = "exists"     // a file or directory that already exists
	KindPermission = "permission" // access that is not allowed
	KindIO         = "io"         // any other failure to read or write
	KindTimeout    = "timeout"    // a wait that ran out of time
	KindCancelled  = "cancelled"  // a task that was cancelled
	KindSyntax     = "syntax"     // text that does not parse, as for json.decode
)

The kinds of error the runtime and the standard library raise. A script can give an error any kind; these are the ones Evie itself uses.

Variables

View Source
var ErrCanceled = errors.New("cancelled")

ErrCanceled is the cause of the error a task stops with when it is cancelled.

View Source
var ErrInterrupted = errors.New("interrupted")

ErrInterrupted is the cause of the error a script stops with when the host calls Interrupt. A run bound to a context stops with the context's cause instead, such as context.DeadlineExceeded.

Functions

func HostArg

func HostArg[T any](c Call, i int) (T, error)

HostArg returns argument i as a Go value of type T

Types

type Array

type Array struct {
	Data []Value
}

Array is the backing store of an evie array value

func NewArray

func NewArray(values ...Value) *Array

NewArray makes an array holding values, without copying them

func (*Array) String

func (arr *Array) String() string

String returns the array as Evie prints it, such as [1, "a"]

type Call

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

Call is what a native receives: the arguments of one invocation, living on the fiber that made it, and a way to call back into evie on that fiber. It is passed by value and costs nothing to create.

func (Call) Arg

func (c Call) Arg(i int) Value

Arg returns argument i, or nil when there is no such argument

func (Call) Args

func (c Call) Args() []Value

Args copies all arguments into a new slice

func (Call) Array

func (c Call) Array(i int) (*Array, error)

Array returns argument i as an array

func (Call) Async

func (c Call) Async(fn func(ctx context.Context) (Value, error)) Value

Async runs fn on its own goroutine tied to the calling instance's lifecycle and cancellation context, returning a Task scripts can await. Engine.Close waits for the task, task.cancel() or Interrupt() cancels ctx, and panics become task errors rather than crashing the host.

func (Call) Bool

func (c Call) Bool(i int) (bool, error)

Bool returns argument i as a boolean

func (Call) Buffer

func (c Call) Buffer(i int) ([]byte, error)

Buffer returns argument i as a buffer

func (Call) Call

func (c Call) Call(fn Value, args ...Value) (Value, error)

Call invokes an evie callable on the same fiber, as a callback

func (Call) Callable

func (c Call) Callable(i int) (Value, error)

Callable returns argument i if it can be called

func (Call) Context

func (c Call) Context() context.Context

Context is done when the script has to stop: the host called Interrupt or the context of the run was cancelled. Blocking natives that wait should watch it, and returning its cause, or any error, once it is done stops the script right away.

func (Call) Int

func (c Call) Int(i int) (int, error)

Int returns argument i as an integer; a number with a fraction, NaN, infinity or a value outside int's range is an error

func (Call) Int64

func (c Call) Int64(i int) (int64, error)

Int64 returns argument i as a 64-bit integer; a number with a fraction, NaN, infinity or a value outside int64's range is an error

func (Call) Len

func (c Call) Len() int

Len returns the number of arguments, the receiver included for a method

func (Call) Number

func (c Call) Number(i int) (float64, error)

Number returns argument i as a number

func (Call) Object

func (c Call) Object(i int) (*Object, error)

Object returns argument i as an object

func (Call) String

func (c Call) String(i int) (string, error)

String returns argument i as a string

func (Call) This

func (c Call) This() Value

This returns the receiver of a method call

type CompileError

type CompileError struct {
	diag.Report
}

CompileError represents an error that occurred during compilation or static analysis.

func (*CompileError) Error

func (e *CompileError) Error() string

Error returns the report prefixed with "compile error: "

type CompileErrors

type CompileErrors []*CompileError

CompileErrors is what compiling a package returns when it finds more than one compile error, in the order it found them. errors.As finds each *CompileError in it.

func (CompileErrors) Diagnostics

func (l CompileErrors) Diagnostics() []*diag.Report

Diagnostics returns the report of every error, for tools that show them all

func (CompileErrors) Error

func (l CompileErrors) Error() string

Error returns the first error, and how many more there are

func (CompileErrors) Unwrap

func (l CompileErrors) Unwrap() []error

Unwrap returns every error in the list, for errors.Is and errors.As

type Error

type Error struct {
	diag.Report
	Cause error
	// contains filtered or unexported fields
}

Error is an exception: what went wrong, where, and the calls that led there. It is what `catch` turns into an error value and what the host gets back from a call that failed.

Besides its message an error has a kind, such as "notFound" or "timeout", that says what sort of failure it is, so code can tell failures apart without reading messages; any fields a script gave it, as in error("no config", {path: p}); and the error it was raised because of, its cause. Cause is that error for the host, so errors.Is and errors.As see through it.

func Errorf

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

Errorf makes an error of a kind, for a native function to return: scripts see the kind as e.kind. Give it fields with With.

func (*Error) CauseValue

func (e *Error) CauseValue() Value

CauseValue is the cause as scripts see it: the error, or other value, the error was raised because of; nil when there is none

func (*Error) Diagnostic

func (e *Error) Diagnostic() *diag.Report

Diagnostic is the error's report, which names its kind unless that is the default, so a rendered error reads error[notFound]: ...

func (*Error) Error

func (e *Error) Error() string

Error returns the error's report as text

func (*Error) Field

func (e *Error) Field(name string) (Value, bool)

Field is a field the error was given, as with With or error(message, fields)

func (*Error) FieldNames

func (e *Error) FieldNames() []string

FieldNames lists the fields the error was given, in the order they were given

func (*Error) Kind

func (e *Error) Kind() string

Kind says what sort of failure the error is, such as "notFound"; see the Kind constants. An error raised by Go code without one takes it from the Go error it came from, as "notFound" from fs.ErrNotExist, and is "error" otherwise.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the Go error this one was made from, if any

func (*Error) With

func (e *Error) With(name string, v Value) *Error

With gives the error a field that scripts read as e.name, and returns it. The names message, kind, cause, file, line, column and trace are the error's own and cannot be fields.

type GoFunc

type GoFunc struct {
	Name string

	Blocking bool
	// contains filtered or unexported fields
}

GoFunc is a native function exposed to evie code. Arguments counts the receiver of a method. A Blocking function gives up the instance runner while it executes, so it must not touch evie values that other fibers can reach; use it for I/O and sleeps.

func Func0

func Func0[R any](f func() R) *GoFunc

Func0 wraps a function of no arguments

func Func0E

func Func0E[R any](f func() (R, error)) *GoFunc

Func0E wraps a function of no arguments that can fail

func Func1

func Func1[A, R any](f func(A) R) *GoFunc

Func1 wraps a function of one argument

func Func1E

func Func1E[A, R any](f func(A) (R, error)) *GoFunc

Func1E wraps a function of one argument that can fail

func Func2

func Func2[A, B, R any](f func(A, B) R) *GoFunc

Func2 wraps a function of two arguments

func Func2E

func Func2E[A, B, R any](f func(A, B) (R, error)) *GoFunc

Func2E wraps a function of two arguments that can fail

func Func3

func Func3[A, B, C, R any](f func(A, B, C) R) *GoFunc

Func3 wraps a function of three arguments

func Func3E

func Func3E[A, B, C, R any](f func(A, B, C) (R, error)) *GoFunc

Func3E wraps a function of three arguments that can fail

func NewFunc

func NewFunc(name string, arity int, fn NativeFn) *GoFunc

NewFunc describes a native taking exactly arity arguments

func NewVariadic

func NewVariadic(name string, min int, fn NativeFn) *GoFunc

NewVariadic describes a native taking at least min arguments

func Reflect

func Reflect(fn any) *GoFunc

Reflect wraps any Go function as a native through reflection, converting each argument to the parameter type and boxing the results. It is the slow but universal path; the typed wrappers in wrap.go avoid reflection.

type HostType

type HostType struct {

	// String renders a value; the default is <TypeName>
	String func(v any) string
	// Equals compares two values; the default compares them with ==
	// when the Go type allows it and by identity otherwise
	Equals func(a, b any) bool
	// contains filtered or unexported fields
}

HostType describes Go values a host lends to scripts as they are, without converting them into evie objects: a file handle, a database connection, a struct the host keeps mutating. Scripts see an opaque value with the methods the host registers, can test it with `x is TypeName` and construct one when a constructor is given. The Go type is registered, so BoxAny and the typed wrappers box and unbox it on their own.

func NewHostType

func NewHostType[T any](name string) *HostType

NewHostType registers Go values of type T under a name scripts see. The registry is shared by every instance in the process, since BoxAny boxes a value without knowing one, so create a host type once, at package level. Registering T again under the same name returns the type registered first, so values of T keep one type in every instance; registering it under another name panics.

func (*HostType) Box

func (t *HostType) Box() Value

Box returns the type itself as a value, to bind under its name so that scripts can construct it and test values against it

func (*HostType) Constructor

func (t *HostType) Constructor(arity int, fn NativeFn) *GoFunc

Constructor makes the type callable from scripts, as in File("x")

func (*HostType) Method

func (t *HostType) Method(name string, arity int, fn NativeFn) *GoFunc

Method registers a method; arity counts the arguments after the receiver, which the native reads with HostArg[T](c, 0)

func (*HostType) Name

func (t *HostType) Name() string

Name returns the name scripts see

func (*HostType) Wrap

func (t *HostType) Wrap(v any) Value

Wrap boxes a Go value of this type

type Instance

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

Instance compiles and runs Evie code: it holds the loaded packages and the fibers running them. Make one with New.

func New

func New(opts Options) (vm *Instance)

New makes an Instance configured by opts

func (*Instance) Call

func (vm *Instance) Call(path string, args ...any) (Value, error)

Call looks a callable up by path, such as "main.add", boxes the Go arguments with BoxAny and calls it on a borrowed fiber. It is the simplest way to call into a script from Go.

func (*Instance) CallContext

func (vm *Instance) CallContext(ctx context.Context, path string, args ...any) (Value, error)

CallContext is Call bound to ctx: when ctx is done, the call stops with an error whose cause is ctx's cause, such as context.DeadlineExceeded. Tasks the call starts stop with it, also after it returns.

func (*Instance) CallValue

func (vm *Instance) CallValue(fn Value, args ...any) (Value, error)

CallValue calls a callable value under this instance, as Call calls one by path: Go arguments are boxed with BoxAny and it runs on a borrowed fiber, holding the instance's runner, so Interrupt stops it and the async work of a native it calls belongs to the instance.

func (*Instance) CheckPackage

func (vm *Instance) CheckPackage(moduleID string, parsed []ParsedUnit) (*Package, error)

CheckPackage compiles a package from its parsed files the way LoadPackage does, and reports the same compile errors, but runs none of its initializers: nothing in the package executes. It is for tools, such as editors, that check code without running it. The package counts as loaded, with its variables unset, so an instance used for checking is not one to run code in.

func (*Instance) CompileUnit

func (vm *Instance) CompileUnit(pu ParsedUnit) (err error)

CompileUnit compiles a parsed bare script without running it, so Dump can show it. A unit that declares a package is loaded the way EvalUnit loads it.

func (*Instance) Dump

func (vm *Instance) Dump(w io.Writer)

Dump writes a human-readable summary of every compiled package, global, class, function, local stack slot, escape analysis decision, and closure capture table in the VM. Enable Options.DebugInfo before compiling to also include local slot names, local classes, nested closures, and resolved capture names.

func (*Instance) EvalSource

func (vm *Instance) EvalSource(ctx context.Context, src *diag.Source) (Value, error)

EvalSource parses and evaluates a named source; errors show its text. A source that declares a package is loaded as that package and gives nil; a bare script gives its result. When ctx is done, the code stops with an error whose cause is ctx's cause, and so do the packages it imports while it loads.

func (*Instance) EvalUnit

func (vm *Instance) EvalUnit(ctx context.Context, pu ParsedUnit) (Value, error)

EvalUnit is EvalSource for a source that is already parsed

func (*Instance) Interrupt

func (vm *Instance) Interrupt()

Interrupt stops all code of the instance that is running or waiting now: calls from the host, package initializers and the tasks they started. Each stops at its next loop iteration or call, or as soon as it wakes from an await or a blocking native, and fails with an error whose cause is ErrInterrupted. Scripts cannot catch it. Calls made after Interrupt returns run normally. A native that is busy in Go finishes first; a blocking native stops early only when it watches Call.Context.

func (*Instance) LoadPackage

func (vm *Instance) LoadPackage(ctx context.Context, moduleID string, parsed []ParsedUnit) (*Package, error)

LoadPackage compiles one package from its parsed files and runs its initializers. The files are compiled together, so any of them can use what another declares; each must declare the same package. moduleID identifies the module, such as its canonical file or directory path; when empty, the package's declared name is used. When ctx is done, the initializers stop with an error whose cause is ctx's cause, and so do those of the packages it imports.

func (*Instance) Lookup

func (vm *Instance) Lookup(path string) (Value, bool)

Lookup resolves a symbol Value from the VM. If path contains a dot (e.g. "main.add", "io.println"), it resolves the symbol from that package. Otherwise, it checks package "main" and then the prelude.

func (*Instance) NewSession

func (vm *Instance) NewSession(name string) *Session

NewSession opens an incremental evaluation session against package name (defaulting to "main"). If a compiled package with that name is already loaded in the instance, the session attaches to it; otherwise a new package is created and registered.

func (*Instance) Package

func (vm *Instance) Package(key string) *Package

Package retrieves a loaded package by canonical module ID or declared short name; returns nil if not found.

func (*Instance) PackageByID

func (vm *Instance) PackageByID(id string) *Package

PackageByID retrieves a loaded package by its exact canonical module ID.

func (*Instance) Packages

func (vm *Instance) Packages() iter.Seq[*Package]

Packages iterates through loaded packages

func (*Instance) SetStatic

func (vm *Instance) SetStatic(name string, val Value)

SetStatic binds a symbol in the prelude, visible to every package

func (*Instance) Wait

func (vm *Instance) Wait()

Wait blocks until every task the instance's code started has finished

type Member

type Member struct {
	Name string
	// Signature shows how to call it, as in "readFile(path)"; for anything that
	// is not a function it is the name
	Signature string
	Doc       string // what it does, when documented
	// Yields reports that calling it waits on the outside world, such as a file
	// or a timer, and lets the instance's other tasks run in the meantime
	Yields bool
	Value  Value
}

Member describes a public member of a package for tools such as editors

type NameEvent

type NameEvent struct {
	Name     string
	Kind     NameKind
	Source   *diag.Source // the file the name is written in
	Pos      diag.Pos     // where it is written
	Declares bool         // a declaration, rather than a use

	// for a use, where the name is declared; unknown for names the host or the
	// prelude defines. A declaration declares itself.
	DeclSource *diag.Source
	DeclPos    diag.Pos

	IsStatic bool     // the binding cannot be assigned
	Package  *Package // for an import or a member of another package, that package
}

NameEvent is a name the compiler declared or resolved, for tools such as editors: go to definition, find references, hover. Options.OnName receives them while code compiles. A name can be reported more than once.

type NameKind

type NameKind uint8

NameKind says what a name refers to

const (
	NameVariable  NameKind = iota // a var or const inside a function or script, or a loop variable
	NameParameter                 // a function's parameter
	NameGlobal                    // a var or const at the top level of a package
	NameFunction                  // a function declared with a name
	NameClass                     // a class
	NameField                     // a field or method of a class, as in this.x
	NameImport                    // a package bound by imports(...)
	NameMember                    // a member of another package, as in util.f
	NamePrelude                   // a builtin, or a symbol the host makes visible everywhere
)

func (NameKind) String

func (k NameKind) String() string

String returns the kind in words, such as "parameter"

type NativeFn

type NativeFn = func(c Call) (Value, error)

NativeFn is a Go function exposed to evie code. It receives its arguments through the Call and returns a value or an error; an error becomes an evie exception the script can catch.

type Object

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

Object is the storage of an evie object: named fields in the order they were added. Keys and values sit in order in two slices. A small object finds a key by comparing them in turn, which beats hashing for a handful of fields; the objects one literal makes share their keys until one of them gets a new key or loses one.

An object with more than maxLinearKeys keys also keeps a hash table of slots, the way CPython's dict does (see hashIndex). A lookup or an insert hashes the key once and probes the table; growing it reuses the stored hashes; and the order stays the order of the slices. The table hangs off a pointer so that the many small objects stay small.

func NewObject

func NewObject(capacity int) *Object

NewObject makes an empty object with room for capacity fields

func ObjectOf

func ObjectOf(m map[string]Value) *Object

ObjectOf makes an object holding the entries of m, in the order of their keys

func (*Object) All

func (o *Object) All() iter.Seq2[string, Value]

All iterates over the keys and their values in order. Keys added while it runs are not visited and removed ones are skipped.

func (*Object) Clear

func (o *Object) Clear()

Clear removes every key

func (*Object) Delete

func (o *Object) Delete(key string) bool

Delete removes key and reports whether the object had it. The remaining keys keep their order. It never changes the old key slice in place, so a loop over the keys can go on while the object changes.

func (*Object) Get

func (o *Object) Get(key string) (Value, bool)

Get returns the value of key

func (*Object) Has

func (o *Object) Has(key string) bool

Has reports whether the object has key

func (*Object) Keys

func (o *Object) Keys() []string

Keys returns the keys in order

func (*Object) Len

func (o *Object) Len() int

Len is the number of keys

func (*Object) Map

func (o *Object) Map() map[string]Value

Map copies the object into a Go map

func (*Object) Set

func (o *Object) Set(key string, v Value)

Set sets key to v, adding it after the others when it is new. A big object hashes key once, whether it finds it or adds it.

type Options

type Options struct {
	Resolver PackageResolver // finds a package by import path when it is not loaded yet
	Prelude  *Package        // symbols visible everywhere without an import; the builtin types are added to it
	Stdout   io.Writer       // where echo writes; defaults to os.Stdout

	DebugInfo       bool // record slot names, local classes and nested closures during compilation for Dump
	DisableInlining bool // compile without the fast paths for constants, locals and known callees; for debugging the compiler

	// OnName, when set, receives every name the compiler declares or resolves,
	// with where it is declared, for tools such as editors. It is called while
	// code compiles, under the instance's runner.
	OnName func(NameEvent)
}

Options configures a new Instance

type Package

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

Package is a namespace of symbols: the globals of a compiled evie file, or the functions and constants a host registers for scripts to import.

func NewPackage

func NewPackage(name string) *Package

NewPackage creates an empty host package. Scripts import it by the name it is resolved under; an empty name is filled in from the import path.

func (*Package) Box

func (pkg *Package) Box() Value

Box boxes the package to be used as a value

func (*Package) Clone

func (pkg *Package) Clone() *Package

Clone returns an independent copy of the package's namespace so an engine can attach per-engine hints or prelude builtins without mutating a package shared with the caller or other engines.

func (*Package) Compiled

func (pkg *Package) Compiled() bool

Compiled reports whether the package was compiled from Evie source, rather than made by a host in Go

func (*Package) Describe

func (pkg *Package) Describe(name string) (Member, bool)

Describe tells tools about a public member: how to call it, what it does and whether calling it yields

func (*Package) Document

func (pkg *Package) Document(name, signature, doc string) *Package

Document describes a member, for tools; it does not change what the member does. signature shows how to call it, as in "readFile(path)".

func (*Package) Func

func (pkg *Package) Func(name string, arity int, fn NativeFn) *GoFunc

Func binds a native taking exactly arity arguments and returns it so that flags such as Blocking can be set

func (*Package) Get

func (pkg *Package) Get(name string) (value Value, exists bool)

Get returns a symbol's value

func (*Package) Has

func (pkg *Package) Has(name string) bool

Has reports whether a symbol exists

func (*Package) ID

func (pkg *Package) ID() string

ID returns the package's canonical module identifier (falling back to Name).

func (*Package) Members

func (pkg *Package) Members() []string

Members returns the names of the package's public members, sorted

func (*Package) Name

func (pkg *Package) Name() string

Name returns the package's declared name

func (*Package) Native

func (pkg *Package) Native(name string, fn *GoFunc) *GoFunc

Native binds an already built native under a name without mutating fn in place

func (*Package) Set

func (pkg *Package) Set(name string, value Value) *Package

Set binds a public read-only symbol on the package. Immutable values such as numbers, strings, functions and types may be folded by the compiler; mutable containers such as objects, arrays and buffers are read dynamically so later mutations are always visible.

func (*Package) SetID

func (pkg *Package) SetID(id string)

SetID sets the package's canonical module identifier.

func (*Package) SetMemberHint

func (pkg *Package) SetMemberHint(hint string)

SetMemberHint sets the help shown when a script asks the package for a member it does not have, such as which import to use instead

func (*Package) Variadic

func (pkg *Package) Variadic(name string, min int, fn NativeFn) *GoFunc

Variadic binds a native taking at least min arguments

type PackageResolver

type PackageResolver func(name string) (*Package, error)

PackageResolver resolves a package by import name or path.

type ParsedUnit

type ParsedUnit struct {
	Source *diag.Source
	Node   ast.Node
}

ParsedUnit pairs a named source with its already-parsed AST so a pre-parsed program (such as an evie.Bundle) can be compiled into multiple VM instances without re-reading or re-parsing source files.

type Session

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

Session supports incremental compilation and execution against a persistent package inside an Instance. Top-level variables, functions, classes, and imports persist across Eval calls, and failed turns roll back any bindings they added or shadowed.

func (*Session) BindImport

func (s *Session) BindImport(bindName, importPath string, dep *Package)

BindImport registers dep under bindName inside the session's package.

func (*Session) Compile

func (s *Session) Compile(src *diag.Source, node ast.Node) error

Compile compiles a parsed snippet against the session without executing its top-level statements (intended for syntax/compile checks and Dump).

func (*Session) Eval

func (s *Session) Eval(src *diag.Source, node ast.Node) (Value, bool, error)

Eval compiles and executes a parsed snippet in the session.

func (*Session) EvalContext

func (s *Session) EvalContext(ctx context.Context, src *diag.Source, node ast.Node) (Value, bool, error)

EvalContext compiles and executes a parsed snippet inside the session, bound to ctx. Top-level variables, functions, and classes persist across turns (and may be redeclared on later turns). If compilation or execution fails, any declarations added or overwritten by this turn are rolled back.

func (*Session) Has

func (s *Session) Has(name string) bool

Has reports whether name is currently defined in the session (as a user binding or an import).

func (*Session) Package

func (s *Session) Package() *Package

Package returns the underlying package that holds this session's symbols.

func (*Session) Symbols

func (s *Session) Symbols() []Symbol

Symbols returns every binding currently defined in the session, sorted by name.

type Symbol

type Symbol struct {
	Name     string
	Value    Value
	IsStatic bool
	IsImport bool
}

Symbol describes one binding currently defined in a Session's package.

type Task

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

Task represents an asynchronous unit of execution with memoized state.

func (*Task) Cancel

func (t *Task) Cancel()

Cancel asks the task to stop. It has no effect when the task has already settled.

func (*Task) Done

func (t *Task) Done() <-chan struct{}

Done returns a channel that is closed when the task completes.

func (*Task) Result

func (t *Task) Result() (Value, error)

Result returns what the task finished with, or an error that it failed with. It does not wait; use Done to wait for the task to finish.

type Value

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

Value represents a boxed value

func BoxAny

func BoxAny(v any) (Value, error)

BoxAny converts any Go value into an Evie Value.

func BoxArray

func BoxArray(arr *Array) Value

BoxArray boxes an evie array

func BoxBool

func BoxBool(b bool) Value

BoxBool boxes a boolean into

func BoxBuffer

func BoxBuffer(bytes []byte) Value

BoxBuffer boxes a Golang byte slice

func BoxGoFunc

func BoxGoFunc(fn *GoFunc) Value

BoxGoFunc boxes a Go function

func BoxNumber

func BoxNumber(f float64) Value

BoxNumber boxes a float64

func BoxObject

func BoxObject(obj *Object) Value

BoxObject boxes an evie object; nil boxes a new empty one

func BoxString

func BoxString(str string) Value

BoxString boxes a string

func (Value) AcceptsArgs

func (x Value) AcceptsArgs() bool

AcceptsArgs reports whether a callable value accepts one or more arguments

func (Value) AsArray

func (x Value) AsArray() (arr *Array, ok bool)

AsArray returns the value as an array, and whether it is one

func (Value) AsBool

func (x Value) AsBool() (b bool, ok bool)

AsBool returns the value as a bool, and whether it is one

func (Value) AsBuffer

func (x Value) AsBuffer() (buffer []byte, ok bool)

AsBuffer returns the value as a buffer's bytes, and whether it is one; the bytes are shared, not copied

func (Value) AsError

func (x Value) AsError() (err *Error, ok bool)

AsError returns the value as an error, and whether it is one

func (Value) AsFloat64

func (x Value) AsFloat64() (f float64, ok bool)

AsFloat64 returns the value as a number, and whether it is one

func (Value) AsGoFunc

func (x Value) AsGoFunc() (fn *GoFunc, ok bool)

AsGoFunc returns the value as a native function, and whether it is one

func (Value) AsHost

func (x Value) AsHost() (v any, t *HostType, ok bool)

AsHost unboxes a host value

func (Value) AsObject

func (x Value) AsObject() (obj *Object, ok bool)

AsObject returns the value as an object, and whether it is one

func (Value) AsPackage

func (x Value) AsPackage() (pkg *Package, ok bool)

AsPackage returns the value as a package, and whether it is one

func (Value) AsString

func (x Value) AsString() (s string, ok bool)

AsString returns the value as a string, and whether it is one

func (Value) AsTask

func (x Value) AsTask() (task *Task, ok bool)

AsTask returns the value as a task, and whether it is one

func (Value) Call

func (x Value) Call(args ...Value) (Value, error)

Call calls a callable value from Go: a script function, a native, a bound method or a type. A script function runs on a fiber of the instance it belongs to. A native or a builtin method belongs to no instance and runs as a plain Go call on the calling goroutine: outside the instance's runner, not stopped by Interrupt, and unable to start async work. Use Instance.CallValue to call one under an instance.

func (Value) ClassName

func (x Value) ClassName() (string, bool)

ClassName is the name of the class a class instance was made from

func (Value) Equals

func (x Value) Equals(y Value) bool

Equals reports whether x == y in Evie: nil, bools, numbers and strings compare by value, host values by their own equality, and everything else by identity

func (Value) Field

func (x Value) Field(name string) (Value, bool)

Field reads a field of an object or of a class instance by name

func (Value) IsCallable

func (x Value) IsCallable() bool

IsCallable reports whether the value can be invoked via Call: functions, bound methods, and class or builtin types, which construct a value.

func (Value) IsNil

func (x Value) IsNil() bool

IsNil reports whether the value is nil

func (Value) IsTruthy

func (x Value) IsTruthy() bool

IsTruthy reports whether the value counts as true in a condition: nil, false, 0 and an empty string, array, object or buffer do not, everything else does

func (Value) MarshalJSON

func (v Value) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for Evie values. It encodes nil, bool, finite numbers, strings, arrays, objects and class instances (without synthetic metadata keys) and rejects cycles, NaN/Inf, and non-JSON values such as functions, tasks, packages, errors and buffers.

func (Value) MarshalJSONTo

func (v Value) MarshalJSONTo(enc *jsontext.Encoder) error

MarshalJSONTo implements encoding/json/v2.MarshalerTo, streaming Evie values directly into a jsontext.Encoder without intermediate Go map/slice copies.

func (Value) SetField

func (x Value) SetField(name string, v Value) error

SetField sets a field of an object or a declared mutable field of a class instance by name.

func (Value) String

func (x Value) String() string

String returns the value as echo prints it

func (Value) ToGo

func (v Value) ToGo() any

ToGo converts an Evie Value into a standard Go type.

func (Value) TypeOf

func (x Value) TypeOf() string

TypeOf returns the name of the value's type, such as "number" or "array"

func (Value) Unmarshal

func (v Value) Unmarshal(target any) error

Unmarshal decodes the Evie Value into a Go target pointer.

func (*Value) UnmarshalJSON

func (v *Value) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler for Evie values.

func (*Value) UnmarshalJSONFrom

func (v *Value) UnmarshalJSONFrom(dec *jsontext.Decoder) error

UnmarshalJSONFrom implements encoding/json/v2.UnmarshalerFrom, decoding JSON directly into Evie values without intermediate Go map/slice allocations.

Jump to

Keyboard shortcuts

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