tengo

package module
Version: v2.6.4 Latest Latest
Warning

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

Go to latest
Published: Mar 6, 2021 License: MIT Imports: 18 Imported by: 0

README

The Tengo Language

GoDoc test Go Report Card

Tengo is a small, dynamic, fast, secure script language for Go.

Tengo is fast and secure because it's compiled/executed as bytecode on stack-based VM that's written in native Go.

/* The Tengo Language */
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"

Test this Tengo code in the Tengo Playground

Features

Benchmark

fib(35) fibt(35) Language (Type)
Tengo 2,931ms 4ms Tengo (VM)
go-lua 4,824ms 4ms Lua (VM)
GopherLua 5,365ms 4ms Lua (VM)
goja 5,533ms 5ms JavaScript (VM)
starlark-go 11,495ms 5ms Starlark (Interpreter)
Yaegi 15,645ms 12ms Yaegi (Interpreter)
gpython 16,322ms 5ms Python (Interpreter)
otto 73,093ms 10ms JavaScript (Interpreter)
Anko 79,809ms 8ms Anko (Interpreter)
- - - -
Go 53ms 3ms Go (Native)
Lua 1,612ms 3ms Lua (Native)
Python 2,632ms 23ms Python 2 (Native)

_* fib(35): Fibonacci(35)_
_* fibt(35): tail-call version of Fibonacci(35)_
_* **Go** does not read the source code from file, while all other cases do_
_* See here for commands/codes used_

Quick Start

go get github.com/d5/tengo/v2

A simple Go example code that compiles/runs Tengo script code with some input/output values:

package main

import (
	"context"
	"fmt"

	"github.com/d5/tengo/v2"
)

func main() {
	// Tengo 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 := tengo.NewScript([]byte(src))

	// set values
	_ = script.Add("a", 1)
	_ = script.Add("b", 9)
	_ = script.Add("c", 8)
	_ = script.Add("d", 4)

	// run the script
	compiled, err := script.RunContext(context.Background())
	if err != nil {
		panic(err)
	}

	// retrieve values
	sum := compiled.Get("sum")
	mul := compiled.Get("mul")
	fmt.Println(sum, mul) // "22 288"
}

References

♥️ Like writing Go code? Come work at Skool. We're hiring!

Documentation

Overview

Example
// Tengo 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 := tengo.NewScript([]byte(src))

// set values
_ = script.Add("a", 1)
_ = script.Add("b", 9)
_ = script.Add("c", 8)
_ = script.Add("d", 4)

// run the script
compiled, err := script.RunContext(context.Background())
if err != nil {
	panic(err)
}

// retrieve values
sum := compiled.Get("sum")
mul := compiled.Get("mul")
fmt.Println(sum, mul)
Output:

22 288

Index

Examples

Constants

View Source
const (
	// GlobalsSize is the maximum number of global variables for a VM.
	GlobalsSize = 1024

	// StackSize is the maximum stack size for a VM.
	StackSize = 2048

	// MaxFrames is the maximum number of function frames for a VM.
	MaxFrames = 1024
)

Variables

View Source
var (
	// ErrStackOverflow is a stack overflow error.
	ErrStackOverflow = errors.New("stack overflow")

	// ErrObjectAllocLimit is an objects allocation limit error.
	ErrObjectAllocLimit = errors.New("object allocation limit exceeded")

	// ErrIndexOutOfBounds is an error where a given index is out of the
	// bounds.
	ErrIndexOutOfBounds = errors.New("index out of bounds")

	// ErrInvalidIndexType represents an invalid index type.
	ErrInvalidIndexType = errors.New("invalid index type")

	// ErrInvalidIndexValueType represents an invalid index value type.
	ErrInvalidIndexValueType = errors.New("invalid index value type")

	// ErrInvalidIndexOnError represents an invalid index on error.
	ErrInvalidIndexOnError = errors.New("invalid index on error")

	// ErrInvalidOperator represents an error for invalid operator usage.
	ErrInvalidOperator = errors.New("invalid operator")

	// ErrWrongNumArguments represents a wrong number of arguments error.
	ErrWrongNumArguments = errors.New("wrong number of arguments")

	// ErrBytesLimit represents an error where the size of bytes value exceeds
	// the limit.
	ErrBytesLimit = errors.New("exceeding bytes size limit")

	// ErrStringLimit represents an error where the size of string value
	// exceeds the limit.
	ErrStringLimit = errors.New("exceeding string size limit")

	// ErrNotIndexable is an error where an Object is not indexable.
	ErrNotIndexable = errors.New("not indexable")

	// ErrNotIndexAssignable is an error where an Object is not index
	// assignable.
	ErrNotIndexAssignable = errors.New("not index-assignable")

	// ErrNotImplemented is an error where an Object has not implemented a
	// required method.
	ErrNotImplemented = errors.New("not implemented")
)
View Source
var (
	// MaxStringLen is the maximum byte-length for string value. Note this
	// limit applies to all compiler/VM instances in the process.
	MaxStringLen = 2147483647

	// MaxBytesLen is the maximum length for bytes value. Note this limit
	// applies to all compiler/VM instances in the process.
	MaxBytesLen = 2147483647
)

