ugo

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2023 License: MIT Imports: 18 Imported by: 2

README

The uGO Language

Go Reference Go Report Card uGO Test uGO Dev Test Maintainability

uGO is a fast, dynamic scripting language to embed in Go applications. uGO is compiled and executed as bytecode on stack-based VM that's written in native Go.

uGO is actively used in production to evaluate Sigma Rules' conditions, and to perform compromise assessment dynamically.

To see how fast uGO is, please have a look at fibonacci benchmarks (not updated frequently).

Play with uGO via Playground built for WebAssembly.

Fibonacci Example

param arg0

var fib

fib = func(x) {
    if x == 0 {
        return 0
    } else if x == 1 {
        return 1
    }
    return fib(x-1) + fib(x-2)
}
return fib(arg0)

Features

  • Written in native Go (no cgo).
  • Supports Go 1.15 and above.
  • if else statements.
  • for and for in statements.
  • try catch finally statements.
  • param, global, var and const declarations.
  • Rich builtins.
  • Pure uGO and Go Module support.
  • Go like syntax with additions.
  • Call uGO functions from Go.
  • Import uGO modules from any source (file system, HTTP, etc.).
  • Create wrapper functions for Go functions using code generation.

Why uGO

uGO name comes from the initials of my daughter's, wife's and my name. It is not related with Go.

I needed a faster embedded scripting language with runtime error handling.

Quick Start

go get github.com/ozanh/ugo@latest

uGO has a REPL application to learn and test uGO scripts.

go install github.com/ozanh/ugo/cmd/ugo@latest

./ugo

repl-gif

This example is to show some features of uGO.

https://play.golang.org/p/1Tj6joRmLiX

package main

import (
    "fmt"

    "github.com/ozanh/ugo"
)

func main() {
    script := `
param ...args

mapEach := func(seq, fn) {

    if !isArray(seq) {
        return error("want array, got " + typeName(seq))
    }

    var out = []

    if sz := len(seq); sz > 0 {
        out = repeat([0], sz)
    } else {
        return out
    }

    try {
        for i, v in seq {
            out[i] = fn(v)
        }
    } catch err {
        println(err)
    } finally {
        return out, err
    }
}

global multiplier

v, err := mapEach(args, func(x) { return x*multiplier })
if err != undefined {
    return err
}
return v
`

    bytecode, err := ugo.Compile([]byte(script), ugo.DefaultCompilerOptions)
    if err != nil {
        panic(err)
    }
    globals := ugo.Map{"multiplier": ugo.Int(2)}
    ret, err := ugo.NewVM(bytecode).Run(
        globals,
        ugo.Int(1), ugo.Int(2), ugo.Int(3), ugo.Int(4),
    )
    if err != nil {
        panic(err)
    }
    fmt.Println(ret) // [2, 4, 6, 8]
}

Roadmap

Examples for best practices (2023).

Better Playground (2023).

More standard library modules (2023).

Configurable Stdin, Stdout and Stderr per Virtual Machine (2023).

Deferring function calls (2024).

Concurrency support (2024).

Documentation

LICENSE

uGO is licensed under the MIT License.

See LICENSE for the full license text.

Acknowledgements

uGO is inspired by script language Tengo by Daniel Kang. A special thanks to Tengo's creater and contributors.

Documentation

Index

Constants

View Source
const (
	// True represents a true value.
	True = Bool(true)

	// False represents a false value.
	False = Bool(false)
)
View Source
const (
	// AttrModuleName is a special attribute injected into modules to identify
	// the modules by name.
	AttrModuleName = "__module_name__"
)

Variables

View Source
var (
	// DefaultCompilerOptions holds default Compiler options.
	DefaultCompilerOptions = CompilerOptions{
		OptimizerMaxCycle: 100,
		OptimizeConst:     true,
		OptimizeExpr:      true,
	}
	// TraceCompilerOptions holds Compiler options to print trace output
	// to stdout for Parser, Optimizer, Compiler.
	TraceCompilerOptions = CompilerOptions{
		Trace:             os.Stdout,
		TraceParser:       true,
		TraceCompiler:     true,
		TraceOptimizer:    true,
		OptimizerMaxCycle: 1<<8 - 1,
		OptimizeConst:     true,
		OptimizeExpr:      true,
	}
)
View Source
var (
	// ErrSymbolLimit represents a symbol limit error which is returned by
	// Compiler when number of local symbols exceeds the symbo limit for
	// a function that is 256.
	ErrSymbolLimit = &Error{
		Name:    "SymbolLimitError",
		Message: "number of local symbols exceeds the limit",
	}

	// ErrStackOverflow represents a stack overflow error.
	ErrStackOverflow = &Error{Name: "StackOverflowError"}

	// ErrVMAborted represents a VM aborted error.
	ErrVMAborted = &Error{Name: "VMAbortedError"}

	// ErrWrongNumArguments represents a wrong number of arguments error.
	ErrWrongNumArguments = &Error{Name: "WrongNumberOfArgumentsError"}

	// ErrInvalidOperator represents an error for invalid operator usage.
	ErrInvalidOperator = &Error{Name: "InvalidOperatorError"}

	// ErrIndexOutOfBounds represents an out of bounds index error.
	ErrIndexOutOfBounds = &Error{Name: "IndexOutOfBoundsError"}

	// ErrInvalidIndex represents an invalid index error.
	ErrInvalidIndex = &Error{Name: "InvalidIndexError"}

	// ErrNotIterable is an error where an Object is not iterable.
	ErrNotIterable = &Error{Name: "NotIterableError"}

	// ErrNotIndexable is an error where an Object is not indexable.
	ErrNotIndexable = &Error{Name: "NotIndexableError"}

	// ErrNotIndexAssignable is an error where an Object is not index assignable.
	ErrNotIndexAssignable = &Error{Name: "NotIndexAssignableError"}

	// ErrNotCallable is an error where Object is not callable.
	ErrNotCallable = &Error{Name: "NotCallableError"}

	// ErrNotImplemented is an error where an Object has not implemented a required method.
	ErrNotImplemented = &Error{Name: "NotImplementedError"}

	// ErrZeroDivision is an error where divisor is zero.
	ErrZeroDivision = &Error{Name: "ZeroDivisionError"}

	// ErrType represents a type error.
	ErrType = &Error{Name: "TypeError"}
)
View Source
var BuiltinObjects = [...]Object{

	BuiltinMakeArray: &BuiltinFunction{
		Name:    ":makeArray",
		Value:   funcPiOROe(builtinMakeArrayFunc),
		ValueEx: funcPiOROeEx(builtinMakeArrayFunc),
	},
	BuiltinAppend: &BuiltinFunction{
		Name:    "append",
		Value:   callExAdapter(builtinAppendFunc),
		ValueEx: builtinAppendFunc,
	},
	BuiltinDelete: &BuiltinFunction{
		Name:    "delete",
		Value:   funcPOsRe(builtinDeleteFunc),
		ValueEx: funcPOsReEx(builtinDeleteFunc),
	},
	BuiltinCopy: &BuiltinFunction{
		Name:    "copy",
		Value:   funcPORO(builtinCopyFunc),
		ValueEx: funcPOROEx(builtinCopyFunc),
	},
	BuiltinRepeat: &BuiltinFunction{
		Name:    "repeat",
		Value:   funcPOiROe(builtinRepeatFunc),
		ValueEx: funcPOiROeEx(builtinRepeatFunc),
	},
	BuiltinContains: &BuiltinFunction{
		Name:    "contains",
		Value:   funcPOOROe(builtinContainsFunc),
		ValueEx: funcPOOROeEx(builtinContainsFunc),
	},
	BuiltinLen: &BuiltinFunction{
		Name:    "len",
		Value:   funcPORO(builtinLenFunc),
		ValueEx: funcPOROEx(builtinLenFunc),
	},
	BuiltinCap: &BuiltinFunction{
		Name:    "cap",
		Value:   funcPORO(builtinCapFunc),
		ValueEx: funcPOROEx(builtinCapFunc),
	},
	BuiltinSort: &BuiltinFunction{
		Name:    "sort",
		Value:   funcPOROe(builtinSortFunc),
		ValueEx: funcPOROeEx(builtinSortFunc),
	},
	BuiltinSortReverse: &BuiltinFunction{
		Name:    "sortReverse",
		Value:   funcPOROe(builtinSortReverseFunc),
		ValueEx: funcPOROeEx(builtinSortReverseFunc),
	},
	BuiltinError: &BuiltinFunction{
		Name:    "error",
		Value:   funcPORO(builtinErrorFunc),
		ValueEx: funcPOROEx(builtinErrorFunc),
	},
	BuiltinTypeName: &BuiltinFunction{
		Name:    "typeName",
		Value:   funcPORO(builtinTypeNameFunc),
		ValueEx: funcPOROEx(builtinTypeNameFunc),
	},
	BuiltinBool: &BuiltinFunction{
		Name:    "bool",
		Value:   funcPORO(builtinBoolFunc),
		ValueEx: funcPOROEx(builtinBoolFunc),
	},
	BuiltinInt: &BuiltinFunction{
		Name:    "int",
		Value:   funcPi64RO(builtinIntFunc),
		ValueEx: funcPi64ROEx(builtinIntFunc),
	},
	BuiltinUint: &BuiltinFunction{
		Name:    "uint",
		Value:   funcPu64RO(builtinUintFunc),
		ValueEx: funcPu64ROEx(builtinUintFunc),
	},
	BuiltinFloat: &BuiltinFunction{
		Name:    "float",
		Value:   funcPf64RO(builtinFloatFunc),
		ValueEx: funcPf64ROEx(builtinFloatFunc),
	},
	BuiltinChar: &BuiltinFunction{
		Name:    "char",
		Value:   funcPOROe(builtinCharFunc),
		ValueEx: funcPOROeEx(builtinCharFunc),
	},
	BuiltinString: &BuiltinFunction{
		Name:    "string",
		Value:   funcPORO(builtinStringFunc),
		ValueEx: funcPOROEx(builtinStringFunc),
	},
	BuiltinBytes: &BuiltinFunction{
		Name:    "bytes",
		Value:   callExAdapter(builtinBytesFunc),
		ValueEx: builtinBytesFunc,
	},
	BuiltinChars: &BuiltinFunction{
		Name:    "chars",
		Value:   funcPOROe(builtinCharsFunc),
		ValueEx: funcPOROeEx(builtinCharsFunc),
	},
	BuiltinPrintf: &BuiltinFunction{
		Name:    "printf",
		Value:   callExAdapter(builtinPrintfFunc),
		ValueEx: builtinPrintfFunc,
	},
	BuiltinPrintln: &BuiltinFunction{
		Name:    "println",
		Value:   callExAdapter(builtinPrintlnFunc),
		ValueEx: builtinPrintlnFunc,
	},
	BuiltinSprintf: &BuiltinFunction{
		Name:    "sprintf",
		Value:   callExAdapter(builtinSprintfFunc),
		ValueEx: builtinSprintfFunc,
	},
	BuiltinGlobals: &BuiltinFunction{
		Name:    "globals",
		Value:   callExAdapter(builtinGlobalsFunc),
		ValueEx: builtinGlobalsFunc,
	},
	BuiltinIsError: &BuiltinFunction{
		Name:    "isError",
		Value:   callExAdapter(builtinIsErrorFunc),
		ValueEx: builtinIsErrorFunc,
	},
	BuiltinIsInt: &BuiltinFunction{
		Name:    "isInt",
		Value:   funcPORO(builtinIsIntFunc),
		ValueEx: funcPOROEx(builtinIsIntFunc),
	},
	BuiltinIsUint: &BuiltinFunction{
		Name:    "isUint",
		Value:   funcPORO(builtinIsUintFunc),
		ValueEx: funcPOROEx(builtinIsUintFunc),
	},
	BuiltinIsFloat: &BuiltinFunction{
		Name:    "isFloat",
		Value:   funcPORO(builtinIsFloatFunc),
		ValueEx: funcPOROEx(builtinIsFloatFunc),
	},
	BuiltinIsChar: &BuiltinFunction{
		Name:    "isChar",
		Value:   funcPORO(builtinIsCharFunc),
		ValueEx: funcPOROEx(builtinIsCharFunc),
	},
	BuiltinIsBool: &BuiltinFunction{
		Name:    "isBool",
		Value:   funcPORO(builtinIsBoolFunc),
		ValueEx: funcPOROEx(builtinIsBoolFunc),
	},
	BuiltinIsString: &BuiltinFunction{
		Name:    "isString",
		Value:   funcPORO(builtinIsStringFunc),
		ValueEx: funcPOROEx(builtinIsStringFunc),
	},
	BuiltinIsBytes: &BuiltinFunction{
		Name:    "isBytes",
		Value:   funcPORO(builtinIsBytesFunc),
		ValueEx: funcPOROEx(builtinIsBytesFunc),
	},
	BuiltinIsMap: &BuiltinFunction{
		Name:    "isMap",
		Value:   funcPORO(builtinIsMapFunc),
		ValueEx: funcPOROEx(builtinIsMapFunc),
	},
	BuiltinIsSyncMap: &BuiltinFunction{
		Name:    "isSyncMap",
		Value:   funcPORO(builtinIsSyncMapFunc),
		ValueEx: funcPOROEx(builtinIsSyncMapFunc),
	},
	BuiltinIsArray: &BuiltinFunction{
		Name:    "isArray",
		Value:   funcPORO(builtinIsArrayFunc),
		ValueEx: funcPOROEx(builtinIsArrayFunc),
	},
	BuiltinIsUndefined: &BuiltinFunction{
		Name:    "isUndefined",
		Value:   funcPORO(builtinIsUndefinedFunc),
		ValueEx: funcPOROEx(builtinIsUndefinedFunc),
	},
	BuiltinIsFunction: &BuiltinFunction{
		Name:    "isFunction",
		Value:   funcPORO(builtinIsFunctionFunc),
		ValueEx: funcPOROEx(builtinIsFunctionFunc),
	},
	BuiltinIsCallable: &BuiltinFunction{
		Name:  "isCallable",
		Value: funcPORO(builtinIsCallableFunc),
	},
	BuiltinIsIterable: &BuiltinFunction{
		Name:    "isIterable",
		Value:   funcPORO(builtinIsIterableFunc),
		ValueEx: funcPOROEx(builtinIsIterableFunc),
	},

	BuiltinWrongNumArgumentsError:  ErrWrongNumArguments,
	BuiltinInvalidOperatorError:    ErrInvalidOperator,
	BuiltinIndexOutOfBoundsError:   ErrIndexOutOfBounds,
	BuiltinNotIterableError:        ErrNotIterable,
	BuiltinNotIndexableError:       ErrNotIndexable,
	BuiltinNotIndexAssignableError: ErrNotIndexAssignable,
	BuiltinNotCallableError:        ErrNotCallable,
	BuiltinNotImplementedError:     ErrNotImplemented,
	BuiltinZeroDivisionError:       ErrZeroDivision,
	BuiltinTypeError:               ErrType,
}

