rumo

package module
v0.0.0-...-b829c44 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 10, 2026 License: MIT Imports: 28 Imported by: 0

README

rumo logo

test Release Go Report Card License

rumo is a small, fast and secure script language for Go supporting routines and channels

This is pre release software so expect bugs and breaking changes

Usage

package usage
package main

import (
	"fmt"
	"github.com/malivvan/rumo"
)

func main() {
	// script code
	src := `
each := func(seq, fn) {
    for x in seq { fn(x) }
}

sum := 0
mul := 1
each([a, b, c, d], func(x) {
	sum += x
	mul *= x
})`

	// create a new script instance
	script := rumo.NewScript([]byte(src))

	// add variables with default values
	_ = script.Add("a", 0)
	_ = script.Add("b", 0)
	_ = script.Add("c", 0)
	_ = script.Add("d", 0)

	// compile script to program
	program, err := script.Compile()
	if err != nil {
		panic(err)
	}
	
	// clone a new instance of the program and set values
	instance := program.Clone()
	_ = instance.Set("a", 1)
	_ = instance.Set("b", 9)
	_ = instance.Set("c", 8)
	_ = instance.Set("d", 4)
	
	// run the instance
	err = instance.Run()
	if err != nil {
		panic(err)
	}

	// retrieve variable values
	sum := instance.Get("sum")
	mul := instance.Get("mul")
	fmt.Println(sum, mul) // "22 288"
}
language usage
fmt := import("fmt")

each := func(seq, fn) {
    for x in seq { fn(x) }
}

sum := func(init, seq) {
each(seq, func(x) { init += x })
    return init
}

fmt.println(sum(0, [1, 2, 3]))   // "6"
fmt.println(sum("", [1, 2, 3]))  // "123"
Routines
v := 0

f1 := func(a,b) { v = 10; return a+b }
f2 := func(a,b,c) { v = 11; return a+b+c }

rvm1 := start(f1,1,2)
rvm2 := start(f2,1,2,5)

fmt.println(rvm1.result()) // 3
fmt.println(rvm2.result()) // 8
fmt.println(v) // 10 or 11
Channels
unbufferedChan := chan()
bufferedChan := chan(128)

// Send will block if the channel is full.
bufferedChan.send("hello") // send string
bufferedChan.send(55) // send int
bufferedChan.send([66, chan(1)]) // channel in channel

// Receive will block if the channel is empty.
obj := bufferedChan.recv()

// Send to a closed channel causes panic.
// Receive from a closed channel returns undefined value.
unbufferedChan.close()
bufferedChan.close()
Routines and Channels
reqChan := chan(8)
repChan := chan(8)

client := func(interval) {
	reqChan.send("hello")
	for i := 0; true; i++ {
		fmt.println(repChan.recv())
		times.sleep(interval*times.second)
		reqChan.send(i)
	}
}

server := func() {
	for {
		req := reqChan.recv()
		if req == "hello" {
			fmt.println(req)
			repChan.send("world")
		} else {
			repChan.send(req+100)
		}
	}
}

rClient := start(client, 2)
rServer := start(server)

if ok := rClient.wait(5); !ok {
	rClient.abort()
}
rServer.abort()

//output:
//hello
//world
//100
//101

Building

make test       # run tests
make install    # install tools 
make build      # build for current platform 
make release    # build for all platforms

Fork / Credits

This is a continuation of the github.com/d5/tengo project starting of this pull request implementing go routines and channels. Special thanks goes to d5 for his work on the tengo language and Bai-Yingjie for implementing the foundation of concurrency while retaining the original tests of the project.

Documentation

Index

Constants

View Source
const Magic = "VVC\x00"

Magic is a magic number every encoded Program starts with. format: [4]MAGIC [4]SIZE [N]DATA [8]CRC64(ECMA)

Variables

