evie

package module
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: 24 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

The Evie Programming Language

Evie is a lightweight, dynamically typed scripting language written in pure Go without CGO. Combining the dynamic ergonomics of JavaScript and Python with Go's simplicity and Rust's safe-by-default immutability, Evie features cooperative fibers with go and await, first-class OOP with classes and inheritance, and seamless Go host embedding.

On an eight-workload cross-language suite, Evie is the fastest of the languages a Go program can embed: 4 to 10 times faster than gopher-lua, Tengo, Starlark, goja and Yaegi. It is also slightly faster overall than PUC Lua 5.4, written in C, and about twice as fast as Google's V8 Ignition JavaScript interpreter. See here.


Showcase

Recursive Fibonacci (examples/fib.ev)
A snippet of Evie code
String Interpolation & I/O (examples/input.ev)
A snippet of Evie code
Concurrent Tasks with go (examples/go.ev)
A snippet of Evie code

Tasks spawned with go run as fibers of the instance and return stateful, memoized Task handles that can be awaited (await task, await.all, await.any, await.race, await.timeout) or cancelled (task.cancel()). Only one fiber of an instance executes Evie code at a time; a fiber hands over at await and inside blocking host functions such as time.wait, so shared state never needs locking and a script can never race.

To test this program, run go run ./evie -t ./examples/go.ev.

The flag -t prints how long the program took, parsing and compiling included.

Shared state without locks (examples/race.ev)

Two tasks incrementing one global always end at the exact total, because fibers of an instance interleave only at await and in blocking host calls. To use several CPU cores, a host creates several instances; each has its own heap and nothing is shared between them.


Key Features

  • Cooperative & Expressive Concurrency:
    • go spawns concurrent fibers returning stateful Task instances.
    • await pauses the fiber until task resolution with multi-await memoization.
    • Multi-task coordination, deadlines, and cancellation via await.all(), await.any(), await.race(), await.timeout(), and task.cancel().
  • One Running Fiber per Instance:
    • Fibers hand over at await and inside blocking host functions, so arrays, objects, classes and globals need no locks and cannot race.
    • Parallelism across instances: every vm.Instance has its own runner and heap.
  • Safe-by-Default Immutability:
    • x := 10 creates an immutable binding.
    • var x := 10 is explicitly required for mutability.
  • First-Class Classes & OOP:
    • Fixed-shape classes with declared body fields (field := ... immutable, var field := ... mutable) and per-instance initializers.
    • Encapsulated methods with implicit this.
    • Classical single inheritance (class Sub : Super { ... }) with super.method() calls.
    • First-class bound methods (fnVal := p.greet).
    • Polymorphic type checks (p is Person, dog is Animal).
  • Modern Control Flow & Collections:
    • if, else, switch, while, break, and continue.
    • for item in collection and for idx, item in collection over arrays, objects, strings, and buffers.
    • Indexing and slicing (arr[a:b], str[a:b], buf[a:b]) with UTF-8 character semantics on strings.
  • Robust Error Handling:
    • throw and catch(expr) or catch { ... } with first-class error values: a message, a kind such as "notFound" or "timeout" to tell failures apart, any fields and a cause, and the file, line, column and call trace.
    • Compiler-grade diagnostics: every error shows the offending line with the span underlined, related places, a hint, and suggestions for misspelled names.
  • Compact 16-Byte Tagged Value:
    • Compact 16-byte tagged Value (uint64 + unsafe.Pointer) storing number, bool, and nil inline without heap allocation (number, bool, string, buffer, array, object, class, task, error, function, nil).
  • Seamless Go Host Embedding:
    • Go functions become natives through typed wrappers (vm.Func1(goFunc)) or reflection (vm.Reflect(goFunc)).
    • Bidirectional marshaling and unmarshaling into native Go structs (val.Unmarshal(&struct), json.Marshal(val)).
    • Per-engine stdlib sandboxing (Options.Stdlib, Options.NoStdlib), virtual/embedded filesystems (Options.FS confines imports and the fs package, which can then only read from it), and custom I/O streams (Options.Stdin, Options.Stdout).
    • Parse once, run anywhere: evie.ParseFile, ParseProject and ParseSource produce an immutable *evie.Bundle that eng.RunBundle runs in any number of independent engines at once.
    • One-line script execution (evie.Eval(...)).
    • Stopping runaway scripts with Interrupt() or a context deadline, without the script being able to catch it.
  • Pure Go (Zero CGO):
    • 100% Go codebase, fast builds, effortless cross-compilation, and zero external dependencies.