BuiltinObjects is list of builtins, exported for REPL.

View Source
var BuiltinsMap = map[string]BuiltinType{
	"append":      BuiltinAppend,
	"delete":      BuiltinDelete,
	"copy":        BuiltinCopy,
	"repeat":      BuiltinRepeat,
	"contains":    BuiltinContains,
	"len":         BuiltinLen,
	"sort":        BuiltinSort,
	"sortReverse": BuiltinSortReverse,
	"error":       BuiltinError,
	"typeName":    BuiltinTypeName,
	"bool":        BuiltinBool,
	"int":         BuiltinInt,
	"uint":        BuiltinUint,
	"float":       BuiltinFloat,
	"char":        BuiltinChar,
	"string":      BuiltinString,
	"bytes":       BuiltinBytes,
	"chars":       BuiltinChars,
	"printf":      BuiltinPrintf,
	"println":     BuiltinPrintln,
	"sprintf":     BuiltinSprintf,
	"globals":     BuiltinGlobals,

	"isError":     BuiltinIsError,
	"isInt":       BuiltinIsInt,
	"isUint":      BuiltinIsUint,
	"isFloat":     BuiltinIsFloat,
	"isChar":      BuiltinIsChar,
	"isBool":      BuiltinIsBool,
	"isString":    BuiltinIsString,
	"isBytes":     BuiltinIsBytes,
	"isMap":       BuiltinIsMap,
	"isSyncMap":   BuiltinIsSyncMap,
	"isArray":     BuiltinIsArray,
	"isUndefined": BuiltinIsUndefined,
	"isFunction":  BuiltinIsFunction,
	"isCallable":  BuiltinIsCallable,
	"isIterable":  BuiltinIsIterable,

	"WrongNumArgumentsError":  BuiltinWrongNumArgumentsError,
	"InvalidOperatorError":    BuiltinInvalidOperatorError,
	"IndexOutOfBoundsError":   BuiltinIndexOutOfBoundsError,
	"NotIterableError":        BuiltinNotIterableError,
	"NotIndexableError":       BuiltinNotIndexableError,
	"NotIndexAssignableError": BuiltinNotIndexAssignableError,
	"NotCallableError":        BuiltinNotCallableError,
	"NotImplementedError":     BuiltinNotImplementedError,
	"ZeroDivisionError":       BuiltinZeroDivisionError,
	"TypeError":               BuiltinTypeError,

	":makeArray": BuiltinMakeArray,
	"cap":        BuiltinCap,
}

BuiltinsMap is list of builtin types, exported for REPL.

View Source
var OpcodeNames = [...]string{
	OpNoOp:         "NOOP",
	OpConstant:     "CONSTANT",
	OpCall:         "CALL",
	OpGetGlobal:    "GETGLOBAL",
	OpSetGlobal:    "SETGLOBAL",
	OpGetLocal:     "GETLOCAL",
	OpSetLocal:     "SETLOCAL",
	OpGetBuiltin:   "GETBUILTIN",
	OpBinaryOp:     "BINARYOP",
	OpUnary:        "UNARY",
	OpEqual:        "EQUAL",
	OpNotEqual:     "NOTEQUAL",
	OpJump:         "JUMP",
	OpJumpFalsy:    "JUMPFALSY",
	OpAndJump:      "ANDJUMP",
	OpOrJump:       "ORJUMP",
	OpMap:          "MAP",
	OpArray:        "ARRAY",
	OpSliceIndex:   "SLICEINDEX",
	OpGetIndex:     "GETINDEX",
	OpSetIndex:     "SETINDEX",
	OpNull:         "NULL",
	OpPop:          "POP",
	OpGetFree:      "GETFREE",
	OpSetFree:      "SETFREE",
	OpGetLocalPtr:  "GETLOCALPTR",
	OpGetFreePtr:   "GETFREEPTR",
	OpClosure:      "CLOSURE",
	OpIterInit:     "ITERINIT",
	OpIterNext:     "ITERNEXT",
	OpIterKey:      "ITERKEY",
	OpIterValue:    "ITERVALUE",
	OpLoadModule:   "LOADMODULE",
	OpStoreModule:  "STOREMODULE",
	OpReturn:       "RETURN",
	OpSetupTry:     "SETUPTRY",
	OpSetupCatch:   "SETUPCATCH",
	OpSetupFinally: "SETUPFINALLY",
	OpThrow:        "THROW",
	OpFinalizer:    "FINALIZER",
	OpDefineLocal:  "DEFINELOCAL",
	OpTrue:         "TRUE",
	OpFalse:        "FALSE",
	OpCallName:     "CALLNAME",
}