Functions

func CountObjects

func CountObjects(o Object) (c int)

CountObjects returns the number of objects that a given object o contains. For scalar value types, it will always be 1. For compound value types, this will include its elements and all of their elements recursively.

func Format

func Format(format string, a ...Object) (string, error)

Format is like fmt.Sprintf but using Objects.

func FormatInstructions

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

FormatInstructions returns string representation of bytecode instructions.

func MakeInstruction

func MakeInstruction(opcode parser.Opcode, operands ...int) []byte

MakeInstruction returns a bytecode for an opcode and the operands.

func ToBool

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

ToBool will try to convert object o to bool value.

func ToByteSlice

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

ToByteSlice will try to convert object o to []byte value.

func ToFloat64

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

ToFloat64 will try to convert object o to float64 value.

func ToInt

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

ToInt will try to convert object o to int value.

func ToInt64

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

ToInt64 will try to convert object o to int64 value.

func ToInterface

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

ToInterface attempts to convert an object o to an interface{} value

func ToRune

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

ToRune will try to convert object o to rune value.

func ToString

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

ToString will try to convert object o to string value.

func ToTime

func ToTime(o Object) (v time.Time, ok bool)

ToTime will try to convert object o to time.Time value.

Types

type Array

type Array struct {
	ObjectImpl
	Value []Object
}

Array represents an array of objects.

func (*Array) BinaryOp

func (o *Array) BinaryOp(op token.Token, rhs Object) (Object, error)

BinaryOp returns another object that is the result of a given binary operator and a right-hand side object.

func (*Array) CanIterate

func (o *Array) CanIterate() bool

CanIterate returns whether the Object can be Iterated.

func (*Array) Copy

func (o *Array) Copy() Object

Copy returns a copy of the type.

func (*Array) Equals

func (o *Array) Equals(x Object) bool

Equals returns true if the value of the type is equal to the value of another object.

func (*Array) IndexGet

func (o *Array) IndexGet(index Object) (res Object, err error)

IndexGet returns an element at a given index.

func (*Array) IndexSet

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

IndexSet sets an element at a given index.

func (*Array) IsFalsy

func (o *Array) IsFalsy() bool

IsFalsy returns true if the value of the type is falsy.

func (*Array) Iterate

func (o *Array) Iterate() Iterator

Iterate creates an array iterator.

func (*Array) String

func (o *Array) String() string

func (*Array) TypeName

func (o *Array) TypeName() string

TypeName returns the name of the type.

type ArrayIterator

type ArrayIterator struct {
	ObjectImpl
	// contains filtered or unexported fields
}

ArrayIterator is an iterator for an array.

func (*ArrayIterator) Copy

func (i *ArrayIterator) Copy() Object

Copy returns a copy of the type.

func (*ArrayIterator) Equals

func (i *ArrayIterator) Equals(Object) bool

Equals returns true if the value of the type is equal to the value of another object.

func (*ArrayIterator) IsFalsy

func (i *ArrayIterator) IsFalsy() bool

IsFalsy returns true if the value of the type is falsy.

func (*ArrayIterator) Key

func (i *ArrayIterator) Key() Object

Key returns the key or index value of the current element.

func (*ArrayIterator) Next

func (i *ArrayIterator) Next() bool

Next returns true if there are more elements to iterate.

func (*ArrayIterator) String

func (i *ArrayIterator) String() string

func (*ArrayIterator) TypeName

func (i *ArrayIterator) TypeName() string

TypeName returns the name of the type.

func (*ArrayIterator) Value

func (i *ArrayIterator) Value() Object

Value returns the value of the current element.

type Bool

type Bool struct {
	ObjectImpl
	// contains filtered or unexported fields
}

Bool represents a boolean value.

func (*Bool) Copy

func (o *Bool) Copy() Object

Copy returns a copy of the type.

func (*Bool) Equals

func (o *Bool) Equals(x Object) bool

Equals returns true if the value of the type is equal to the value of another object.

func (*Bool) GobDecode

func (o *Bool) GobDecode(b []byte) (err error)

GobDecode decodes bool value from input bytes.

func (*Bool) GobEncode

func (o *Bool) GobEncode() (b []byte, err error)

GobEncode encodes bool values into bytes.

func (*Bool) IsFalsy

