Language guide · 11 of 12
Go Host Embedding
Evie is designed to embed seamlessly in Go applications with bidirectional marshaling:
package main
import (
"fmt"
"github.com/hxkhan/evie"
"github.com/hxkhan/evie/vm"
)
type OrderResult struct {
Total float64 `json:"total"`
Message string `json:"message"`
}
func main() {
// 1. An engine; the prelude holds symbols every script sees without an import
eng := evie.New()
defer eng.Close()
eng.SetStatic("calculateTax", vm.BoxGoFunc(vm.Func1(func(subtotal float64) float64 {
return subtotal * 0.15
})))
// 2. Load a script
_, err := eng.Eval(`package main
fn processOrder(price) {
tax := calculateTax(price)
return { total: price + tax, message: "Order processed successfully" }
}`)
if err != nil {
panic(err)
}
// 3. Call it with Go arguments and unmarshal the result into a struct
val, err := eng.Call("main.processOrder", 100.0)
if err != nil {
panic(err)
}
var res OrderResult
if err := val.Unmarshal(&res); err != nil {
panic(err)
}
fmt.Printf("Total: $%.2f, Status: %s\n", res.Total, res.Message)
// Output: Total: $115.00, Status: Order processed successfully
// 4. One-line quick evaluation
ans, err := evie.Eval("return [1, 2, 3].map(fn(x) => x * 10)")
if err != nil {
panic(err)
}
fmt.Println(ans) // [10, 20, 30]
}The pieces, from most to least convenient:
| need | use |
|---|---|
| expose a Go function | vm.Func0..Func3 and the E variants for (R, error); vm.Reflect for any other signature |
| full control of arguments and errors | pkg.Func(name, arity, func(c vm.Call) (vm.Value, error)); mark it Blocking if it sleeps or waits on I/O, and watch c.Context() so it wakes when the script is stopped |
| a group of functions scripts import by name | vm.NewPackage("name") passed in evie.Options.Packages; pkg.Document(name, "f(x)", "what it does") describes a member for editors, which pkg.Describe(name) reads back |
| check a program without running it | eng.Check(b) or evie.Check(b) compile a bundle and its imports and report their compile errors, up to ten per package; nothing runs |
| learn what every name refers to, for an editor | evie.Options.OnName receives a vm.NameEvent for each name the compiler declares or resolves: its kind and where it is declared, across files |
| sandbox stdlib, filesystem imports, or I/O per engine | evie.Options.FS (embed.FS / io/fs.FS; confines imports, and fs reads only from it and cannot write), Options.Stdlib (allowlist), Options.NoStdlib, Options.Stdin, Options.Stdout |
| parse a multi-file program once and run in many engines | evie.ParseFile(fsys, path), ParseProject(fsys, dir) (a nil fsys is the OS) or ParseSource(name, src) → *evie.Bundle, then eng.RunBundle(ctx, b) or eng.LoadBundle(ctx, b) |
| symbols visible without an import | eng.SetStatic or evie.Options.Prelude |
| lend a Go value to scripts as it is | vm.NewHostType[T]("Name") with Method, Constructor, Wrap |
| a native whose work takes a while | return c.Async(func(ctx context.Context) (vm.Value, error) { ... }) (lifecycle-bound task) |
| call a script function | eng.Call("pkg.fn", goArgs...), or value.Call(evieArgs...) on a value from eng.Lookup("pkg.fn") |
| run a file or a project directory | eng.RunFile, eng.RunProject, or evie.RunFile for a one-off |
| read a result | AsFloat64, AsString, AsArray, AsObject and the other As methods, Field(name) / ClassName() on objects and class instances, ToGo, Unmarshal(&target), json.Marshal(val) |
| compare values the way the language does | a.Equals(b), v.IsTruthy() |
| show an error | evie.Format(err, colors) renders it the way the evie command does |
| raise an error scripts can tell apart | return vm.Errorf(vm.KindNotFound, "no user %d", id).With("id", vm.BoxNumber(id)) from a native; a plain Go error works too and takes its kind from what it wraps, as "notFound" from fs.ErrNotExist and "timeout" from context.DeadlineExceeded |
| read an error a script raised | errors.As(err, &e) with e *vm.Error, then e.Kind(), e.Field(name), e.FieldNames() and e.CauseValue(); errors.Is sees through the causes a script gave |
| stop a runaway script | eng.Interrupt(), or a context: eng.RunFileContext, EvalContext, CallContext, RunBundle(ctx, b) |
| finish with an engine | eng.Wait() lets background tasks finish; eng.Close() stops them, waits, and makes later calls return evie.ErrClosed |
A stopped script fails at its next loop iteration or call, or as soon as it wakes from an await, time.sleep or a blocking native that watches c.Context(). The error says where it stopped, its cause is vm.ErrInterrupted or the context's cause, and catch lets it pass. A context stops only the run it was given and the tasks that run started; Interrupt stops everything the instance is running, and the instance stays usable afterwards.
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
if _, err := eng.RunFileContext(ctx, "main.ev"); errors.Is(err, context.DeadlineExceeded) {
fmt.Print(evie.Format(err, false)) // error[timeout]: context deadline exceeded, at the loop it was in
}