OpcodeNames are string representation of opcodes.

View Source
var OpcodeOperands = [...][]int{
	OpNoOp:         {},
	OpConstant:     {2},
	OpCall:         {1, 1},
	OpGetGlobal:    {2},
	OpSetGlobal:    {2},
	OpGetLocal:     {1},
	OpSetLocal:     {1},
	OpGetBuiltin:   {1},
	OpBinaryOp:     {1},
	OpUnary:        {1},
	OpEqual:        {},
	OpNotEqual:     {},
	OpJump:         {2},
	OpJumpFalsy:    {2},
	OpAndJump:      {2},
	OpOrJump:       {2},
	OpMap:          {2},
	OpArray:        {2},
	OpSliceIndex:   {},
	OpGetIndex:     {1},
	OpSetIndex:     {},
	OpNull:         {},
	OpPop:          {},
	OpGetFree:      {1},
	OpSetFree:      {1},
	OpGetLocalPtr:  {1},
	OpGetFreePtr:   {1},
	OpClosure:      {2, 1},
	OpIterInit:     {},
	OpIterNext:     {},
	OpIterKey:      {},
	OpIterValue:    {},
	OpLoadModule:   {2, 2},
	OpStoreModule:  {2},
	OpReturn:       {1},
	OpSetupTry:     {2, 2},
	OpSetupCatch:   {},
	OpSetupFinally: {},
	OpThrow:        {1},
	OpFinalizer:    {1},
	OpDefineLocal:  {1},
	OpTrue:         {},
	OpFalse:        {},
	OpCallName:     {1, 1},
}

OpcodeOperands is the number of operands.

View Source
var (
	// PrintWriter is the default writer for printf and println builtins.
	PrintWriter io.Writer = os.Stdout
)

Functions

func FormatInstructions

func FormatInstructions(b []byte, posOffset int) []string

FormatInstructions returns string representation of bytecode instructions.

func IterateInstructions

func IterateInstructions(insts []byte,
	fn func(pos int, opcode Opcode, operands []int, offset int) bool)

IterateInstructions iterate instructions and call given function for each instruction. Note: Do not use operands slice in callback, it is reused for less allocation.

func MakeInstruction

func MakeInstruction(buf []byte, op Opcode, args ...int) ([]byte, error)

MakeInstruction returns a bytecode for an Opcode and the operands.

Provide "buf" slice which is a returning value to reduce allocation or nil to create new byte slice. This is implemented to reduce compilation allocation that resulted in -15% allocation, +2% speed in compiler. It takes ~8ns/op with zero allocation.

Returning error is required to identify bugs faster when VM and Opcodes are under heavy development.

Warning: Unknown Opcode causes panic!

func ReadOperands

func ReadOperands(numOperands []int, ins []byte, operands []int) ([]int, int)

ReadOperands reads operands from the bytecode. Given operands slice is used to fill operands and is returned to allocate less.

func ToGoBool added in v0.2.0

func ToGoBool(o Object) (v bool, ok bool)

ToGoBool will try to convert an Object to Go bool value.

func ToGoByteSlice added in v0.2.0

func ToGoByteSlice(o Object) (v []byte, ok bool)

ToGoByteSlice will try to convert an Object to Go byte slice.

func ToGoFloat64 added in v0.2.0

func ToGoFloat64(o Object) (v float64, ok bool)

ToGoFloat64 will try to convert a numeric, bool or string Object to Go float64 value.

func ToGoInt added in v0.2.0

func ToGoInt(o Object) (v int, ok bool)

ToGoInt will try to convert a numeric, bool or string Object to Go int value.

func ToGoInt64 added in v0.2.0

func ToGoInt64(o Object) (v int64, ok bool)

ToGoInt64 will try to convert a numeric, bool or string Object to Go int64 value.

func ToGoRune added in v0.2.0

func ToGoRune(o Object) (v rune, ok bool)

ToGoRune will try to convert a int like Object to Go rune value.

func ToGoString added in v0.2.0

func ToGoString(o Object) (v string, ok bool)

ToGoString will try to convert an Object to Go string value.

func ToGoUint64 added in v0.2.0

func ToGoUint64(o Object) (v uint64, ok bool)

ToGoUint64 will try to convert a numeric, bool or string Object to Go uint64 value.

func ToInterface added in v0.2.0

func ToInterface(o Object) (ret interface{})

ToInterface tries to convert an Object o to an interface{} value.

Types

type Array

type Array []Object

Array represents array of objects and implements Object interface.

func ToArray added in v0.2.0

func ToArray(o Object) (v Array, ok bool)

ToArray will try to convert an Object to uGO array value.

func (Array) BinaryOp

func (o Array) BinaryOp(tok token.Token, right Object) (Object, error)

BinaryOp implements Object interface.

func (Array) Call

func (Array) Call(...Object) (Object, error)

Call implements Object interface.

func (Array) CanCall

func (Array) CanCall() bool

CanCall implements Object interface.

func (Array) CanIterate

func (Array) CanIterate() bool

CanIterate implements Object interface.

func (Array) Copy

func (o Array) Copy() Object

Copy implements Copier interface.

func (Array) Equal

func (o Array) Equal(right Object) bool

Equal implements Object interface.

func (Array) IndexGet

func (o Array) IndexGet(index Object) (Object, error)

IndexGet implements Object interface.

func (Array) IndexSet

func (o Array) IndexSet(index, value Object) error

IndexSet implements Object interface.

func (Array) IsFalsy

func (o Array) IsFalsy() bool

IsFalsy implements Object interface.

func (Array) Iterate

func (o Array) Iterate() Iterator

Iterate implements Iterable interface.

func (Array) Len added in v0.2.0

func (o Array) Len() int

Len implements LengthGetter interface.

func (Array) String

func (o Array) String() string

String implements Object interface.

func (Array) TypeName

func (Array) TypeName() string

TypeName implements Object interface.

type ArrayIterator

type ArrayIterator struct {
	V Array
	// contains filtered or unexported fields
}

ArrayIterator represents an iterator for the array.

func (*ArrayIterator) Key

func (it *ArrayIterator) Key() Object

Key implements Iterator interface.

func (*ArrayIterator) Next

func (it *ArrayIterator) Next() bool

Next implements Iterator interface.

func (*ArrayIterator) Value

func (it *ArrayIterator) Value() Object

Value implements Iterator interface.

type Bool

type Bool bool

Bool represents boolean values and implements Object interface.

func ToBool added in v0.2.0

func ToBool(o Object) (v Bool, ok bool)

ToBool will try to convert an Object to uGO bool value.

func (Bool) BinaryOp

func (o Bool) BinaryOp(tok token.Token, right Object) (Object, error)

BinaryOp implements Object interface.

func (Bool) Call

func (Bool) Call(_ ...Object) (Object, error)

Call implements Object interface.

func (Bool) CanCall

func (Bool) CanCall() bool

CanCall implements Object interface.

func (Bool) CanIterate

func (Bool) CanIterate() bool

CanIterate implements Object interface.

func (Bool) Equal

func (o Bool) Equal(right Object) bool

Equal implements Object interface.

func (Bool) Format added in v0.4.0

func (o Bool) Format(s fmt.State, verb rune)

Format implements fmt.Formatter interface.

func (Bool) IndexGet

func (Bool) IndexGet(index Object) (value Object, err error)

IndexGet implements Object interface.

func (Bool) IndexSet

func (Bool) IndexSet(index, value Object) error

IndexSet implements Object interface.

func (Bool) IsFalsy

func (o Bool) IsFalsy() bool

IsFalsy implements Object interface.

func (Bool) Iterate

func (Bool) Iterate() Iterator

Iterate implements Object interface.

func (Bool) String

func (o Bool) String() string

String implements Object interface.

func (Bool) TypeName

func (Bool) TypeName() string

TypeName implements Object interface.

type BuiltinFunction

type BuiltinFunction struct {
	ObjectImpl
	Name    string
	Value   func(args ...Object) (Object, error)
	ValueEx func(Call) (Object, error)
}

BuiltinFunction represents a builtin function object and implements Object interface.

func (*BuiltinFunction) Call

func (o *BuiltinFunction) Call(args ...Object) (Object, error)

Call implements Object interface.

func (*BuiltinFunction) CallEx added in v0.4.0

func (o *BuiltinFunction) CallEx(c Call) (Object, error)

func (*BuiltinFunction) CanCall

func (*BuiltinFunction) CanCall() bool

CanCall implements Object interface.

func (*BuiltinFunction) Copy

func (o *BuiltinFunction) Copy() Object

Copy implements Copier interface.

func (*BuiltinFunction) Equal

func (o *BuiltinFunction) Equal(right Object) bool

Equal implements Object interface.

func (*BuiltinFunction) IsFalsy

func (*BuiltinFunction) IsFalsy() bool

IsFalsy implements Object interface.

func (*BuiltinFunction) String

func (o *BuiltinFunction) String() string

String implements Object interface.

func (*BuiltinFunction) TypeName

func (*BuiltinFunction) TypeName() string

TypeName implements Object interface.

type BuiltinModule

type BuiltinModule struct {
	Attrs map[string]Object
}

BuiltinModule is an importable module that's written in Go.

func (*BuiltinModule) Import

func (m *BuiltinModule) Import(moduleName string) (interface{}, error)

Import returns an immutable map for the module.

type BuiltinType

type BuiltinType byte

