vv

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Aug 3, 2025 License: MIT Imports: 20 Imported by: 0

README

test Release Go Report Card License

vv 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/vv"
)

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 := vv.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
make docs       # generate docs

Milestones

  • console ui module
  • routines and channels
  • scriptable webserver module
  • sh compatible shell for direct bytecode execution
  • secure self updates using github-releases
  • ssh system service for running programs in the background
  • webassembly port with web worker support for concurrency

NOTE there will never be any form of cgo support / usage

Packages

package repository license
cui codeberg.org/tslocum/cview MIT
cui/bind.go codeberg.org/tslocum/cbind MIT
cui/chart github.com/navidys/tvxwidgets MIT
cui/editor github.com/pgavlin/femto MIT, MIT
cui/menu github.com/Racinettee/tmenu BSD 3-Clause License
cui/vte git.sr.ht/~rockorager/tcell-term MIT
sh/readline github.com/ergochat/readline MIT
ssh github.com/ferama/rospo MIT
cli github.com/aperturerobotics/cli MIT

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

Functions

func Commit

func Commit() string

func CompileAndRun

func CompileAndRun(ctx context.Context, data []byte, inputFile 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 NewCli

func NewCli(ui cli.ActionFunc) (*cli.App, error)

func RunCompiled

func RunCompiled(ctx context.Context, data []byte) (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)

RunREPL starts REPL.

func Version

func Version() string

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() *vvm.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) 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 *vvm.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 0 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 0 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 0 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() vvm.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 0 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
pkg
cli
Package cli provides a minimal framework for creating and organizing command line Go applications.
Package cli provides a minimal framework for creating and organizing command line Go applications.
cui
sh
sh/readline/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.
vvm
encoding
Package encoding provides functions to marshal and unmarshal data types.
Package encoding 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