View Source
var BuiltinModules = map[string]*module.BuiltinModule{
	"base64": base64.Module,
	"cui":    cui.Module,
	"fmt":    fmt.Module,
	"hex":    hex.Module,
	"json":   json.Module,
	"math":   math.Module,
	"rand":   rand.Module,
	"shell":  shell.Module,
	"text":   text.Module,
	"times":  times.Module,
}

BuiltinModules are builtin type standard library modules.

View Source
var SourceModules = map[string]*module.SourceModule{
	"enum": module.NewSource("is_enumerable := func(x) {\n  return is_array(x) || is_map(x) || is_immutable_array(x) || is_immutable_map(x)\n}\n\nis_array_like := func(x) {\n  return is_array(x) || is_immutable_array(x)\n}\n\nexport {\n  // all(x map, fn func(key, value) bool) (result bool)\n  // all returns true if the given function 'fn' evaluates to a truthy value on\n  // all of the items in 'x'. It returns undefined if 'x' is not enumerable.\n  all: func(x, fn) {\n    if !is_enumerable(x) { return undefined }\n\n    for k, v in x {\n      if !fn(k, v) { return false }\n    }\n\n    return true\n  },\n\n  // any(x map, fn func(key, value) bool) (result bool)\n  // any returns true if the given function 'fn' evaluates to a truthy value on\n  // any of the items in 'x'. It returns undefined if 'x' is not enumerable.\n  any: func(x, fn) {\n    if !is_enumerable(x) { return undefined }\n\n    for k, v in x {\n      if fn(k, v) { return true }\n    }\n\n    return false\n  },\n\n  // chunk(x array, size int) (result array)\n  // chunk returns an array of elements split into groups the length of size.\n  // If 'x' can't be split evenly, the final chunk will be the remaining elements.\n  // It returns undefined if 'x' is not array.\n  chunk: func(x, size) {\n    if !is_array_like(x) || !size { return undefined }\n\n    numElements := len(x)\n    if !numElements { return [] }\n\n    res := []\n    idx := 0\n    for idx < numElements {\n      res = append(res, x[idx:idx+size])\n      idx += size\n    }\n\n    return res\n  },\n\n  // at(x map, key string) (result any)\n  // at returns an element at the given index (if 'x' is array) or\n  // key (if 'x' is map). It returns undefined if 'x' is not enumerable.\n  at: func(x, key) {\n    if !is_enumerable(x) { return undefined }\n\n    if is_array_like(x) {\n        if !is_int(key) { return undefined }\n    } else {\n        if !is_string(key) { return undefined }\n    }\n\n    return x[key]\n  },\n\n  // each(x map, fn func(key, value)) (result undefined)\n  // each iterates over elements of 'x' and invokes 'fn' for each element. 'fn' is\n  // invoked with two arguments: 'key' and 'value'. 'key' is an int index\n  // if 'x' is array. 'key' is a string key if 'x' is map. It does not iterate\n  // and returns undefined if 'x' is not enumerable.\n  each: func(x, fn) {\n    if !is_enumerable(x) { return undefined }\n\n    for k, v in x {\n      fn(k, v)\n    }\n  },\n\n  // filter(x map, fn func(key, value) bool) (result array)\n  // filter iterates over elements of 'x', returning an array of all elements 'fn'\n  // returns truthy for. 'fn' is invoked with two arguments: 'key' and 'value'.\n  // 'key' is an int index if 'x' is array. 'key' is a string key if 'x' is map.\n  // It returns undefined if 'x' is not enumerable.\n  filter: func(x, fn) {\n    if !is_array_like(x) { return undefined }\n\n    dst := []\n    for k, v in x {\n      if fn(k, v) { dst = append(dst, v) }\n    }\n\n    return dst\n  },\n\n  // find(x map, fn func(key, value) bool) (result any)\n  // find iterates over elements of 'x', returning value of the first element 'fn'\n  // returns truthy for. 'fn' is invoked with two arguments: 'key' and 'value'.\n  // 'key' is an int index if 'x' is array. 'key' is a string key if 'x' is map.\n  // It returns undefined if 'x' is not enumerable.\n  find: func(x, fn) {\n    if !is_enumerable(x) { return undefined }\n\n    for k, v in x {\n      if fn(k, v) { return v }\n    }\n  },\n\n  // find_key(x map, fn func(key, value) bool) (result any)\n  // find_key iterates over elements of 'x', returning key or index of the first\n  // element 'fn' returns truthy for. 'fn' is invoked with two arguments: 'key'\n  // and 'value'. 'key' is an int index if 'x' is array. 'key' is a string key if\n  // 'x' is map. It returns undefined if 'x' is not enumerable.\n  find_key: func(x, fn) {\n    if !is_enumerable(x) { return undefined }\n\n    for k, v in x {\n      if fn(k, v) { return k }\n    }\n  },\n\n  // map(x map, fn func(key, value) any) (result array)\n  // map creates an array of values by running each element in 'x' through 'fn'.\n  // 'fn' is invoked with two arguments: 'key' and 'value'. 'key' is an int index\n  // if 'x' is array. 'key' is a string key if 'x' is map. It returns undefined\n  // if 'x' is not enumerable.\n  map: func(x, fn) {\n    if !is_enumerable(x) { return undefined }\n\n    dst := []\n    for k, v in x {\n      dst = append(dst, fn(k, v))\n    }\n\n    return dst\n  },\n\n  // key(k, v) (result any)\n  // key returns the first argument.\n  key: func(k, _) { return k },\n\n  // value(k, v) (result any)\n  // value returns the second argument.\n  value: func(_, v) { return v }\n}\n"),
}