BuiltinType represents a builtin type

const (
	BuiltinAppend BuiltinType = iota
	BuiltinDelete
	BuiltinCopy
	BuiltinRepeat
	BuiltinContains
	BuiltinLen
	BuiltinSort
	BuiltinSortReverse
	BuiltinError
	BuiltinTypeName
	BuiltinBool
	BuiltinInt
	BuiltinUint
	BuiltinFloat
	BuiltinChar
	BuiltinString
	BuiltinBytes
	BuiltinChars
	BuiltinPrintf
	BuiltinPrintln
	BuiltinSprintf
	BuiltinGlobals

	BuiltinIsError
	BuiltinIsInt
	BuiltinIsUint
	BuiltinIsFloat
	BuiltinIsChar
	BuiltinIsBool
	BuiltinIsString
	BuiltinIsBytes
	BuiltinIsMap
	BuiltinIsSyncMap
	BuiltinIsArray
	BuiltinIsUndefined
	BuiltinIsFunction
	BuiltinIsCallable
	BuiltinIsIterable

	BuiltinWrongNumArgumentsError
	BuiltinInvalidOperatorError
	BuiltinIndexOutOfBoundsError
	BuiltinNotIterableError
	BuiltinNotIndexableError
	BuiltinNotIndexAssignableError
	BuiltinNotCallableError
	BuiltinNotImplementedError
	BuiltinZeroDivisionError
	BuiltinTypeError

	BuiltinMakeArray
	BuiltinCap
)

Builtins

type Bytecode

type Bytecode struct {
	FileSet    *parser.SourceFileSet
	Main       *CompiledFunction
	Constants  []Object
	NumModules int
}

Bytecode holds the compiled functions and constants.

func Compile

func Compile(script []byte, opts CompilerOptions) (*Bytecode, error)

Compile compiles given script to Bytecode.

func (*Bytecode) Fprint

func (bc *Bytecode) Fprint(w io.Writer)

Fprint writes constants and instructions to given Writer in a human readable form.

func (*Bytecode) String

func (bc *Bytecode) String() string

type Bytes

type Bytes []byte

Bytes represents byte slice and implements Object interface.

func ToBytes added in v0.2.0

func ToBytes(o Object) (v Bytes, ok bool)

ToBytes will try to convert an Object to uGO bytes value.

func (Bytes) BinaryOp

func (o Bytes) BinaryOp(tok token.Token, right Object) (Object, error)

BinaryOp implements Object interface.

func (Bytes) Call

func (o Bytes) Call(_ ...Object) (Object, error)

Call implements Object interface.

func (Bytes) CanCall

func (o Bytes) CanCall() bool

CanCall implements Object interface.

func (Bytes) CanIterate

func (Bytes) CanIterate() bool

CanIterate implements Object interface.

func (Bytes) Copy

func (o Bytes) Copy() Object

Copy implements Copier interface.

func (Bytes) Equal

func (o Bytes) Equal(right Object) bool

Equal implements Object interface.

func (Bytes) Format added in v0.4.0

func (o Bytes) Format(s fmt.State, verb rune)

Format implements fmt.Formatter interface.

func (Bytes) IndexGet

func (o Bytes) IndexGet(index Object) (Object, error)

IndexGet represents string values and implements Object interface.

func (Bytes) IndexSet

func (o Bytes) IndexSet(index, value Object) error

IndexSet implements Object interface.

func (Bytes) IsFalsy

func (o Bytes) IsFalsy() bool

IsFalsy implements Object interface.

func (Bytes) Iterate

func (o Bytes) Iterate() Iterator

Iterate implements Object interface.

func (Bytes) Len added in v0.2.0

func (o Bytes) Len() int

Len implements LengthGetter interface.

func (Bytes) String

func (o Bytes) String() string

func (Bytes) TypeName

func (Bytes) TypeName() string

TypeName implements Object interface.

type BytesIterator

type BytesIterator struct {
	V Bytes
	// contains filtered or unexported fields
}

BytesIterator represents an iterator for the bytes.

func (*BytesIterator) Key

func (it *BytesIterator) Key() Object

Key implements Iterator interface.

func (*BytesIterator) Next

func (it *BytesIterator) Next() bool

Next implements Iterator interface.

func (*BytesIterator) Value

func (it *BytesIterator) Value() Object

Value implements Iterator interface.

type Call added in v0.4.0

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

Call is a struct to pass arguments to CallEx and CallName methods. It provides VM for various purposes.

Call struct intentionally does not provide access to normal and variadic arguments directly. Using Len() and Get() methods is preferred. It is safe to create Call with a nil VM as long as VM is not required by the callee.

func NewCall added in v0.4.0

func NewCall(vm *VM, args []Object, vargs ...Object) Call

NewCall creates a new Call struct with the given arguments.

func (*Call) CheckLen added in v0.4.0

func (c *Call) CheckLen(n int) error

CheckLen checks the number of arguments and variadic arguments. If the number of arguments is not equal to n, it returns an error.

func (*Call) Get added in v0.4.0

func (c *Call) Get(n int) Object

Get returns the nth argument. If n is greater than the number of arguments, it returns the nth variadic argument. If n is greater than the number of arguments and variadic arguments, it panics!

func (*Call) Len added in v0.4.0

func (c *Call) Len() int

Len returns the number of arguments including variadic arguments.

func (*Call) VM added in v0.4.0

func (c *Call) VM() *VM

VM returns the VM of the call.

type CallableExFunc added in v0.4.0

type CallableExFunc = func(Call) (ret Object, err error)

CallableExFunc is a function signature for a callable function that accepts a Call struct.

type CallableFunc

type CallableFunc = func(args ...Object) (ret Object, err error)

CallableFunc is a function signature for a callable function.

type Char

type Char rune

Char represents a rune and implements Object interface.

func ToChar added in v0.2.0

func ToChar(o Object) (v Char, ok bool)

ToChar will try to convert an Object to uGO char value.

func (Char) BinaryOp

func (o Char) BinaryOp(tok token.Token, right Object) (Object, error)

BinaryOp implements Object interface.

func (Char) Call

func (o Char) Call(_ ...Object) (Object, error)

Call implements Object interface.

func (Char) CanCall

func (o Char) CanCall() bool

CanCall implements Object interface.

func (Char) CanIterate

func (Char) CanIterate() bool

CanIterate implements Object interface.

func (Char) Equal

func (o Char) Equal(right Object) bool

Equal implements Object interface.

func (Char) Format added in v0.4.0

func (o Char) Format(s fmt.State, verb rune)

Format implements fmt.Formatter interface.

func (Char) IndexGet

func (Char) IndexGet(index Object) (Object, error)

IndexGet implements Object interface.

func (Char) IndexSet

func (Char) IndexSet(index, value Object) error

IndexSet implements Object interface.

func (Char) IsFalsy

func (o Char) IsFalsy() bool

IsFalsy implements Object interface.

func (Char) Iterate

func (Char) Iterate() Iterator

Iterate implements Object interface.

func (Char) String

func (o Char) String() string

String implements Object interface.

func (Char) TypeName

func (Char) TypeName() string

TypeName implements Object interface.

type CompiledFunction

type CompiledFunction struct {
	// number of parameters
	NumParams int
	// number of local variabls including parameters NumLocals>=NumParams
	NumLocals    int
	Instructions []byte
	Variadic     bool
	Free         []*ObjectPtr
	// SourceMap holds the index of instruction and token's position.
	SourceMap map[int]int
}

CompiledFunction holds the constants and instructions to pass VM.

func (*CompiledFunction) BinaryOp

func (*CompiledFunction) BinaryOp(token.Token, Object) (Object, error)

BinaryOp implements Object interface.

func (*CompiledFunction) Call

func (*CompiledFunction) Call(...Object) (Object, error)

Call implements Object interface. CompiledFunction is not directly callable. You should use Invoker to call it with a Virtual Machine. Because of this, it always returns an error.

func (*CompiledFunction) CanCall

func (*CompiledFunction) CanCall() bool

CanCall implements Object interface.

func (*CompiledFunction) CanIterate

func (*CompiledFunction) CanIterate() bool

CanIterate implements Object interface.

func (*CompiledFunction) Copy

func (o *CompiledFunction) Copy() Object

Copy implements the Copier interface.

func (*CompiledFunction) Equal

func (o *CompiledFunction) Equal(right Object) bool

Equal implements Object interface.

func (*CompiledFunction) Fprint

func (o *CompiledFunction) Fprint(w io.Writer)

Fprint writes constants and instructions to given Writer in a human readable form.

func (*CompiledFunction) IndexGet

func (*CompiledFunction) IndexGet(index Object) (Object, error)

IndexGet represents string values and implements Object interface.

func (*CompiledFunction) IndexSet

func (*CompiledFunction) IndexSet(index, value Object) error

IndexSet implements Object interface.

func (*CompiledFunction) IsFalsy

func (*CompiledFunction) IsFalsy() bool

IsFalsy implements Object interface.

func (*CompiledFunction) Iterate

func (*CompiledFunction) Iterate() Iterator

Iterate implements Object interface.

func (*CompiledFunction) SourcePos

func (o *CompiledFunction) SourcePos(ip int) parser.Pos

SourcePos returns the source position of the instruction at ip.

func (*CompiledFunction) String

func (o *CompiledFunction) String() string

func (*CompiledFunction) TypeName

func (*CompiledFunction) TypeName() string

TypeName implements Object interface

type Compiler

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

Compiler compiles the AST into a bytecode.

func NewCompiler

func NewCompiler(file *parser.SourceFile, opts CompilerOptions) *Compiler

NewCompiler creates a new Compiler object.

func (*Compiler) Bytecode