func (o *Bool) IsFalsy() bool

IsFalsy returns true if the value of the type is falsy.

func (*Bool) String

func (o *Bool) String() string

func (*Bool) TypeName

func (o *Bool) TypeName() string

TypeName returns the name of the type.

type BuiltinFunction

type BuiltinFunction struct {
	ObjectImpl
	Name  string
	Value CallableFunc
}

BuiltinFunction represents a builtin function.

func GetAllBuiltinFunctions

func GetAllBuiltinFunctions() []*BuiltinFunction

GetAllBuiltinFunctions returns all builtin function objects.

func (*BuiltinFunction) Call

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

Call executes a builtin function.

func (*BuiltinFunction) CanCall

func (o *BuiltinFunction) CanCall() bool

CanCall returns whether the Object can be Called.

func (*BuiltinFunction) Copy

func (o *BuiltinFunction) Copy() Object

Copy returns a copy of the type.

func (*BuiltinFunction) Equals

func (o *BuiltinFunction) Equals(_ Object) bool

Equals returns true if the value of the type is equal to the value of another object.

func (*BuiltinFunction) String

func (o *BuiltinFunction) String() string

func (*BuiltinFunction) TypeName

func (o *BuiltinFunction) TypeName() string

TypeName returns the name of the type.

type BuiltinModule

type BuiltinModule struct {
	Attrs map[string]Object
}

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

func (*BuiltinModule) AsImmutableMap

func (m *BuiltinModule) AsImmutableMap(moduleName string) *ImmutableMap

AsImmutableMap converts builtin module into an immutable map.

func (*BuiltinModule) Import

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

Import returns an immutable map for the module.

type Bytecode

type Bytecode struct {
	FileSet      *parser.SourceFileSet
	MainFunction *CompiledFunction
	Constants    []Object
}

Bytecode is a compiled instructions and constants.

func (*Bytecode) CountObjects

func (b *Bytecode) CountObjects() int

CountObjects returns the number of objects found in Constants.

func (*Bytecode) Decode

func (b *Bytecode) Decode(r io.Reader, modules *ModuleMap) error

Decode reads Bytecode data from the reader.

func (*Bytecode) Encode

func (b *Bytecode) Encode(w io.Writer) error

Encode writes Bytecode data to the writer.

func (*Bytecode) FormatConstants

func (b *Bytecode) FormatConstants() (output []string)

FormatConstants returns human readable string representations of compiled constants.

func (*Bytecode) FormatInstructions

func (b *Bytecode) FormatInstructions() []string

FormatInstructions returns human readable string representations of compiled instructions.

func (*Bytecode) RemoveDuplicates

func (b *Bytecode) RemoveDuplicates()

RemoveDuplicates finds and remove the duplicate values in Constants. Note this function mutates Bytecode.

type Bytes

type Bytes struct {
	ObjectImpl
	Value []byte
}

Bytes represents a byte array.

func (*Bytes) BinaryOp

func (o *Bytes) BinaryOp(op token.Token, rhs Object) (Object, error)

BinaryOp returns another object that is the result of a given binary operator and a right-hand side object.

func (*Bytes) CanIterate

func (o *Bytes) CanIterate() bool

CanIterate returns whether the Object can be Iterated.

func (*Bytes) Copy

func (o *Bytes) Copy() Object

Copy returns a copy of the type.

func (*Bytes) Equals

func (o *Bytes) Equals(x Object) bool

Equals returns true if the value of the type is equal to the value of another object.

func (*Bytes) IndexGet

func (o *Bytes) IndexGet(index Object) (res Object, err error)

IndexGet returns an element (as Int) at a given index.

func (*Bytes) IsFalsy

func (o *Bytes) IsFalsy() bool

IsFalsy returns true if the value of the type is falsy.

func (*Bytes) Iterate

func (o *Bytes) Iterate() Iterator

Iterate creates a bytes iterator.

func (*Bytes) String

func (o *Bytes) String() string

func (*Bytes) TypeName

func (o *Bytes) TypeName() string

TypeName returns the name of the type.

type BytesIterator

type BytesIterator struct {
	ObjectImpl
	// contains filtered or unexported fields
}

BytesIterator represents an iterator for a string.

func (*BytesIterator) Copy

func (i *BytesIterator) Copy() Object

Copy returns a copy of the type.

func (*BytesIterator) Equals

func (i *BytesIterator) Equals(Object) bool

Equals returns true if the value of the type is equal to the value of another object.

func (*BytesIterator) Key

func (i *BytesIterator) Key() Object

Key returns the key or index value of the current element.

func (*BytesIterator) Next

func (i *BytesIterator) Next() bool

Next returns true if there are more elements to iterate.

func (*BytesIterator) String