SourceModules are source type standard library modules.

Functions

func AllModuleNames

func AllModuleNames() []string

AllModuleNames returns a list of all default module names.

func Commit

func Commit() string

Commit returns the commit hash of rumo.

func CompileAndRun

func CompileAndRun(ctx context.Context, data []byte, inputFile string, args []string) (err error)

CompileAndRun compiles the source code and executes it.

func CompileOnly

func CompileOnly(data []byte, inputFile, outputFile string) (err error)

CompileOnly compiles the source code and writes the compiled binary into outputFile.

func Exports

func Exports() map[string]map[string]*module.Export

Exports returns the lazily-initialized export map of all standard library modules. The map is computed on first call and cached for subsequent calls.

func GetExportMap

func GetExportMap(names ...string) map[string]map[string]*module.Export

GetExportMap returns the export map of all modules for the given module names.

func GetModuleMap

func GetModuleMap(names ...string) *vm.ModuleMap

GetModuleMap returns the module map that includes all modules for the given module names.

func Modules

func Modules() *vm.ModuleMap

Modules returns the lazily-initialized module map containing all standard library modules. The map is computed on first call and cached for subsequent calls. (Issue #11: avoids eager init that forces all stdlib into every binary.)

func RunCompiled

func RunCompiled(ctx context.Context, data []byte, args []string) (err error)

RunCompiled reads the compiled binary from file and executes it.

func RunREPL

func RunREPL(ctx context.Context, in io.Reader, out io.Writer, prompt string, 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 Version

func Version() string

Version returns the version of rumo.

Types

type Program

type Program struct {
	// contains filtered or unexported fields
}

Program is a compiled instance of the user script. Use Script.Compile() to create Compiled object.

func (*Program) Bytecode

func (p *Program) Bytecode() *vm.Bytecode

Bytecode returns the compiled bytecode of the Program.

func (*Program) Clone

func (p *Program) Clone() *Program

Clone creates a new copy of Compiled. Cloned copies are safe for concurrent use by multiple goroutines.

func (*Program) Equals

func (p *Program) Equals(other *Program) bool

Equals compares two Program objects for equality.

func (*Program) Get

func (p *Program) Get(name string) *Variable

Get returns a variable identified by the name.

func (*Program) GetAll

func (p *Program) GetAll() []*Variable

GetAll returns all the variables that are defined by the compiled script.

func (*Program) IsDefined

func (p *Program) IsDefined(name string) bool

IsDefined returns true if the variable name is defined (has value) before or after the execution.

func (*Program) Marshal

func (p *Program) Marshal() ([]byte, error)

Marshal serializes the Program into a byte slice.

func (*Program) Run

func (p *Program) Run() error

Run executes the compiled script in the virtual machine.

func (*Program) RunContext

func (p *Program) RunContext(ctx context.Context) (err error)

RunContext is like Run but includes a context.

func (*Program) Set

func (p *Program) Set(name string, value interface{}) error

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

func (p *Program) SetArgs(args []string)

SetArgs sets the argument list that will be visible to the script via args().

func (*Program) Unmarshal

func (p *Program) Unmarshal(b []byte) (err error)

Unmarshal deserializes the Program from a byte slice.

type Script

type Script struct {
	// contains filtered or unexported fields
}

Script can simplify compilation and execution of embedded scripts.

func NewScript

func NewScript(input []byte) *Script

NewScript creates a Script instance with an input script.

func (*Script) Add

func (s *Script) Add(name string, value interface{}) error

Add adds a new variable or updates an existing variable to the script.

func (*Script) Compile

func (s *Script) Compile() (*Program, error)

Compile compiles the script with all the defined variables and returns Program object.

func (*Script) EnableFileImport

func (s *Script) EnableFileImport(enable bool)

EnableFileImport enables or disables module loading from local files. Local file modules are disabled by default.

func (*Script) Remove

func (s *Script) Remove(name string) bool

Remove removes (undefines) an existing variable for the script. It returns false if the variable name is not defined.

func (*Script) Run

func (s *Script) Run() (program *Program, err error)

Run compiles and runs the scripts. Use returned compiled object to access global variables.

func (*Script) RunContext

func (s *Script) RunContext(ctx context.Context) (program *Program, err error)

RunContext is like Run but includes a context.

func (*Script) SetImportDir

func (s *Script) SetImportDir(dir string) error

SetImportDir sets the initial import directory for script files.

func (*Script) SetImports

func (s *Script) SetImports(modules *vm.ModuleMap)

SetImports sets import modules.

func (*Script) SetMaxAllocs

func (s *Script) SetMaxAllocs(n int64)

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

func (s *Script) SetMaxConstObjects(n int)

SetMaxConstObjects sets the maximum number of objects in the compiled constants.

func (*Script) SetName

func (s *Script) SetName(name string)

SetName sets the name of the script.

type Variable

type Variable struct {
	// contains filtered or unexported fields
}

Variable is a user-defined variable for the script.

func NewVariable

func NewVariable(name string, value interface{}) (*Variable, error)

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

func (v *Variable) Bool() bool

Bool returns bool value of the variable value. It returns false if the value is not convertible to bool.

func (*Variable) Bytes

func (v *Variable) Bytes() []byte

Bytes returns a byte slice of the variable value. It returns nil if the value is not convertible to byte slice.

func (*Variable) Char

func (v *Variable) Char() rune

Char returns rune value of the variable value. It returns 0 if the value is not convertible to rune.

func (*Variable) Error

func (v *Variable) Error() error

Error returns an error if the underlying value is error object. If not, this returns nil.

func (*Variable) Float

func (v *Variable) Float() float64

Float returns float64 value of the variable value. It returns 0.0 if the value is not convertible to float64.

func (*Variable) Int

func (v *Variable) Int() int

Int returns int value of the variable value. It returns 0 if the value is not convertible to int.

func (*Variable) Int64

func (v *Variable) Int64() int64

Int64 returns int64 value of the variable value. It returns 0 if the value is not convertible to int64.

func (*Variable) IsUndefined

func (v *Variable) IsUndefined() bool

IsUndefined returns true if the underlying value is undefined.

func (*Variable) Map

func (v *Variable) Map() map[string]interface{}

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

func (v *Variable) Name() string

Name returns the name of the variable.

func (*Variable) Object

func (v *Variable) Object() vm.Object

Object returns an underlying Object of the variable value. Note that returned Object is a copy of an actual Object used in the script.

func (*Variable) String

func (v *Variable) String() string

String returns string value of the variable value. It returns an empty string if the value is not convertible to string.

func (*Variable) Value

func (v *Variable) Value() interface{}

Value returns an empty interface of the variable value.

func (*Variable) ValueType

func (v *Variable) ValueType() string

ValueType returns the name of the value type.

Directories

Path Synopsis
std
cui
Package cui implements rich widgets for terminal based user interfaces.
Package cui implements rich widgets for terminal based user interfaces.
cui/demo/barchart command
Demo code for the bar chart widget.
Demo code for the bar chart widget.
cui/demo/box command
Demo code for the Box widget.
Demo code for the Box widget.
cui/demo/button command
Demo code for the Button widget.
Demo code for the Button widget.
cui/demo/checkbox command
Demo code for the CheckBox widget.
Demo code for the CheckBox widget.
cui/demo/dialog command
Demo code for the bar chart widget.
Demo code for the bar chart widget.
cui/demo/dropdown command
Demo code for the DropDown widget.
Demo code for the DropDown widget.
cui/demo/edit command
cui/demo/edit/autocomplete command
Demo code for edit.View autocomplete.
Demo code for edit.View autocomplete.
cui/demo/flex command
Demo code for the Flex widget.
Demo code for the Flex widget.
cui/demo/focusmanager command
Demo code for the FocusManager utility.
Demo code for the FocusManager utility.
cui/demo/form command
Demo code for the Form widget.
Demo code for the Form widget.
cui/demo/frame command
Demo code for the Frame widget.
Demo code for the Frame widget.
cui/demo/gauge_pm command
Demo code for the bar chart widget.
Demo code for the bar chart widget.
cui/demo/gauge_um command
Demo code for the bar chart widget.
Demo code for the bar chart widget.
cui/demo/grid command
Demo code for the Grid widget.
Demo code for the Grid widget.
cui/demo/hexview command
Demo code for the Box widget.
Demo code for the Box widget.
cui/demo/image command
cui/demo/inputfield/simple command
Demo code for the InputField widget.
Demo code for the InputField widget.
cui/demo/list command
Demo code for the List widget.
Demo code for the List widget.
cui/demo/menu command
cui/demo/modal command
Demo code for the Modal widget.
Demo code for the Modal widget.
cui/demo/panels command
Demo code for the Panels widget.
Demo code for the Panels widget.
cui/demo/plot command
cui/demo/presentation command
A presentation of the cui package, implemented with cui.
A presentation of the cui package, implemented with cui.
cui/demo/primitive command
Demo code which illustrates how to implement your own widget.
Demo code which illustrates how to implement your own widget.
cui/demo/progressbar command
Demo code for the ProgressBar widget.
Demo code for the ProgressBar widget.
cui/demo/tabbedpanels command
Demo code for the TabbedPanels widget.
Demo code for the TabbedPanels widget.
cui/demo/table command
Demo code for the Table widget.
Demo code for the Table widget.
cui/demo/textview command
Demo code for the TextView widget.
Demo code for the TextView widget.
cui/demo/treeview command
Demo code for the TreeView widget.
Demo code for the TreeView widget.
cui/demo/unicode command
Demo code for unicode support (demonstrates wide Chinese characters).
Demo code for unicode support (demonstrates wide Chinese characters).
cui/demo/vte/bash command
Demo showing how to run an interactive shell inside a cui terminal widget.
Demo showing how to run an interactive shell inside a cui terminal widget.
cui/demo/vte/command command
Demo showing how to run a one-shot command inside a cui terminal widget.
Demo showing how to run a one-shot command inside a cui terminal widget.
fmt
hex
shell/term
Package term provides support functions for dealing with terminals, as commonly found on UNIX systems.
Package term provides support functions for dealing with terminals, as commonly found on UNIX systems.
vm
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.

Jump to

Keyboard shortcuts

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