func (c *Compiler) Bytecode() *Bytecode

Bytecode returns compiled Bytecode ready to run in VM.

func (*Compiler) Compile

func (c *Compiler) Compile(node parser.Node) error

Compile compiles parser.Node and builds Bytecode.

func (*Compiler) SetGlobalSymbolsIndex added in v0.2.0

func (c *Compiler) SetGlobalSymbolsIndex()

SetGlobalSymbolsIndex sets index of a global symbol. This is only required when a global symbol is defined in SymbolTable and provided to compiler. Otherwise, caller needs to append the constant to Constants, set the symbol index and provide it to the Compiler. This should be called before Compiler.Compile call.

type CompilerError

type CompilerError struct {
	FileSet *parser.SourceFileSet
	Node    parser.Node
	Err     error
}

CompilerError represents a compiler error.

func (*CompilerError) Error

func (e *CompilerError) Error() string

func (*CompilerError) Unwrap

func (e *CompilerError) Unwrap() error

type CompilerOptions

type CompilerOptions struct {
	ModuleMap         *ModuleMap
	ModulePath        string
	Constants         []Object
	SymbolTable       *SymbolTable
	Trace             io.Writer
	TraceParser       bool
	TraceCompiler     bool
	TraceOptimizer    bool
	OptimizerMaxCycle int
	OptimizeConst     bool
	OptimizeExpr      bool
	// contains filtered or unexported fields
}

CompilerOptions represents customizable options for Compile().

type Copier

type Copier interface {
	Copy() Object
}

Copier wraps the Copy method to create a deep copy of the object.

type Error

type Error struct {
	Name    string
	Message string
	Cause   error
}

Error represents Error Object and implements error and Object interfaces.

func NewArgumentTypeError

func NewArgumentTypeError(pos, expectType, foundType string) *Error

NewArgumentTypeError creates a new Error from ErrType.

func NewIndexTypeError

func NewIndexTypeError(expectType, foundType string) *Error

NewIndexTypeError creates a new Error from ErrType.

func NewIndexValueTypeError

func NewIndexValueTypeError(expectType, foundType string) *Error

NewIndexValueTypeError creates a new Error from ErrType.

func NewOperandTypeError

func NewOperandTypeError(token, leftType, rightType string) *Error

NewOperandTypeError creates a new Error from ErrType.

func (*Error) BinaryOp

func (o *Error) BinaryOp(tok token.Token, right Object) (Object, error)

BinaryOp implements Object interface.

func (*Error) Call

func (*Error) Call(_ ...Object) (Object, error)

Call implements Object interface.

func (*Error) CanCall

func (*Error) CanCall() bool

CanCall implements Object interface.

func (*Error) CanIterate

func (*Error) CanIterate() bool

CanIterate implements Object interface.

func (*Error) Copy

func (o *Error) Copy() Object

Copy implements Copier interface.

func (*Error) Equal

func (o *Error) Equal(right Object) bool

Equal implements Object interface.

func (*Error) Error

func (o *Error) Error() string

Error implements error interface.

func (*Error) IndexGet

func (o *Error) IndexGet(index Object) (Object, error)

IndexGet implements Object interface.

func (*Error) IndexSet

func (*Error) IndexSet(index, value Object) error

IndexSet implements Object interface.

func (*Error) IsFalsy

func (o *Error) IsFalsy() bool

IsFalsy implements Object interface.

func (*Error) Iterate

func (*Error) Iterate() Iterator

Iterate implements Object interface.

func (*Error) NewError

func (o *Error) NewError(messages ...string) *Error

NewError creates a new Error and sets original Error as its cause which can be unwrapped.

func (*Error) String

func (o *Error) String() string

String implements Object interface.

func (*Error) TypeName

func (*Error) TypeName() string

TypeName implements Object interface.

func (*Error) Unwrap

func (o *Error) Unwrap() error

type Eval

type Eval struct {
	Locals       []Object
	Globals      Object
	Opts         CompilerOptions
	VM           *VM
	ModulesCache []Object
}

Eval compiles and runs scripts within same scope. If executed script's return statement has no value to return or return is omitted, it returns last value on stack. Warning: Eval is not safe to use concurrently.

func NewEval

func NewEval(opts CompilerOptions, globals Object, args ...Object) *Eval

NewEval returns new Eval object.

func (*Eval) Run

func (r *Eval) Run(ctx context.Context, script []byte) (Object, *Bytecode, error)

Run compiles, runs given script and returns last value on stack.

type ExCallerObject added in v0.4.0

type ExCallerObject interface {
	Object
	CallEx(c Call) (Object, error)
}

ExCallerObject is an interface for objects that can be called with CallEx method. It is an extended version of the Call method that can be used to call an object with a Call struct. Objects implementing this interface is called with CallEx method instead of Call method. Note that CanCall() should return true for objects implementing this interface.

type ExtImporter added in v0.2.0

type ExtImporter interface {
	Importable
	// Get returns Extimporter instance which will import a module.
	Get(moduleName string) ExtImporter
	// Name returns the full name of the module e.g. absoule path of a file.
	// Import names are generally relative, this overwrites module name and used
	// as unique key for compiler module cache.
	Name() string
	// Fork returns an ExtImporter instance which will be used to import the
	// modules. Fork will get the result of Name() if it is not empty, otherwise
	// module name will be same with the Get call.
	Fork(moduleName string) ExtImporter
}

ExtImporter wraps methods for a module which will be impored dynamically like a file.

type Float

type Float float64

Float represents float values and implements Object interface.

func ToFloat added in v0.2.0

func ToFloat(o Object) (v Float, ok bool)

ToFloat will try to convert an Object to uGO float value.

func (Float) BinaryOp

func (o Float) BinaryOp(tok token.Token, right Object) (Object, error)

BinaryOp implements Object interface.

func (Float) Call

func (o Float) Call(_ ...Object) (Object, error)

Call implements Object interface.

func (Float) CanCall

func (o Float) CanCall() bool

CanCall implements Object interface.

func (Float) CanIterate

func (Float) CanIterate() bool

CanIterate implements Object interface.

func (Float) Equal

func (o Float) Equal(right Object) bool

Equal implements Object interface.

func (Float) Format added in v0.4.0

func (o Float) Format(s fmt.State, verb rune)

Format implements fmt.Formatter interface.

func (Float) IndexGet

func (Float) IndexGet(index Object) (Object, error)

IndexGet implements Object interface.

func (Float) IndexSet

func (Float) IndexSet(index, value Object) error

IndexSet implements Object interface.

func (Float) IsFalsy

func (o Float) IsFalsy() bool

IsFalsy implements Object interface.

func (Float) Iterate

func (Float) Iterate() Iterator

Iterate implements Object interface.

func (Float) String

func (o Float) String() string

String implements Object interface.

func (Float) TypeName

func (Float) TypeName() string

TypeName implements Object interface.

type Function

type Function struct {
	ObjectImpl
	Name    string
	Value   func(args ...Object) (Object, error)
	ValueEx func(Call) (Object, error)
}

Function represents a function object and implements Object interface.

func (*Function) Call

func (o *Function) Call(args ...Object) (Object, error)

Call implements Object interface.

func (*Function) CallEx added in v0.4.0

func (o *Function) CallEx(call Call) (Object, error)

func (*Function) CanCall

func (*Function) CanCall() bool

CanCall implements Object interface.

func (*Function) Copy

func (o *Function) Copy() Object

Copy implements Copier interface.

func (*Function) Equal

func (o *Function) Equal(right Object) bool

Equal implements Object interface.

func (*Function) IsFalsy

func (*Function) IsFalsy() bool

IsFalsy implements Object interface.

func (*Function) String

func (o *Function) String() string

String implements Object interface.

func (*Function) TypeName

func (*Function) TypeName() string

TypeName implements Object interface.

type Importable

type Importable interface {
	// Import should return either an Object or module source code ([]byte).
	Import(moduleName string) (interface{}, error)
}

Importable interface represents importable module instance.

type IndexDeleter added in v0.2.0

type IndexDeleter interface {
	IndexDelete(Object) error
}

IndexDeleter wraps the IndexDelete method to delete an index of an object.

type Int

type Int int64

Int represents signed integer values and implements Object interface.

func ToInt added in v0.2.0

func ToInt(o Object) (v Int, ok bool)

ToInt will try to convert an Object to uGO int value.

func (Int) BinaryOp

func (o Int) BinaryOp(tok token.Token, right Object) (Object, error)

BinaryOp implements Object interface.

func (Int) Call

func (o Int) Call(_ ...Object) (Object, error)

Call implements Object interface.

func (Int) CanCall

func (o Int) CanCall() bool

CanCall implements Object interface.

func (Int) CanIterate

func (Int) CanIterate() bool

CanIterate implements Object interface.

func (Int) Equal

func (o Int) Equal(right Object) bool

Equal implements Object interface.

func (Int) Format added in v0.4.0

func (o Int) Format(s fmt.State, verb rune)

Format implements fmt.Formatter interface.

func (Int) IndexGet

func (Int) IndexGet(index Object) (Object, error)

IndexGet implements Object interface.

func (Int) IndexSet

func (Int) IndexSet(index, value Object) error

IndexSet implements Object interface.

func (Int) IsFalsy

func (o Int) IsFalsy() bool

IsFalsy implements Object interface.

func (Int) Iterate

func (Int) Iterate() Iterator

Iterate implements Object interface.

func (Int) String

func (o Int) String() string

String implements Object interface.

func (Int) TypeName

func (Int) TypeName() string

TypeName implements Object interface.

type Invoker added in v0.4.0

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

Invoker invokes a given callee object (either a CompiledFunction or any other callable object) with the given arguments.

