Documentation
¶
Overview ¶
Package evie embeds the Evie scripting language in a Go program.
Create an Engine with New to evaluate scripts, call Evie functions from Go, and expose host packages with Options. For multi-file programs or concurrent execution across isolated engines, parse once into an immutable Bundle with ParseFile, ParseProject or ParseSource. Use Format to render parse, compile, and runtime errors with source excerpts and traces.
eng := evie.New()
defer eng.Close()
eng.Eval(`package main
fn add(a, b) => a + b`)
sum, err := eng.Call("main.add", 2, 3)
Index ¶
- Variables
- func Check(b *Bundle) error
- func Eval(script string) (vm.Value, error)
- func Format(err error, colors bool) string
- func RunFile(path string) (vm.Value, error)
- type Bundle
- type Debug
- type Engine
- func (e *Engine) Call(path string, args ...any) (vm.Value, error)
- func (e *Engine) CallContext(ctx context.Context, path string, args ...any) (vm.Value, error)
- func (e *Engine) CallValue(fn vm.Value, args ...any) (vm.Value, error)
- func (e *Engine) Check(b *Bundle) error
- func (e *Engine) Close()
- func (e *Engine) Dump(w goio.Writer)
- func (e *Engine) Eval(script string) (vm.Value, error)
- func (e *Engine) EvalContext(ctx context.Context, script string) (vm.Value, error)
- func (e *Engine) Interrupt()
- func (e *Engine) Load(name string, src []byte) (*vm.Package, error)
- func (e *Engine) LoadBundle(ctx context.Context, b *Bundle) error
- func (e *Engine) Lookup(path string) (vm.Value, bool)
- func (e *Engine) NewSession() *Session
- func (e *Engine) RunBundle(ctx context.Context, b *Bundle) (vm.Value, error)
- func (e *Engine) RunFile(filePath string) (vm.Value, error)
- func (e *Engine) RunFileContext(ctx context.Context, filePath string) (vm.Value, error)
- func (e *Engine) RunProject(dirPath string) (vm.Value, error)
- func (e *Engine) SetStatic(name string, val vm.Value)
- func (e *Engine) Wait()
- type Options
- type Session
- func (s *Session) Compile(code string) error
- func (s *Session) Eval(code string) (val vm.Value, hasVal bool, err error)
- func (s *Session) EvalContext(ctx context.Context, code string) (val vm.Value, hasVal bool, err error)
- func (s *Session) Import(importPath, alias string) (*vm.Package, error)
- func (s *Session) LoadFile(filePath string) (vm.Value, bool, error)
- func (s *Session) Symbols() []vm.Symbol
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrClosed = errors.New("the engine is closed")
ErrClosed is returned by an engine that was closed
var ErrRanAlready = errors.New("this engine already ran a program; create a new engine for each program")
ErrRanAlready is returned when an engine is asked to run a second program
Functions ¶
func Check ¶
Check compiles a parsed program in a fresh engine without running any of it, and returns the compile errors a run would stop with, or nil. Parse with ParseFile or ParseProject first; their errors are the syntax errors.
func Eval ¶
Eval runs a script in a fresh engine and returns its result; ToGo turns it into a Go value
Example ¶
package main
import (
"fmt"
"github.com/hxkhan/evie"
)
func main() {
val, err := evie.Eval("return [1, 2, 3, 4].filter(fn(x) => x % 2 == 0).map(fn(x) => x * 10)")
if err != nil {
panic(err)
}
fmt.Println(val)
}
Output: [20, 40]
func Format ¶
Format renders an error the way the evie command prints it: the message, the source line with the span underlined, related places, a hint and the trace. Colors are for terminals. An error without a report renders as its text.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/hxkhan/evie"
)
func main() {
_, err := evie.Eval("x := 1\nx = 2")
fmt.Println(strings.Contains(evie.Format(err, false), "cannot assign to 'x'"))
}
Output: true
Types ¶
type Bundle ¶
type Bundle struct {
// contains filtered or unexported fields
}
Bundle is a parsed, import-resolved Evie program ready to be loaded or run in one or more independent Engines without touching the filesystem or re-parsing source files. A Bundle is immutable and safe to share across goroutines.
func ParseFile ¶
ParseFile parses a single Evie file and every package it imports by path, without running any code. The file and its imports are read from fsys, and cannot escape its root; a nil fsys means the operating system's file system.
func ParsePackage ¶
ParsePackage parses the package a directory holds, made of every .ev file in it, and every package it imports by path, without running any code. Every file must declare the same package. It is how a tool reads a package that a program imports by its directory, to check it on its own.
func ParseProject ¶
ParseProject parses an Evie project directory (every top-level file declaring package main) and every package it imports by path, without running any code. It reads from fsys the way ParseFile does.
Example ¶
package main
import (
"bytes"
"context"
"fmt"
"strings"
"testing/fstest"
"github.com/hxkhan/evie"
)
func main() {
fsys := fstest.MapFS{
"main.ev": &fstest.MapFile{
Data: []byte(`package main imports("io", "./util" as u)
fn main() {
io.println(u.greet("world"))
return u.greet("evie")
}`),
},
"util.ev": &fstest.MapFile{
Data: []byte(`package util
fn greet(name) => "hello, " + name`),
},
}
// Parse once into an immutable Bundle, then run in a sandboxed Engine.
bundle, err := evie.ParseProject(fsys, ".")
if err != nil {
panic(err)
}
var stdout bytes.Buffer
val, err := evie.New(evie.Options{
Stdlib: []string{"io"},
Stdout: &stdout,
}).RunBundle(context.Background(), bundle)
if err != nil {
panic(err)
}
fmt.Println("stdout:", strings.TrimSpace(stdout.String()))
fmt.Println("return:", val)
}
Output: stdout: hello, world return: hello, evie
func ParseSource ¶
ParseSource parses a program given as source text, and every package it imports by path, without running any code. name is what errors call the source; path imports resolve against the working directory.
type Debug ¶
type Debug struct {
DebugInfo bool // record slot names, local classes and nested closures during compilation for Dump
NoFastPaths bool // compile without the compiler's fast paths, to tell whether a bug is in one
}
Debug holds switches for working on Evie itself; hosts leave them off
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine is a VM instance together with everything needed to load programs: host packages, the standard library, and files or Bundles found through imports.
An engine runs one program. Packages are identified by the file or folder they come from, and each package name can be loaded once. Close an engine when done with it.
An engine can be used from several goroutines: loads and evaluations take turns, while Call, Lookup and Interrupt work alongside them. Looking up a package's symbols while that same package is still loading is not safe.
func New ¶
New creates an engine. With no options it offers the standard library and resolves imports relative to the file being run.
func (*Engine) Call ¶
Call looks up a callable by path (such as "main.add"), boxes the Go arguments with BoxAny and invokes it on a borrowed fiber.
Example ¶
package main
import (
"fmt"
"github.com/hxkhan/evie"
"github.com/hxkhan/evie/vm"
)
func main() {
api := vm.NewPackage("api")
api.Native("double", vm.Func1(func(n int) int { return n * 2 }))
eng := evie.New(evie.Options{Packages: []*vm.Package{api}})
defer eng.Close()
_, err := eng.Eval(`package main imports("api")
fn compute(name, n) {
return { name: name, value: api.double(n) + 1 }
}`)
if err != nil {
panic(err)
}
val, err := eng.Call("main.compute", "score", 20)
if err != nil {
panic(err)
}
var out struct {
Name string `json:"name"`
Value int `json:"value"`
}
if err := val.Unmarshal(&out); err != nil {
panic(err)
}
fmt.Printf("%s = %d\n", out.Name, out.Value)
}
Output: score = 41
func (*Engine) CallContext ¶
CallContext is Call bound to ctx: when ctx is done, the call and any tasks it starts stop with ctx's cause.
Example ¶
package main
import (
"context"
"errors"
"fmt"
"time"
"github.com/hxkhan/evie"
)
func main() {
eng := evie.New(evie.Options{NoStdlib: true})
defer eng.Close()
_, err := eng.Eval(`package main
fn spin() {
while true {}
}`)
if err != nil {
panic(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
_, err = eng.CallContext(ctx, "main.spin")
fmt.Println("timed out:", errors.Is(err, context.DeadlineExceeded))
}
Output: timed out: true
func (*Engine) CallValue ¶
CallValue calls a callable value, such as one a script returned, under the engine: see vm.Instance.CallValue
func (*Engine) Check ¶
Check compiles a pre-parsed Bundle, and every package it imports, without running any of it: no package initializer, no main, nothing a script does at its top level. It returns the compile errors a run would stop with before starting (a vm.CompileErrors when a package has several), or nil. Like a run, it uses the engine's host packages and options. The checked packages count as loaded but never ran, so use an engine for checking only.
func (*Engine) Close ¶
func (e *Engine) Close()
Close stops everything still running in the engine, waits for it to end, and makes every later load, run or call return ErrClosed. Use Wait instead to let background tasks finish.
func (*Engine) Dump ¶
Dump writes a human-readable summary of every compiled package, global, class, function, local stack slot, escape decision, and closure capture in the engine. Set Options.Debug.DebugInfo before loading to include slot names, local classes, nested closures, and resolved capture names.
func (*Engine) Eval ¶
Eval parses and runs a script. A script that declares a package is loaded as that package and nil is returned; a bare script returns its result.
func (*Engine) EvalContext ¶
EvalContext is Eval bound to ctx: when ctx is done, the script stops with an error whose cause is ctx's cause, such as context.DeadlineExceeded
func (*Engine) Interrupt ¶
func (e *Engine) Interrupt()
Interrupt stops all code currently running or waiting in this engine. The engine stays usable.
func (*Engine) Load ¶
Load compiles a source that declares a package and returns the package; name is what errors call the source. Loading a package name a second time is an error.
func (*Engine) LoadBundle ¶
LoadBundle compiles and loads a pre-parsed Bundle into the engine in dependency order without running main.main (or a bare script). When ctx is done, package initializers stop with ctx's cause.
func (*Engine) Lookup ¶
Lookup resolves a symbol from a loaded package ("pkg.sym") or main/prelude ("sym").
func (*Engine) NewSession ¶
NewSession opens an incremental evaluation session on e's "main" package. If e has already loaded a compiled "main" package, the session attaches to it so existing globals and functions are directly accessible.
func (*Engine) RunBundle ¶
RunBundle compiles, loads, and runs a pre-parsed Bundle without touching the filesystem or re-parsing any source files: main.main for a program, or the script itself. When ctx is done, package initializers, main.main, and any tasks they start stop with ctx's cause.
func (*Engine) RunFile ¶
RunFile evaluates a script file, resolving its imports relative to it (or inside Options.FS when configured), and runs main.main when defined.
func (*Engine) RunFileContext ¶
RunFileContext is RunFile bound to ctx: when ctx is done, the program stops with an error whose cause is ctx's cause, such as context.DeadlineExceeded.
func (*Engine) RunProject ¶
RunProject runs the program in a directory (on disk or inside Options.FS). Every file at its top level that declares package main is part of the main package; the other files and subfolders are packages imported by path. To bind the run to a context, parse it with ParseProject and use RunBundle.
type Options ¶
type Options struct {
FS iofs.FS // filesystem for file/project loading, relative imports and the fs package, which can then only read from it; defaults to the OS filesystem
NoStdlib bool // do not offer the standard library packages
Stdlib []string // when non-empty, only allow these standard library packages (e.g. "math", "json"); New panics on a name that is not one
Packages []*vm.Package // host packages, importable by their names
Resolve func(path string) (*vm.Package, error) // consulted last, for an import by name that no host, standard or loaded package answers; path imports never reach it
Root string // where an import that is not relative to its file, such as "lib/x", and a path import in Eval start from; the entry file's directory when empty
Prelude *vm.Package // symbols visible to every script without an import
Args []string // arguments passed to main when it accepts parameters
Stdin goio.Reader // standard input for the io package; defaults to os.Stdin
Stdout goio.Writer // standard output for the io package and echo; defaults to os.Stdout
// OnName, when set, receives every name the compiler declares or resolves,
// with where it is declared, for tools such as editors; see vm.NameEvent.
// Use it with Check to learn about a program without running it.
OnName func(vm.NameEvent)
Debug Debug // switches for working on Evie itself
}
Options configures an Engine. The zero value gives the standard library, relative imports resolved against the entry file, and no host packages.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session runs Evie code incrementally against a persistent package inside an Engine. Variables, functions, classes, and imports persist across Eval calls, trailing expressions return their value (and bind `_`), and standard library packages referenced as `pkg.sym` auto-import when allowed by Options.
A Session can be opened on a fresh Engine (for a REPL, notebook, or stateful scripting) or on an Engine that already loaded a program (for a live debug console attached to package main).
func (*Session) Compile ¶
Compile parses and compiles code against the session without running its top-level statements (intended for validation or Engine.Dump).
func (*Session) Eval ¶
Eval parses and executes one snippet against the session. When hasVal is true, val is the result of the trailing expression (or an explicit return).
func (*Session) EvalContext ¶
func (s *Session) EvalContext(ctx context.Context, code string) (val vm.Value, hasVal bool, err error)
EvalContext is Eval bound to ctx.
func (*Session) Import ¶
Import resolves importPath (a stdlib name, host package, or relative file / directory path) and binds it in the session under alias (or the package's declared name when alias is empty).
Directories
¶
| Path | Synopsis |
|---|---|
|
Package analysis checks Evie code without running it and answers what an editor asks about it: errors, an outline, where a name is declared and used, hover text and completions.
|
Package analysis checks Evie code without running it and answers what an editor asks about it: errors, an outline, where a name is declared and used, hover text and completions. |
|
Command benchmarks runs the Evie benchmark suite, verifies each program's result and optionally compares the timings against a previously saved run.
|
Command benchmarks runs the Evie benchmark suite, verifies each program's result and optionally compares the timings against a previously saved run. |
|
compare
command
Command compare benchmarks Evie against other scripting languages across a shared suite of workloads, verifying that every implementation prints the exact expected checksum.
|
Command compare benchmarks Evie against other scripting languages across a shared suite of workloads, verifying that every implementation prints the exact expected checksum. |
|
Package diag renders errors the way a compiler should: the message, the offending line with the span underlined and labelled, related places, a hint, and for runtime errors the chain of calls that led there.
|
Package diag renders errors the way a compiler should: the message, the offending line with the span underlined and labelled, related places, a hint, and for runtime errors the chain of calls that led there. |
|
embedding
|
|
|
ex1
command
|
|
|
ex2
command
|
|
|
ex3
command
|
|
|
Command evie runs Evie programs or starts an interactive REPL.
|
Command evie runs Evie programs or starts an interactive REPL. |
|
extensions
|
|
|
vscode/lsp
command
Command lsp is Evie's analysis compiled to WebAssembly for the VS Code extension's language server.
|
Command lsp is Evie's analysis compiled to WebAssembly for the VS Code extension's language server. |
|
internal
|
|
|
token
Package token holds the tokens the lexer hands the parser.
|
Package token holds the tokens the lexer hands the parser. |
|
site
|
|
|
wasm
command
Command wasm is Evie compiled to WebAssembly for the website's playground.
|
Command wasm is Evie compiled to WebAssembly for the website's playground. |
|
std
|
|
|
fs
Package fs is Evie's file system package.
|
Package fs is Evie's file system package. |
|
io
Package io is Evie's console package: print, println, prompt and readln.
|
Package io is Evie's console package: print, println, prompt and readln. |
|
math
Package math is Evie's math package: constants, rounding, powers and logarithms, trigonometry and random numbers.
|
Package math is Evie's math package: constants, rounding, powers and logarithms, trigonometry and random numbers. |
|
time
Package time is Evie's time package.
|
Package time is Evie's time package. |