Documentation
¶
Overview ¶
Package interp implements an interpreter.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ParseTraceModes ¶ added in v0.2.0
ParseTraceModes parses a comma-separated trace-mode value (used by both MVM_TRACE and the -x CLI flag). Recognized tokens: "1" or "line" enable line tracing; "op" or "bytecode" enable bytecode tracing; "all" enables both. Unknown or empty tokens are ignored.
Types ¶
type Interp ¶
Interp represents the state of an interpreter.
func NewInterpreter ¶
NewInterpreter returns a new interpreter.
func (*Interp) AutoImportPackages ¶
func (i *Interp) AutoImportPackages()
AutoImportPackages registers every package already loaded in i.Packages under its short name, so that REPL or -e users can reference them (e.g. time.Now()) without writing an explicit import statement.
Call it after ImportPackageValues and before Eval/Repl. Explicit import statements parsed later will cleanly overwrite the pre-registered symbol.
func (*Interp) Eval ¶
Eval evaluates code string and return the last produced value if any, or an error. name labels the source for error positions (a file path or any identifier).
Example ¶
ExampleInterp_Eval shows how to embed the interpreter, expose custom Go functions to interpreted code via a synthetic package, and read back the value of an evaluated expression.
package main
import (
"fmt"
"reflect"
"github.com/mvm-sh/mvm/interp"
"github.com/mvm-sh/mvm/lang/golang"
"github.com/mvm-sh/mvm/stdlib"
_ "github.com/mvm-sh/mvm/stdlib/all"
)
func main() {
i := interp.NewInterpreter(golang.GoSpec)
// Bring in the standard library bindings (fmt, strings, ...).
i.ImportPackageValues(stdlib.Values)
// Expose a custom package "host" with a function and a constant.
i.ImportPackageValues(map[string]map[string]reflect.Value{
"host": {
"Greet": reflect.ValueOf(func(s string) string { return "hello, " + s + "!" }),
"Answer": reflect.ValueOf(42),
},
})
// Register every loaded package under its short name so the snippet does
// not need explicit import statements.
i.AutoImportPackages()
res, err := i.Eval("m:expr", `fmt.Sprintf("%s answer=%d", host.Greet("world"), host.Answer)`)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(res.Interface())
}
Output: hello, world! answer=42