Invoker creates a new VM instance if the callee is a CompiledFunction, otherwise it runs the callee directly. Every Invoker call checks if the VM is aborted. If it is, it returns ErrVMAborted.

Invoker is not safe for concurrent use by multiple goroutines.

Acquire and Release methods are used to acquire and release a VM from the pool. So it is possible to reuse a VM instance for multiple Invoke calls. This is useful when you want to execute multiple functions in a single VM. For example, you can use Acquire and Release to execute multiple functions in a single VM instance. Note that you should call Release after Acquire, if you want to reuse the VM. If you don't want to use the pool, you can just call Invoke method. It is unsafe to hold a reference to the VM after Release is called. Using VM pool is about three times faster than creating a new VM for each Invoke call.

func NewInvoker added in v0.4.0

func NewInvoker(vm *VM, callee Object) *Invoker

NewInvoker creates a new Invoker object.

func (*Invoker) Acquire added in v0.4.0

func (inv *Invoker) Acquire()

Acquire acquires a VM from the pool.

func (*Invoker) Invoke added in v0.4.0

func (inv *Invoker) Invoke(args ...Object) (Object, error)

Invoke invokes the callee object with the given arguments.

func (*Invoker) Release added in v0.4.0

func (inv *Invoker) Release()

Release releases the VM back to the pool if it was acquired from the pool.

type Iterator

type Iterator interface {
	// Next returns true if there are more elements to iterate.
	Next() bool

	// Key returns the key or index value of the current element.
	Key() Object

	// Value returns the value of the current element.
	Value() Object
}

Iterator wraps the methods required to iterate Objects in VM.

type LengthGetter added in v0.2.0

type LengthGetter interface {
	Len() int
}

LengthGetter wraps the Len method to get the number of elements of an object.

type Map

type Map map[string]Object

Map represents map of objects and implements Object interface.

func ToMap added in v0.2.0

func ToMap(o Object) (v Map, ok bool)

ToMap will try to convert an Object to uGO map value.

func (Map) BinaryOp

func (o Map) BinaryOp(tok token.Token, right Object) (Object, error)

BinaryOp implements Object interface.

func (Map) Call

func (Map) Call(...Object) (Object, error)

Call implements Object interface.

func (Map) CanCall

func (Map) CanCall() bool

CanCall implements Object interface.

func (Map) CanIterate

func (Map) CanIterate() bool

CanIterate implements Object interface.

func (Map) Copy

func (o Map) Copy() Object

Copy implements Copier interface.

func (Map) Equal

func (o Map) Equal(right Object) bool

Equal implements Object interface.

func (Map) IndexDelete added in v0.2.0

func (o Map) IndexDelete(key Object) error

IndexDelete tries to delete the string value of key from the map. IndexDelete implements IndexDeleter interface.

func (Map) IndexGet

func (o Map) IndexGet(index Object) (Object, error)

IndexGet implements Object interface.

func (Map) IndexSet

func (o Map) IndexSet(index, value Object) error

IndexSet implements Object interface.

func (Map) IsFalsy

func (o Map) IsFalsy() bool

IsFalsy implements Object interface.

func (Map) Iterate

func (o Map) Iterate() Iterator

Iterate implements Iterable interface.

func (Map) Len added in v0.2.0

func (o Map) Len() int

Len implements LengthGetter interface.

func (Map) String

func (o Map) String() string

String implements Object interface.

func (Map) TypeName

func (Map) TypeName() string

TypeName implements Object interface.

type MapIterator

type MapIterator struct {
	V Map
	// contains filtered or unexported fields
}

MapIterator represents an iterator for the map.

func (*MapIterator) Key

func (it *MapIterator) Key() Object

Key implements Iterator interface.

func (*MapIterator) Next

func (it *MapIterator) Next() bool

Next implements Iterator interface.

func (*MapIterator) Value

func (it *MapIterator) Value() Object

Value implements Iterator interface.

type ModuleMap

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

ModuleMap represents a set of named modules. Use NewModuleMap to create a new module map.

func NewModuleMap

func NewModuleMap() *ModuleMap

NewModuleMap creates a new module map.

func (*ModuleMap) Add

func (m *ModuleMap) Add(name string, module Importable) *ModuleMap

Add adds an importable module.

func (*ModuleMap) AddBuiltinModule

func (m *ModuleMap) AddBuiltinModule(
	name string,
	attrs map[string]Object,
) *ModuleMap

AddBuiltinModule adds a builtin module.

func (*ModuleMap) AddSourceModule

func (m *ModuleMap) AddSourceModule(name string, src []byte) *ModuleMap

AddSourceModule adds a source module.

func (*ModuleMap) Copy

func (m *ModuleMap) Copy() *ModuleMap

Copy creates a copy of the module map.

func (*ModuleMap) Fork added in v0.2.0

func (m *ModuleMap) Fork(moduleName string) *ModuleMap

Fork creates a new ModuleMap instance if ModuleMap has an ExtImporter to make ExtImporter preseve state.

func (*ModuleMap) Get

func (m *ModuleMap) Get(name string) Importable

Get returns an import module identified by name. It returns nil if the name is not found.

func (*ModuleMap) Remove

func (m *ModuleMap) Remove(name string)

Remove removes a named module.

func (*ModuleMap) SetExtImporter added in v0.2.0

func (m *ModuleMap) SetExtImporter(im ExtImporter) *ModuleMap

SetExtImporter sets an ExtImporter to ModuleMap, which will be used to import modules dynamically.

type NameCallerObject added in v0.4.0

type NameCallerObject interface {
	Object
	CallName(name string, c Call) (Object, error)
}

NameCallerObject is an interface for objects that can be called with CallName method to call a method of an object. Objects implementing this interface can reduce allocations by not creating a callable object for each method call.

type Object

type Object interface {
	// TypeName should return the name of the type.
	TypeName() string

	// String should return a string of the type's value.
	String() string

	// BinaryOp handles +,-,*,/,%,<<,>>,<=,>=,<,> operators.
	// Returned error stops VM execution if not handled with an error handler
	// and VM.Run returns the same error as wrapped.
	BinaryOp(tok token.Token, right Object) (Object, error)

	// IsFalsy returns true if value is falsy otherwise false.
	IsFalsy() bool

	// Equal checks equality of objects.
	Equal(right Object) bool

	// Call is called from VM if CanCall() returns true. Check the number of
	// arguments provided and their types in the method. Returned error stops VM
	// execution if not handled with an error handler and VM.Run returns the
	// same error as wrapped.
	Call(args ...Object) (Object, error)

	// CanCall returns true if type can be called with Call() method.
	// VM returns an error if one tries to call a noncallable object.
	CanCall() bool

	// Iterate should return an Iterator for the type.
	Iterate() Iterator

	// CanIterate should return whether the Object can be Iterated.
	CanIterate() bool

	// IndexGet should take an index Object and return a result Object or an
	// error for indexable objects. Indexable is an object that can take an
	// index and return an object. Returned error stops VM execution if not
	// handled with an error handler and VM.Run returns the same error as
	// wrapped. If Object is not indexable, ErrNotIndexable should be returned
	// as error.
	IndexGet(index Object) (value Object, err error)

	// IndexSet should take an index Object and a value Object for index
	// assignable objects. Index assignable is an object that can take an index
	// and a value on the left-hand side of the assignment statement. If Object
	// is not index assignable, ErrNotIndexAssignable should be returned as
	// error. Returned error stops VM execution if not handled with an error
	// handler and VM.Run returns the same error as wrapped.
	IndexSet(index, value Object) error
}

Object represents an object in the VM.

var (
	// Undefined represents undefined value.
	Undefined Object = &UndefinedType{}
)

func ToObject added in v0.2.0

func ToObject(v interface{}) (ret Object, err error)

ToObject will try to convert an interface{} v to an Object.

func ToObjectAlt added in v0.2.2

func ToObjectAlt(v interface{}) (ret Object, err error)

ToObjectAlt is analogous to ToObject but it will always convert signed integers to Int and unsigned integers to Uint. It is an alternative to ToObject. Note that, this function is subject to change in the future.

type ObjectImpl

type ObjectImpl struct{}

ObjectImpl is the basic Object implementation and it does not nothing, and helps to implement Object interface by embedding and overriding methods in custom implementations. String and TypeName must be implemented otherwise calling these methods causes panic.

func (ObjectImpl) BinaryOp

func (ObjectImpl) BinaryOp(_ token.Token, _ Object) (Object, error)

BinaryOp implements Object interface.

func (ObjectImpl) Call

func (ObjectImpl) Call(_ ...Object) (Object, error)

Call implements Object interface.

func (ObjectImpl) CanCall

func (ObjectImpl) CanCall() bool

CanCall implements Object interface.

func (ObjectImpl) CanIterate

func (ObjectImpl) CanIterate() bool

CanIterate implements Object interface.

func (ObjectImpl) Equal

func (ObjectImpl) Equal(Object) bool

Equal implements Object interface.

func (ObjectImpl) IndexGet

func (ObjectImpl) IndexGet(index Object) (value Object, err error)

IndexGet implements Object interface.

func (ObjectImpl) IndexSet

func (ObjectImpl) IndexSet(index, value Object) error

IndexSet implements Object interface.

func (ObjectImpl) IsFalsy

func (ObjectImpl) IsFalsy() bool

IsFalsy implements Object interface.

func (ObjectImpl) Iterate

func (ObjectImpl) Iterate() Iterator

Iterate implements Object interface.

func (ObjectImpl) String

func (ObjectImpl) String() string

String implements Object interface.

func (ObjectImpl) TypeName

func (ObjectImpl) TypeName() string

TypeName implements Object interface.

type ObjectPtr