func (i *BytesIterator) String() string

func (*BytesIterator) TypeName

func (i *BytesIterator) TypeName() string

TypeName returns the name of the type.

func (*BytesIterator) Value

func (i *BytesIterator) Value() Object

Value returns the value of the current element.

type CallableFunc

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

CallableFunc is a function signature for the callable functions.

type Char

type Char struct {
	ObjectImpl
	Value rune
}

Char represents a character value.

func (*Char) BinaryOp

func (o *Char) BinaryOp(op token.Token, rhs Object) (Object, error)

BinaryOp returns another object that is the result of a given binary operator and a right-hand side object.

func (*Char) Copy

func (o *Char) Copy() Object

Copy returns a copy of the type.

func (*Char) Equals

func (o *Char) Equals(x Object) bool

Equals returns true if the value of the type is equal to the value of another object.

func (*Char) IsFalsy

func (o *Char) IsFalsy() bool

IsFalsy returns true if the value of the type is falsy.

func (*Char) String

func (o *Char) String() string

func (*Char) TypeName

func (o *Char) TypeName() string

TypeName returns the name of the type.

type Compiled

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

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

func (*Compiled) Clone

func (c *Compiled) Clone() *Compiled

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

func (*Compiled) Get

func (c *Compiled) Get(name string) *Variable

Get returns a variable identified by the name.

func (*Compiled) GetAll

func (c *Compiled) GetAll() []*Variable

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

func (*Compiled) IsDefined

func (c *Compiled) IsDefined(name string) bool

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

func (*Compiled) Run

func (c *Compiled) Run() error

Run executes the compiled script in the virtual machine.

func (*Compiled) RunContext

func (c *Compiled) RunContext(ctx context.Context) (err error)

RunContext is like Run but includes a context.

func (*Compiled) Set

func (c *Compiled) 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.

type CompiledFunction

type CompiledFunction struct {
	ObjectImpl
	Instructions  []byte
	NumLocals     int // number of local variables (including function parameters)
	NumParameters int
	VarArgs       bool
	SourceMap     map[int]parser.Pos
	Free          []*ObjectPtr
	UsesReceiver  bool
}

CompiledFunction represents a compiled function.

func (*CompiledFunction) CanCall

func (o *CompiledFunction) CanCall() bool

CanCall returns whether the Object can be Called.

func (*CompiledFunction) Copy

func (o *CompiledFunction) Copy() Object

Copy returns a copy of the type.

func (*CompiledFunction) Equals

func (o *CompiledFunction) Equals(_ Object) bool

Equals returns true if the value of the type is equal to the value of another object.

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 (o *CompiledFunction) TypeName() string

TypeName returns the name of the type.

type Compiler

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

Compiler compiles the AST into a bytecode.

func NewCompiler

func NewCompiler(
	file *parser.SourceFile,
	symbolTable *SymbolTable,
	constants []Object,
	modules *ModuleMap,
	trace io.Writer,
) *Compiler

NewCompiler creates a Compiler.

func (*Compiler) Bytecode

func (c *Compiler) Bytecode() *Bytecode

Bytecode returns a compiled bytecode.

func (*Compiler) Compile

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

Compile compiles the AST node.

func (*Compiler) EnableFileImport

func (c *Compiler) EnableFileImport(enable bool)

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

func (*Compiler) SetImportDir

func (c *Compiler) SetImportDir(dir string)

SetImportDir sets the initial import directory path for file imports.

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

type ErrInvalidArgumentType

type ErrInvalidArgumentType struct {
	Name     string
	Expected string
	Found    string
}

ErrInvalidArgumentType represents an invalid argument value type error.

func (ErrInvalidArgumentType) Error

func (e ErrInvalidArgumentType) Error() string

type Error

type Error struct {
	ObjectImpl
	Value Object
}

Error represents an error value.

func (*Error) Copy

func (o *Error) Copy() Object

Copy returns a copy of the type.

func (*Error) Equals

func (o *Error) Equals(x Object) bool

Equals returns true if the value of the type is equal to the value of another object.

func (*Error) IndexGet

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

IndexGet returns an element at a given index.

func (*Error) IsFalsy

func (o *Error) IsFalsy() bool

IsFalsy returns true if the value of the type is falsy.

func (*Error) String

func (o *Error) String() string

func (*Error) TypeName

func (o *Error) TypeName() string

TypeName returns the name of the type.

type Float

type Float struct {
	ObjectImpl
	Value float64
}

Float represents a floating point number value.

func (*Float) BinaryOp

func (o *Float) BinaryOp(op token.Token, rhs Object) (Object, error)

BinaryOp returns another object that is the result of a given binary operator and a right-hand side object.

func (*Float) Copy

