Documentation
¶
Index ¶
- Constants
- Variables
- func HostArg[T any](c Call, i int) (T, error)
- type Array
- type Call
- func (c Call) Arg(i int) Value
- func (c Call) Args() []Value
- func (c Call) Array(i int) (*Array, error)
- func (c Call) Async(fn func(ctx context.Context) (Value, error)) Value
- func (c Call) Bool(i int) (bool, error)
- func (c Call) Buffer(i int) ([]byte, error)
- func (c Call) Call(fn Value, args ...Value) (Value, error)
- func (c Call) Callable(i int) (Value, error)
- func (c Call) Context() context.Context
- func (c Call) Int(i int) (int, error)
- func (c Call) Int64(i int) (int64, error)
- func (c Call) Len() int
- func (c Call) Number(i int) (float64, error)
- func (c Call) Object(i int) (*Object, error)
- func (c Call) String(i int) (string, error)
- func (c Call) This() Value
- type CompileError
- type CompileErrors
- type Error
- func (e *Error) CauseValue() Value
- func (e *Error) Diagnostic() *diag.Report
- func (e *Error) Error() string
- func (e *Error) Field(name string) (Value, bool)
- func (e *Error) FieldNames() []string
- func (e *Error) Kind() string
- func (e *Error) Unwrap() error
- func (e *Error) With(name string, v Value) *Error
- type GoFunc
- func Func0[R any](f func() R) *GoFunc
- func Func0E[R any](f func() (R, error)) *GoFunc
- func Func1[A, R any](f func(A) R) *GoFunc
- func Func1E[A, R any](f func(A) (R, error)) *GoFunc
- func Func2[A, B, R any](f func(A, B) R) *GoFunc
- func Func2E[A, B, R any](f func(A, B) (R, error)) *GoFunc
- func Func3[A, B, C, R any](f func(A, B, C) R) *GoFunc
- func Func3E[A, B, C, R any](f func(A, B, C) (R, error)) *GoFunc
- func NewFunc(name string, arity int, fn NativeFn) *GoFunc
- func NewVariadic(name string, min int, fn NativeFn) *GoFunc
- func Reflect(fn any) *GoFunc
- type HostType
- type Instance
- func (vm *Instance) Call(path string, args ...any) (Value, error)
- func (vm *Instance) CallContext(ctx context.Context, path string, args ...any) (Value, error)
- func (vm *Instance) CallValue(fn Value, args ...any) (Value, error)
- func (vm *Instance) CheckPackage(moduleID string, parsed []ParsedUnit) (*Package, error)
- func (vm *Instance) CompileUnit(pu ParsedUnit) (err error)
- func (vm *Instance) Dump(w io.Writer)
- func (vm *Instance) EvalSource(ctx context.Context, src *diag.Source) (Value, error)
- func (vm *Instance) EvalUnit(ctx context.Context, pu ParsedUnit) (Value, error)
- func (vm *Instance) Interrupt()
- func (vm *Instance) LoadPackage(ctx context.Context, moduleID string, parsed []ParsedUnit) (*Package, error)
- func (vm *Instance) Lookup(path string) (Value, bool)
- func (vm *Instance) NewSession(name string) *Session
- func (vm *Instance) Package(key string) *Package
- func (vm *Instance) PackageByID(id string) *Package
- func (vm *Instance) Packages() iter.Seq[*Package]
- func (vm *Instance) SetStatic(name string, val Value)
- func (vm *Instance) Wait()
- type Member
- type NameEvent
- type NameKind
- type NativeFn
- type Object
- func (o *Object) All() iter.Seq2[string, Value]
- func (o *Object) Clear()
- func (o *Object) Delete(key string) bool
- func (o *Object) Get(key string) (Value, bool)
- func (o *Object) Has(key string) bool
- func (o *Object) Keys() []string
- func (o *Object) Len() int
- func (o *Object) Map() map[string]Value
- func (o *Object) Set(key string, v Value)
- type Options
- type Package
- func (pkg *Package) Box() Value
- func (pkg *Package) Clone() *Package
- func (pkg *Package) Compiled() bool
- func (pkg *Package) Describe(name string) (Member, bool)
- func (pkg *Package) Document(name, signature, doc string) *Package
- func (pkg *Package) Func(name string, arity int, fn NativeFn) *GoFunc
- func (pkg *Package) Get(name string) (value Value, exists bool)
- func (pkg *Package) Has(name string) bool
- func (pkg *Package) ID() string
- func (pkg *Package) Members() []string
- func (pkg *Package) Name() string
- func (pkg *Package) Native(name string, fn *GoFunc) *GoFunc
- func (pkg *Package) Set(name string, value Value) *Package
- func (pkg *Package) SetID(id string)
- func (pkg *Package) SetMemberHint(hint string)
- func (pkg *Package) Variadic(name string, min int, fn NativeFn) *GoFunc
- type PackageResolver
- type ParsedUnit
- type Session
- func (s *Session) BindImport(bindName, importPath string, dep *Package)
- func (s *Session) Compile(src *diag.Source, node ast.Node) error
- func (s *Session) Eval(src *diag.Source, node ast.Node) (Value, bool, error)
- func (s *Session) EvalContext(ctx context.Context, src *diag.Source, node ast.Node) (Value, bool, error)
- func (s *Session) Has(name string) bool
- func (s *Session) Package() *Package
- func (s *Session) Symbols() []Symbol
- type Symbol
- type Task
- type Value
- func (x Value) AcceptsArgs() bool
- func (x Value) AsArray() (arr *Array, ok bool)
- func (x Value) AsBool() (b bool, ok bool)
- func (x Value) AsBuffer() (buffer []byte, ok bool)
- func (x Value) AsError() (err *Error, ok bool)
- func (x Value) AsFloat64() (f float64, ok bool)
- func (x Value) AsGoFunc() (fn *GoFunc, ok bool)
- func (x Value) AsHost() (v any, t *HostType, ok bool)
- func (x Value) AsObject() (obj *Object, ok bool)
- func (x Value) AsPackage() (pkg *Package, ok bool)
- func (x Value) AsString() (s string, ok bool)
- func (x Value) AsTask() (task *Task, ok bool)
- func (x Value) Call(args ...Value) (Value, error)
- func (x Value) ClassName() (string, bool)
- func (x Value) Equals(y Value) bool
- func (x Value) Field(name string) (Value, bool)
- func (x Value) IsCallable() bool
- func (x Value) IsNil() bool
- func (x Value) IsTruthy() bool
- func (v Value) MarshalJSON() ([]byte, error)
- func (v Value) MarshalJSONTo(enc *jsontext.Encoder) error
- func (x Value) SetField(name string, v Value) error
- func (x Value) String() string
- func (v Value) ToGo() any
- func (x Value) TypeOf() string
- func (v Value) Unmarshal(target any) error
- func (v *Value) UnmarshalJSON(data []byte) error
- func (v *Value) UnmarshalJSONFrom(dec *jsontext.Decoder) error
Constants ¶
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 ¶
var ErrCanceled = errors.New("cancelled")
ErrCanceled is the cause of the error a task stops with when it is cancelled.
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 ¶
Types ¶
type Array ¶
type Array struct {
Data []Value
}
Array is the backing store of an evie array value
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) Async ¶
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) 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 ¶
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 ¶
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
type CompileError ¶
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 ¶
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 ¶
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 ¶
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 ¶
Diagnostic is the error's report, which names its kind unless that is the default, so a rendered error reads error[notFound]: ...
func (*Error) FieldNames ¶
FieldNames lists the fields the error was given, in the order they were given
func (*Error) Kind ¶
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.
type GoFunc ¶
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 NewVariadic ¶
NewVariadic describes a native taking at least min arguments
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 ¶
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 ¶
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 ¶
Constructor makes the type callable from scripts, as in File("x")
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 (*Instance) Call ¶
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 ¶
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 ¶
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 ¶
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 ¶
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) 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 ¶
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 ¶
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 ¶
Package retrieves a loaded package by canonical module ID or declared short name; returns nil if not found.
func (*Instance) PackageByID ¶
PackageByID retrieves a loaded package by its exact canonical module ID.
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 )
type NativeFn ¶
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 (*Object) All ¶
All iterates over the keys and their values in order. Keys added while it runs are not visited and removed ones are skipped.
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 ¶
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) Clone ¶
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 ¶
Compiled reports whether the package was compiled from Evie source, rather than made by a host in Go
func (*Package) Describe ¶
Describe tells tools about a public member: how to call it, what it does and whether calling it yields
func (*Package) Document ¶
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 binds a native taking exactly arity arguments and returns it so that flags such as Blocking can be set
func (*Package) Native ¶
Native binds an already built native under a name without mutating fn in place
func (*Package) Set ¶
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) SetMemberHint ¶
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
type PackageResolver ¶
PackageResolver resolves a package by import name or path.
type ParsedUnit ¶
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 ¶
BindImport registers dep under bindName inside the session's package.
func (*Session) Compile ¶
Compile compiles a parsed snippet against the session without executing its top-level statements (intended for syntax/compile checks and Dump).
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 ¶
Has reports whether name is currently defined in the session (as a user binding or an import).
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.
type Value ¶
type Value struct {
// contains filtered or unexported fields
}
Value represents a boxed value
func (Value) AcceptsArgs ¶
AcceptsArgs reports whether a callable value accepts one or more arguments
func (Value) AsBuffer ¶
AsBuffer returns the value as a buffer's bytes, and whether it is one; the bytes are shared, not copied
func (Value) Call ¶
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) Equals ¶
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) IsCallable ¶
IsCallable reports whether the value can be invoked via Call: functions, bound methods, and class or builtin types, which construct a value.
func (Value) IsTruthy ¶
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 ¶
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 ¶
MarshalJSONTo implements encoding/json/v2.MarshalerTo, streaming Evie values directly into a jsontext.Encoder without intermediate Go map/slice copies.
func (Value) SetField ¶
SetField sets a field of an object or a declared mutable field of a class instance by name.
func (*Value) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler for Evie values.