type ObjectPtr struct {
	ObjectImpl
	Value *Object
}

ObjectPtr represents a pointer variable.

func (*ObjectPtr) BinaryOp

func (o *ObjectPtr) BinaryOp(tok token.Token, right Object) (Object, error)

BinaryOp implements Object interface.

func (*ObjectPtr) Call

func (o *ObjectPtr) Call(args ...Object) (Object, error)

Call implements Object interface.

func (*ObjectPtr) CanCall

func (o *ObjectPtr) CanCall() bool

CanCall implements Object interface.

func (*ObjectPtr) Copy

func (o *ObjectPtr) Copy() Object

Copy implements Copier interface.

func (*ObjectPtr) Equal

func (o *ObjectPtr) Equal(x Object) bool

Equal implements Object interface.

func (*ObjectPtr) IsFalsy

func (o *ObjectPtr) IsFalsy() bool

IsFalsy implements Object interface.

func (*ObjectPtr) String

func (o *ObjectPtr) String() string

String implements Object interface.

func (*ObjectPtr) TypeName

func (o *ObjectPtr) TypeName() string

TypeName implements Object interface.

type Opcode

type Opcode = byte

Opcode represents a single byte operation code.

const (
	OpNoOp Opcode = iota
	OpConstant
	OpCall
	OpGetGlobal
	OpSetGlobal
	OpGetLocal
	OpSetLocal
	OpGetBuiltin
	OpBinaryOp
	OpUnary
	OpEqual
	OpNotEqual
	OpJump
	OpJumpFalsy
	OpAndJump
	OpOrJump
	OpMap
	OpArray
	OpSliceIndex
	OpGetIndex
	OpSetIndex
	OpNull
	OpPop
	OpGetFree
	OpSetFree
	OpGetLocalPtr
	OpGetFreePtr
	OpClosure
	OpIterInit
	OpIterNext
	OpIterKey
	OpIterValue
	OpLoadModule
	OpStoreModule
	OpSetupTry
	OpSetupCatch
	OpSetupFinally
	OpThrow
	OpFinalizer
	OpReturn
	OpDefineLocal
	OpTrue
	OpFalse
	OpCallName
)

List of opcodes

type OptimizerError

type OptimizerError struct {
	FilePos parser.SourceFilePos
	Node    parser.Node
	Err     error
}

OptimizerError represents an optimizer error.

func (*OptimizerError) Error

func (e *OptimizerError) Error() string

func (*OptimizerError) Unwrap

func (e *OptimizerError) Unwrap() error

type RuntimeError

type RuntimeError struct {
	Err *Error

	Trace []parser.Pos
	// contains filtered or unexported fields
}

RuntimeError represents a runtime error that wraps Error and includes trace information.

func (*RuntimeError) BinaryOp

func (o *RuntimeError) BinaryOp(tok token.Token, right Object) (Object, error)

BinaryOp implements Object interface.

func (*RuntimeError) Call

func (*RuntimeError) Call(_ ...Object) (Object, error)

Call implements Object interface.

func (*RuntimeError) CanCall

func (*RuntimeError) CanCall() bool

CanCall implements Object interface.

func (*RuntimeError) CanIterate

func (*RuntimeError) CanIterate() bool

CanIterate implements Object interface.

func (*RuntimeError) Copy

func (o *RuntimeError) Copy() Object

Copy implements Copier interface.

func (*RuntimeError) Equal

func (o *RuntimeError) Equal(right Object) bool

Equal implements Object interface.

func (*RuntimeError) Error

func (o *RuntimeError) Error() string

Error implements error interface.

func (*RuntimeError) Format

func (o *RuntimeError) Format(s fmt.State, verb rune)

Format implements fmt.Formater interface.

func (*RuntimeError) IndexGet

func (o *RuntimeError) IndexGet(index Object) (Object, error)

IndexGet implements Object interface.

func (*RuntimeError) IndexSet

func (*RuntimeError) IndexSet(index, value Object) error

IndexSet implements Object interface.

func (*RuntimeError) IsFalsy

func (o *RuntimeError) IsFalsy() bool

IsFalsy implements Object interface.

func (*RuntimeError) Iterate

func (*RuntimeError) Iterate() Iterator

Iterate implements Object interface.

func (*RuntimeError) NewError

func (o *RuntimeError) NewError(messages ...string) *RuntimeError

NewError creates a new Error and sets original Error as its cause which can be unwrapped.

func (*RuntimeError) StackTrace

func (o *RuntimeError) StackTrace() StackTrace

StackTrace returns stack trace if set otherwise returns nil.

func (*RuntimeError) String

func (o *RuntimeError) String() string

String implements Object interface.

func (*RuntimeError) TypeName

func (*RuntimeError) TypeName() string

TypeName implements Object interface.

func (*RuntimeError) Unwrap

func (o *RuntimeError) Unwrap() error

type SimpleOptimizer

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

SimpleOptimizer optimizes given parsed file by evaluating constants and expressions. It is not safe to call methods concurrently.

func NewOptimizer

func NewOptimizer(
	file *parser.File,
	base *SymbolTable,
	opts CompilerOptions,
) *SimpleOptimizer

NewOptimizer creates an Optimizer object.

func (*SimpleOptimizer) Optimize

func (so *SimpleOptimizer) Optimize() error

Optimize optimizes ast tree by simple constant folding and evaluating simple expressions.

func (*SimpleOptimizer) Total

func (so *SimpleOptimizer) Total() int

Total returns total number of evaluated constants and expressions.

type SourceModule

type SourceModule struct {
	Src []byte
}

SourceModule is an importable module that's written in Tengo.

func (*SourceModule) Import

func (m *SourceModule) Import(_ string) (interface{}, error)

Import returns a module source code.

type StackTrace

type StackTrace []parser.SourceFilePos

StackTrace is the stack of source file positions.

func (StackTrace) Format

func (st StackTrace) Format(s fmt.State, verb rune)

Format formats the StackTrace to the fmt.Formatter interface.

type String

type String string

String represents string values and implements Object interface.

func ToString added in v0.2.0

func ToString(o Object) (v String, ok bool)

ToString will try to convert an Object to uGO string value.

func (String) BinaryOp

func (o String) BinaryOp(tok token.Token, right Object) (Object, error)

BinaryOp implements Object interface.

func (String) Call

func (o String) Call(_ ...Object) (Object, error)

Call implements Object interface.

func (String) CanCall

func (o String) CanCall() bool

CanCall implements Object interface.

func (String) CanIterate

func (String) CanIterate() bool

CanIterate implements Object interface.

func (String) Equal

func (o String) Equal(right Object) bool

Equal implements Object interface.

func (String) Format added in v0.4.0

func (o String) Format(s fmt.State, verb rune)

Format implements fmt.Formatter interface.

func (String) IndexGet

func (o String) IndexGet(index Object) (Object, error)

IndexGet represents string values and implements Object interface.

func (String) IndexSet

func (String) IndexSet(index, value Object) error

IndexSet implements Object interface.

func (String) IsFalsy

func (o String) IsFalsy() bool

IsFalsy implements Object interface.

func (String) Iterate

func (o String) Iterate() Iterator

Iterate implements Object interface.

func (String) Len added in v0.2.0

func (o String) Len() int

Len implements LengthGetter interface.

func (String) String

func (o String) String() string

func (String) TypeName

func (String) TypeName() string

TypeName implements Object interface.

type StringIterator

type StringIterator struct {
	V String
	// contains filtered or unexported fields
}

StringIterator represents an iterator for the string.

func (*StringIterator) Key

func (it *StringIterator) Key() Object

Key implements Iterator interface.

func (*StringIterator) Next

func (it *StringIterator) Next() bool

Next implements Iterator interface.

func (*StringIterator) Value

func (it *StringIterator) Value() Object

Value implements Iterator interface.

type Symbol

type Symbol struct {
	Name     string
	Index    int
	Scope    SymbolScope
	Assigned bool
	Constant bool
	Original *Symbol
}

Symbol represents a symbol in the symbol table.

func (*Symbol) String

func (s *Symbol) String() string

type SymbolScope

type SymbolScope string

SymbolScope represents a symbol scope.

const (
	ScopeGlobal  SymbolScope = "GLOBAL"
	ScopeLocal   SymbolScope = "LOCAL"
	ScopeBuiltin SymbolScope = "BUILTIN"
	ScopeFree    SymbolScope = "FREE"
)

List of symbol scopes

type SymbolTable

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

SymbolTable represents a symbol table.

func NewSymbolTable

func NewSymbolTable() *SymbolTable

NewSymbolTable creates new symbol table object.

func (*SymbolTable) DefineGlobal

func (st *SymbolTable) DefineGlobal(name string) (*Symbol, error)

DefineGlobal adds a new symbol with ScopeGlobal in the current scope.

func (*SymbolTable) DefineLocal

func (st *SymbolTable) DefineLocal(name string) (*Symbol, bool)

DefineLocal adds a new symbol with ScopeLocal in the current scope.

func (*SymbolTable) DisableBuiltin

func (st *SymbolTable) DisableBuiltin(names ...string) *SymbolTable

DisableBuiltin disables given builtin name(s). Compiler returns `Compile Error: unresolved reference "builtin name"` if a disabled builtin is used.

func (*SymbolTable) DisabledBuiltins

func (st *SymbolTable) DisabledBuiltins() []string

DisabledBuiltins returns disabled builtin names.

func (*SymbolTable) EnableParams

func (st *SymbolTable) EnableParams(v bool) *SymbolTable

EnableParams enables or disables definition of parameters.

func (*SymbolTable) Fork

func (st *SymbolTable) Fork(block bool) *SymbolTable

Fork creates a new symbol table for a new scope.