func (o *Float) Copy() Object

Copy returns a copy of the type.

func (*Float) Equals

func (o *Float) Equals(x Object) bool

Equals returns true if the value of the type is equal to the value of another object.

func (*Float) IsFalsy

func (o *Float) IsFalsy() bool

IsFalsy returns true if the value of the type is falsy.

func (*Float) String

func (o *Float) String() string

func (*Float) TypeName

func (o *Float) TypeName() string

TypeName returns the name of the type.

type ImmutableArray

type ImmutableArray struct {
	ObjectImpl
	Value []Object
}

ImmutableArray represents an immutable array of objects.

func (*ImmutableArray) BinaryOp

func (o *ImmutableArray) BinaryOp(op token.Token, rhs Object) (Object, error)

BinaryOp returns another object that is the result of a given binary operator and a right-hand side object.

func (*ImmutableArray) CanIterate

func (o *ImmutableArray) CanIterate() bool

CanIterate returns whether the Object can be Iterated.

func (*ImmutableArray) Copy

func (o *ImmutableArray) Copy() Object

Copy returns a copy of the type.

func (*ImmutableArray) Equals

func (o *ImmutableArray) Equals(x Object) bool

Equals returns true if the value of the type is equal to the value of another object.

func (*ImmutableArray) IndexGet

func (o *ImmutableArray) IndexGet(index Object) (res Object, err error)

IndexGet returns an element at a given index.

func (*ImmutableArray) IsFalsy

func (o *ImmutableArray) IsFalsy() bool

IsFalsy returns true if the value of the type is falsy.

func (*ImmutableArray) Iterate

func (o *ImmutableArray) Iterate() Iterator

Iterate creates an array iterator.

func (*ImmutableArray) String

func (o *ImmutableArray) String() string

func (*ImmutableArray) TypeName

func (o *ImmutableArray) TypeName() string

TypeName returns the name of the type.

type ImmutableMap

type ImmutableMap struct {
	ObjectImpl
	Value map[string]Object
}

ImmutableMap represents an immutable map object.

func (*ImmutableMap) CanIterate

func (o *ImmutableMap) CanIterate() bool

CanIterate returns whether the Object can be Iterated.

func (*ImmutableMap) Copy

func (o *ImmutableMap) Copy() Object

Copy returns a copy of the type.

func (*ImmutableMap) Equals

func (o *ImmutableMap) Equals(x Object) bool

Equals returns true if the value of the type is equal to the value of another object.

func (*ImmutableMap) IndexGet

func (o *ImmutableMap) IndexGet(index Object) (res Object, err error)

IndexGet returns the value for the given key.

func (*ImmutableMap) IsFalsy

func (o *ImmutableMap) IsFalsy() bool

IsFalsy returns true if the value of the type is falsy.

func (*ImmutableMap) Iterate

func (o *ImmutableMap) Iterate() Iterator

Iterate creates an immutable map iterator.

func (*ImmutableMap) String

func (o *ImmutableMap) String() string

func (*ImmutableMap) TypeName

func (o *ImmutableMap) TypeName() string

TypeName returns the name of the type.

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 Int

type Int struct {
	ObjectImpl
	Value int64
}

Int represents an integer value.

func (*Int) BinaryOp

func (o *Int) BinaryOp(op token.Token, rhs Object) (Object, error)

BinaryOp returns another object that is the result of a given binary operator and a right-hand side object.

func (*Int) Copy

func (o *Int) Copy() Object

Copy returns a copy of the type.

func (*Int) Equals

func (o *Int) Equals(x Object) bool

Equals returns true if the value of the type is equal to the value of another object.

func (*Int) IsFalsy

func (o *Int) IsFalsy() bool

IsFalsy returns true if the value of the type is falsy.

func (*Int) String

func (o *Int) String() string

func (*Int) TypeName

func (o *Int) TypeName() string

TypeName returns the name of the type.

type Iterator

