Documentation
¶
Index ¶
- Constants
- Variables
- func AllModuleNames() []string
- func Commit() string
- func CompileAndRun(ctx context.Context, inputFile string, args []string) (err error)
- func CompileOnly(inputFile, outputFile string) (err error)
- func Exports() map[string]map[string]*module.Export
- func GetExportMap(names ...string) map[string]map[string]*module.Export
- func GetModuleMap(names ...string) *vm.ModuleMap
- func MapFS(files map[string][]byte) fs.FS
- func ModuleAvailable(name string) bool
- func Modules() *vm.ModuleMap
- func NativeAvailable(name string) string
- func RunCompiled(ctx context.Context, data []byte, args []string) (err error)
- func RunCompiledWithModules(ctx context.Context, data []byte, args []string, modules *vm.ModuleMap) (err error)
- func RunREPL(ctx context.Context, stdin io.Reader, stdout io.Writer, stderr io.Writer, ...)
- func SetReadlineFactory(f ReadlineFactory)
- func Version() string
- type Completer
- type EmbedInfo
- type FileInfo
- type Info
- type Program
- func (p *Program) Bytecode() *vm.Bytecode
- func (p *Program) Clone() *Program
- func (p *Program) Equals(other *Program) bool
- func (p *Program) Get(name string) *Variable
- func (p *Program) GetAll() []*Variable
- func (p *Program) IsDefined(name string) bool
- func (p *Program) Marshal() ([]byte, error)
- func (p *Program) Run() error
- func (p *Program) RunContext(ctx context.Context) (err error)
- func (p *Program) Set(name string, value interface{}) error
- func (p *Program) SetArgs(args []string)
- func (p *Program) SetChanFactory(f func(buf int) (vm.Object, error))
- func (p *Program) SetMaxStringLen(n int)
- func (p *Program) SetPermissions(perm vm.Permissions)
- func (p *Program) SetSpawner(...)
- func (p *Program) SetStdin(r io.Reader)
- func (p *Program) SetStdout(w io.Writer)
- func (p *Program) Unmarshal(b []byte) error
- func (p *Program) UnmarshalWithModules(b []byte, modules *vm.ModuleMap) (err error)
- type ReadLine
- type ReadlineFactory
- type Script
- func (s *Script) Add(name string, value interface{}) error
- func (s *Script) Compile() (*Program, error)
- func (s *Script) Remove(name string) bool
- func (s *Script) Run() (program *Program, err error)
- func (s *Script) RunContext(ctx context.Context) (program *Program, err error)
- func (s *Script) SetImports(modules *vm.ModuleMap)
- func (s *Script) SetMaxAllocs(n int64)
- func (s *Script) SetMaxConstObjects(n int)
- func (s *Script) SetMaxStringLen(n int)
- func (s *Script) SetPermissions(p vm.Permissions)
- type Variable
- func (v *Variable) Array() []interface{}
- func (v *Variable) Bool() bool
- func (v *Variable) Bytes() []byte
- func (v *Variable) Char() rune
- func (v *Variable) Error() error
- func (v *Variable) Float() float64
- func (v *Variable) Int() int
- func (v *Variable) Int64() int64
- func (v *Variable) IsUndefined() bool
- func (v *Variable) Map() map[string]interface{}
- func (v *Variable) Name() string
- func (v *Variable) Object() vm.Object
- func (v *Variable) String() string
- func (v *Variable) Value() interface{}
- func (v *Variable) ValueType() string
Constants ¶
const FormatVersion uint16 = 6
FormatVersion is the current bytecode format version. It is stored as a little-endian uint16 in bytes [4:6] of the header. Increment this constant whenever the on-disk format changes in an incompatible way so that old compiled files produce a clear error ("incompatible bytecode version") instead of cryptic decode failures.
Version history:
1: initial format; trailer was an 8-byte CRC64/ECMA checksum. 2: trailer replaced with a 32-byte SHA-256 digest. 3: ImmutableMap encoding prepends an out-of-band module-name string so the __module_name__ namespace cannot be spoofed by user script data. 4: Bytecode encoding prepends a builtin name table so that OpGetBuiltin indices are resolved by name at load time. New builtins may now be inserted anywhere in the registration list without corrupting compiled bytecode (fixes issue 5.10: Builtin index baked into bytecode).
FormatVersion history:
1 – original CRC64/ECMA trailer
2 – SHA-256 trailer
3 – Ptr serialisation removed
4 – various encoding hardening
5 – Time encoding now includes timezone name (fixes silent UTC coercion)
6 – Embed table appended to bytecode body; every //embed directive is
recorded so tools like rumo.Stat can report embedded files.
const Magic = "RUMO"
Magic is a magic number every encoded Program starts with. format: [4]MAGIC [2]VERSION [4]SIZE [N]DATA [32]SHA256(DATA)
Variables ¶
var BuiltinModules = map[string]*module.BuiltinModule{ "base64": base64.Module, "fmt": fmt.Module, "hex": hex.Module, "json": json.Module, "math": math.Module, "os": os.Module, "rand": rand.Module, "sys": sys.Module, "text": text.Module, "time": time.Module, }
BuiltinModules are builtin type standard library modules.
var SourceModules = map[string]*module.SourceModule{ "enum": module.NewSource(`is_enumerable := func(x) { return is_array(x) || is_map(x) } is_array_like := func(x) { return is_array(x) } export { // all(x map, fn func(key, value) bool) (result bool) // all returns true if the given function 'fn' evaluates to a truthy value on // all of the items in 'x'. It returns undefined if 'x' is not enumerable. all: func(x, fn) { if !is_enumerable(x) { return undefined } for k, v in x { if !fn(k, v) { return false } } return true }, // any(x map, fn func(key, value) bool) (result bool) // any returns true if the given function 'fn' evaluates to a truthy value on // any of the items in 'x'. It returns undefined if 'x' is not enumerable. any: func(x, fn) { if !is_enumerable(x) { return undefined } for k, v in x { if fn(k, v) { return true } } return false }, // chunk(x array, size int) (result array) // chunk returns an array of elements split into groups the length of size. // If 'x' can't be split evenly, the final chunk will be the remaining elements. // It returns undefined if 'x' is not array. chunk: func(x, size) { if !is_array_like(x) || !size { return undefined } numElements := len(x) if !numElements { return [] } res := [] idx := 0 for idx < numElements { res = append(res, x[idx:idx+size]) idx += size } return res }, // at(x map, key string) (result any) // at returns an element at the given index (if 'x' is array) or // key (if 'x' is map). It returns undefined if 'x' is not enumerable. at: func(x, key) { if !is_enumerable(x) { return undefined } if is_array_like(x) { if !is_int(key) { return undefined } } else { if !is_string(key) { return undefined } } return x[key] }, // each(x map, fn func(key, value)) (result undefined) // each iterates over elements of 'x' and invokes 'fn' for each element. 'fn' is // invoked with two arguments: 'key' and 'value'. 'key' is an int index // if 'x' is array. 'key' is a string key if 'x' is map. It does not iterate // and returns undefined if 'x' is not enumerable. each: func(x, fn) { if !is_enumerable(x) { return undefined } for k, v in x { fn(k, v) } }, // filter(x map, fn func(key, value) bool) (result array) // filter iterates over elements of 'x', returning an array of all elements 'fn' // returns truthy for. 'fn' is invoked with two arguments: 'key' and 'value'. // 'key' is an int index if 'x' is array. 'key' is a string key if 'x' is map. // It returns undefined if 'x' is not enumerable. filter: func(x, fn) { if !is_array_like(x) { return undefined } dst := [] for k, v in x { if fn(k, v) { dst = append(dst, v) } } return dst }, // find(x map, fn func(key, value) bool) (result any) // find iterates over elements of 'x', returning value of the first element 'fn' // returns truthy for. 'fn' is invoked with two arguments: 'key' and 'value'. // 'key' is an int index if 'x' is array. 'key' is a string key if 'x' is map. // It returns undefined if 'x' is not enumerable. find: func(x, fn) { if !is_enumerable(x) { return undefined } for k, v in x { if fn(k, v) { return v } } }, // find_key(x map, fn func(key, value) bool) (result any) // find_key iterates over elements of 'x', returning key or index of the first // element 'fn' returns truthy for. 'fn' is invoked with two arguments: 'key' // and 'value'. 'key' is an int index if 'x' is array. 'key' is a string key if // 'x' is map. It returns undefined if 'x' is not enumerable. find_key: func(x, fn) { if !is_enumerable(x) { return undefined } for k, v in x { if fn(k, v) { return k } } }, // map(x map, fn func(key, value) any) (result array) // map creates an array of values by running each element in 'x' through 'fn'. // 'fn' is invoked with two arguments: 'key' and 'value'. 'key' is an int index // if 'x' is array. 'key' is a string key if 'x' is map. It returns undefined // if 'x' is not enumerable. map: func(x, fn) { if !is_enumerable(x) { return undefined } dst := [] for k, v in x { dst = append(dst, fn(k, v)) } return dst }, // key(k, v) (result any) // key returns the first argument. key: func(k, _) { return k }, // value(k, v) (result any) // value returns the second argument. value: func(_, v) { return v } } `), }
SourceModules are source type standard library modules.
Functions ¶
func AllModuleNames ¶
func AllModuleNames() []string
AllModuleNames returns a list of all default module names.
func CompileAndRun ¶
CompileAndRun compiles the script at inputFile and executes it.
func CompileOnly ¶
CompileOnly compiles the script at inputFile and writes the compiled binary into outputFile.
func Exports ¶
Exports returns a fresh export map of all currently registered standard library modules. Like Modules, it is recomputed on every call so that modules added after startup are visible.
func GetExportMap ¶
GetExportMap returns the export map of all modules for the given module names.
func GetModuleMap ¶
GetModuleMap returns the module map that includes all modules for the given module names.
func MapFS ¶
MapFS creates an fs.FS backed by the provided in-memory map of filename → content. It is a convenience wrapper for creating in-memory filesystems (e.g. for tests or scripts whose source is generated at runtime).
func ModuleAvailable ¶
ModuleAvailable reports whether the named module is registered in the current interpreter's standard library (BuiltinModules or SourceModules).
func Modules ¶
Modules returns a fresh module map containing all currently registered standard library modules. A new map is built on every call so that modules added to BuiltinModules or SourceModules after startup are always reflected. Callers that need a stable snapshot should capture the result once and reuse it; callers that want to pick up late-registered modules should call Modules each time they create a new Script or VM.
func NativeAvailable ¶
NativeAvailable reports whether the shared library identified by name is loadable on the current system using the same dlopen logic as the vm package. If the library can be opened, the resolved path (which equals name) is returned; otherwise an empty string is returned.
NativeAvailable always returns an empty string when the interpreter was not compiled with -tags native, regardless of name.
func RunCompiled ¶
RunCompiled reads the compiled binary from file and executes it.
func RunCompiledWithModules ¶
func RunCompiledWithModules(ctx context.Context, data []byte, args []string, modules *vm.ModuleMap) (err error)
RunCompiledWithModules reads the compiled binary and executes it using the provided module map for deserialization. Use this variant when the compiled script imports custom builtin modules that are not part of the standard library; pass a ModuleMap that contains both the standard modules and any custom ones required by the bytecode.
func RunREPL ¶
func RunREPL(ctx context.Context, stdin io.Reader, stdout io.Writer, stderr io.Writer, modules []string)
RunREPL starts REPL. If modules is non-nil, each named module is imported globally (available as a top-level variable without an explicit import call).
func SetReadlineFactory ¶
func SetReadlineFactory(f ReadlineFactory)
SetReadlineFactory replaces the readline implementation used by RunREPL. Call this before RunREPL to provide a richer line-editor (history, tab completion, etc.). Pass nil to restore the built-in fallback.
Types ¶
type Completer ¶
type Completer struct {
// contains filtered or unexported fields
}
Completer implements shell.AutoCompleter for the REPL, providing tab-completion for builtin functions, globally imported module names, user-defined symbols, and module member access (e.g. fmt.println).
type EmbedInfo ¶
type EmbedInfo struct {
// Name is the path of the file relative to the script's source directory,
// using forward slashes (e.g. "assets/logo.png").
Name string
// Size is the byte length of the file content at compile time.
Size int
}
EmbedInfo describes a single file baked into the bytecode by an //embed directive at compile time.
type FileInfo ¶
type FileInfo struct {
// Name is the filename or module name as recorded by the compiler's debug
// FileSet (e.g. "(main)", "math", "/abs/path/to/helper.rumo").
Name string
// Size is the byte length of the source text that was compiled.
Size int
}
FileInfo describes a source file compiled into a bytecode blob.
type Info ¶
type Info struct {
// FormatVersion is the bytecode format version stored in the header.
FormatVersion uint16
// BodySize is the byte length of the encoded bytecode body (excludes the
// 10-byte header and the 32-byte SHA-256 trailer).
BodySize uint32
// Checksum is the SHA-256 hex digest of the bytecode body.
Checksum string
// FileSize is the total size of the file on disk.
FileSize int64
// Modules is the sorted list of builtin module names the bytecode imports
// (e.g. "math", "json"). Source modules compiled inline are reflected in
// SourceFiles rather than here.
Modules []string
// SourceFiles lists every source file recorded in the compiler's debug
// FileSet, in the order they were compiled. This includes the main script
// and any imported source-module files.
SourceFiles []FileInfo
// NativeLibs is the sorted list of native shared-library paths (as stored
// in the bytecode) that the script requires via `native` statements. An
// empty slice means no native FFI is needed.
NativeLibs []string
// Embeds lists every file that was baked into the bytecode at compile time
// via an //embed directive, in the order they were embedded.
Embeds []EmbedInfo
}
Info contains metadata extracted from a compiled rumo bytecode file.
func Stat ¶
Stat reads the compiled rumo bytecode at path, validates its header and checksum, and returns an Info struct describing the file's metadata, required modules, embedded source files, and native library dependencies.
func (*Info) CanRun ¶
CanRun reports whether every requirement of the bytecode described by Info is satisfied by the current interpreter:
- every module in Modules is available (ModuleAvailable returns true), and
- if NativeLibs is non-empty, the interpreter was compiled with native FFI support (NativeAvailable returns a non-empty string for at least one name). Individual library paths are not checked because a script may use a fallback chain (e.g. try gtk4, fall back to gtk3) where only one of the listed libraries needs to be present at runtime.
func (*Info) String ¶
String returns a human-readable summary of the Info suitable for display in a terminal. Each required module is listed with a ✓ or ✗ availability mark, and a top-level "Can Run" line gives the overall verdict. Native library dependencies are listed with their resolved path (or ✗ if not found).
type Program ¶
type Program struct {
// contains filtered or unexported fields
}
func (*Program) Clone ¶
Clone creates a new copy of Compiled. Cloned copies are safe for concurrent use by multiple goroutines.
func (*Program) IsDefined ¶
IsDefined returns true if the variable name is defined (has value) before or after the execution.
func (*Program) RunContext ¶
RunContext is like Run but includes a context.
func (*Program) Set ¶
Set replaces the value of a global variable identified by the name. An error will be returned if the name was not defined during compilation.
func (*Program) SetArgs ¶
SetArgs sets the argument list that will be visible to the script via args().
func (*Program) SetChanFactory ¶
SetChanFactory installs a custom channel factory on the program. The js/wasm runtime uses this to return a remote-backed channel whose send/recv hop through the coordinator SharedWorker. When nil, the VM falls back to the local Go-channel implementation.
func (*Program) SetMaxStringLen ¶
SetMaxStringLen updates the maximum string length for future Run/RunContext calls.
func (*Program) SetPermissions ¶
func (p *Program) SetPermissions(perm vm.Permissions)
SetPermissions updates the permission policy for future Run/RunContext calls.
func (*Program) SetSpawner ¶
func (p *Program) SetSpawner(s func(ctx context.Context, fn vm.Object, args []vm.Object) (vm.RoutineHandle, error))
SetSpawner installs a custom routine spawner on the program. The js/wasm runtime uses this to make `go fn(...)` create a fresh SharedWorker per routine. When nil (the default), the VM falls back to the goroutine-backed implementation in vm/routinevm.go.
func (*Program) SetStdin ¶
SetStdin overrides the reader used for the script's standard input. When nil (the default), os.Stdin is used.
func (*Program) SetStdout ¶
SetStdout overrides the writer used for the script's standard output. When nil (the default), os.Stdout is used.
func (*Program) Unmarshal ¶
Unmarshal deserializes the Program from a byte slice. The global Modules() map is used to resolve imported builtin modules. Use UnmarshalWithModules to supply a custom module map (e.g. when the compiled script imports modules not present in the standard library).
func (*Program) UnmarshalWithModules ¶
UnmarshalWithModules deserializes the Program from a byte slice using the provided module map to resolve imported builtin modules. Pass a ModuleMap that contains every builtin module referenced by the compiled bytecode; the global Modules() map is a sensible starting point for standard-library modules, and custom modules can be added via ModuleMap.AddBuiltinModule.
type ReadlineFactory ¶
type ReadlineFactory func(prompt string, stdin io.Reader, stdout, stderr io.Writer) func(completer *Completer) (ReadLine, error)
ReadlineFactory is the signature of a function that creates a ReadLine for the given prompt, streams and completer. Callers can replace the default line-reader with a richer implementation (e.g. one backed by a readline library) by calling SetReadlineFactory.
type Script ¶
type Script struct {
// contains filtered or unexported fields
}
Script can simplify compilation and execution of embedded scripts.
func NewScript ¶
NewScript creates a Script that reads its entrypoint from fsys at path.
If fsys is nil, the current working directory is used (via os.DirFS). When path is absolute and fsys is nil, the FS is rooted at the directory containing path and the entrypoint becomes its base name.
By default, the script runs with:
- deny-all Permissions (no file I/O, exec, env write, or chdir allowed); call SetPermissions(vm.UnrestrictedPermissions()) to opt in.
- bounded resource limits (MaxAllocs, MaxStringLen, MaxBytesLen from vm.DefaultConfig); call SetMaxAllocs(-1) etc. or pass vm.UnlimitedConfig() to disable limits for trusted scripts.
func (*Script) Compile ¶
Compile compiles the script with all the defined variables and returns Program object.
func (*Script) Remove ¶
Remove removes (undefines) an existing variable for the script. It returns false if the variable name is not defined.
func (*Script) Run ¶
Run compiles and runs the scripts. Use returned compiled object to access global variables.
func (*Script) RunContext ¶
RunContext is like Run but includes a context.
func (*Script) SetImports ¶
SetImports sets import modules.
func (*Script) SetMaxAllocs ¶
SetMaxAllocs sets the maximum number of objects allocations during the run time. Compiled script will return ErrObjectAllocLimit error if it exceeds this limit.
func (*Script) SetMaxConstObjects ¶
SetMaxConstObjects sets the maximum number of objects in the compiled constants.
func (*Script) SetMaxStringLen ¶
SetMaxStringLen sets the maximum byte-length for string values produced during script execution. Zero (the default) defers to DefaultConfig.
func (*Script) SetPermissions ¶
func (s *Script) SetPermissions(p vm.Permissions)
SetPermissions configures which privileged os-module operations the script is allowed to perform. The zero value of Permissions (default) denies all operations; use vm.UnrestrictedPermissions() to allow everything, or set individual Allow* fields to grant only the capabilities your script needs.
type Variable ¶
type Variable struct {
// contains filtered or unexported fields
}
Variable is a user-defined variable for the script.
func NewVariable ¶
NewVariable creates a Variable.
func (*Variable) Array ¶
func (v *Variable) Array() []interface{}
Array returns []interface value of the variable value. It returns nil if the value is not convertible to []interface.
func (*Variable) Bool ¶
Bool returns bool value of the variable value. It returns false if the value is not convertible to bool.
func (*Variable) Bytes ¶
Bytes returns a byte slice of the variable value. It returns nil if the value is not convertible to byte slice.
func (*Variable) Char ¶
Char returns rune value of the variable value. It returns 0 if the value is not convertible to rune.
func (*Variable) Error ¶
Error returns an error if the underlying value is error object. If not, this returns nil.
func (*Variable) Float ¶
Float returns float64 value of the variable value. It returns 0.0 if the value is not convertible to float64.
func (*Variable) Int ¶
Int returns int value of the variable value. It returns 0 if the value is not convertible to int.
func (*Variable) Int64 ¶
Int64 returns int64 value of the variable value. It returns 0 if the value is not convertible to int64.
func (*Variable) IsUndefined ¶
IsUndefined returns true if the underlying value is undefined.
func (*Variable) Map ¶
Map returns map[string]interface{} value of the variable value. It returns nil if the value is not convertible to map[string]interface{}.
func (*Variable) Object ¶
Object returns an underlying Object of the variable value. Note that returned Object is the live VM object. Modifying it may cause unexpected side effects.
func (*Variable) String ¶
String returns string value of the variable value. It returns an empty string if the value is not convertible to string.
Directories
¶
| Path | Synopsis |
|---|---|
|
web
command
devserver — small static file server with the COOP / COEP / CORP headers that Chrome and Firefox require before they expose `SharedArrayBuffer` and `Atomics.wait` to the page.
|
devserver — small static file server with the COOP / COEP / CORP headers that Chrome and Firefox require before they expose `SharedArrayBuffer` and `Atomics.wait` to the page. |
|
sys
Package sys exposes a cross-platform subset of operating-system / system-call functionality to rumo scripts.
|
Package sys exposes a cross-platform subset of operating-system / system-call functionality to rumo scripts. |
|
time
Package time exposes Go's time.Time / time.Duration helpers as a Rumo standard-library module.
|
Package time exposes Go's time.Time / time.Duration helpers as a Rumo standard-library module. |
|
Package vm provides a virtual machine for executing rumo bytecode
|
Package vm provides a virtual machine for executing rumo bytecode |
|
codec
Package codec provides functions to marshal and unmarshal data types.
|
Package codec provides functions to marshal and unmarshal data types. |