func (*SymbolTable) FreeSymbols

func (st *SymbolTable) FreeSymbols() []*Symbol

FreeSymbols returns registered free symbols for the scope.

func (*SymbolTable) InBlock

func (st *SymbolTable) InBlock() bool

InBlock returns true if symbol table belongs to a block.

func (*SymbolTable) MaxSymbols

func (st *SymbolTable) MaxSymbols() int

MaxSymbols returns the total number of symbols defined in the scope.

func (*SymbolTable) NextIndex

func (st *SymbolTable) NextIndex() int

NextIndex returns the next symbol index.

func (*SymbolTable) NumParams

func (st *SymbolTable) NumParams() int

NumParams returns number of parameters for the scope.

func (*SymbolTable) Parent

func (st *SymbolTable) Parent(skipBlock bool) *SymbolTable

Parent returns the outer scope of the current symbol table.

func (*SymbolTable) Resolve

func (st *SymbolTable) Resolve(name string) (symbol *Symbol, ok bool)

Resolve resolves a symbol with a given name.

func (*SymbolTable) SetParams

func (st *SymbolTable) SetParams(params ...string) error

SetParams sets parameters defined in the scope. This can be called only once.

func (*SymbolTable) ShadowedBuiltins

func (st *SymbolTable) ShadowedBuiltins() []string

ShadowedBuiltins returns all shadowed builtin names including parent symbol tables'. Returing slice may contain duplicate names.

func (*SymbolTable) Symbols

func (st *SymbolTable) Symbols() []*Symbol

Symbols returns registered symbols for the scope.

type SyncIterator

type SyncIterator struct {
	Iterator
	// contains filtered or unexported fields
}

SyncIterator represents an iterator for the SyncMap.

func (*SyncIterator) Key

func (it *SyncIterator) Key() Object

Key implements Iterator interface.

func (*SyncIterator) Next

func (it *SyncIterator) Next() bool

Next implements Iterator interface.

func (*SyncIterator) Value

func (it *SyncIterator) Value() Object

Value implements Iterator interface.

type SyncMap

type SyncMap struct {
	Value Map
	// contains filtered or unexported fields
}

SyncMap represents map of objects and implements Object interface.

func ToSyncMap added in v0.2.0

func ToSyncMap(o Object) (v *SyncMap, ok bool)

ToSyncMap will try to convert an Object to uGO syncMap value.

func (*SyncMap) BinaryOp added in v0.2.0

func (o *SyncMap) BinaryOp(tok token.Token, right Object) (Object, error)

BinaryOp implements Object interface.

func (*SyncMap) Call added in v0.2.0

func (*SyncMap) Call(...Object) (Object, error)

Call implements Object interface.

func (*SyncMap) CanCall added in v0.2.0

func (*SyncMap) CanCall() bool

CanCall implements Object interface.

func (*SyncMap) CanIterate

func (o *SyncMap) CanIterate() bool

CanIterate implements Object interface.

func (*SyncMap) Copy

func (o *SyncMap) Copy() Object

Copy implements Copier interface.

func (*SyncMap) Equal

func (o *SyncMap) Equal(right Object) bool

Equal implements Object interface.

func (*SyncMap) Get

func (o *SyncMap) Get(index string) (value Object, exists bool)

Get returns Object in map if exists.

func (*SyncMap) IndexDelete added in v0.2.0

func (o *SyncMap) IndexDelete(key Object) error

IndexDelete tries to delete the string value of key from the map.

func (*SyncMap) IndexGet

func (o *SyncMap) IndexGet(index Object) (Object, error)

IndexGet implements Object interface.

func (*SyncMap) IndexSet

func (o *SyncMap) IndexSet(index, value Object) error

IndexSet implements Object interface.

func (*SyncMap) IsFalsy

func (o *SyncMap) IsFalsy() bool

IsFalsy implements Object interface.

func (*SyncMap) Iterate

func (o *SyncMap) Iterate() Iterator

Iterate implements Iterable interface.

func (*SyncMap) Len added in v0.2.0

func (o *SyncMap) Len() int

Len returns the number of items in the map. Len implements LengthGetter interface.

func (*SyncMap) Lock added in v0.2.0

func (o *SyncMap) Lock()

Lock locks the underlying mutex for writing.

func (*SyncMap) RLock added in v0.2.0

func (o *SyncMap) RLock()

RLock locks the underlying mutex for reading.

func (*SyncMap) RUnlock added in v0.2.0

func (o *SyncMap) RUnlock()

RUnlock unlocks the underlying mutex for reading.

func (*SyncMap) String

func (o *SyncMap) String() string

String implements Object interface.

func (*SyncMap) TypeName

func (*SyncMap) TypeName() string

TypeName implements Object interface.

func (*SyncMap) Unlock added in v0.2.0

func (o *SyncMap) Unlock()

Unlock unlocks the underlying mutex for writing.

type Uint

type Uint uint64

Uint represents unsigned integer values and implements Object interface.

func ToUint added in v0.2.0

func ToUint(o Object) (v Uint, ok bool)

ToUint will try to convert an Object to uGO uint value.

func (Uint) BinaryOp

func (o Uint) BinaryOp(tok token.Token, right Object) (Object, error)

BinaryOp implements Object interface.

func (Uint) Call

func (o Uint) Call(_ ...Object) (Object, error)

Call implements Object interface.

func (Uint) CanCall

func (o Uint) CanCall() bool

CanCall implements Object interface.

func (Uint) CanIterate

func (Uint) CanIterate() bool

CanIterate implements Object interface.

func (Uint) Equal

func (o Uint) Equal(right Object) bool

Equal implements Object interface.

func (Uint) Format added in v0.4.0

func (o Uint) Format(s fmt.State, verb rune)

Format implements fmt.Formatter interface.

func (Uint) IndexGet

func (Uint) IndexGet(index Object) (Object, error)

IndexGet implements Object interface.

func (Uint) IndexSet

func (Uint) IndexSet(index, value Object) error

IndexSet implements Object interface.

func (Uint) IsFalsy

func (o Uint) IsFalsy() bool

IsFalsy implements Object interface.

func (Uint) Iterate

func (Uint) Iterate() Iterator

Iterate implements Object interface.

func (Uint) String

func (o Uint) String() string

String implements Object interface.

func (Uint) TypeName

func (Uint) TypeName() string

TypeName implements Object interface.

type UndefinedType added in v0.2.0

type UndefinedType struct {
	ObjectImpl
}

UndefinedType represents the type of global Undefined Object. One should use the UndefinedType in type switches only.

func (*UndefinedType) BinaryOp added in v0.2.0

func (o *UndefinedType) BinaryOp(tok token.Token, right Object) (Object, error)

BinaryOp implements Object interface.

func (*UndefinedType) Call added in v0.2.0

func (*UndefinedType) Call(_ ...Object) (Object, error)

Call implements Object interface.

func (*UndefinedType) Equal added in v0.2.0

func (o *UndefinedType) Equal(right Object) bool

Equal implements Object interface.

func (*UndefinedType) IndexGet added in v0.2.0

func (*UndefinedType) IndexGet(key Object) (Object, error)

IndexGet implements Object interface.

func (*UndefinedType) IndexSet added in v0.2.0

func (*UndefinedType) IndexSet(key, value Object) error

IndexSet implements Object interface.

func (*UndefinedType) String added in v0.2.0

func (o *UndefinedType) String() string

String implements Object interface.

func (*UndefinedType) TypeName added in v0.2.0

func (o *UndefinedType) TypeName() string

TypeName implements Object interface.

type VM

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

VM executes the instructions in Bytecode.

func NewVM

func NewVM(bc *Bytecode) *VM

NewVM creates a VM object.

func (*VM) Abort

func (vm *VM) Abort()

Abort aborts the VM execution. It is safe to call this method from another goroutine.

func (*VM) Aborted added in v0.4.0

func (vm *VM) Aborted() bool

Aborted reports whether VM is aborted. It is safe to call this method from another goroutine.

func (*VM) Clear

func (vm *VM) Clear() *VM

Clear clears stack by setting nil to stack indexes and removes modules cache.

func (*VM) GetGlobals added in v0.4.0

func (vm *VM) GetGlobals() Object

GetGlobals returns global variables.

func (*VM) GetLocals

func (vm *VM) GetLocals(locals []Object) []Object

GetLocals returns variables from stack up to the NumLocals of given Bytecode. This must be called after Run() before Clear().

func (*VM) Run

func (vm *VM) Run(globals Object, args ...Object) (Object, error)

Run runs VM and executes the instructions until the OpReturn Opcode or Abort call.

func (*VM) RunCompiledFunction

func (vm *VM) RunCompiledFunction(
	f *CompiledFunction,
	globals Object,
	args ...Object,
) (Object, error)

RunCompiledFunction runs given CompiledFunction as if it is Main function. Bytecode must be set before calling this method, because Fileset and Constants are copied.

func (*VM) SetBytecode

func (vm *VM) SetBytecode(bc *Bytecode) *VM

SetBytecode enables to set a new Bytecode.

func (*VM) SetRecover

func (vm *VM) SetRecover(v bool) *VM

SetRecover recovers panic when Run panics and returns panic as an error. If error handler is present `try-catch-finally`, VM continues to run from catch/finally.

Directories

Path Synopsis
cmd
ugo
internal
fmt
strings
Package strings provides strings module implementing simple functions to manipulate UTF-8 encoded strings for uGO script language.
Package strings provides strings module implementing simple functions to manipulate UTF-8 encoded strings for uGO script language.
time
Package time provides time module for measuring and displaying time for uGO script language.
Package time provides time module for measuring and displaying time for uGO script language.

Jump to

Keyboard shortcuts

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