type Iterator interface {
	Object

	// 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 represents an iterator for underlying data type.

type Map

type Map struct {
	ObjectImpl
	Value map[string]Object
}

Map represents a map of objects.

func (*Map) CanIterate

func (o *Map) CanIterate() bool

CanIterate returns whether the Object can be Iterated.

func (*Map) Copy

func (o *Map) Copy() Object

Copy returns a copy of the type.

func (*Map) Equals

func (o *Map) Equals(x Object) bool

Equals returns true if the value of the type is equal to the value of another object.

func (*Map) IndexGet

func (o *Map) IndexGet(index Object) (res Object, err error)

IndexGet returns the value for the given key.

func (*Map) IndexSet

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

IndexSet sets the value for the given key.

func (*Map) IsFalsy

func (o *Map) IsFalsy() bool

IsFalsy returns true if the value of the type is falsy.

func (*Map) Iterate

func (o *Map) Iterate() Iterator

Iterate creates a map iterator.

func (*Map) String

func (o *Map) String() string

func (*Map) TypeName

func (o *Map) TypeName() string

TypeName returns the name of the type.

type MapIterator

type MapIterator struct {
	ObjectImpl
	// contains filtered or unexported fields
}

MapIterator represents an iterator for the map.

func (*MapIterator) Copy

func (i *MapIterator) Copy() Object

Copy returns a copy of the type.

func (*MapIterator) Equals

func (i *MapIterator) Equals(Object) bool

Equals returns true if the value of the type is equal to the value of another object.

func (*MapIterator) IsFalsy

func (i *MapIterator) IsFalsy() bool

IsFalsy returns true if the value of the type is falsy.

func (*MapIterator) Key

func (i *MapIterator) Key() Object

Key returns the key or index value of the current element.

func (*MapIterator) Next

func (i *MapIterator) Next() bool

Next returns true if there are more elements to iterate.

func (*MapIterator) String

func (i *MapIterator) String() string

func (*MapIterator) TypeName

func (i *MapIterator) TypeName() string

TypeName returns the name of the type.

func (*MapIterator) Value

func (i *MapIterator) Value() Object

Value returns the value of the current element.

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)

Add adds an import module.

func (*ModuleMap) AddBuiltinModule

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

AddBuiltinModule adds a builtin module.

func (*ModuleMap) AddMap

func (m *ModuleMap) AddMap(o *ModuleMap)

AddMap adds named modules from another module map.

func (*ModuleMap) AddSourceModule

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

AddSourceModule adds a source module.

func (*ModuleMap) Copy

func (m *ModuleMap) Copy() *ModuleMap

Copy creates a copy of the module map.

func (*ModuleMap) Get

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

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

func (*ModuleMap) GetBuiltinModule

func (m *ModuleMap) GetBuiltinModule(name string) *BuiltinModule

GetBuiltinModule returns a builtin module identified by name. It returns if the name is not found or the module is not a builtin module.

func (*ModuleMap) GetSourceModule

func (m *ModuleMap) GetSourceModule(name string) *SourceModule

GetSourceModule returns a source module identified by name. It returns if the name is not found or the module is not a source module.

func (*ModuleMap) Len

func (m *ModuleMap) Len() int

Len returns the number of named modules.

func (*ModuleMap) Remove

func (m *ModuleMap) Remove(name string)

Remove removes a named module.

type Object

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

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

	// BinaryOp should return another object that is the result of a given
	// binary operator and a right-hand side object. If BinaryOp returns an
	// error, the VM will treat it as a run-time error.
	BinaryOp(op token.Token, rhs Object) (Object, error)

	// IsFalsy should return true if the value of the type should be considered
	// as falsy.
	IsFalsy() bool

	// Equals should return true if the value of the type should be considered
	// as equal to the value of another object.
	Equals(another Object) bool

	// Copy should return a copy of the type (and its value). Copy function
	// will be used for copy() builtin function which is expected to deep-copy
	// the values generally.
	Copy() Object

	// 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. If error is returned, the runtime will treat
	// it as a run-time error and ignore returned value. If Object is not
	// indexable, ErrNotIndexable should be returned as error. If nil is
	// returned as value, it will be converted to UndefinedToken value by the
	// runtime.
	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. If an error is returned, it will be treated as a run-time error.
	IndexSet(index, value Object) error

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

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

	// Call should take an arbitrary number of arguments and returns a return
	// value and/or an error, which the VM will consider as a run-time error.
	Call(args ...Object) (ret Object, err error)

	// CanCall should return whether the Object can be Called.
	CanCall() bool
}

Object represents an object in the VM.

var (
	// TrueValue represents a true value.
	TrueValue Object = &Bool{value: true}

	// FalseValue represents a false value.
	FalseValue Object = &Bool{value: false}

	// UndefinedValue represents an undefined value.
	UndefinedValue Object = &Undefined{}
)

func FromInterface

func FromInterface(v interface{}) (Object, error)

FromInterface will attempt to convert an interface{} v to a Tengo Object

type ObjectImpl

type ObjectImpl struct {
}

ObjectImpl represents a default Object Implementation. To defined a new value type, one can embed ObjectImpl in their type declarations to avoid implementing all non-significant methods. TypeName() and String() methods still need to be implemented.

func (*ObjectImpl) BinaryOp

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

BinaryOp returns another object that is the result of a given binary operator and a right-hand side object.

func (*ObjectImpl) Call

func (o *ObjectImpl) Call(_ ...Object) (ret Object, err error)

Call takes an arbitrary number of arguments and returns a return value and/or an error.