Go Host Embedding Example

Embedding Evie in your Go application requires no CGO or complicated bindings:

package main

import (
    "fmt"
    "github.com/hxkhan/evie"
    "github.com/hxkhan/evie/vm"
)

func main() {
    // 1. A host package the script can import. Func1 wraps a Go function without reflection.
    api := vm.NewPackage("api")
    api.Native("fetchData", vm.Func1(func(id int) map[string]any {
        return map[string]any{"id": id, "status": "active"}
    }))

    // 2. An engine with the standard library and the host package
    eng := evie.New(evie.Options{Packages: []*vm.Package{api}})
    defer eng.Close()

    // 3. Load a script
    _, err := eng.Eval(`package main imports("api")
        fn status(id) {
            data := api.fetchData(id)
            return data.status
        }`)
    if err != nil {
        panic(err)
    }

    // 4. Call into it with Go arguments; evie.Format prints an error the way the CLI does
    val, err := eng.Call("main.status", 42)
    if err != nil {
        fmt.Print(evie.Format(err, false))
    }
    fmt.Println(val) // active

    // 5. One-line evaluation
    result, _ := evie.Eval("return [1, 2, 3].len() * 10")
    fmt.Println(result) // 30
}

Natives can also be written against the call context directly, which is the fastest path and gives full control over argument checking (use c.Async for background tasks tied to the engine's lifecycle):

pkg.Func("wait", 1, func(c vm.Call) (vm.Value, error) {
    ms, err := c.Number(0) // "wait: argument 1 must be a number, got string"
    if err != nil {
        return vm.Value{}, err
    }
    timer := time.NewTimer(time.Duration(ms) * time.Millisecond)
    defer timer.Stop()
    select {
    case <-timer.C:
        return vm.Value{}, nil
    case <-c.Context().Done(): // the script was stopped
        return vm.Value{}, context.Cause(c.Context())
    }
}).Blocking = true // gives the instance to other fibers while it sleeps

Runaway scripts can be stopped from any goroutine with eng.Interrupt(), or bounded by a context:

ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
_, err := eng.CallContext(ctx, "main.status", 42) // errors.Is(err, context.DeadlineExceeded) after 2s

Features Checklist

  • Variables & Immutability (:= vs var :=)
  • Functions, Closures & Variadic Arguments (...args)
  • Primitive types (number, bool, nil)
  • Reference types (string, buffer, array, object, function, task, error)
  • Classes & OOP (fixed-shape layout, body fields, methods, this, single inheritance, super, bound methods)
  • Control flow (if, else, switch, while, break, continue)
  • For loops (for item in col, for idx, item in col) & slicing (arr[a:b], str[a:b], buf[a:b])
  • Operators (+, -, *, /, %, ==, !=, <, <=, >, >=, ?)
  • Logical operators (!, &&, ||)
  • Type checking (is operator)
  • Concurrency (go, await, await.all, await.any, await.race, await.timeout, Task, task.cancel)
  • One running fiber per instance (no locks, no data races, cooperative await)
  • Scoping (global, package, function, block, captured closures)
  • Error handling (throw, catch, error values with kinds, fields and causes)
  • Go Host Embedding (bidirectional marshaling, function reflection, struct unmarshaling, stdlib sandboxing, custom I/O)
  • Standard library (io, fs, math, time, json)
  • Compiler-style diagnostics (source excerpts, spans, hints, did-you-mean, stack traces)
  • Interrupts and deadlines for runaway scripts (Interrupt, RunFileContext, CallContext)
  • Interactive REPL (evie with multi-line input, persistent vm.Session state, and :help commands)
  • Package management ⏳

Documentation

For a comprehensive guide covering grammar, types, standard methods, and concurrency patterns, see:


Benchmarks

Across the 8-workload checksum-verified cross-language suite (median wall time of 5 runs after 1 warm-up on P-cores, process startup included). Every program must print the same checksum in every language, so a broken port fails instead of posting a time.

Languages you can embed in Go. Evie is the fastest on every benchmark:

Benchmark Evie gopher-lua Tengo Starlark goja (JS) Yaegi (Go)
classes 31.2ms 165.8ms 141.7ms 227.6ms 189.7ms 1.92s
closures 33.8ms 196.1ms 127.4ms 283.7ms 188.8ms 1.08s
fib 337.4ms 1.78s 1.77s 4.80s 2.68s 17.54s
mandelbrot 79.7ms 272.8ms 562.7ms 750.2ms 1.17s 485.1ms
matmul 38.1ms 110.3ms 198.7ms 266.8ms 256.5ms 207.6ms
objects 34.7ms 108.0ms 109.7ms 104.7ms 136.2ms 111.6ms
sieve 61.1ms 218.4ms 411.8ms 457.9ms 610.1ms 369.4ms
strings 40.3ms 283.2ms 84.4ms 64.0ms 102.9ms 94.0ms
Geomean 55.7ms 241.7ms 246.6ms 342.7ms 353.8ms 587.4ms
vs Evie 1.00x 4.34x 4.43x 6.16x 6.36x 10.55x

Interpreters written in C and C++. Evie is slightly ahead of Lua 5.4 overall, though Lua still wins numeric loops and big dictionaries:

Benchmark Evie (Go) Lua 5.4 (C) QuickJS (C) Python 3 (C) V8 --jitless (C++) Wren (C)
classes 31.2ms 39.3ms 46.8ms 69.7ms 73.0ms 49.3ms
closures 33.8ms 35.1ms 50.0ms 88.7ms 76.9ms 76.9ms
fib 337.4ms 449.0ms 640.0ms 908.1ms 663.8ms 956.0ms
mandelbrot 79.7ms 61.6ms 151.2ms 226.3ms 166.3ms 242.2ms
matmul 38.1ms 28.5ms 58.4ms 82.0ms 92.9ms 133.9ms
objects 34.7ms 21.7ms 39.5ms 53.3ms 73.5ms 60.2ms
sieve 61.1ms 55.4ms 102.5ms 134.5ms 125.1ms 151.0ms
strings 40.3ms 90.9ms 43.7ms 41.1ms 85.1ms 361.3ms
Geomean 55.7ms 57.5ms 83.4ms 115.0ms 120.7ms 157.9ms
vs Evie 1.00x 1.03x 1.50x 2.07x 2.17x 2.84x

Measured on an Intel i5-13400F under Windows 11 (.\benchmarks\compare\bench.ps1 -Runs 5 -Warmup 1 -Affinity 0x0FFF). >1.00x means Evie is faster.

The internal benchmark suite tracks 30 programs covering calls, closures, classes, method dispatch, host calls, strings, objects, errors and tasks; results/latest.md has the current numbers.


Setup & Quick Start

Prerequisites
Install or Build
# Install the CLI directly with Go
go install github.com/hxkhan/evie/evie@latest

# Or clone and build from source
git clone https://github.com/hxkhan/evie.git
cd evie
go build ./evie

# Start an interactive REPL (multi-line input, persistent state, :help for commands)
./evie

# Run an example
./evie ./examples/fib.ev

# Ctrl+C stops a running script with an error that shows where it was; press it again to exit at once

# Run code without a file; the standard packages it names are imported for it
./evie -e 'math.sqrt(2)'
./evie -e 'for w in "go evie go".fields() { io.println(w.toUpper()) }'

# Inspect compiled packages, globals, classes, slots, escapes and closure captures without running main
./evie -dump ./examples/captures.ev

# Report syntax and compile errors without running anything; exit status 1 when there are any
./evie -check ./examples/fib.ev

# Print the version (also -v), or the commit the binary was built from
./evie --version
Editor Support

The VS Code extension in extensions/vscode shows errors as you type, and offers go to definition, find all references, hover, completion and an outline. Its analysis is Evie's own compiler, compiled to WebAssembly, so it needs nothing else installed. Build it with npm install && npm run package in that folder, then install the .vsix. Other tools can use the analysis package directly.

Run Tests
go test ./...
go vet ./...

License

Licensed under the Apache License, Version 2.0. See NOTICE for attribution details.

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

Examples

Constants

This section is empty.

Variables

View Source
var ErrClosed = errors.New("the engine is closed")

ErrClosed is returned by an engine that was closed

View Source
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

func Check(b *Bundle) error

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

func Eval(script string) (vm.Value, error)

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

func Format(err error, colors bool) string

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

func RunFile

func RunFile(path string) (vm.Value, error)

RunFile executes a script file in a fresh engine and runs its main function

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

func ParseFile(fsys iofs.FS, filePath string) (*Bundle, error)

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

func ParsePackage(fsys iofs.FS, dirPath string) (*Bundle, error)

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

func ParseProject(fsys iofs.FS, dirPath string) (*Bundle, error)

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

func ParseSource(name string, src []byte) (*Bundle, error)

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.

func (*Bundle) Files

func (b *Bundle) Files() []string

Files returns a copy of every source file path in the bundle, in load order.

func (*Bundle) Packages

func (b *Bundle) Packages() []string

Packages returns a copy of the declared package names in topological load order.

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

func New(opts ...Options) *Engine

New creates an engine. With no options it offers the standard library and resolves imports relative to the file being run.

func (*Engine) Call

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

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

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

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

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

CallValue calls a callable value, such as one a script returned, under the engine: see vm.Instance.CallValue

func (*Engine) Check

func (e *Engine) Check(b *Bundle) error

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

func (e *Engine) Dump(w goio.Writer)

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

func (e *Engine) Eval(script string) (vm.Value, error)

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

func (e *Engine) EvalContext(ctx context.Context, script string) (vm.Value, error)

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

func (e *Engine) Load(name string, src []byte) (*vm.Package, error)

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

func (e *Engine) LoadBundle(ctx context.Context, b *Bundle) error

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

func (e *Engine) Lookup(path string) (vm.Value, bool)

Lookup resolves a symbol from a loaded package ("pkg.sym") or main/prelude ("sym").

func (*Engine) NewSession

func (e *Engine) NewSession() *Session

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

func (e *Engine) RunBundle(ctx context.Context, b *Bundle) (vm.Value, error)

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

func (e *Engine) RunFile(filePath string) (vm.Value, error)

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

func (e *Engine) RunFileContext(ctx context.Context, filePath string) (vm.Value, error)

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

func (e *Engine) RunProject(dirPath string) (vm.Value, error)

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.

func (*Engine) SetStatic

func (e *Engine) SetStatic(name string, val vm.Value)

SetStatic binds a symbol in the engine's prelude, visible to every package without an import.

func (*Engine) Wait

func (e *Engine) Wait()

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

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

func (s *Session) Compile(code string) error

Compile parses and compiles code against the session without running its top-level statements (intended for validation or Engine.Dump).

func (*Session) Eval

func (s *Session) Eval(code string) (val vm.Value, hasVal bool, err error)

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

func (s *Session) Import(importPath, alias string) (*vm.Package, error)

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).

func (*Session) LoadFile

func (s *Session) LoadFile(filePath string) (vm.Value, bool, error)

LoadFile reads a .ev file, inside Options.FS when one is set, and evaluates its statements into the session; its imports resolve relative to the file. A file that declares a package other than main is imported as that package.

func (*Session) Symbols

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

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

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
ds
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.

Jump to

Keyboard shortcuts

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