func (*ObjectImpl) CanCall

func (o *ObjectImpl) CanCall() bool

CanCall returns whether the Object can be Called.

func (*ObjectImpl) CanIterate

func (o *ObjectImpl) CanIterate() bool

CanIterate returns whether the Object can be Iterated.

func (*ObjectImpl) Copy

func (o *ObjectImpl) Copy() Object

Copy returns a copy of the type.

func (*ObjectImpl) Equals

func (o *ObjectImpl) Equals(x Object) bool

Equals returns true if the value of the type is equal to the value of another object.

func (*ObjectImpl) IndexGet

func (o *ObjectImpl) IndexGet(_ Object) (res Object, err error)

IndexGet returns an element at a given index.

func (*ObjectImpl) IndexSet

func (o *ObjectImpl) IndexSet(_, _ Object) (err error)

IndexSet sets an element at a given index.

func (*ObjectImpl) IsFalsy

func (o *ObjectImpl) IsFalsy() bool

IsFalsy returns true if the value of the type is falsy.

func (*ObjectImpl) Iterate

func (o *ObjectImpl) Iterate() Iterator

Iterate returns an iterator.

func (*ObjectImpl) String

func (o *ObjectImpl) String() string

func (*ObjectImpl) TypeName

func (o *ObjectImpl) TypeName() string

TypeName returns the name of the type.

type ObjectPtr

type ObjectPtr struct {
	ObjectImpl
	Value *Object
}

ObjectPtr represents a free variable.

func (*ObjectPtr) Copy

func (o *ObjectPtr) Copy() Object

Copy returns a copy of the type.

func (*ObjectPtr) Equals

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

Equals returns true if the value of the type is equal to the value of another object.

func (*ObjectPtr) IsFalsy

func (o *ObjectPtr) IsFalsy() bool

IsFalsy returns true if the value of the type is falsy.

func (*ObjectPtr) String

func (o *ObjectPtr) String() string

func (*ObjectPtr) TypeName

func (o *ObjectPtr) TypeName() string

TypeName returns the name of the type.

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() (*Compiled, error)

Compile compiles the script with all the defined variables, and, returns Compiled 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() (compiled *Compiled, 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,
) (compiled *Compiled, 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 *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.

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 String

type String struct {
	ObjectImpl
	Value string
	// contains filtered or unexported fields
}

String represents a string value.

func (*String) BinaryOp

func (o *String) BinaryOp(op token.Token, rhs Object) (Object, error)

BinaryOp returns another object that is the result of a given binary operator and a right-hand side object.

func (*String) CanIterate

func (o *String) CanIterate() bool

CanIterate returns whether the Object can be Iterated.

func (*String) Copy

func (o *String) Copy() Object

Copy returns a copy of the type.

func (*String) Equals

func (o *String) Equals(x Object) bool

Equals returns true if the value of the type is equal to the value of another object.

func (*String) IndexGet

func (o *String) IndexGet(index Object) (res Object, err error)

IndexGet returns a character at a given index.

func (*String) IsFalsy

func (o *String) IsFalsy() bool

IsFalsy returns true if the value of the type is falsy.

func (*String) Iterate

func (o *String) Iterate() Iterator

Iterate creates a string iterator.

func (*String) String

func (o *String) String() string

func (*String) TypeName

func (o *String) TypeName() string

TypeName returns the name of the type.

type StringIterator

type StringIterator struct {
	ObjectImpl
	// contains filtered or unexported fields
}

StringIterator represents an iterator for a string.

func (*StringIterator) Copy

func (i *StringIterator) Copy() Object

Copy returns a copy of the type.

func (*StringIterator) Equals

func (i *StringIterator) Equals(Object) bool

Equals returns true if the value of the type is equal to the value of another object.

func (*StringIterator) IsFalsy

func (i *StringIterator) IsFalsy() bool

IsFalsy returns true if the value of the type is falsy.

func (*StringIterator) Key

func (i *StringIterator) Key() Object

Key returns the key or index value of the current element.

func (*StringIterator) Next

func (i *StringIterator) Next() bool

Next returns true if there are more elements to iterate.

func (*StringIterator) String

func (i *StringIterator) String() string

func (*StringIterator) TypeName

func (i *StringIterator) TypeName() string

TypeName returns the name of the type.

func (*StringIterator) Value

func (i *StringIterator) Value() Object

Value returns the value of the current element.

type Symbol

type Symbol struct {
	Name          string
	Scope         SymbolScope
	Index         int
	LocalAssigned bool // if the local symbol is assigned at least once
}

Symbol represents a symbol in the symbol table.

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 a SymbolTable.

func (*SymbolTable) BuiltinSymbols

func (t *SymbolTable) BuiltinSymbols() []*Symbol

BuiltinSymbols returns builtin symbols for the scope.

func (*SymbolTable) Define

func (t *SymbolTable) Define(name string) *Symbol

Define adds a new symbol in the current scope.

func (*SymbolTable) DefineBuiltin

func (t *SymbolTable) DefineBuiltin(index int, name string) *Symbol

DefineBuiltin adds a symbol for builtin function.

func (*SymbolTable) Fork

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

Fork creates a new symbol table for a new scope.

func (*SymbolTable) FreeSymbols

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

FreeSymbols returns free symbols for the scope.

func (*SymbolTable) MaxSymbols

func (t *SymbolTable) MaxSymbols() int

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

func (*SymbolTable) Names

func (t *SymbolTable) Names() []string

Names returns the name of all the symbols.

func (*SymbolTable) Parent

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

Parent returns the outer scope of the current symbol table.

func (*SymbolTable) Resolve

func (t *SymbolTable) Resolve(
	name string,
	recur bool,
) (*Symbol, int, bool)

Resolve resolves a symbol with a given name.

type Time

type Time struct {
	ObjectImpl
	Value time.Time
}

Time represents a time value.

func (*Time) BinaryOp

func (o *Time) BinaryOp(op token.Token, rhs Object) (Object, error)

BinaryOp returns another object that is the result of a given binary operator and a right-hand side object.

func (*Time) Copy

func (o *Time) Copy() Object

Copy returns a copy of the type.

func (*Time) Equals

func (o *Time) Equals(x Object) bool

Equals returns true if the value of the type is equal to the value of another object.

func (*Time) IsFalsy

func (o *Time) IsFalsy() bool

IsFalsy returns true if the value of the type is falsy.

func (*Time) String

func (o *Time) String() string

func (*Time) TypeName

func (o *Time) TypeName() string

TypeName returns the name of the type.

type Undefined

type Undefined struct {
	ObjectImpl
}

Undefined represents an undefined value.

func (*Undefined) CanIterate

func (o *Undefined) CanIterate() bool

CanIterate returns whether the Object can be Iterated.

func (*Undefined) Copy

func (o *Undefined) Copy() Object

Copy returns a copy of the type.

func (*Undefined) Equals

func (o *Undefined) Equals(x Object) bool

Equals returns true if the value of the type is equal to the value of another object.

func (*Undefined) IndexGet

func (o *Undefined) IndexGet(_ Object) (Object, error)

IndexGet returns an element at a given index.

func (*Undefined) IsFalsy

func (o *Undefined) IsFalsy() bool

IsFalsy returns true if the value of the type is falsy.

func (*Undefined) Iterate

func (o *Undefined) Iterate() Iterator

Iterate creates a map iterator.

func (*Undefined) Key

func (o *Undefined) Key() Object

Key returns the key or index value of the current element.

func (*Undefined) Next

func (o *Undefined) Next() bool

Next returns true if there are more elements to iterate.

func (*Undefined) String

func (o *Undefined) String() string

func (*Undefined) TypeName

func (o *Undefined) TypeName() string

TypeName returns the name of the type.

func (*Undefined) Value

func (o *Undefined) Value() Object

Value returns the value of the current element.

type UserFunction

type UserFunction struct {
	ObjectImpl
	Name       string
	Value      CallableFunc
	EncodingID string
}

UserFunction represents a user function.

func (*UserFunction) Call

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

Call invokes a user function.

func (*UserFunction) CanCall

func (o *UserFunction) CanCall() bool

CanCall returns whether the Object can be Called.

func (*UserFunction) Copy

func (o *UserFunction) Copy() Object

Copy returns a copy of the type.

func (*UserFunction) Equals

func (o *UserFunction) Equals(_ Object) bool

Equals returns true if the value of the type is equal to the value of another object.

func (*UserFunction) String

func (o *UserFunction) String() string

func (*UserFunction) TypeName

func (o *UserFunction) TypeName() string

TypeName returns the name of the type.

type VM

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

VM is a virtual machine that executes the bytecode compiled by Compiler.

func NewVM

func NewVM(
	bytecode *Bytecode,
	globals []Object,
	maxAllocs int64,
) *VM

NewVM creates a VM.

func (*VM) Abort

func (v *VM) Abort()

Abort aborts the execution.

func (*VM) IsStackEmpty

func (v *VM) IsStackEmpty() bool

IsStackEmpty tests if the stack is empty or not.

func (*VM) Run

func (v *VM) Run() (err error)

Run starts the execution.

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() 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
cmd
examples
interoperability
An example to demonstrate an alternative way to run tengo functions from go.
An example to demonstrate an alternative way to run tengo functions from go.

Jump to

Keyboard shortcuts

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