gad

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

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

Go to latest
Published: Mar 28, 2024 License: MIT Imports: 32 Imported by: 0

README

The Gad Language

Go Reference Go Report Card Gad Test Gad Dev Test Maintainability

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

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

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

Play with Gad 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 Gad and Go Module support.
  • Go like syntax with additions.
  • Call Gad functions from Go.
  • Import Gad modules from any source (file system, HTTP, etc.).
  • Create wrapper functions for Go functions using code generation.

Why Gad

Gad (Hebrew: גָּד‎, Modern: Gad, Tiberian: Gāḏ, "luck") was, according to the Book of Genesis, the first of the two sons of Jacob and Zilpah (Jacob's seventh son) and the founder of the Israelite tribe of Gad.[2] The text of the Book of Genesis implies that the name of Gad means luck/fortunate, in Hebrew.

Quick Start

go get github.com/gad-lang/gad@latest

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

go install github.com/gad-lang/gad/cmd/gad@latest

./gad

repl-gif

This example is to show some features of Gad.

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

package main

import (
    "fmt"

    "github.com/gad-lang/gad"
)

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 != nil {
    return err
}
return v
`

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

TODO

  • Dollar as valid ident char
  • Nullisch Coalescing
  • Named arguments
  • Array Expansion
  • Array Comprehensions
  • Map Expansion
  • Map Comprehensions
  • Examples for best practices
  • Better Playground
  • Configurable Stdin, Stdout and Stderr per Virtual Machine
  • Deferring function calls
  • Concurrency support

Documentation

LICENSE

Gad is licensed under the MIT License.

See LICENSE for the full license text.

Acknowledgements

Gad is inspired by script language uGo by Ozan Hacıbekiroğlu. A special thanks to uGo's creater and contributors.

Documentation

Overview

Code generated by 'go generate'; DO NOT EDIT.

Index

Constants

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

	// False represents a false value.
	False = Bool(false)

	// Yes represents a flag on.
	Yes = Flag(true)

	// Yes represents a flag off.
	No = Flag(false)
)
View Source
const (
	// AttrModuleName is a special attribute injected into modules to identify
	// the modules by name.
	AttrModuleName = "__module_name__"
)
View Source
const MainName = "(main)"

Variables

View Source
var (
	TOperator           = &Type{TypeName: "Operator", Parent: TBase}
	BinaryOperatorTypes = map[token.Token]*BinaryOperatorType{}
)
View Source
var (
	TBinOpAdd       = &BinaryOperatorType{OpName: "Add", Token: token.Add}             // +
	TBinOpSub       = &BinaryOperatorType{OpName: "Sub", Token: token.Sub}             // -
	TBinOpMul       = &BinaryOperatorType{OpName: "Mul", Token: token.Mul}             // *
	TBinOpQuo       = &BinaryOperatorType{OpName: "Quo", Token: token.Quo}             // /
	TBinOpRem       = &BinaryOperatorType{OpName: "Rem", Token: token.Rem}             // %
	TBinOpAnd       = &BinaryOperatorType{OpName: "And", Token: token.And}             // &
	TBinOpOr        = &BinaryOperatorType{OpName: "Or", Token: token.Or}               // |
	TBinOpXor       = &BinaryOperatorType{OpName: "Xor", Token: token.Xor}             // ^
	TBinOpShl       = &BinaryOperatorType{OpName: "Shl", Token: token.Shl}             // <<
	TBinOpShr       = &BinaryOperatorType{OpName: "Shr", Token: token.Shr}             // >>
	TBinOpAndNot    = &BinaryOperatorType{OpName: "AndNot", Token: token.AndNot}       // &^
	TBinOpLAnd      = &BinaryOperatorType{OpName: "LAnd", Token: token.LAnd}           // &&
	TBinOpEqual     = &BinaryOperatorType{OpName: "Equal", Token: token.Equal}         // ==
	TBinOpNotEqual  = &BinaryOperatorType{OpName: "NotEqual", Token: token.NotEqual}   // !=
	TBinOpLess      = &BinaryOperatorType{OpName: "Less", Token: token.Less}           // <
	TBinOpGreater   = &BinaryOperatorType{OpName: "Greater", Token: token.Greater}     // >
	TBinOpLessEq    = &BinaryOperatorType{OpName: "LessEq", Token: token.LessEq}       // <=
	TBinOpGreaterEq = &BinaryOperatorType{OpName: "GreaterEq", Token: token.GreaterEq} // >=
)
View Source
var (
	TNil,
	TFlag,
	TBool,
	TInt,
	TUint,
	TFloat,
	TDecimal,
	TChar,
	TRawStr,
	TStr,
	TBytes,
	TBuffer,
	TArray,
	TDict,
	TSyncDict,
	TKeyValue,
	TKeyValueArray,
	TError ObjectType

	TBuiltinFunction = &BuiltinObjType{
		NameValue: "builtinFunction",
	}
	TCallWrapper = &BuiltinObjType{
		NameValue: "callwrap",
	}
	TCompiledFunction = &BuiltinObjType{
		NameValue: "compiledFunction",
	}
	TFunction = &BuiltinObjType{
		NameValue: "function",
	}
	TKeyValueArrays = &BuiltinObjType{
		NameValue: "keyValueArrays",
	}
	TArgs = &BuiltinObjType{
		NameValue: "args",
	}
	TNamedArgs = &BuiltinObjType{
		NameValue: "namedArgs",
	}
	TObjectPtr = &BuiltinObjType{
		NameValue: "objectPtr",
	}
	TReader = &BuiltinObjType{
		NameValue: "reader",
	}
	TWriter = &BuiltinObjType{
		NameValue: "writer",
	}
	TDiscardWriter = &BuiltinObjType{
		NameValue: "discardWriter",
	}
	TObjectTypeArray = &BuiltinObjType{
		NameValue: "objectTypeArray",
	}
	TReflectMethod = &BuiltinObjType{
		NameValue: "reflectMethod",
	}
	TIndexGetProxy = &BuiltinObjType{
		NameValue: "indexGetProxy",
	}
)
View Source
var (
	TAny                    = &Type{TypeName: "Any"}
	TSymbol                 = &Type{Parent: TAny, TypeName: "Symbol"}
	TIterationStateFlag     = &Type{Parent: TAny, TypeName: "IterationStateFlag"}
	IterationStop           = &Type{Parent: TIterationStateFlag, TypeName: "IterationStop"}
	IterationSkip           = &Type{Parent: TIterationStateFlag, TypeName: "IterationSkip"}
	TBase                   = &Type{Parent: TAny, TypeName: "Base"}
	TIterator               = &Type{Parent: TAny, TypeName: "Iterator"}
	TIterabler              = &Type{Parent: TAny, TypeName: "Iterabler"}
	TNilIterator            = &Type{Parent: TIterator, TypeName: "NilIterator"}
	TStateIterator          = &Type{Parent: TIterator, TypeName: "StateIterator"}
	TStrIterator            = &Type{Parent: TIterator, TypeName: "StrIterator"}
	TRawStrIterator         = &Type{Parent: TIterator, TypeName: "RawStrIterator"}
	TArrayIterator          = &Type{Parent: TIterator, TypeName: "ArrayIterator"}
	TDictIterator           = &Type{Parent: TIterator, TypeName: "DictIterator"}
	TBytesIterator          = &Type{Parent: TIterator, TypeName: "BytesIterator"}
	TKeyValueArrayIterator  = &Type{Parent: TIterator, TypeName: "KeyValueArrayIterator"}
	TKeyValueArraysIterator = &Type{Parent: TIterator, TypeName: "KeyValueArraysIterator"}
	TArgsIterator           = &Type{Parent: TIterator, TypeName: "ArgsIterator"}
	TReflectArrayIterator   = &Type{Parent: TIterator, TypeName: "ReflectArrayIterator"}
	TReflectMapIterator     = &Type{Parent: TIterator, TypeName: "ReflectMapIterator"}
	TReflectStructIterator  = &Type{Parent: TIterator, TypeName: "ReflectStructIterator"}
	TKeysIterator           = &Type{Parent: TIterator, TypeName: "KeysIterator"}
	TValuesIterator         = &Type{Parent: TIterator, TypeName: "ValuesIterator"}
	TEnumerateIterator      = &Type{Parent: TIterator, TypeName: "EnumerateIterator"}
	TItemsIterator          = &Type{Parent: TIterator, TypeName: "ItemsIterator"}
	TCallbackIterator       = &Type{Parent: TIterator, TypeName: "CallbackIterator"}
	TEachIterator           = &Type{Parent: TIterator, TypeName: "EachIterator"}
	TMapIterator            = &Type{Parent: TIterator, TypeName: "MapIterator"}
	TFilterIterator         = &Type{Parent: TIterator, TypeName: "FilterIterator"}
	TZipIterator            = &Type{Parent: TIterator, TypeName: "ZipIterator"}
	TPipedInvokeIterator    = &Type{Parent: TIterator, TypeName: "PipedInvokeIterator"}
)
View Source
var (
	// DefaultCompilerOptions holds default Compiler options.
	DefaultCompilerOptions = CompilerOptions{
		OptimizerMaxCycle: 100,
		OptimizeConst:     true,
		OptimizeExpr:      true,
	}

	DefaultCompileOptions = CompileOptions{
		CompilerOptions: DefaultCompilerOptions,
	}
	// 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"}

	// ErrNotIndexDeletable is an error where an Object is not index deletable.
	ErrNotIndexDeletable = &Error{Name: "NotIndexDeletableError"}

	// 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"}

	// ErrUnexpectedNamedArg is an error where unexpected kwarg.
	ErrUnexpectedNamedArg = &Error{Name: "ErrUnexpectedNamedArg"}

	// ErrUnexpectedArgValue is an error where unexpected argument value.
	ErrUnexpectedArgValue = &Error{Name: "ErrUnexpectedArgValue"}

	// ErrIncompatibleCast is an error where incompatible cast.
	ErrIncompatibleCast = &Error{Name: "ErrIncompatibleCast"}

	// ErrIncompatibleReflectFuncType is an error where incompatible reflect func type.
	ErrIncompatibleReflectFuncType = &Error{Name: "ErrIncompatibleReflectFuncType"}

	// ErrReflectCallPanicsType is an error where call reflect function panics.
	ErrReflectCallPanicsType = &Error{Name: "ErrReflectCallPanicsType"}

	// ErrMethodDuplication is an error where method was duplication.
	ErrMethodDuplication = &Error{Name: "ErrMethodDuplication"}

	// ErrType represents a type error.
	ErrType = &Error{Name: "TypeError"}

	// ErrNotInitializable represents a not initializable type error.
	ErrNotInitializable = &Error{Name: "ErrNotInitializable"}

	// ErrNotWriteable represents a not writeable type error.
	ErrNotWriteable = &Error{Name: "ErrNotWriteable"}
)
View Source
var (
	ReprQuote      = repr.Quote
	ReprQuoteTyped = repr.QuoteTyped
)
View Source
var BuiltinObjects = BuiltinObjectsMap{

	BuiltinMakeArray: &BuiltinFunction{
		Name:                  ":makeArray",
		Value:                 funcPiOROe(BuiltinMakeArrayFunc),
		AcceptMethodsDisabled: true,
	},
	BuiltinBinaryOp: &BuiltinFunction{
		Name:  "binaryOp",
		Value: BuiltinBinaryOpFunc,
	},
	BuiltinCast: &BuiltinFunction{
		Name:  "cast",
		Value: BuiltinCastFunc,
	},
	BuiltinChars: &BuiltinFunction{
		Name:  "chars",
		Value: funcPOROe(BuiltinCharsFunc),
	},
	BuiltinAppend: &BuiltinFunction{
		Name:  "append",
		Value: BuiltinAppendFunc,
	},
	BuiltinDelete: &BuiltinFunction{
		Name:  "delete",
		Value: BuiltinDeleteFunc,
	},
	BuiltinCopy: &BuiltinFunction{
		Name:  "copy",
		Value: BuiltinCopyFunc,
	},
	BuiltinDeepCopy: &BuiltinFunction{
		Name:  "dcopy",
		Value: BuiltinDeepCopyFunc,
	},
	BuiltinRepeat: &BuiltinFunction{
		Name:  "repeat",
		Value: funcPOiROe(BuiltinRepeatFunc),
	},
	BuiltinContains: &BuiltinFunction{
		Name:  "contains",
		Value: funcPOOROe(BuiltinContainsFunc),
	},
	BuiltinLen: &BuiltinFunction{
		Name:  "len",
		Value: funcPORO(BuiltinLenFunc),
	},
	BuiltinCap: &BuiltinFunction{
		Name:  "cap",
		Value: funcPORO(BuiltinCapFunc),
	},
	BuiltinSort: &BuiltinFunction{
		Name:  "sort",
		Value: funcPpVM_OCo_less_ROe(BuiltinSortFunc),
	},
	BuiltinSortReverse: &BuiltinFunction{
		Name:  "sortReverse",
		Value: funcPpVM_OCo_less_ROe(BuiltinSortReverseFunc),
	},
	BuiltinTypeName: &BuiltinFunction{
		Name:                  "typeName",
		Value:                 funcPORO(BuiltinTypeNameFunc),
		AcceptMethodsDisabled: true,
	},
	BuiltinPrint: &BuiltinFunction{
		Name:  "print",
		Value: BuiltinPrintFunc,
	},
	BuiltinPrintf: &BuiltinFunction{
		Name:  "printf",
		Value: BuiltinPrintfFunc,
	},
	BuiltinPrintln: &BuiltinFunction{
		Name:  "println",
		Value: BuiltinPrintlnFunc,
	},
	BuiltinSprintf: &BuiltinFunction{
		Name:                  "sprintf",
		Value:                 BuiltinSprintfFunc,
		AcceptMethodsDisabled: true,
	},
	BuiltinGlobals: &BuiltinFunction{
		Name:                  "globals",
		Value:                 BuiltinGlobalsFunc,
		AcceptMethodsDisabled: true,
	},
	BuiltinRepr: &BuiltinFunction{
		Name:  "repr",
		Value: BuiltinReprFunc,
	},
	BuiltinNamedParamTypeCheck: &BuiltinFunction{
		Name:                  "namedParamTypeCheck",
		Value:                 BuiltinNamedParamTypeCheckFunc,
		AcceptMethodsDisabled: true,
	},
	BuiltinIs: &BuiltinFunction{
		Name:                  "is",
		Value:                 BuiltinIsFunc,
		AcceptMethodsDisabled: true,
	},
	BuiltinIsError: &BuiltinFunction{
		Name:                  "isError",
		Value:                 BuiltinIsErrorFunc,
		AcceptMethodsDisabled: true,
	},
	BuiltinIsInt: &BuiltinFunction{
		Name:                  "isInt",
		Value:                 funcPORO(BuiltinIsIntFunc),
		AcceptMethodsDisabled: true,
	},
	BuiltinIsUint: &BuiltinFunction{
		Name:                  "isUint",
		Value:                 funcPORO(BuiltinIsUintFunc),
		AcceptMethodsDisabled: true,
	},
	BuiltinIsFloat: &BuiltinFunction{
		Name:                  "isFloat",
		Value:                 funcPORO(BuiltinIsFloatFunc),
		AcceptMethodsDisabled: true,
	},
	BuiltinIsChar: &BuiltinFunction{
		Name:                  "isChar",
		Value:                 funcPORO(BuiltinIsCharFunc),
		AcceptMethodsDisabled: true,
	},
	BuiltinIsBool: &BuiltinFunction{
		Name:                  "isBool",
		Value:                 funcPORO(BuiltinIsBoolFunc),
		AcceptMethodsDisabled: true,
	},
	BuiltinIsStr: &BuiltinFunction{
		Name:                  "isStr",
		Value:                 funcPORO(BuiltinIsStrFunc),
		AcceptMethodsDisabled: true,
	},
	BuiltinIsRawStr: &BuiltinFunction{
		Name:                  "isRawStr",
		Value:                 funcPORO(BuiltinIsRawStrFunc),
		AcceptMethodsDisabled: true,
	},
	BuiltinIsBytes: &BuiltinFunction{
		Name:                  "isBytes",
		Value:                 funcPORO(BuiltinIsBytesFunc),
		AcceptMethodsDisabled: true,
	},
	BuiltinIsDict: &BuiltinFunction{
		Name:                  "isDict",
		Value:                 funcPORO(BuiltinIsDictFunc),
		AcceptMethodsDisabled: true,
	},
	BuiltinIsSyncDict: &BuiltinFunction{
		Name:                  "isSyncDict",
		Value:                 funcPORO(BuiltinIsSyncDictFunc),
		AcceptMethodsDisabled: true,
	},
	BuiltinIsArray: &BuiltinFunction{
		Name:                  "isArray",
		Value:                 funcPORO(BuiltinIsArrayFunc),
		AcceptMethodsDisabled: true,
	},
	BuiltinIsNil: &BuiltinFunction{
		Name:                  "isNil",
		Value:                 funcPORO(BuiltinIsNilFunc),
		AcceptMethodsDisabled: true,
	},
	BuiltinIsFunction: &BuiltinFunction{
		Name:                  "isFunction",
		Value:                 funcPORO(BuiltinIsFunctionFunc),
		AcceptMethodsDisabled: true,
	},
	BuiltinIsCallable: &BuiltinFunction{
		Name:  "isCallable",
		Value: funcPORO(BuiltinIsCallableFunc),
	},
	BuiltinIsIterable: &BuiltinFunction{
		Name:  "isIterable",
		Value: funcPpVM_ORO(BuiltinIsIterableFunc),
	},
	BuiltinIsIterator: &BuiltinFunction{
		Name:  "isIterator",
		Value: funcPORO(BuiltinIsIteratorFunc),
	},
	BuiltinStdIO: &BuiltinFunction{
		Name:  "stdio",
		Value: BuiltinStdIOFunc,
	},
	BuiltinWrap: &BuiltinFunction{
		Name:  "wrap",
		Value: BuiltinWrapFunc,
	},
	BuiltinStruct: &BuiltinFunction{
		Name:                  "struct",
		Value:                 BuiltinStructFunc,
		AcceptMethodsDisabled: true,
	},
	BuiltinNew: &BuiltinFunction{
		Name:  "new",
		Value: BuiltinNewFunc,
	},
	BuiltinTypeOf: &BuiltinFunction{
		Name:                  "typeof",
		Value:                 BuiltinTypeOfFunc,
		AcceptMethodsDisabled: true,
	},
	BuiltinAddCallMethod: &BuiltinFunction{
		Name:                  "addCallMethod",
		Value:                 funcPpVM_CoCob_override_Re(BuiltinAddCallMethodFunc),
		AcceptMethodsDisabled: true,
	},
	BuiltinRawCaller: &BuiltinFunction{
		Name:                  "rawCaller",
		Value:                 BuiltinRawCallerFunc,
		AcceptMethodsDisabled: true,
	},
	BuiltinVMPushWriter: &BuiltinFunction{
		Name:                  "vmPushWriter",
		Value:                 BuiltinPushWriterFunc,
		AcceptMethodsDisabled: true,
	},
	BuiltinVMPopWriter: &BuiltinFunction{
		Name:  "vmPopWriter",
		Value: BuiltinPopWriterFunc,
	},
	BuiltinOBStart: &BuiltinFunction{
		Name:                  "obstart",
		Value:                 BuiltinOBStartFunc,
		AcceptMethodsDisabled: true,
	},
	BuiltinOBEnd: &BuiltinFunction{
		Name:                  "obend",
		Value:                 BuiltinOBEndFunc,
		AcceptMethodsDisabled: true,
	},
	BuiltinFlush: &BuiltinFunction{
		Name:  "flush",
		Value: BuiltinFlushFunc,
	},
	BuiltinUserData: &BuiltinFunction{
		Name:  "userData",
		Value: BuiltinUserDataFunc,
	},

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

	BuiltinDiscardWriter: DiscardWriter,
}

BuiltinObjects is list of builtins, exported for REPL.

View Source
var BuiltinsMap = map[string]BuiltinType{
	"binaryOp":            BuiltinBinaryOp,
	"cast":                BuiltinCast,
	"append":              BuiltinAppend,
	"delete":              BuiltinDelete,
	"copy":                BuiltinCopy,
	"dcopy":               BuiltinDeepCopy,
	"repeat":              BuiltinRepeat,
	"contains":            BuiltinContains,
	"len":                 BuiltinLen,
	"sort":                BuiltinSort,
	"sortReverse":         BuiltinSortReverse,
	"filter":              BuiltinFilter,
	"map":                 BuiltinMap,
	"each":                BuiltinEach,
	"reduce":              BuiltinReduce,
	"typeName":            BuiltinTypeName,
	"chars":               BuiltinChars,
	"write":               BuiltinWrite,
	"print":               BuiltinPrint,
	"printf":              BuiltinPrintf,
	"println":             BuiltinPrintln,
	"sprintf":             BuiltinSprintf,
	"globals":             BuiltinGlobals,
	"stdio":               BuiltinStdIO,
	"wrap":                BuiltinWrap,
	"struct":              BuiltinStruct,
	"new":                 BuiltinNew,
	"typeof":              BuiltinTypeOf,
	"addCallMethod":       BuiltinAddCallMethod,
	"rawCaller":           BuiltinRawCaller,
	"repr":                BuiltinRepr,
	"userData":            BuiltinUserData,
	"namedParamTypeCheck": BuiltinNamedParamTypeCheck,

	"is":         BuiltinIs,
	"isError":    BuiltinIsError,
	"isInt":      BuiltinIsInt,
	"isUint":     BuiltinIsUint,
	"isFloat":    BuiltinIsFloat,
	"isChar":     BuiltinIsChar,
	"isBool":     BuiltinIsBool,
	"isStr":      BuiltinIsStr,
	"isRawStr":   BuiltinIsRawStr,
	"isBytes":    BuiltinIsBytes,
	"isDict":     BuiltinIsDict,
	"isSyncDict": BuiltinIsSyncDict,
	"isArray":    BuiltinIsArray,
	"isNil":      BuiltinIsNil,
	"isFunction": BuiltinIsFunction,
	"isCallable": BuiltinIsCallable,
	"isIterable": BuiltinIsIterable,
	"isIterator": BuiltinIsIterator,

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

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

	"iterate":       BuiltinIterate,
	"keys":          BuiltinKeys,
	"values":        BuiltinValues,
	"items":         BuiltinItems,
	"collect":       BuiltinCollect,
	"enumerate":     BuiltinEnumerate,
	"iterator":      BuiltinIterator,
	"iteratorInput": BuiltinIteratorInput,
	"zip":           BuiltinZipIterator,
	"keyValue":      BuiltinKeyValue,
	"keyValueArray": BuiltinKeyValueArray,

	"vmPushWriter":   BuiltinVMPushWriter,
	"vmPopWriter":    BuiltinVMPopWriter,
	"obstart":        BuiltinOBStart,
	"obend":          BuiltinOBEnd,
	"flush":          BuiltinFlush,
	"DISCARD_WRITER": BuiltinDiscardWriter,
}

BuiltinsMap is list of builtin types, exported for REPL.

View Source
var DecimalZero = Decimal(decimal.Zero)
View Source
var EmptyNamedArgs = &NamedArgs{ro: true}
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",
	OpStdIn:         "STDIN",
	OpStdOut:        "STDOUT",
	OpStdErr:        "STDERR",
	OpDotName:       "DOTNAME",
	OpDotFile:       "DOTFILE",
	OpIsModule:      "ISMODULE",
	OpPop:           "POP",
	OpGetFree:       "GETFREE",
	OpSetFree:       "SETFREE",
	OpGetLocalPtr:   "GETLOCALPTR",
	OpGetFreePtr:    "GETFREEPTR",
	OpClosure:       "CLOSURE",
	OpIterInit:      "ITERINIT",
	OpIterNext:      "ITERNEXT",
	OpIterNextElse:  "ITERNEXTELSE",
	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",
	OpYes:           "YES",
	OpNo:            "NO",
	OpCallName:      "CALLNAME",
	OpJumpNil:       "JUMPNULL",
	OpJumpNotNil:    "JUMPNOTNULL",
	OpKeyValueArray: "KVARRAY",
	OpKeyValue:      "KV",
	OpCallee:        "CALLEE",
	OpArgs:          "ARGS",
	OpNamedArgs:     "NAMEDARGS",
	OpIsNil:         "ISNIL",
	OpNotIsNil:      "NOTISNIL",
}

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:    {2},
	OpBinaryOp:      {1},
	OpUnary:         {1},
	OpEqual:         {},
	OpNotEqual:      {},
	OpIsNil:         {},
	OpNotIsNil:      {},
	OpJump:          {2},
	OpJumpFalsy:     {2},
	OpAndJump:       {2},
	OpOrJump:        {2},
	OpMap:           {2},
	OpArray:         {2},
	OpSliceIndex:    {},
	OpGetIndex:      {1},
	OpSetIndex:      {},
	OpNull:          {},
	OpStdIn:         {},
	OpStdOut:        {},
	OpStdErr:        {},
	OpDotName:       {},
	OpDotFile:       {},
	OpIsModule:      {},
	OpPop:           {},
	OpGetFree:       {1},
	OpSetFree:       {1},
	OpGetLocalPtr:   {1},
	OpGetFreePtr:    {1},
	OpClosure:       {2, 1},
	OpIterInit:      {},
	OpIterNext:      {},
	OpIterNextElse:  {2, 2},
	OpIterKey:       {},
	OpIterValue:     {},
	OpLoadModule:    {2, 2},
	OpStoreModule:   {2},
	OpReturn:        {1},
	OpSetupTry:      {2, 2},
	OpSetupCatch:    {},
	OpSetupFinally:  {},
	OpThrow:         {1},
	OpFinalizer:     {1},
	OpDefineLocal:   {1},
	OpTrue:          {},
	OpFalse:         {},
	OpYes:           {},
	OpNo:            {},
	OpCallName:      {1, 1},
	OpJumpNil:       {2},
	OpJumpNotNil:    {2},
	OpKeyValueArray: {2},
	OpCallee:        {},
	OpArgs:          {},
	OpNamedArgs:     {},
	OpKeyValue:      {1},
}

OpcodeOperands is the number of operands.

View Source
var Types = map[reflect.Type]ObjectType{}

Functions

func ArrayRepr

func ArrayRepr(typName string, vm *VM, len int, get func(i int) Object) (_ string, err error)

func ArrayToString

func ArrayToString(len int, get func(i int) Object) string

func BuiltinAddCallMethodFunc

func BuiltinAddCallMethodFunc(vm *VM, fn CallerObject, handler CallerObject, override bool) (err error)

func Callable

func Callable(o Object) (ok bool)

func Filterable

func Filterable(obj Object) bool

func FormatInstructions

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

FormatInstructions returns string representation of bytecode instructions.

func IsIndexDeleter

func IsIndexDeleter(obj Object) (ok bool)

func IsIndexGetter

func IsIndexGetter(obj Object) (ok bool)

func IsIndexSetter

func IsIndexSetter(obj Object) (ok bool)

func IsIterator

func IsIterator(obj Object) bool

func IsObjector

func IsObjector(obj Object) (ok bool)

func IsType

func IsType(obj Object) (ok bool)

func IsTypeAssignableTo

func IsTypeAssignableTo(a, b ObjectType) bool

func IsZero

func IsZero(value interface{}) bool

func Iterable

func Iterable(vm *VM, obj Object) bool

func Iterate

func Iterate(vm *VM, it Iterator, init func(state *IteratorState) error, cb func(e *KeyValue) error) (err error)

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 IterateObject

func IterateObject(vm *VM, o Object, na *NamedArgs, init func(state *IteratorState) error, cb func(e *KeyValue) error) (err error)

func IteratorStateCheck

func IteratorStateCheck(vm *VM, it Iterator, state *IteratorState) (err error)

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 Mapable

func Mapable(obj Object) bool

func NamedParamTypeCheck

func NamedParamTypeCheck(name string, typeso, value Object) (badTypes string, err error)

func NamedParamTypeCheckAssertion

func NamedParamTypeCheckAssertion(name string, assertion *TypeAssertion, value Object) (err error)

func NewArgCaller

func NewArgCaller(vm *VM, co CallerObject, args Array, namedArgs NamedArgs) func() (ret Object, err error)

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 Reducable

func Reducable(obj Object) bool

func ToCode

func ToCode(o Object) string

func ToGoBool

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

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

func ToGoByteSlice

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

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

func ToGoFloat64

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

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

func ToGoInt

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

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

func ToGoInt64

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

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

func ToGoRune

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

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

func ToGoString

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

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

func ToGoUint64

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

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

func ToInterface

func ToInterface(o Object) (ret any)

ToInterface tries to convert an Object o to an any value.

func ToReprTypedRS

func ToReprTypedRS(vm *VM, typ ObjectType, o any) (s string, err error)

func ToReprTypedS

func ToReprTypedS(vm *VM, typ ObjectType, o Object) (_ string, err error)

func ToWritable

func ToWritable(obj Object) bool

func WithArgs

func WithArgs(args ...Object) func(c *Call)

func WithArgsV

func WithArgsV(args []Object, vargs ...Object) func(c *Call)

func WithNamedArgs

func WithNamedArgs(na *NamedArgs) func(c *Call)

func WrapIterator

func WrapIterator(iterator Iterator, wrap func(state *IteratorState) error) *wrapIterator

Types

type Adder

type Adder interface {
	Object
	Add(vm *VM, arr ...Object) (err error)
}

type Appender

type Appender interface {
	Object
	Append(vm *VM, arr ...Object) (Object, error)
}

type Arg

type Arg struct {
	Name  string
	Value Object
	*TypeAssertion
}

Arg is a struct to destructure arguments from Call object.

type ArgType

type ArgType []ObjectType

func (ArgType) String

func (t ArgType) String() string

type Args

type Args []Array

func (Args) Array

func (o Args) Array() (ret Array)

func (Args) BinaryOp

func (o Args) BinaryOp(_ *VM, tok token.Token, right Object) (Object, error)

func (Args) CheckLen

func (o Args) 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 (Args) CheckMaxLen

func (o Args) CheckMaxLen(n int) error

CheckMaxLen checks the number of arguments and variadic arguments. If the number of arguments is greather then to n, it returns an error.

func (Args) CheckMinLen

func (o Args) CheckMinLen(n int) error

CheckMinLen checks the number of arguments and variadic arguments. If the number of arguments is less then to n, it returns an error.

func (Args) CheckRangeLen

func (o Args) CheckRangeLen(min, max int) error

CheckRangeLen checks the number of arguments and variadic arguments. If the number of arguments is less then to min or greather then to max, it returns an error.

func (Args) Copy

func (o Args) Copy() Object

Copy implements Copier interface.

func (Args) DeepCopy

func (o Args) DeepCopy(vm *VM) (r Object, err error)

DeepCopy implements DeepCopier interface.

func (Args) Destructure

func (o Args) Destructure(dst ...*Arg) (err error)

Destructure shifts argument and set value to dst. If the number of arguments not equals to called args length, it returns an error. If type check of arg is fails, returns ArgumentTypeError.

func (Args) DestructureValue

func (o Args) DestructureValue(dst ...*Arg) (err error)

DestructureValue shifts argument and set value to dst. If type check of arg is fails, returns ArgumentTypeError.

func (Args) DestructureVar

func (o Args) DestructureVar(dst ...*Arg) (other Array, err error)

DestructureVar shifts argument and set value to dst, and returns left arguments. If the number of arguments is less then to called args length, it returns an error. If type check of arg is fails, returns ArgumentTypeError.

func (Args) Equal

func (o Args) Equal(right Object) (ok bool)

func (Args) Get

func (o Args) Get(n int) (v 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 (Args) GetDefault

func (o Args) GetDefault(n int, defaul Object) (v Object)

GetDefault 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, return defaul.

func (Args) GetIJ

func (o Args) GetIJ(n int) (i, j int, ok bool)

func (Args) GetOnly

func (o Args) GetOnly(n int) Object

GetOnly returns the nth argument.

func (Args) IndexGet

func (o Args) IndexGet(_ *VM, index Object) (Object, error)

IndexGet implements Object interface.

func (Args) IsFalsy

func (o Args) IsFalsy() bool

func (Args) Iterate

func (o Args) Iterate(_ *VM, na *NamedArgs) Iterator

func (Args) Length

func (o Args) Length() (l int)

Length returns the number of arguments including variadic arguments.

func (Args) MustGet

func (o Args) MustGet(n int) Object

MustGet returns the nth argument. If n is greater than the number of arguments, it returns the nth variadic argument or Nil.

func (*Args) Prepend

func (o *Args) Prepend(items ...Object)

func (*Args) Shift

func (o *Args) Shift() (v Object)

Shift returns the first argument and removes it from the arguments. If it cannot Shift, it returns nil.

func (Args) ShiftArg

func (o Args) ShiftArg(shifts *int, dst *Arg) (ok bool, err error)

ShiftArg shifts argument and set value to dst. If is empty, retun ok as false. If type check of arg is fails, returns ArgumentTypeError.

func (*Args) ShiftOk

func (o *Args) ShiftOk() (Object, bool)

ShiftOk returns the first argument and removes it from the arguments. It updates the arguments and variadic arguments accordingly. If it cannot ShiftOk, it returns nil and false.

func (Args) ToString

func (o Args) ToString() string

func (Args) Type

func (o Args) Type() ObjectType

func (Args) Values

func (o Args) Values() (ret Array)

func (Args) Walk

func (o Args) Walk(cb func(i int, arg Object) any) (v any)

Walk iterates over all values and call callback function.

func (Args) WalkSkip

func (o Args) WalkSkip(skip int, cb func(i int, arg Object) any) (v any)

WalkSkip iterates over all values skiping skip and call callback function.

type Array

type Array []Object

Array represents array of objects and implements Object interface.

func CollectCb

func CollectCb(vm *VM, o Object, na *NamedArgs, cb func(e *KeyValue, i *Int) Object) (values Array, err error)

func ToArray

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

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

func ValuesOf

func ValuesOf(vm *VM, o Object, na *NamedArgs) (values Array, err error)

func (*Array) Add

func (o *Array) Add(_ *VM, items ...Object) error

func (Array) Append

func (o Array) Append(_ *VM, items ...Object) (Object, error)

func (Array) AppendToArray

func (o Array) AppendToArray(arr *Array)

func (Array) BinaryOp

func (o Array) BinaryOp(vm *VM, tok token.Token, right Object) (_ Object, err error)

BinaryOp implements Object interface.

func (Array) Copy

func (o Array) Copy() Object

Copy implements Copier interface.

func (Array) DeepCopy

func (o Array) DeepCopy(vm *VM) (_ Object, err error)

DeepCopy implements DeepCopier interface.

func (Array) Equal

func (o Array) Equal(right Object) bool

Equal implements Object interface.

func (Array) Format

func (o Array) Format(f fmt.State, verb rune)

func (Array) IndexGet

func (o Array) IndexGet(_ *VM, index Object) (Object, error)

IndexGet implements Object interface.

func (Array) IndexSet

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

IndexSet implements Object interface.

func (Array) IsFalsy

func (o Array) IsFalsy() bool

IsFalsy implements Object interface.

func (Array) Items

func (o Array) Items(*VM) (arr KeyValueArray, _ error)

func (Array) Iterate

func (o Array) Iterate(_ *VM, na *NamedArgs) Iterator

func (Array) Keys

func (o Array) Keys() (arr Array)

func (Array) Length

func (o Array) Length() int

Length implements LengthGetter interface.

func (Array) Repr

func (o Array) Repr(vm *VM) (string, error)

func (Array) Sort

func (o Array) Sort(vm *VM, less CallerObject) (_ Object, err error)

func (Array) SortReverse

func (o Array) SortReverse(vm *VM) (_ Object, err error)

func (Array) ToAnyArray

func (o Array) ToAnyArray(vm *VM) []any

func (Array) ToInterface

func (o Array) ToInterface(vm *VM) any

func (Array) ToString

func (o Array) ToString() string

func (Array) Type

func (o Array) Type() ObjectType

type BinaryOperatorHandler

type BinaryOperatorHandler interface {
	// 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(vm *VM, tok token.Token, right Object) (Object, error)
}

type BinaryOperatorType

type BinaryOperatorType struct {
	OpName string
	Token  token.Token
}

func (BinaryOperatorType) Call

func (*BinaryOperatorType) Equal

func (b *BinaryOperatorType) Equal(right Object) bool

func (BinaryOperatorType) Fields

func (BinaryOperatorType) Fields() Dict

func (BinaryOperatorType) Getters

func (BinaryOperatorType) Getters() Dict

func (BinaryOperatorType) IsChildOf

func (BinaryOperatorType) IsChildOf(t ObjectType) bool

func (*BinaryOperatorType) IsFalsy

func (b *BinaryOperatorType) IsFalsy() bool

func (BinaryOperatorType) Methods

func (BinaryOperatorType) Methods() Dict

func (BinaryOperatorType) MethodsDisabled

func (BinaryOperatorType) MethodsDisabled() bool

func (*BinaryOperatorType) Name

func (b *BinaryOperatorType) Name() string

func (BinaryOperatorType) New

func (BinaryOperatorType) Setters

func (BinaryOperatorType) Setters() Dict

func (BinaryOperatorType) ToString

func (b BinaryOperatorType) ToString() string

func (BinaryOperatorType) Type

func (b BinaryOperatorType) Type() ObjectType

type Bool

type Bool bool

Bool represents boolean values and implements Object interface.

func ToBool

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

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

func (Bool) BinaryOp

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

BinaryOp implements Object interface.

func (Bool) Equal

func (o Bool) Equal(right Object) bool

Equal implements Object interface.

func (Bool) Format

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

Format implements fmt.Formatter interface.

func (Bool) IsFalsy

func (o Bool) IsFalsy() bool

IsFalsy implements Object interface.

func (Bool) ToString

func (o Bool) ToString() string

func (Bool) Type

func (o Bool) Type() ObjectType

type Buffer

type Buffer struct {
	bytes.Buffer
}

func (*Buffer) CallName

func (o *Buffer) CallName(name string, c Call) (Object, error)

func (*Buffer) Equal

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

func (*Buffer) GoReader

func (o *Buffer) GoReader() io.Reader

func (*Buffer) GoWriter

func (o *Buffer) GoWriter() io.Writer

func (*Buffer) IndexGet

func (o *Buffer) IndexGet(_ *VM, index Object) (Object, error)

IndexGet represents string values and implements Object interface.

func (*Buffer) IndexSet

func (o *Buffer) IndexSet(_ *VM, index, value Object) error

IndexSet implements Object interface.

func (*Buffer) IsFalsy

func (o *Buffer) IsFalsy() bool

func (*Buffer) Iterate

func (o *Buffer) Iterate(_ *VM, na *NamedArgs) Iterator

func (*Buffer) Length

func (o *Buffer) Length() int

func (*Buffer) ToBytes

func (o *Buffer) ToBytes() (Bytes, error)

func (*Buffer) ToString

func (o *Buffer) ToString() string

func (*Buffer) Type

func (o *Buffer) Type() ObjectType

type BuiltinFunction

type BuiltinFunction struct {
	ObjectImpl
	Name                  string
	Value                 func(Call) (Object, error)
	Header                FunctionHeader
	AcceptMethodsDisabled bool
}

BuiltinFunction represents a builtin function object and implements Object interface.

func (*BuiltinFunction) Call

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

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

func (o *BuiltinFunction) MethodsDisabled() bool

func (*BuiltinFunction) ParamTypes

func (o *BuiltinFunction) ParamTypes(*VM) (MultipleObjectTypes, error)

func (*BuiltinFunction) ToString

func (o *BuiltinFunction) ToString() string

func (*BuiltinFunction) Type

func (*BuiltinFunction) Type() ObjectType

type BuiltinModule

type BuiltinModule struct {
	Attrs map[string]Object
}

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

func (*BuiltinModule) Import

func (m *BuiltinModule) Import(_ context.Context, moduleName string) (any, string, error)

Import returns an immutable map for the module.

type BuiltinObjType

type BuiltinObjType struct {
	NameValue string
	Value     CallableFunc
	// contains filtered or unexported fields
}

func NewBuiltinObjType

func NewBuiltinObjType(name string, init CallableFunc) *BuiltinObjType

func RegisterBuiltinType

func RegisterBuiltinType(typ BuiltinType, name string, val any, init CallableFunc) *BuiltinObjType

func (*BuiltinObjType) Call

func (b *BuiltinObjType) Call(c Call) (Object, error)

func (*BuiltinObjType) Equal

func (b *BuiltinObjType) Equal(right Object) bool

func (*BuiltinObjType) Fields

func (b *BuiltinObjType) Fields() Dict

func (*BuiltinObjType) Getters

func (b *BuiltinObjType) Getters() Dict

func (*BuiltinObjType) IsChildOf

func (b *BuiltinObjType) IsChildOf(t ObjectType) bool

func (*BuiltinObjType) IsFalsy

func (b *BuiltinObjType) IsFalsy() bool

func (*BuiltinObjType) Methods

func (b *BuiltinObjType) Methods() Dict

func (*BuiltinObjType) Name

func (b *BuiltinObjType) Name() string

func (*BuiltinObjType) New

func (b *BuiltinObjType) New(*VM, Dict) (Object, error)

func (*BuiltinObjType) Setters

func (b *BuiltinObjType) Setters() Dict

func (*BuiltinObjType) String

func (b *BuiltinObjType) String() string

func (*BuiltinObjType) ToString

func (b *BuiltinObjType) ToString() string

func (*BuiltinObjType) Type

func (b *BuiltinObjType) Type() ObjectType

type BuiltinObjectsMap

type BuiltinObjectsMap map[BuiltinType]Object

func (BuiltinObjectsMap) Append

func (m BuiltinObjectsMap) Append(obj ...Object) BuiltinObjectsMap

func (BuiltinObjectsMap) Build

type BuiltinType

type BuiltinType uint16

BuiltinType represents a builtin type

const (
	BuiltinTypesBegin_ BuiltinType = iota
	// types
	BuiltinNil
	BuiltinFlag
	BuiltinBool
	BuiltinInt
	BuiltinUint
	BuiltinFloat
	BuiltinDecimal
	BuiltinChar
	BuiltinRawStr
	BuiltinStr
	BuiltinBytes
	BuiltinArray
	BuiltinDict
	BuiltinSyncDic
	BuiltinKeyValue
	BuiltinKeyValueArray
	BuiltinError
	BuiltinBuffer
	BuiltinIterator
	BuiltinZipIterator
	BuiltinTypesEnd_

	BuiltinFunctionsBegin_
	BuiltinBinaryOp
	BuiltinRepr
	BuiltinCast
	BuiltinAppend
	BuiltinDelete
	BuiltinCopy
	BuiltinDeepCopy
	BuiltinRepeat
	BuiltinContains
	BuiltinLen
	BuiltinSort
	BuiltinSortReverse
	BuiltinFilter
	BuiltinMap
	BuiltinEach
	BuiltinReduce
	BuiltinTypeName
	BuiltinChars
	BuiltinWrite
	BuiltinPrint
	BuiltinPrintf
	BuiltinPrintln
	BuiltinSprintf
	BuiltinGlobals
	BuiltinStdIO
	BuiltinWrap
	BuiltinStruct
	BuiltinNew
	BuiltinTypeOf
	BuiltinAddCallMethod
	BuiltinRawCaller
	BuiltinMakeArray
	BuiltinCap
	BuiltinIterate
	BuiltinKeys
	BuiltinValues
	BuiltinItems
	BuiltinCollect
	BuiltinEnumerate
	BuiltinIteratorInput
	BuiltinVMPushWriter
	BuiltinVMPopWriter
	BuiltinOBStart
	BuiltinOBEnd
	BuiltinFlush
	BuiltinUserData
	BuiltinNamedParamTypeCheck

	BuiltinIs
	BuiltinIsError
	BuiltinIsInt
	BuiltinIsUint
	BuiltinIsFloat
	BuiltinIsChar
	BuiltinIsBool
	BuiltinIsStr
	BuiltinIsRawStr
	BuiltinIsBytes
	BuiltinIsDict
	BuiltinIsSyncDict
	BuiltinIsArray
	BuiltinIsNil
	BuiltinIsFunction
	BuiltinIsCallable
	BuiltinIsIterable
	BuiltinIsIterator

	BuiltinFunctionsEnd_
	BuiltinErrorsBegin_
	// errors
	BuiltinWrongNumArgumentsError
	BuiltinInvalidOperatorError
	BuiltinIndexOutOfBoundsError
	BuiltinNotIterableError
	BuiltinNotIndexableError
	BuiltinNotIndexAssignableError
	BuiltinNotCallableError
	BuiltinNotImplementedError
	BuiltinZeroDivisionError
	BuiltinTypeError
	BuiltinErrorsEnd_

	BuiltinConstantsBegin_
	BuiltinDiscardWriter
	BuiltinConstantsEnd_

	BuiltinBinOperatorsBegin_
	BuiltinBinOpAdd
	BuiltinBinOpSub
	BuiltinBinOpMul
	BuiltinBinOpQuo
	BuiltinBinOpRem
	BuiltinBinOpAnd
	BuiltinBinOpOr
	BuiltinBinOpXor
	BuiltinBinOpShl
	BuiltinBinOpShr
	BuiltinBinOpAndNot
	BuiltinBinOpLAnd
	BuiltinBinOpEqual
	BuiltinBinOpNotEqual
	BuiltinBinOpLess
	BuiltinBinOpGreater
	BuiltinBinOpLessEq
	BuiltinBinOpGreaterEq
	BuiltinBinOperatorsEnd_
)

Builtins

func NewBuiltinType

func NewBuiltinType() (t BuiltinType)

func (BuiltinType) String

func (t BuiltinType) String() string

type Builtins

type Builtins struct {
	Objects BuiltinObjectsMap
	Map     map[string]BuiltinType
	// contains filtered or unexported fields
}

func NewBuiltins

func NewBuiltins() *Builtins

func (*Builtins) AppendMap

func (s *Builtins) AppendMap(m map[string]Object)

func (*Builtins) ArgsInvoker

func (s *Builtins) ArgsInvoker(t BuiltinType, c Call) func(arg ...Object) (Object, error)

func (*Builtins) Call

func (s *Builtins) Call(t BuiltinType, c Call) (Object, error)

func (*Builtins) Caller

func (s *Builtins) Caller(t BuiltinType) CallerObject

func (*Builtins) Get

func (s *Builtins) Get(t BuiltinType) Object

func (*Builtins) Invoker

func (s *Builtins) Invoker(t BuiltinType, c Call) func() (Object, error)

func (*Builtins) Set

func (s *Builtins) Set(name string, obj Object) *Builtins

func (*Builtins) SetType

func (s *Builtins) SetType(typ ObjectType) *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 CompileOptions) (*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

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

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

func (Bytes) BinaryOp

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

BinaryOp 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

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

Format implements fmt.Formatter interface.

func (Bytes) IndexGet

func (o Bytes) IndexGet(_ *VM, index Object) (Object, error)

IndexGet represents string values and implements Object interface.

func (Bytes) IndexSet

func (o Bytes) IndexSet(_ *VM, 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(_ *VM, na *NamedArgs) Iterator

func (Bytes) Length

func (o Bytes) Length() int

Length implements LengthGetter interface.

func (Bytes) ToString

func (o Bytes) ToString() string

func (Bytes) Type

func (o Bytes) Type() ObjectType

func (Bytes) WriteTo

func (o Bytes) WriteTo(_ *VM, w io.Writer) (int64, error)

type BytesConverter

type BytesConverter interface {
	Object
	ToBytes() (Bytes, error)
}

BytesConverter is to bytes converter

type Call

type Call struct {
	VM        *VM
	Args      Args
	NamedArgs NamedArgs
	SafeArgs  bool
}

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 Length() 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

func NewCall(vm *VM, opts ...CallOpt) Call

NewCall creates a new Call struct.

func (Call) InvokerOf

func (c Call) InvokerOf(co CallerObject) *Invoker

type CallOpt

type CallOpt func(c *Call)

type CallWrapper

type CallWrapper struct {
	Caller    CallerObject
	Args      Args
	NamedArgs KeyValueArray
}

func NewCallWrapper

func NewCallWrapper(caller CallerObject, args Args, namedArgs KeyValueArray) *CallWrapper

func (*CallWrapper) Call

func (i *CallWrapper) Call(c Call) (Object, error)

func (CallWrapper) Equal

func (CallWrapper) Equal(Object) bool

func (CallWrapper) IsFalsy

func (CallWrapper) IsFalsy() bool

func (*CallWrapper) ToString

func (i *CallWrapper) ToString() string

func (*CallWrapper) Type

func (i *CallWrapper) Type() ObjectType

type CallableFunc

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

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

type CallerMethod

type CallerMethod struct {
	Default bool
	CallerObject
	Types []ObjectType
	// contains filtered or unexported fields
}

func (*CallerMethod) Caller

func (o *CallerMethod) Caller() CallerObject

func (*CallerMethod) Remove

func (o *CallerMethod) Remove()

func (*CallerMethod) String

func (o *CallerMethod) String() string

type CallerObject

type CallerObject interface {
	Object
	Call(c Call) (Object, error)
}

CallerObject is an interface for objects that can be called with Call method.

func ExprToTextOverride

func ExprToTextOverride(name string, f func(vm *VM, w Writer, old func(w Writer, expr Object) (n Int, err error), expr Object) (n Int, err error)) CallerObject

func YieldCall

func YieldCall(callerObject CallerObject, c *Call) CallerObject

type CallerObjectWithMethods

type CallerObjectWithMethods struct {
	CallerObject
	Methods MethodArgType
	// contains filtered or unexported fields
}

func NewCallerObjectWithMethods

func NewCallerObjectWithMethods(callerObject CallerObject) *CallerObjectWithMethods

func NewTypedFunction

func NewTypedFunction(fn *Function, types MultipleObjectTypes) *CallerObjectWithMethods

func (*CallerObjectWithMethods) AddCallerMethod

func (o *CallerObjectWithMethods) AddCallerMethod(vm *VM, types MultipleObjectTypes, handler CallerObject, override bool) error

func (*CallerObjectWithMethods) Call

func (o *CallerObjectWithMethods) Call(c Call) (Object, error)

func (*CallerObjectWithMethods) Caller

func (*CallerObjectWithMethods) CallerMethods

func (o *CallerObjectWithMethods) CallerMethods() *MethodArgType

func (*CallerObjectWithMethods) CallerOf

func (o *CallerObjectWithMethods) CallerOf(args Args) (CallerObject, bool)

func (*CallerObjectWithMethods) CallerOfTypes

func (o *CallerObjectWithMethods) CallerOfTypes(types []ObjectType) (co CallerObject, validate bool)

func (*CallerObjectWithMethods) Equal

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

func (*CallerObjectWithMethods) GetMethod

func (o *CallerObjectWithMethods) GetMethod(types []ObjectType) (co CallerObject)

func (*CallerObjectWithMethods) HasCallerMethods

func (o *CallerObjectWithMethods) HasCallerMethods() bool

func (*CallerObjectWithMethods) MethodWalk

func (o *CallerObjectWithMethods) MethodWalk(cb func(m *CallerMethod) any) (v any)

func (*CallerObjectWithMethods) MethodWalkSorted

func (o *CallerObjectWithMethods) MethodWalkSorted(cb func(m *CallerMethod) any) (v any)

func (*CallerObjectWithMethods) RegisterDefaultWithTypes

func (o *CallerObjectWithMethods) RegisterDefaultWithTypes(types MultipleObjectTypes) *CallerObjectWithMethods

func (*CallerObjectWithMethods) String

func (o *CallerObjectWithMethods) String() string

func (*CallerObjectWithMethods) ToString

func (o *CallerObjectWithMethods) ToString() string

type CallerObjectWithParamTypes

type CallerObjectWithParamTypes interface {
	CallerObject
	ParamTypes(vm *VM) (MultipleObjectTypes, error)
}

CallerObjectWithParamTypes is an interface for objects that can be called with Call method with parameters with types.

type CanCallerObject

type CanCallerObject interface {
	CallerObject
	// 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
}

CanCallerObject is an interface for objects that can be objects implements this CallerObject interface. Note if CallerObject implements this interface, CanCall() is called for check if object is callable.

type CanCallerObjectMethodsEnabler

type CanCallerObjectMethodsEnabler interface {
	CallerObject
	MethodsDisabled() bool
}

type CanCallerObjectTypesValidation

type CanCallerObjectTypesValidation interface {
	CallerObject
	ValidateParamTypes(vm *VM, args Args) (err error)
	CanValidateParamTypes() bool
}

type CanFilterabler

type CanFilterabler interface {
	CanFilter() bool
}

type CanIterabler

type CanIterabler interface {
	Iterabler
	// CanIterate should return whether the Object can be Iterated.
	CanIterate() bool
}

type CanMapeabler

type CanMapeabler interface {
	CanMap() bool
}

type CanReducer

type CanReducer interface {
	CanReduce() bool
}

type CanToWriter

type CanToWriter interface {
	CanWriteTo() bool
}

type Char

type Char rune

Char represents a rune and implements Object interface.

func ToChar

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

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

func (Char) BinaryOp

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

BinaryOp implements Object interface.

func (Char) Equal

func (o Char) Equal(right Object) bool

Equal implements Object interface.

func (Char) Format

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

Format implements fmt.Formatter interface.

func (Char) IsFalsy

func (o Char) IsFalsy() bool

IsFalsy implements Object interface.

func (Char) ToBytes

func (o Char) ToBytes() (Bytes, error)

func (Char) ToString

func (o Char) ToString() string

func (Char) Type

func (o Char) Type() ObjectType

type CollectableIterator

type CollectableIterator interface {
	Iterator
	Collect(vm *VM) (Object, error)
}

type CompilableImporter

type CompilableImporter interface {
	Importable
	CompileModule(compiler *Compiler, nd ast.Node, module *ModuleInfo, moduleMap *ModuleMap, src []byte) (bc *Bytecode, err error)
}

type CompileOptions

type CompileOptions struct {
	CompilerOptions
	ParserOptions  parser.ParserOptions
	ScannerOptions parser.ScannerOptions
}

type CompiledFunction

type CompiledFunction struct {
	Name string

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

	Params Params

	NamedParams NamedParams

	// NamedParamsMap is a map of NamedParams with index
	// this value allow to perform named args validation.
	NamedParamsMap map[string]int
	// contains filtered or unexported fields
}

CompiledFunction holds the constants and instructions to pass VM.

func (*CompiledFunction) Call

func (o *CompiledFunction) Call(c Call) (Object, error)

func (*CompiledFunction) CanValidateParamTypes

func (o *CompiledFunction) CanValidateParamTypes() bool

func (CompiledFunction) ClearSourceFileInfo

func (o CompiledFunction) ClearSourceFileInfo() *CompiledFunction

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

func (o *CompiledFunction) Format(f fmt.State, verb rune)

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

func (*CompiledFunction) IsFalsy() bool

IsFalsy implements Object interface.

func (*CompiledFunction) ParamTypes

func (o *CompiledFunction) ParamTypes(vm *VM) (types MultipleObjectTypes, err error)

func (*CompiledFunction) Repr

func (o *CompiledFunction) Repr(vm *VM) (_ string, err error)

func (*CompiledFunction) SetNamedParams

func (o *CompiledFunction) SetNamedParams(params ...*NamedParam)

func (*CompiledFunction) SourcePos

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

SourcePos returns the source position of the instruction at ip.

func (*CompiledFunction) ToString

func (o *CompiledFunction) ToString() string

func (*CompiledFunction) Type

func (*CompiledFunction) Type() ObjectType

func (*CompiledFunction) ValidateParamTypes

func (o *CompiledFunction) ValidateParamTypes(vm *VM, args Args) (err error)

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(nd ast.Node) error

Compile compiles parser.Node and builds Bytecode.

func (*Compiler) CompileModule

func (c *Compiler) CompileModule(
	nd ast.Node,
	module *ModuleInfo,
	moduleMap *ModuleMap,
	src []byte,
	parserOptions *parser.ParserOptions,
	scannerOptions *parser.ScannerOptions,
) (bc *Bytecode, err error)

func (*Compiler) SetGlobalSymbolsIndex

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    ast.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 {
	Context             context.Context
	ModuleMap           *ModuleMap
	Module              *ModuleInfo
	ModuleFile          string
	Constants           []Object
	SymbolTable         *SymbolTable
	Trace               io.Writer
	TraceParser         bool
	TraceCompiler       bool
	TraceOptimizer      bool
	OptimizerMaxCycle   int
	OptimizeConst       bool
	OptimizeExpr        bool
	MixedWriteFunction  node.Expr
	MixedExprToTextFunc node.Expr
	// contains filtered or unexported fields
}

CompilerOptions represents customizable options for Compile().

type Copier

type Copier interface {
	Object
	Copy() Object
}

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

type Decimal

type Decimal decimal.Decimal

Decimal represents a fixed-point decimal. It is immutable. number = value * 10 ^ exp

func DecimalFromFloat

func DecimalFromFloat(v Float) Decimal

func DecimalFromInt

func DecimalFromInt(v Int) Decimal

func DecimalFromString

func DecimalFromString(v Str) (Decimal, error)

func DecimalFromUint

func DecimalFromUint(v Uint) Decimal

func MustDecimalFromString

func MustDecimalFromString(v Str) Decimal

func (Decimal) BinaryOp

func (o Decimal) BinaryOp(vm *VM, tok token.Token, right Object) (Object, error)

BinaryOp implements Object interface.

func (Decimal) CallName

func (o Decimal) CallName(name string, c Call) (_ Object, err error)

func (Decimal) Equal

func (o Decimal) Equal(right Object) bool

Equal implements Object interface.

func (Decimal) Format

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

Format implements fmt.Formatter interface.

func (Decimal) Go

func (o Decimal) Go() decimal.Decimal

func (*Decimal) GobDecode

func (o *Decimal) GobDecode(bytes []byte) (err error)

func (Decimal) GobEncode

func (o Decimal) GobEncode() ([]byte, error)

func (Decimal) IsFalsy

func (o Decimal) IsFalsy() bool

IsFalsy implements Object interface.

func (Decimal) ToBytes

func (o Decimal) ToBytes() (b Bytes, err error)

func (Decimal) ToString

func (o Decimal) ToString() string

func (Decimal) Type

func (o Decimal) Type() ObjectType

type DeepCopier

type DeepCopier interface {
	Object
	DeepCopy(vm *VM) (Object, error)
}

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

type Dict

type Dict map[string]Object

Dict represents map of objects and implements Object interface.

func AnyMapToMap

func AnyMapToMap(src map[string]any) (m Dict, err error)

func ToMap

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

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

func (Dict) BinaryOp

func (o Dict) BinaryOp(vm *VM, tok token.Token, right Object) (_ Object, err error)

BinaryOp implements Object interface.

func (Dict) Copy

func (o Dict) Copy() Object

Copy implements Copier interface.

func (Dict) DeepCopy

func (o Dict) DeepCopy(vm *VM) (_ Object, err error)

DeepCopy implements DeepCopier interface.

func (Dict) Equal

func (o Dict) Equal(right Object) bool

Equal implements Object interface.

func (Dict) Filter

func (o Dict) Filter(f func(k string, v Object) bool) Dict

func (Dict) Format

func (o Dict) Format(f fmt.State, verb rune)

func (Dict) IndexDelete

func (o Dict) IndexDelete(_ *VM, key Object) error

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

func (Dict) IndexGet

func (o Dict) IndexGet(_ *VM, index Object) (Object, error)

IndexGet implements Object interface.

func (Dict) IndexSet

func (o Dict) IndexSet(_ *VM, index, value Object) error

IndexSet implements Object interface.

func (Dict) IsFalsy

func (o Dict) IsFalsy() bool

IsFalsy implements Object interface.

func (Dict) Items

func (o Dict) Items(*VM) (KeyValueArray, error)

func (Dict) Iterate

func (o Dict) Iterate(_ *VM, na *NamedArgs) Iterator

func (Dict) Keys

func (o Dict) Keys() Array

func (Dict) Length

func (o Dict) Length() int

Length implements LengthGetter interface.

func (Dict) Repr

func (o Dict) Repr(vm *VM) (_ string, err error)

func (*Dict) Set

func (o *Dict) Set(key string, value Object)

func (Dict) SortedKeys

func (o Dict) SortedKeys() Array

func (Dict) ToInterface

func (o Dict) ToInterface(vm *VM) any

func (Dict) ToInterfaceMap

func (o Dict) ToInterfaceMap(vm *VM) (m map[string]any)

func (Dict) ToKeyValueArray

func (o Dict) ToKeyValueArray() KeyValueArray

func (Dict) ToString

func (o Dict) ToString() string

func (Dict) Type

func (o Dict) Type() ObjectType

func (Dict) Values

func (o Dict) Values() Array

type Error

type Error struct {
	Name    string
	Message string
	Cause   error
}

Error represents Error Object and implements error and Object interfaces.

func IsError

func IsError(a, b error) *Error

func NewArgumentTypeError

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

NewArgumentTypeError creates a new Error from ErrType.

func NewArgumentTypeErrorT

func NewArgumentTypeErrorT(pos string, foundType ObjectType, expectType ...ObjectType) *Error

NewArgumentTypeErrorT creates a new Error from ErrType.

func NewIndexTypeError

func NewIndexTypeError(expectType, foundType string) *Error

NewIndexTypeError creates a new Error from ErrType.

func NewIndexTypeErrorT

func NewIndexTypeErrorT(foundType ObjectType, expectType ...ObjectType) *Error

NewIndexTypeErrorT creates a new Error from ErrType.

func NewIndexValueTypeError

func NewIndexValueTypeError(expectType, foundType string) *Error

NewIndexValueTypeError creates a new Error from ErrType.

func NewIndexValueTypeErrorT

func NewIndexValueTypeErrorT(foundType ObjectType, expectType ...ObjectType) *Error

NewIndexValueTypeErrorT creates a new Error from ErrType.

func NewNamedArgumentTypeError

func NewNamedArgumentTypeError(name, expectType, foundType string) *Error

NewNamedArgumentTypeError creates a new Error from ErrType.

func NewOperandTypeError

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

NewOperandTypeError creates a new Error from ErrType.

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(_ *VM, index Object) (Object, error)

IndexGet implements Object interface.

func (*Error) IsFalsy

func (o *Error) IsFalsy() bool

IsFalsy 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) ToString

func (o *Error) ToString() string

func (*Error) Type

func (o *Error) Type() ObjectType

func (*Error) Unwrap

func (o *Error) Unwrap() error

type Eval

type Eval struct {
	Locals []Object
	*RunOpts
	Opts         CompileOptions
	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 CompileOptions, runOpts ...*RunOpts) *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 ExtImporter

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, error)
	// 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 Falser

type Falser interface {
	// IsFalsy returns true if value is falsy otherwise false.
	IsFalsy() bool
}

Falser represents an Falser object.

type Filterabler

type Filterabler interface {
	Object
	Filter(vm *VM, args Array, handler VMCaller) (Object, error)
}

type Flag

type Flag bool

func ToFlag

func ToFlag(o Object) (v Flag, ok bool)

ToFlag will try to convert an Object to Gad Flag value.

func (Flag) BinaryOp

func (o Flag) BinaryOp(vm *VM, tok token.Token, right Object) (Object, error)

func (Flag) Equal

func (o Flag) Equal(right Object) bool

Equal implements Object interface.

func (Flag) IsFalsy

func (o Flag) IsFalsy() bool

IsFalsy implements Object interface.

func (Flag) ToString

func (o Flag) ToString() string

func (Flag) Type

func (o Flag) Type() ObjectType

type Float

type Float float64

Float represents float values and implements Object interface.

func ToFloat

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

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

func (Float) BinaryOp

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

BinaryOp implements Object interface.

func (Float) Equal

func (o Float) Equal(right Object) bool

Equal implements Object interface.

func (Float) Format

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

Format implements fmt.Formatter interface.

func (Float) IsFalsy

func (o Float) IsFalsy() bool

IsFalsy implements Object interface.

func (Float) ToString

func (o Float) ToString() string

func (Float) Type

func (o Float) Type() ObjectType

type Function

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

Function represents a function object and implements Object interface.

func (*Function) Call

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

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

func (o *Function) ToString() string

func (*Function) Type

func (*Function) Type() ObjectType

type FunctionHeader

type FunctionHeader struct {
	Params      []Params
	NamedParams []Params
}

func (*FunctionHeader) String

func (h *FunctionHeader) String() string

type FunctionHeaderParam

type FunctionHeaderParam struct {
	Name  string
	Types []ObjectType
	Value string
}

func (*FunctionHeaderParam) String

func (p *FunctionHeaderParam) String() string

type Importable

type Importable interface {
	// Import should return either an Object or module source code ([]byte).
	Import(ctx context.Context, moduleName string) (data any, uri string, err error)
}

Importable interface represents importable module instance.

type IndexDelProxy

type IndexDelProxy struct {
	Del func(vm *VM, key Object) error
}

func (*IndexDelProxy) IndexDelete

func (p *IndexDelProxy) IndexDelete(vm *VM, key Object) error

type IndexDeleteProxy

type IndexDeleteProxy struct {
	IndexGetProxy
	IndexSetProxy
	IndexDelProxy
}

func (*IndexDeleteProxy) BinaryOp

func (o *IndexDeleteProxy) BinaryOp(vm *VM, tok token.Token, right Object) (_ Object, err error)

BinaryOp implements Object interface.

type IndexDeleter

type IndexDeleter interface {
	Object
	IndexDelete(vm *VM, key Object) error
}

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

type IndexGetProxy

type IndexGetProxy struct {
	GetIndex        func(vm *VM, index Object) (value Object, err error)
	ToStr           func() string
	It              func(vm *VM, na *NamedArgs) Iterator
	InterfaceValue  any
	CallNameHandler func(name string, c Call) (Object, error)
}

func StringIndexGetProxy

func StringIndexGetProxy(handler func(vm *VM, index string) (value Object, err error)) *IndexGetProxy

func (*IndexGetProxy) CallName

func (i *IndexGetProxy) CallName(name string, c Call) (Object, error)

func (*IndexGetProxy) CanIterate

func (i *IndexGetProxy) CanIterate() bool

func (*IndexGetProxy) Equal

func (i *IndexGetProxy) Equal(right Object) bool

func (IndexGetProxy) IndexGet

func (i IndexGetProxy) IndexGet(vm *VM, index Object) (value Object, err error)

func (*IndexGetProxy) IsFalsy

func (i *IndexGetProxy) IsFalsy() bool

func (*IndexGetProxy) Iterate

func (i *IndexGetProxy) Iterate(vm *VM, na *NamedArgs) Iterator

func (*IndexGetProxy) ToInterface

func (i *IndexGetProxy) ToInterface() any

func (*IndexGetProxy) ToString

func (i *IndexGetProxy) ToString() string

func (*IndexGetProxy) Type

func (i *IndexGetProxy) Type() ObjectType

type IndexGetSetter

type IndexGetSetter interface {
	IndexGetter
	IndexSetter
}

type IndexGetter

type IndexGetter interface {
	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. 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(vm *VM, index Object) (value Object, err error)
}

IndexGetter wraps the IndexGet method to get index value.

type IndexProxy

type IndexProxy struct {
	IndexGetProxy
	IndexSetProxy
}

func (*IndexProxy) BinaryOp

func (o *IndexProxy) BinaryOp(vm *VM, tok token.Token, right Object) (_ Object, err error)

BinaryOp implements Object interface.

type IndexSetProxy

type IndexSetProxy struct {
	Set func(vm *VM, key, value Object) error
}

func (*IndexSetProxy) IndexSet

func (s *IndexSetProxy) IndexSet(vm *VM, index, value Object) error

type IndexSetter

type IndexSetter interface {
	Object
	// 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(vm *VM, index, value Object) error
}

IndexSetter wraps the IndexSet method to set index value.

type IndexableStructField

type IndexableStructField struct {
	reflect.StructField
	Index []int
	Names []string
}

func FieldsOfReflectType

func FieldsOfReflectType(ityp reflect.Type) (result []*IndexableStructField)

type Indexer

type Indexer interface {
	IndexGetter
	IndexSetter
	IndexDeleter
}

type Int

type Int int64

Int represents signed integer values and implements Object interface.

func ToInt

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

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

func (Int) BinaryOp

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

BinaryOp implements Object interface.

func (Int) Equal

func (o Int) Equal(right Object) bool

Equal implements Object interface.

func (Int) Format

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

Format implements fmt.Formatter interface.

func (Int) IsFalsy

func (o Int) IsFalsy() bool

IsFalsy implements Object interface.

func (Int) ToString

func (o Int) ToString() string

func (Int) Type

func (o Int) Type() ObjectType

type Invoker

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 CallWrapper 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 CallWrapper 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 CallWrapper call.

func NewInvoker

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

NewInvoker creates a new Invoker object.

func (*Invoker) Acquire

func (inv *Invoker) Acquire()

Acquire acquires a VM from the pool.

func (*Invoker) Caller

func (inv *Invoker) Caller(args Args, namedArgs *NamedArgs) (VMCaller, error)

Caller create new VM caller object.

func (*Invoker) Invoke

func (inv *Invoker) Invoke(args Args, namedArgs *NamedArgs) (Object, error)

Invoke invokes the callee object with the given arguments.

func (*Invoker) Release

func (inv *Invoker) Release()

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

func (*Invoker) ValidArgs

func (inv *Invoker) ValidArgs(v bool) *Invoker

type ItemsGetter

type ItemsGetter interface {
	Object
	Items(vm *VM) (arr KeyValueArray, err error)
}

ItemsGetter is an interface for returns pairs of fields or keys with same values.

type Iterabler

type Iterabler interface {
	Object

	// Iterate should return an Iterator for the type.
	Iterate(vm *VM, na *NamedArgs) Iterator
}

type Iteration

type Iteration struct {
	StartHandler StartIterationHandler
	NextHandler  NextIterationHandler
	// contains filtered or unexported fields
}

func NewIterator

func NewIterator(start StartIterationHandler, next NextIterationHandler) *Iteration

func (*Iteration) Input

func (it *Iteration) Input() Object

func (*Iteration) ItType

func (it *Iteration) ItType() ObjectType

func (*Iteration) Next

func (it *Iteration) Next(vm *VM, state *IteratorState) (err error)

func (*Iteration) Repr

func (it *Iteration) Repr(vm *VM) (string, error)

func (*Iteration) SetInput

func (it *Iteration) SetInput(input Object) *Iteration

func (*Iteration) SetItType

func (it *Iteration) SetItType(itType ObjectType) *Iteration

func (*Iteration) Start

func (it *Iteration) Start(vm *VM) (state *IteratorState, err error)

func (*Iteration) Type

func (it *Iteration) Type() ObjectType

type Iterator

type Iterator interface {
	Representer
	Type() ObjectType
	Input() Object
	Start(vm *VM) (state *IteratorState, err error)
	Next(vm *VM, state *IteratorState) (err error)
}

Iterator wraps the methods required to iterate Objects in VM.

func CollectModeIterator

func CollectModeIterator(iterator Iterator, mode IteratorStateCollectMode) Iterator

func ToIterator

func ToIterator(vm *VM, obj Object, na *NamedArgs) (l int, it Iterator, err error)

func ZipIterator

func ZipIterator(its ...Iterator) Iterator

type IteratorState

type IteratorState struct {
	Mode        IteratorStateMode
	CollectMode IteratorStateCollectMode
	Entry       KeyValue
	Value       Object
}

func (IteratorState) Get

func (s IteratorState) Get() Object

type IteratorStateCollectMode

type IteratorStateCollectMode uint8
const (
	IteratorStateCollectModeValues IteratorStateCollectMode = iota
	IteratorStateCollectModeKeys
	IteratorStateCollectModePair
)

func (IteratorStateCollectMode) String

func (m IteratorStateCollectMode) String() string

type IteratorStateMode

type IteratorStateMode uint8
const (
	IteratorStateModeEntry IteratorStateMode = iota
	IteratorStateModeContinue
	IteratorStateModeDone
)

type KeyValue

type KeyValue struct {
	K, V Object
}

func (*KeyValue) BinaryOp

func (o *KeyValue) BinaryOp(vm *VM, tok token.Token, right Object) (Object, error)

BinaryOp implements Object interface.

func (KeyValue) Call

func (KeyValue) Call(*NamedArgs, ...Object) (Object, error)

Call implements Object interface.

func (KeyValue) CanCall

func (KeyValue) CanCall() bool

CanCall implements Object interface.

func (KeyValue) CanIterate

func (KeyValue) CanIterate() bool

CanIterate implements Object interface.

func (KeyValue) Copy

func (o KeyValue) Copy() Object

Copy implements Copier interface.

func (KeyValue) DeepCopy

func (o KeyValue) DeepCopy(vm *VM) (_ Object, err error)

DeepCopy implements DeepCopier interface.

func (*KeyValue) Equal

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

Equal implements Object interface.

func (*KeyValue) IndexGet

func (o *KeyValue) IndexGet(vm *VM, index Object) (value Object, err error)

func (*KeyValue) IndexSet

func (o *KeyValue) IndexSet(vm *VM, index, value Object) error

func (*KeyValue) IsFalsy

func (o *KeyValue) IsFalsy() bool

IsFalsy implements Object interface.

func (*KeyValue) IsLess

func (o *KeyValue) IsLess(vm *VM, other *KeyValue) bool

func (*KeyValue) Repr

func (o *KeyValue) Repr(vm *VM) (_ string, err error)

func (*KeyValue) ToString

func (o *KeyValue) ToString() string

func (*KeyValue) Type

func (o *KeyValue) Type() ObjectType

type KeyValueArray

type KeyValueArray []*KeyValue

func ItemsOf

func ItemsOf(vm *VM, o Object, na *NamedArgs) (values KeyValueArray, err error)

func (*KeyValueArray) Add

func (o *KeyValueArray) Add(_ *VM, items ...Object) (err error)

func (KeyValueArray) AddItems

func (o KeyValueArray) AddItems(arg ...*KeyValue) KeyValueArray

func (KeyValueArray) Append

func (o KeyValueArray) Append(_ *VM, items ...Object) (this Object, err error)

func (KeyValueArray) AppendArray

func (o KeyValueArray) AppendArray(arr ...Array) (KeyValueArray, error)

func (KeyValueArray) AppendMap

func (o KeyValueArray) AppendMap(m Dict) KeyValueArray

func (KeyValueArray) AppendObject

func (o KeyValueArray) AppendObject(obj Object) (KeyValueArray, error)

func (KeyValueArray) Array

func (o KeyValueArray) Array() (ret Array)

func (KeyValueArray) BinaryOp

func (o KeyValueArray) BinaryOp(_ *VM, tok token.Token, right Object) (Object, error)

BinaryOp implements Object interface.

func (KeyValueArray) Call

func (KeyValueArray) Call(*NamedArgs, ...Object) (Object, error)

Call implements Object interface.

func (KeyValueArray) CallName

func (o KeyValueArray) CallName(name string, c Call) (_ Object, err error)

func (KeyValueArray) CanCall

func (KeyValueArray) CanCall() bool

CanCall implements Object interface.

func (KeyValueArray) CanIterate

func (KeyValueArray) CanIterate() bool

CanIterate implements Object interface.

func (KeyValueArray) Copy

func (o KeyValueArray) Copy() Object

Copy implements Copier interface.

func (KeyValueArray) DeepCopy

func (o KeyValueArray) DeepCopy(vm *VM) (r Object, err error)

DeepCopy implements DeepCopier interface.

func (KeyValueArray) Delete

func (o KeyValueArray) Delete(keys ...Object) Object

func (KeyValueArray) Dict

func (o KeyValueArray) Dict() (ret Dict)

func (KeyValueArray) Equal

func (o KeyValueArray) Equal(right Object) bool

Equal implements Object interface.

func (KeyValueArray) Get

func (o KeyValueArray) Get(keys ...Object) Object

func (KeyValueArray) IndexGet

func (o KeyValueArray) IndexGet(_ *VM, index Object) (Object, error)

IndexGet implements Object interface.

func (KeyValueArray) IsFalsy

func (o KeyValueArray) IsFalsy() bool

IsFalsy implements Object interface.

func (KeyValueArray) Items

func (o KeyValueArray) Items(*VM) (KeyValueArray, error)

func (KeyValueArray) Iterate

func (o KeyValueArray) Iterate(_ *VM, na *NamedArgs) Iterator

func (KeyValueArray) Keys

func (o KeyValueArray) Keys() (arr Array)

func (KeyValueArray) Length

func (o KeyValueArray) Length() int

Length implements LengthGetter interface.

func (KeyValueArray) Repr

func (o KeyValueArray) Repr(vm *VM) (_ string, err error)

func (KeyValueArray) Sort

func (o KeyValueArray) Sort(vm *VM, less CallerObject) (_ Object, err error)

func (KeyValueArray) SortReverse

func (o KeyValueArray) SortReverse(vm *VM) (Object, error)

func (KeyValueArray) ToString

func (o KeyValueArray) ToString() string

func (KeyValueArray) Type

func (o KeyValueArray) Type() ObjectType

func (KeyValueArray) Values

func (o KeyValueArray) Values() (arr Array)

type KeyValueArrays

type KeyValueArrays []KeyValueArray

func (KeyValueArrays) Array

func (o KeyValueArrays) Array() (ret Array)

func (KeyValueArrays) BinaryOp

func (o KeyValueArrays) BinaryOp(_ *VM, tok token.Token, right Object) (Object, error)

BinaryOp implements Object interface.

func (KeyValueArrays) Call

func (KeyValueArrays) Call(*NamedArgs, ...Object) (Object, error)

Call implements Object interface.

func (KeyValueArrays) CallName

func (o KeyValueArrays) CallName(name string, c Call) (Object, error)

func (KeyValueArrays) CanCall

func (KeyValueArrays) CanCall() bool

CanCall implements Object interface.

func (KeyValueArrays) Copy

func (o KeyValueArrays) Copy() Object

Copy implements Copier interface.

func (KeyValueArrays) DeepCopy

func (o KeyValueArrays) DeepCopy(vm *VM) (_ Object, err error)

DeepCopy implements DeepCopier interface.

func (KeyValueArrays) Equal

func (o KeyValueArrays) Equal(right Object) bool

Equal implements Object interface.

func (KeyValueArrays) IndexGet

func (o KeyValueArrays) IndexGet(_ *VM, index Object) (Object, error)

IndexGet implements Object interface.

func (KeyValueArrays) IsFalsy

func (o KeyValueArrays) IsFalsy() bool

IsFalsy implements Object interface.

func (KeyValueArrays) Iterate

func (o KeyValueArrays) Iterate(_ *VM, na *NamedArgs) Iterator

func (KeyValueArrays) Length

func (o KeyValueArrays) Length() int

Length implements LengthGetter interface.

func (KeyValueArrays) Repr

func (o KeyValueArrays) Repr(vm *VM) (_ string, err error)

func (KeyValueArrays) ToString

func (o KeyValueArrays) ToString() string

func (KeyValueArrays) Type

func (KeyValueArrays) Type() ObjectType

type KeysGetter

type KeysGetter interface {
	Object
	Keys() (arr Array)
}

KeysGetter is an interface for returns keys or fields names.

type LengthGetter

type LengthGetter interface {
	Object
	Length() int
}

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

type LengthIterator

type LengthIterator interface {
	Iterator
	Length() int
}

type LimitedIterator

type LimitedIterator struct {
	Iterator
	Len int
}

func NewLimitedIteration

func NewLimitedIteration(it Iterator, len int) *LimitedIterator

func (*LimitedIterator) Length

func (it *LimitedIterator) Length() int

type Mapabler

type Mapabler interface {
	Object
	Map(c Call, update bool, keyValue Array, handler VMCaller) (Object, error)
}

type MethodArgType

type MethodArgType struct {
	Type    ObjectType
	Methods []*CallerMethod
	Next    Methods
}

func (*MethodArgType) Add

func (at *MethodArgType) Add(types MultipleObjectTypes, m *CallerMethod, override bool) error

func (*MethodArgType) GetMethod

func (at *MethodArgType) GetMethod(types []ObjectType) *CallerMethod

func (*MethodArgType) IsZero

func (at *MethodArgType) IsZero() (ok bool)

func (*MethodArgType) Walk

func (at *MethodArgType) Walk(cb func(m *CallerMethod) any) (v any)

func (*MethodArgType) WalkSorted

func (at *MethodArgType) WalkSorted(cb func(m *CallerMethod) any) (v any)

type MethodCaller

type MethodCaller interface {
	CallerObject
	AddCallerMethod(vm *VM, types MultipleObjectTypes, handler CallerObject, override bool) error
	CallerMethods() *MethodArgType
	CallerOf(args Args) (CallerObject, bool)
	CallerOfTypes(types []ObjectType) (co CallerObject, validate bool)
	GetMethod(types []ObjectType) (co CallerObject)
	HasCallerMethods() bool
	Caller() CallerObject
}

type MethodDefinition

type MethodDefinition struct {
	Args    []ObjectType
	Handler CallerObject
}

type Methods

type Methods map[ObjectType]*MethodArgType

func (Methods) Add

func (args Methods) Add(pth, types ObjectTypes, cm *CallerMethod, override bool) (err error)

func (Methods) GetMethod

func (args Methods) GetMethod(types []ObjectType) (cm *CallerMethod)

func (Methods) IsZero

func (args Methods) IsZero() (ok bool)

func (Methods) Walk

func (args Methods) Walk(cb func(m *CallerMethod) any) (rv any)

func (Methods) WalkSorted

func (args Methods) WalkSorted(cb func(m *CallerMethod) any) (rv any)

type ModuleInfo

type ModuleInfo struct {
	Name string
	File string
}

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

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

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

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

type MultipleObjectTypes

type MultipleObjectTypes []ObjectTypes

func (MultipleObjectTypes) Tree

type NameCallerObject

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 NamedArgVar

type NamedArgVar struct {
	Name   string
	Value  Object
	ValueF func() Object
	*TypeAssertion
}

NamedArgVar is a struct to destructure named arguments from Call object.

type NamedArgs

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

func NewNamedArgs

func NewNamedArgs(pairs ...KeyValueArray) *NamedArgs

func (*NamedArgs) Add

func (o *NamedArgs) Add(obj Object) error

func (*NamedArgs) AllDict

func (o *NamedArgs) AllDict() (ret Dict)

func (*NamedArgs) BinaryOp

func (o *NamedArgs) BinaryOp(_ *VM, tok token.Token, right Object) (Object, error)

func (*NamedArgs) Call

func (o *NamedArgs) Call(c Call) (Object, error)

func (*NamedArgs) CallName

func (o *NamedArgs) CallName(name string, c Call) (Object, error)

func (*NamedArgs) CheckNames

func (o *NamedArgs) CheckNames(accept ...string) error

func (*NamedArgs) CheckNamesFromSet

func (o *NamedArgs) CheckNamesFromSet(set map[string]int) error

func (*NamedArgs) Contains

func (o *NamedArgs) Contains(key string) bool

func (*NamedArgs) Copy

func (o *NamedArgs) Copy() Object

func (NamedArgs) DeepCopy

func (o NamedArgs) DeepCopy(vm *VM) (_ Object, err error)

func (*NamedArgs) Dict

func (o *NamedArgs) Dict() (ret Dict)

Dict return unread keys as Dict

func (*NamedArgs) Empty

func (o *NamedArgs) Empty() bool

Empty return if is empty

func (*NamedArgs) Equal

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

func (*NamedArgs) Get

func (o *NamedArgs) Get(dst ...*NamedArgVar) (err error)

Get destructure. Return errors: - ArgumentTypeError if type check of arg is fail. - UnexpectedNamedArg if have unexpected arg.

func (*NamedArgs) GetOne

func (o *NamedArgs) GetOne(dst ...*NamedArgVar) (err error)

GetOne get one value. Return errors: - ArgumentTypeError if type check of arg is fail.

func (*NamedArgs) GetPassedValue

func (o *NamedArgs) GetPassedValue(key string) (val Object)

GetPassedValue Get passed value

func (*NamedArgs) GetValue

func (o *NamedArgs) GetValue(key string) (val Object)

GetValue Must return value from key

func (*NamedArgs) GetValueOrNil

func (o *NamedArgs) GetValueOrNil(key string) (val Object)

GetValueOrNil Must return value from key

func (*NamedArgs) GetVar

func (o *NamedArgs) GetVar(dst ...*NamedArgVar) (args Dict, err error)

GetVar destructure and return others. Returns ArgumentTypeError if type check of arg is fail.

func (*NamedArgs) IndexGet

func (o *NamedArgs) IndexGet(vm *VM, index Object) (value Object, err error)

func (*NamedArgs) IsFalsy

func (o *NamedArgs) IsFalsy() bool

func (*NamedArgs) Iterate

func (o *NamedArgs) Iterate(vm *VM, na *NamedArgs) Iterator

func (*NamedArgs) Join

func (o *NamedArgs) Join() KeyValueArray

func (*NamedArgs) MustGetValue

func (o *NamedArgs) MustGetValue(key string) (val Object)

MustGetValue Must return value from key but not takes as read

func (*NamedArgs) MustGetValueOrNil

func (o *NamedArgs) MustGetValueOrNil(key string) (val Object)

MustGetValueOrNil Must return value from key nut not takes as read

func (*NamedArgs) Ready

func (o *NamedArgs) Ready() (arr KeyValueArray)

func (*NamedArgs) ToString

func (o *NamedArgs) ToString() string

func (*NamedArgs) Type

func (o *NamedArgs) Type() ObjectType

func (*NamedArgs) UnReady

func (o *NamedArgs) UnReady() *NamedArgs

func (*NamedArgs) UnreadPairs

func (o *NamedArgs) UnreadPairs() (ret KeyValueArray)

func (*NamedArgs) Walk

func (o *NamedArgs) Walk(cb func(na *KeyValue) error) (err error)

Walk pass over all pairs and call `cb` function. if `cb` function returns any error, stop iterator and return then.

type NamedParam

type NamedParam struct {
	Name string
	// Value is a script of default value
	Value string
	Index int
	Type  []*SymbolInfo
}

func NewNamedParam

func NewNamedParam(name string, value string) *NamedParam

type NamedParams

type NamedParams struct {
	Params []*NamedParam
	// contains filtered or unexported fields
}

func NewNamedParams

func NewNamedParams(params ...*NamedParam) (np *NamedParams)

func (*NamedParams) ByName

func (n *NamedParams) ByName() map[string]int

func (*NamedParams) Len

func (n *NamedParams) Len() int

func (*NamedParams) Names

func (n *NamedParams) Names() (names []string)

func (*NamedParams) String

func (n *NamedParams) String() string

func (*NamedParams) ToMap

func (n *NamedParams) ToMap() (np map[string]*NamedParam)

func (*NamedParams) Variadic

func (n *NamedParams) Variadic() bool

type NextIterationHandler

type NextIterationHandler func(vm *VM, state *IteratorState) (err error)

type NilType

type NilType struct {
	ObjectImpl
}

NilType represents the type of global Nil Object. One should use the NilType in type switches only.

func (*NilType) BinaryOp

func (o *NilType) BinaryOp(_ *VM, tok token.Token, right Object) (Object, error)

BinaryOp implements Object interface.

func (*NilType) Equal

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

Equal implements Object interface.

func (*NilType) Format

func (o *NilType) Format(f fmt.State, verb rune)

func (*NilType) IsNil

func (o *NilType) IsNil() bool

func (*NilType) ToString

func (o *NilType) ToString() string

func (*NilType) Type

func (o *NilType) Type() ObjectType

type Niler

type Niler interface {
	Object
	IsNil() bool
}

type Obj

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

Obj represents map of objects and implements Object interface.

func (*Obj) CallName

func (o *Obj) CallName(name string, c Call) (_ Object, err error)

func (*Obj) CastTo

func (o *Obj) CastTo(vm *VM, t ObjectType) (Object, error)

func (Obj) Copy

func (o Obj) Copy() Object

Copy implements Copier interface.

func (Obj) DeepCopy

func (o Obj) DeepCopy(vm *VM) (r Object, err error)

DeepCopy implements DeepCopier interface.

func (*Obj) Equal

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

Equal implements Object interface.

func (*Obj) Fields

func (o *Obj) Fields() Dict

func (*Obj) IndexDelete

func (o *Obj) IndexDelete(_ *VM, key Object) error

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

func (*Obj) IndexGet

func (o *Obj) IndexGet(vm *VM, index Object) (Object, error)

IndexGet implements Object interface.

func (*Obj) IndexSet

func (o *Obj) IndexSet(vm *VM, index, value Object) (err error)

IndexSet implements Object interface.

func (*Obj) IsFalsy

func (o *Obj) IsFalsy() bool

IsFalsy implements Object interface.

func (*Obj) Items

func (o *Obj) Items(vm *VM) (KeyValueArray, error)

func (*Obj) Keys

func (o *Obj) Keys() Array

func (*Obj) Length

func (o *Obj) Length() int

Length implements LengthGetter interface.

func (*Obj) ToString

func (o *Obj) ToString() string

func (*Obj) Type

func (o *Obj) Type() ObjectType

func (*Obj) Values

func (o *Obj) Values() Array

type ObjType

type ObjType struct {
	TypeName    string
	FieldsDict  Dict
	SettersDict Dict
	MethodsDict Dict
	GettersDict Dict
	Inherits    ObjectTypeArray
	// contains filtered or unexported fields
}

ObjType represents type objects and implements Object interface.

func NewObjType

func NewObjType(typeName string) *ObjType

func (*ObjType) AddCallerMethod

func (o *ObjType) AddCallerMethod(vm *VM, types MultipleObjectTypes, handler CallerObject, override bool) error

func (*ObjType) BinaryOp

func (o *ObjType) BinaryOp(_ *VM, tok token.Token, right Object) (Object, error)

func (*ObjType) Call

func (o *ObjType) Call(c Call) (_ Object, err error)

func (*ObjType) CallName

func (o *ObjType) CallName(name string, c Call) (ret Object, err error)

func (*ObjType) Caller

func (o *ObjType) Caller() CallerObject

func (*ObjType) CallerMethods

func (o *ObjType) CallerMethods() *MethodArgType

func (*ObjType) CallerOf

func (o *ObjType) CallerOf(args Args) (co CallerObject, ok bool)

func (*ObjType) CallerOfTypes

func (o *ObjType) CallerOfTypes(types []ObjectType) (co CallerObject, validate bool)

func (*ObjType) Equal

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

Equal implements Object interface.

func (*ObjType) Fields

func (o *ObjType) Fields() Dict

func (*ObjType) Format

func (o *ObjType) Format(f fmt.State, verb rune)

func (*ObjType) GetMethod

func (o *ObjType) GetMethod(types []ObjectType) (co CallerObject)

func (*ObjType) Getters

func (o *ObjType) Getters() Dict

func (*ObjType) HasCallerMethods

func (o *ObjType) HasCallerMethods() bool

func (*ObjType) IndexGet

func (o *ObjType) IndexGet(_ *VM, index Object) (value Object, err error)

func (*ObjType) IsChildOf

func (o *ObjType) IsChildOf(t ObjectType) bool

func (ObjType) IsFalsy

func (ObjType) IsFalsy() bool

func (*ObjType) Methods

func (o *ObjType) Methods() Dict

func (*ObjType) Name

func (o *ObjType) Name() string

func (*ObjType) New

func (o *ObjType) New(_ *VM, fields Dict) (Object, error)

func (*ObjType) NewCall

func (o *ObjType) NewCall(c Call) (Object, error)

func (*ObjType) Setters

func (o *ObjType) Setters() Dict

func (*ObjType) ToString

func (o *ObjType) ToString() string

func (*ObjType) Type

func (o *ObjType) Type() ObjectType

type Object

type Object interface {
	Falser

	// OpDotName should return the name of the type.
	Type() ObjectType

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

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

Object represents an object in the VM.

var (
	// Nil represents nil value.
	Nil Object = &NilType{}
)

func BuiltinAppendFunc

func BuiltinAppendFunc(c Call) (Object, error)

func BuiltinBinaryOpFunc

func BuiltinBinaryOpFunc(c Call) (ret Object, err error)

func BuiltinBoolFunc

func BuiltinBoolFunc(arg Object) Object

func BuiltinBufferFunc

func BuiltinBufferFunc(c Call) (ret Object, err error)

func BuiltinBytesFunc

func BuiltinBytesFunc(c Call) (Object, error)

func BuiltinCapFunc

func BuiltinCapFunc(arg Object) Object

func BuiltinCastFunc

func BuiltinCastFunc(c Call) (ret Object, err error)

func BuiltinCharFunc

func BuiltinCharFunc(arg Object) (Object, error)

func BuiltinCharsFunc

func BuiltinCharsFunc(arg Object) (ret Object, err error)

func BuiltinCollectFunc

func BuiltinCollectFunc(c Call) (_ Object, err error)

func BuiltinContainsFunc

func BuiltinContainsFunc(arg0, arg1 Object) (Object, error)

func BuiltinCopyFunc

func BuiltinCopyFunc(c Call) (_ Object, err error)

func BuiltinDecimalFunc

func BuiltinDecimalFunc(vm *VM, v Object) (Object, error)

func BuiltinDeepCopyFunc

func BuiltinDeepCopyFunc(c Call) (_ Object, err error)

func BuiltinDeleteFunc

func BuiltinDeleteFunc(c Call) (_ Object, err error)

func BuiltinDictFunc

func BuiltinDictFunc(c Call) (ret Object, err error)

func BuiltinEachFunc

func BuiltinEachFunc(c Call) (_ Object, err error)

func BuiltinEnumerateFunc

func BuiltinEnumerateFunc(c Call) (_ Object, err error)

func BuiltinErrorFunc

func BuiltinErrorFunc(arg Object) Object

func BuiltinFilterFunc

func BuiltinFilterFunc(c Call) (_ Object, err error)

func BuiltinFlagFunc

func BuiltinFlagFunc(arg Object) Object

func BuiltinFloatFunc

func BuiltinFloatFunc(v float64) Object

func BuiltinFlushFunc

func BuiltinFlushFunc(c Call) (Object, error)

func BuiltinGlobalsFunc

func BuiltinGlobalsFunc(c Call) (Object, error)

func BuiltinIntFunc

func BuiltinIntFunc(v int64) Object

func BuiltinIsArrayFunc

func BuiltinIsArrayFunc(arg Object) Object

func BuiltinIsBoolFunc

func BuiltinIsBoolFunc(arg Object) Object

func BuiltinIsBytesFunc

func BuiltinIsBytesFunc(arg Object) Object

func BuiltinIsCallableFunc

func BuiltinIsCallableFunc(arg Object) Object

func BuiltinIsCharFunc

func BuiltinIsCharFunc(arg Object) Object

func BuiltinIsDictFunc

func BuiltinIsDictFunc(arg Object) Object

func BuiltinIsErrorFunc

func BuiltinIsErrorFunc(c Call) (ret Object, err error)

func BuiltinIsFloatFunc

func BuiltinIsFloatFunc(arg Object) Object

func BuiltinIsFunc

func BuiltinIsFunc(c Call) (ok Object, err error)

func BuiltinIsFunctionFunc

func BuiltinIsFunctionFunc(arg Object) Object

func BuiltinIsIntFunc

func BuiltinIsIntFunc(arg Object) Object

func BuiltinIsIterableFunc

func BuiltinIsIterableFunc(vm *VM, arg Object) Object

func BuiltinIsIteratorFunc

func BuiltinIsIteratorFunc(arg Object) Object

func BuiltinIsNilFunc

func BuiltinIsNilFunc(arg Object) Object

func BuiltinIsRawStrFunc

func BuiltinIsRawStrFunc(arg Object) Object

func BuiltinIsStrFunc

func BuiltinIsStrFunc(arg Object) Object

func BuiltinIsSyncDictFunc

func BuiltinIsSyncDictFunc(arg Object) Object

func BuiltinIsUintFunc

func BuiltinIsUintFunc(arg Object) Object

func BuiltinItemsFunc

func BuiltinItemsFunc(c Call) (_ Object, err error)

func BuiltinIterateFunc

func BuiltinIterateFunc(c Call) (_ Object, err error)

func BuiltinIteratorInputFunc

func BuiltinIteratorInputFunc(o Object) Object

func BuiltinKeyValueArrayFunc

func BuiltinKeyValueArrayFunc(c Call) (_ Object, err error)

func BuiltinKeyValueFunc

func BuiltinKeyValueFunc(c Call) (ret Object, err error)

func BuiltinKeysFunc

func BuiltinKeysFunc(c Call) (_ Object, err error)

func BuiltinLenFunc

func BuiltinLenFunc(arg Object) Object

func BuiltinMakeArrayFunc

func BuiltinMakeArrayFunc(n int, arg Object) (Object, error)

func BuiltinMapFunc

func BuiltinMapFunc(c Call) (_ Object, err error)

func BuiltinNamedParamTypeCheckFunc

func BuiltinNamedParamTypeCheckFunc(c Call) (val Object, err error)

func BuiltinNewFunc

func BuiltinNewFunc(c Call) (ret Object, err error)

func BuiltinOBEndFunc

func BuiltinOBEndFunc(c Call) (ret Object, err error)

func BuiltinOBStartFunc

func BuiltinOBStartFunc(c Call) (ret Object, err error)

func BuiltinPopWriterFunc

func BuiltinPopWriterFunc(c Call) (ret Object, err error)

func BuiltinPrintFunc

func BuiltinPrintFunc(c Call) (_ Object, err error)

func BuiltinPrintfFunc

func BuiltinPrintfFunc(c Call) (_ Object, err error)

func BuiltinPrintlnFunc

func BuiltinPrintlnFunc(c Call) (ret Object, err error)

func BuiltinPushWriterFunc

func BuiltinPushWriterFunc(c Call) (ret Object, err error)

func BuiltinRawCallerFunc

func BuiltinRawCallerFunc(c Call) (ret Object, err error)

func BuiltinRawStrFunc

func BuiltinRawStrFunc(c Call) (ret Object, err error)

func BuiltinReduceFunc

func BuiltinReduceFunc(c Call) (_ Object, err error)

func BuiltinRepeatFunc

func BuiltinRepeatFunc(arg Object, count int) (ret Object, err error)

func BuiltinReprFunc

func BuiltinReprFunc(c Call) (_ Object, err error)

func BuiltinSortFunc

func BuiltinSortFunc(vm *VM, arg Object, less CallerObject) (ret Object, err error)

func BuiltinSortReverseFunc

func BuiltinSortReverseFunc(vm *VM, arg Object, less CallerObject) (Object, error)

func BuiltinSprintfFunc

func BuiltinSprintfFunc(c Call) (ret Object, err error)

func BuiltinStdIOFunc

func BuiltinStdIOFunc(c Call) (ret Object, err error)

func BuiltinStringFunc

func BuiltinStringFunc(c Call) (ret Object, err error)

func BuiltinStructFunc

func BuiltinStructFunc(c Call) (ret Object, err error)

func BuiltinSyncDictFunc

func BuiltinSyncDictFunc(c Call) (ret Object, err error)

func BuiltinTypeNameFunc

func BuiltinTypeNameFunc(arg Object) Object

func BuiltinTypeOfFunc

func BuiltinTypeOfFunc(c Call) (_ Object, err error)

func BuiltinUintFunc

func BuiltinUintFunc(v uint64) Object

func BuiltinUserDataFunc

func BuiltinUserDataFunc(c Call) (_ Object, err error)

func BuiltinValuesFunc

func BuiltinValuesFunc(c Call) (_ Object, err error)

func BuiltinWrapFunc

func BuiltinWrapFunc(c Call) (ret Object, err error)

func BuiltinWriteFunc

func BuiltinWriteFunc(c Call) (ret Object, err error)

func Copy

func Copy(o Object) Object

func DeepCopy

func DeepCopy(vm *VM, o Object) (Object, error)

func DoCall

func DoCall(co CallerObject, c Call) (ret Object, err error)

func IteratorObject

func IteratorObject(it Iterator) Object

func MustCall

func MustCall(callee Object, args ...Object) (Object, error)

func MustCallVargs

func MustCallVargs(callee Object, args []Object, vargs ...Object) (Object, error)

func MustToObject

func MustToObject(v any) (ret Object)

func ToObject

func ToObject(v any) (ret Object, err error)

ToObject 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.

func TypedIteratorObject

func TypedIteratorObject(typ ObjectType, it Iterator) Object

func Val

func Val(v Object, e error) (ret Object, err error)

type ObjectConverters

type ObjectConverters struct {
	ToGoHandlers     map[ObjectType]func(vm *VM, v Object) any
	ToObjectHandlers map[reflect.Type]func(vm *VM, v any) (Object, error)
}

func NewObjectConverters

func NewObjectConverters() *ObjectConverters

func (*ObjectConverters) Register

func (oc *ObjectConverters) Register(objType ObjectType, togo func(vm *VM, v Object) any, goType reflect.Type, toObject func(vm *VM, v any) (Object, error)) *ObjectConverters

func (*ObjectConverters) ToInterface

func (oc *ObjectConverters) ToInterface(vm *VM, v Object) any

func (*ObjectConverters) ToObject

func (oc *ObjectConverters) ToObject(vm *VM, v any) (Object, error)

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. Str and OpDotName must be implemented otherwise calling these methods causes panic.

func (ObjectImpl) Equal

func (ObjectImpl) Equal(Object) bool

Equal implements Object interface.

func (ObjectImpl) IsFalsy

func (ObjectImpl) IsFalsy() bool

IsFalsy implements Object interface.

func (ObjectImpl) ToString

func (ObjectImpl) ToString() string

func (ObjectImpl) Type

func (ObjectImpl) Type() ObjectType

type ObjectIterator

type ObjectIterator interface {
	Object
	Iterator
	GetIterator() Iterator
}

type ObjectPtr

type ObjectPtr struct {
	ObjectImpl
	Value *Object
}

ObjectPtr represents a pointer variable.

func (*ObjectPtr) BinaryOp

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

BinaryOp implements Object interface.

func (*ObjectPtr) Call

func (o *ObjectPtr) Call(c Call) (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) DeepCopy

func (o *ObjectPtr) DeepCopy(*VM) (Object, error)

DeepCopy implements DeepCopier 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) ToString

func (o *ObjectPtr) ToString() string

func (*ObjectPtr) Type

func (o *ObjectPtr) Type() ObjectType

type ObjectRepresenter

type ObjectRepresenter interface {
	Object
	Representer
}

type ObjectToWriter

type ObjectToWriter interface {
	WriteTo(vm *VM, w io.Writer, obj Object) (handled bool, n int64, err error)
}

type ObjectToWriterFunc

type ObjectToWriterFunc func(vm *VM, w io.Writer, obj Object) (handled bool, n int64, err error)
var DefaultObjectToWrite ObjectToWriterFunc = func(vm *VM, w io.Writer, obj Object) (handled bool, n int64, err error) {
	if ToWritable(obj) {
		n, err = obj.(ToWriter).WriteTo(vm, w)
	} else {
		var s Object
		if s, err = Val(vm.Builtins.Call(BuiltinRawStr, Call{VM: vm, Args: Args{Array{obj}}})); err != nil {
			return false, 0, err
		}
		var n32 int
		n32, err = w.Write([]byte(s.(RawStr)))
		n += int64(n32)
	}
	handled = true
	return
}

func (ObjectToWriterFunc) WriteTo

func (f ObjectToWriterFunc) WriteTo(vm *VM, w io.Writer, obj Object) (handled bool, n int64, err error)

type ObjectToWriters

type ObjectToWriters []ObjectToWriter

func (ObjectToWriters) Append

func (o ObjectToWriters) Append(handlers ...ObjectToWriter) ObjectToWriters

func (ObjectToWriters) Prepend

func (o ObjectToWriters) Prepend(handlers ...ObjectToWriter) ObjectToWriters

func (ObjectToWriters) WriteTo

func (o ObjectToWriters) WriteTo(vm *VM, w io.Writer, obj Object) (handled bool, n int64, err error)

type ObjectType

type ObjectType interface {
	Object
	CallerObject
	Name() string
	Getters() Dict
	Setters() Dict
	Methods() Dict
	Fields() Dict
	New(vm *VM, fields Dict) (Object, error)
	IsChildOf(t ObjectType) bool
}

func DetectTypeOf

func DetectTypeOf(arg Object) ObjectType

func TypeOf

func TypeOf(arg Object) ObjectType

func TypesOf

func TypesOf(obj Object) (types []ObjectType)

type ObjectTypeArray

type ObjectTypeArray []ObjectType

func (ObjectTypeArray) Array

func (o ObjectTypeArray) Array() Array

func (ObjectTypeArray) Equal

func (o ObjectTypeArray) Equal(right Object) bool

func (ObjectTypeArray) IsFalsy

func (o ObjectTypeArray) IsFalsy() bool

func (ObjectTypeArray) ToString

func (o ObjectTypeArray) ToString() string

func (ObjectTypeArray) Type

func (o ObjectTypeArray) Type() ObjectType

type ObjectTypeNode

type ObjectTypeNode struct {
	Type     ObjectType
	Children []*ObjectTypeNode
}

func (*ObjectTypeNode) Append

func (n *ObjectTypeNode) Append(o MultipleObjectTypes)

func (*ObjectTypeNode) Walk

func (n *ObjectTypeNode) Walk(cb func(types ObjectTypes) any) any

func (*ObjectTypeNode) WalkE

func (n *ObjectTypeNode) WalkE(cb func(types ObjectTypes) any) error

type ObjectTypes

type ObjectTypes []ObjectType

func (ObjectTypes) String

func (t ObjectTypes) String() string

type Objector

type Objector interface {
	Object
	Fields() Dict
}

type OpCallFlag

type OpCallFlag byte
const (
	OpCallFlagVarArgs OpCallFlag = 1 << iota
	OpCallFlagNamedArgs
	OpCallFlagVarNamedArgs
)

func (OpCallFlag) Has

func (f OpCallFlag) Has(other OpCallFlag) bool

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
	OpStdIn
	OpStdOut
	OpStdErr
	OpDotName
	OpDotFile
	OpIsModule
	OpPop
	OpGetFree
	OpSetFree
	OpGetLocalPtr
	OpGetFreePtr
	OpClosure
	OpIterInit
	OpIterNext
	OpIterNextElse
	OpIterKey
	OpIterValue
	OpLoadModule
	OpStoreModule
	OpSetupTry
	OpSetupCatch
	OpSetupFinally
	OpThrow
	OpFinalizer
	OpReturn
	OpDefineLocal
	OpTrue
	OpFalse
	OpYes
	OpNo
	OpCallName
	OpJumpNil
	OpJumpNotNil
	OpKeyValueArray
	OpKeyValue
	OpCallee
	OpArgs
	OpNamedArgs
	OpTextWriter
	OpIsNil
	OpNotIsNil
)

List of opcodes

func (Opcode) String

func (o Opcode) String() string

type OptimizerError

type OptimizerError struct {
	FilePos parser.SourceFilePos
	Node    ast.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 ParamType

type ParamType []*SymbolInfo

func (ParamType) Accept

func (t ParamType) Accept(vm *VM, ot ObjectType) (ok bool, err error)

func (ParamType) String

func (t ParamType) String() string

type Params

type Params struct {
	Names []string
	Type  []ParamType
	Typed bool
	Len   int
	Var   bool
}

func (*Params) Min

func (p *Params) Min() int

func (*Params) String

func (p *Params) String() string

type PipedInvokeIterator

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

func NewPipedInvokeIterator

func NewPipedInvokeIterator(it Iterator, args Array, startArgValueIndex int, caller VMCaller) (fe *PipedInvokeIterator)

func (*PipedInvokeIterator) Call

func (f *PipedInvokeIterator) Call(state *IteratorState) (err error)

func (*PipedInvokeIterator) Handler

func (f *PipedInvokeIterator) Handler() func(state *IteratorState) error

func (*PipedInvokeIterator) Input

func (f *PipedInvokeIterator) Input() Object

func (*PipedInvokeIterator) Next

func (f *PipedInvokeIterator) Next(vm *VM, state *IteratorState) (err error)

func (*PipedInvokeIterator) PostCall

func (f *PipedInvokeIterator) PostCall() func(state *IteratorState, ret Object) error

func (*PipedInvokeIterator) PreCall

func (f *PipedInvokeIterator) PreCall() func(k, v Object) (Object, error)

func (*PipedInvokeIterator) Repr

func (f *PipedInvokeIterator) Repr(vm *VM) (s string, err error)

func (*PipedInvokeIterator) SetHandler

func (f *PipedInvokeIterator) SetHandler(handler func(state *IteratorState) error) *PipedInvokeIterator

func (*PipedInvokeIterator) SetPostCall

func (f *PipedInvokeIterator) SetPostCall(postCall func(state *IteratorState, ret Object) error) *PipedInvokeIterator

func (*PipedInvokeIterator) SetPreCall

func (f *PipedInvokeIterator) SetPreCall(preCall func(k, v Object) (Object, error)) *PipedInvokeIterator

func (*PipedInvokeIterator) SetType

func (*PipedInvokeIterator) Start

func (f *PipedInvokeIterator) Start(vm *VM) (state *IteratorState, err error)

func (*PipedInvokeIterator) Type

func (f *PipedInvokeIterator) Type() ObjectType

type RangeIteration

type RangeIteration struct {
	It     Object
	ItType ObjectType

	Len    int
	ReadTo func(e *KeyValue, i int) error
	// contains filtered or unexported fields
}

func NewRangeIteration

func NewRangeIteration(typ ObjectType, o Object, len int, readTo func(e *KeyValue, i int) error) *RangeIteration

func SliceEntryIteration

func SliceEntryIteration[T any](typ ObjectType, o Object, items []T, get func(v T) (key Object, val Object, err error)) *RangeIteration

func SliceIteration

func SliceIteration[T any](typ ObjectType, o Object, items []T, get func(e *KeyValue, i Int, v T) error) *RangeIteration

func (*RangeIteration) Input

func (it *RangeIteration) Input() Object

func (*RangeIteration) Length

func (it *RangeIteration) Length() int

func (*RangeIteration) Next

func (it *RangeIteration) Next(_ *VM, state *IteratorState) (err error)

func (*RangeIteration) ParseNamedArgs

func (it *RangeIteration) ParseNamedArgs(na *NamedArgs) *RangeIteration

func (*RangeIteration) Repr

func (it *RangeIteration) Repr(vm *VM) (string, error)

func (*RangeIteration) SetReversed

func (it *RangeIteration) SetReversed(v bool) *RangeIteration

func (*RangeIteration) Start

func (it *RangeIteration) Start(*VM) (state *IteratorState, err error)

func (*RangeIteration) Type

func (it *RangeIteration) Type() ObjectType

type RawStr

type RawStr string

RawStr represents safe string values and implements Object interface.

func ToRawStr

func ToRawStr(vm *VM, o Object) (_ RawStr, err error)

func (RawStr) BinaryOp

func (o RawStr) BinaryOp(_ *VM, tok token.Token, right Object) (Object, error)

BinaryOp implements Object interface.

func (RawStr) Equal

func (o RawStr) Equal(right Object) bool

func (RawStr) Format

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

Format implements fmt.Formatter interface.

func (RawStr) IndexGet

func (o RawStr) IndexGet(_ *VM, index Object) (Object, error)

func (RawStr) IsFalsy

func (o RawStr) IsFalsy() bool

func (RawStr) Iterate

func (o RawStr) Iterate(_ *VM, na *NamedArgs) Iterator

func (RawStr) Length

func (o RawStr) Length() int

Length implements LengthGetter interface.

func (RawStr) Quoted

func (o RawStr) Quoted() string

func (RawStr) Repr

func (o RawStr) Repr(*VM) (string, error)

func (RawStr) ToString

func (o RawStr) ToString() string

func (RawStr) Type

func (o RawStr) Type() ObjectType

func (RawStr) WriteTo

func (o RawStr) WriteTo(_ *VM, w io.Writer) (int64, error)

type ReadWriter

type ReadWriter interface {
	Writer
	Reader
}

type Reader

type Reader interface {
	Object
	io.Reader
	GoReader() io.Reader
}

func NewReader

func NewReader(r io.Reader) Reader

type Reducer

type Reducer interface {
	Object
	Reduce(vm *VM, initialValue Object, args Array, handler VMCaller) (Object, error)
}

type ReflectArray

type ReflectArray struct {
	ReflectValue
}

func (*ReflectArray) Copy

func (o *ReflectArray) Copy() (obj Object)

func (*ReflectArray) Format

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

func (*ReflectArray) Get

func (o *ReflectArray) Get(vm *VM, i int) (value Object, err error)

func (*ReflectArray) IndexGet

func (o *ReflectArray) IndexGet(vm *VM, index Object) (value Object, err error)

func (*ReflectArray) IndexSet

func (o *ReflectArray) IndexSet(vm *VM, index, value Object) (err error)

func (*ReflectArray) IsFalsy

func (o *ReflectArray) IsFalsy() bool

func (*ReflectArray) Iterate

func (o *ReflectArray) Iterate(vm *VM, na *NamedArgs) Iterator

func (*ReflectArray) Length

func (o *ReflectArray) Length() int

func (*ReflectArray) Repr

func (o *ReflectArray) Repr(vm *VM) (_ string, err error)

func (*ReflectArray) ToString

func (o *ReflectArray) ToString() string

type ReflectField

type ReflectField struct {
	BaseType reflect.Type
	IsPtr    bool
	Struct   IndexableStructField
	Value    reflect.Value
}

func (*ReflectField) Equal

func (r *ReflectField) Equal(right Object) bool

func (*ReflectField) IsFalsy

func (r *ReflectField) IsFalsy() bool

func (*ReflectField) Set

func (r *ReflectField) Set(f reflect.Value, v Object)

func (*ReflectField) String

func (r *ReflectField) String() string

func (*ReflectField) ToString

func (r *ReflectField) ToString() string

func (*ReflectField) Type

func (r *ReflectField) Type() ObjectType

type ReflectFunc

type ReflectFunc struct {
	ReflectValue
}

func (*ReflectFunc) Call

func (r *ReflectFunc) Call(c Call) (_ Object, err error)

func (*ReflectFunc) ToString

func (r *ReflectFunc) ToString() string

type ReflectMap

type ReflectMap struct {
	ReflectValue
}

func (*ReflectMap) Copy

func (o *ReflectMap) Copy() (obj Object)

func (*ReflectMap) Format

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

func (*ReflectMap) IndexDelete

func (o *ReflectMap) IndexDelete(vm *VM, index Object) (err error)

func (*ReflectMap) IndexGet

func (o *ReflectMap) IndexGet(vm *VM, index Object) (value Object, err error)

func (*ReflectMap) IndexSet

func (o *ReflectMap) IndexSet(vm *VM, index, value Object) (err error)

func (*ReflectMap) IsFalsy

func (o *ReflectMap) IsFalsy() bool

func (*ReflectMap) Iterate

func (o *ReflectMap) Iterate(vm *VM, na *NamedArgs) Iterator

func (*ReflectMap) Length

func (o *ReflectMap) Length() int

func (*ReflectMap) Repr

func (o *ReflectMap) Repr(vm *VM) (_ string, err error)

func (*ReflectMap) ToString

func (o *ReflectMap) ToString() string

type ReflectMethod

type ReflectMethod struct {
	Method reflect.Method
	// contains filtered or unexported fields
}

func (*ReflectMethod) Equal

func (r *ReflectMethod) Equal(right Object) bool

func (*ReflectMethod) IsFalsy

func (r *ReflectMethod) IsFalsy() bool

func (*ReflectMethod) ToString

func (r *ReflectMethod) ToString() string

func (*ReflectMethod) Type

func (r *ReflectMethod) Type() ObjectType

type ReflectSlice

type ReflectSlice struct {
	ReflectArray
}

func (*ReflectSlice) Append

func (o *ReflectSlice) Append(vm *VM, items ...Object) (_ Object, err error)

func (*ReflectSlice) Copy

func (o *ReflectSlice) Copy() (obj Object)

func (*ReflectSlice) Format

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

func (*ReflectSlice) Insert

func (o *ReflectSlice) Insert(vm *VM, at int, items ...Object) (_ Object, err error)

func (*ReflectSlice) Slice

func (o *ReflectSlice) Slice(low, high int) Object

func (*ReflectSlice) ToString

func (o *ReflectSlice) ToString() string

type ReflectStruct

type ReflectStruct struct {
	ReflectValue

	Data      Dict
	Interface any
	// contains filtered or unexported fields
}

func (*ReflectStruct) CallName

func (s *ReflectStruct) CallName(name string, c Call) (Object, error)

func (*ReflectStruct) Copy

func (s *ReflectStruct) Copy() (obj Object)

func (*ReflectStruct) FalbackIndexHandler

func (s *ReflectStruct) FalbackIndexHandler(handler func(vm *VM, s *ReflectStruct, name string) (handled bool, value any, err error)) *ReflectStruct

func (*ReflectStruct) Field

func (s *ReflectStruct) Field(vm *VM, name string) (handled bool, value any, err error)

func (*ReflectStruct) FieldHandler

func (s *ReflectStruct) FieldHandler(handler func(vm *VM, s *ReflectStruct, name string, v any) any) *ReflectStruct

func (*ReflectStruct) IndexGet

func (s *ReflectStruct) IndexGet(vm *VM, index Object) (value Object, err error)

func (*ReflectStruct) IndexGetS

func (s *ReflectStruct) IndexGetS(vm *VM, index string) (value Object, err error)

func (*ReflectStruct) IndexSet

func (s *ReflectStruct) IndexSet(vm *VM, index, value Object) (err error)

func (*ReflectStruct) Iterate

func (s *ReflectStruct) Iterate(vm *VM, na *NamedArgs) Iterator

func (*ReflectStruct) Repr

func (s *ReflectStruct) Repr(vm *VM) (_ string, err error)

func (*ReflectStruct) SafeField

func (s *ReflectStruct) SafeField(vm *VM, name string) (handled bool, value any, err error)

func (*ReflectStruct) SetField

func (s *ReflectStruct) SetField(vm *VM, index string, value any) (handled bool, err error)

func (*ReflectStruct) SetFieldValue

func (s *ReflectStruct) SetFieldValue(vm *VM, df *ReflectField, value any) (err error)

func (*ReflectStruct) SetValues

func (s *ReflectStruct) SetValues(vm *VM, values Dict) (err error)

func (*ReflectStruct) ToString

func (s *ReflectStruct) ToString() string

func (*ReflectStruct) UserData

func (s *ReflectStruct) UserData() Indexer

type ReflectType

type ReflectType struct {
	RType       reflect.Type
	RMethods    map[string]*ReflectMethod
	FieldsNames []string
	RFields     map[string]*ReflectField
	// contains filtered or unexported fields
}

func NewReflectType

func NewReflectType(typ reflect.Type) (rt *ReflectType)

func (*ReflectType) Call

func (r *ReflectType) Call(c Call) (obj Object, err error)

func (*ReflectType) Equal

func (r *ReflectType) Equal(right Object) bool

func (*ReflectType) Fields

func (r *ReflectType) Fields() (fields Dict)

func (*ReflectType) Fqn

func (r *ReflectType) Fqn() string

func (*ReflectType) GetRMethods

func (r *ReflectType) GetRMethods() map[string]*ReflectMethod

func (*ReflectType) Getters

func (r *ReflectType) Getters() Dict

func (*ReflectType) IsChildOf

func (r *ReflectType) IsChildOf(t ObjectType) bool

func (*ReflectType) IsFalsy

func (r *ReflectType) IsFalsy() bool

func (*ReflectType) Methods

func (r *ReflectType) Methods() (m Dict)

func (*ReflectType) Name

func (r *ReflectType) Name() string

func (*ReflectType) New

func (r *ReflectType) New(vm *VM, m Dict) (_ Object, err error)

func (*ReflectType) Setters

func (r *ReflectType) Setters() Dict

func (*ReflectType) ToString

func (r *ReflectType) ToString() string

func (*ReflectType) Type

func (r *ReflectType) Type() ObjectType

type ReflectValue

type ReflectValue struct {
	RType  *ReflectType
	RValue reflect.Value

	Options *ReflectValueOptions
	// contains filtered or unexported fields
}

func (*ReflectValue) CallName

func (r *ReflectValue) CallName(name string, c Call) (Object, error)

func (*ReflectValue) CallNameOf

func (r *ReflectValue) CallNameOf(this ReflectValuer, name string, c Call) (Object, error)

func (*ReflectValue) Copy

func (r *ReflectValue) Copy() (obj Object)

func (*ReflectValue) Equal

func (r *ReflectValue) Equal(right Object) bool

func (*ReflectValue) FalbackNameCallerHandler

func (r *ReflectValue) FalbackNameCallerHandler(handler func(s ReflectValuer, name string, c Call) (handled bool, value Object, err error)) *ReflectValue

func (*ReflectValue) Format

func (r *ReflectValue) Format(s fmt.State, verb rune)

func (*ReflectValue) GetRType

func (r *ReflectValue) GetRType() *ReflectType

func (*ReflectValue) GetRValue

func (r *ReflectValue) GetRValue() *ReflectValue

func (*ReflectValue) IsFalsy

func (r *ReflectValue) IsFalsy() bool

func (*ReflectValue) IsNil

func (r *ReflectValue) IsNil() bool

func (*ReflectValue) IsPtr

func (r *ReflectValue) IsPtr() bool

func (*ReflectValue) PtrValue

func (r *ReflectValue) PtrValue() reflect.Value

func (*ReflectValue) ToInterface

func (r *ReflectValue) ToInterface() any

func (*ReflectValue) ToString

func (r *ReflectValue) ToString() string

func (*ReflectValue) ToStringW

func (r *ReflectValue) ToStringW(w io.Writer)

func (*ReflectValue) Type

func (r *ReflectValue) Type() ObjectType

func (*ReflectValue) Value

func (r *ReflectValue) Value() reflect.Value

type ReflectValueOptions

type ReflectValueOptions struct {
	ToStr    func() string
	ItValuer func(value interface{}) (Object, error)
}

type ReflectValuer

type ReflectValuer interface {
	Object
	Copier
	NameCallerObject
	ToIterfaceConverter
	Value() reflect.Value
	GetRValue() *ReflectValue
	GetRType() *ReflectType
	IsPtr() bool
	IsNil() bool
}

func MustNewReflectValue

func MustNewReflectValue(v any, opts ...*ReflectValueOptions) ReflectValuer

func NewReflectValue

func NewReflectValue(v any, opts ...*ReflectValueOptions) (ReflectValuer, error)

type Representer

type Representer interface {
	Repr(vm *VM) (string, error)
}

type ReverseSorter

type ReverseSorter interface {
	Object

	// SortReverse sorts object reversely. if `update`, sort self and return then, other else sorts a self copy object.
	SortReverse(vm *VM) (Object, error)
}

ReverseSorter is an interface for return reverse sorted values.

type RunOpts

type RunOpts struct {
	Globals        IndexGetSetter
	Args           Args
	NamedArgs      *NamedArgs
	StdIn          io.Reader
	StdOut         io.Writer
	StdErr         io.Writer
	ObjectToWriter ObjectToWriter
}

type RuntimeError

type RuntimeError struct {
	Err *Error

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

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

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(vm *VM, index Object) (Object, error)

IndexGet implements Object interface.

func (*RuntimeError) IsFalsy

func (o *RuntimeError) IsFalsy() bool

IsFalsy 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) ToString

func (o *RuntimeError) ToString() string

func (*RuntimeError) Type

func (*RuntimeError) Type() ObjectType

func (*RuntimeError) Unwrap

func (o *RuntimeError) Unwrap() error

type SetupOpts

type SetupOpts struct {
	ObjectConverters *ObjectConverters
	Builtins         *Builtins
	ToRawStrHandler  func(vm *VM, s Str) RawStr
}

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 Slicer

type Slicer interface {
	LengthGetter
	Slice(low, high int) Object
}

type Sorter

type Sorter interface {
	Object

	// Sort sorts object. if `update`, sort self and return then, other else sorts a self copy object.
	Sort(vm *VM, less CallerObject) (Object, error)
}

Sorter is an interface for return sorted values.

type SourceModule

type SourceModule struct {
	Src []byte
}

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

func (*SourceModule) Import

func (m *SourceModule) Import(_ context.Context, name string) (any, string, error)

Import returns a module source code.

type StackReader

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

func NewStackReader

func NewStackReader(readers ...io.Reader) *StackReader

func (*StackReader) Equal

func (s *StackReader) Equal(right Object) bool

func (*StackReader) GoReader

func (s *StackReader) GoReader() io.Reader

func (*StackReader) IsFalsy

func (s *StackReader) IsFalsy() bool

func (*StackReader) Pop

func (s *StackReader) Pop()

func (*StackReader) Push

func (s *StackReader) Push(r io.Reader)

func (*StackReader) Read

func (s *StackReader) Read(p []byte) (n int, err error)

func (*StackReader) ToString

func (s *StackReader) ToString() string

func (*StackReader) Type

func (s *StackReader) Type() ObjectType

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 StackWriter

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

func NewStackWriter

func NewStackWriter(writers ...io.Writer) *StackWriter

func (*StackWriter) Current

func (w *StackWriter) Current() Writer

func (*StackWriter) Equal

func (w *StackWriter) Equal(right Object) bool

func (*StackWriter) Flush

func (w *StackWriter) Flush() (n Int, err error)

func (*StackWriter) GoWriter

func (w *StackWriter) GoWriter() io.Writer

func (*StackWriter) IsFalsy

func (w *StackWriter) IsFalsy() bool

func (*StackWriter) Old

func (w *StackWriter) Old() Writer

func (*StackWriter) Pop

func (w *StackWriter) Pop() Writer

func (*StackWriter) Push

func (w *StackWriter) Push(sw io.Writer)

func (*StackWriter) ToString

func (w *StackWriter) ToString() string

func (*StackWriter) Type

func (w *StackWriter) Type() ObjectType

func (*StackWriter) Write

func (w *StackWriter) Write(p []byte) (n int, err error)

type StartIterationHandler

type StartIterationHandler func(vm *VM) (state *IteratorState, err error)

type StateIteratorObject

type StateIteratorObject struct {
	Iterator
	State         *IteratorState
	VM            *VM
	StartHandlers []func(s *StateIteratorObject)
}

func NewStateIteratorObject

func NewStateIteratorObject(vm *VM, it Iterator) *StateIteratorObject

func ToStateIterator

func ToStateIterator(vm *VM, obj Object, na *NamedArgs) (l int, sit *StateIteratorObject, err error)

func (*StateIteratorObject) AddStartHandler

func (s *StateIteratorObject) AddStartHandler(f func(s *StateIteratorObject))

func (*StateIteratorObject) Equal

func (s *StateIteratorObject) Equal(right Object) bool

func (*StateIteratorObject) GetIterator

func (s *StateIteratorObject) GetIterator() Iterator

func (*StateIteratorObject) IndexGet

func (s *StateIteratorObject) IndexGet(vm *VM, index Object) (value Object, err error)

func (*StateIteratorObject) Info

func (s *StateIteratorObject) Info() Dict

func (*StateIteratorObject) IsFalsy

func (s *StateIteratorObject) IsFalsy() bool

func (*StateIteratorObject) Key

func (s *StateIteratorObject) Key() Object

func (*StateIteratorObject) Next

func (s *StateIteratorObject) Next(vm *VM, state *IteratorState) (err error)

func (*StateIteratorObject) Read

func (s *StateIteratorObject) Read() (_ bool, err error)

func (*StateIteratorObject) Repr

func (s *StateIteratorObject) Repr(vm *VM) (r string, err error)

func (*StateIteratorObject) Start

func (s *StateIteratorObject) Start(vm *VM) (state *IteratorState, err error)

func (*StateIteratorObject) ToString

func (s *StateIteratorObject) ToString() string

func (*StateIteratorObject) Type

func (s *StateIteratorObject) Type() ObjectType

func (*StateIteratorObject) Value

func (s *StateIteratorObject) Value() Object

type Str

type Str string

Str represents string values and implements Object interface.

func ToRepr

func ToRepr(vm *VM, o Object) (_ Str, err error)

func ToReprTyped

func ToReprTyped(vm *VM, typ ObjectType, o Object) (s Str, err error)

func ToStr

func ToStr(vm *VM, o Object) (_ Str, err error)

func ToString

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

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

func (Str) BinaryOp

func (o Str) BinaryOp(_ *VM, tok token.Token, right Object) (Object, error)

BinaryOp implements Object interface.

func (Str) Equal

func (o Str) Equal(right Object) bool

Equal implements Object interface.

func (Str) Format

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

Format implements fmt.Formatter interface.

func (Str) IndexGet

func (o Str) IndexGet(_ *VM, index Object) (Object, error)

IndexGet represents string values and implements Object interface.

func (Str) IsFalsy

func (o Str) IsFalsy() bool

IsFalsy implements Object interface.

func (Str) Iterate

func (o Str) Iterate(_ *VM, na *NamedArgs) Iterator

func (Str) Length

func (o Str) Length() int

Length implements LengthGetter interface.

func (Str) Quoted

func (o Str) Quoted() string

func (Str) Repr

func (o Str) Repr(*VM) (string, error)

func (Str) ToString

func (o Str) ToString() string

func (Str) Type

func (o Str) Type() ObjectType

type Symbol

type Symbol struct {
	SymbolInfo
	Assigned bool
	Constant bool
	Original *Symbol
}

Symbol represents a symbol in the symbol table.

func (*Symbol) String

func (s *Symbol) String() string

type SymbolInfo

type SymbolInfo struct {
	Name  string
	Index int
	Scope SymbolScope
}

func (*SymbolInfo) Equal

func (s *SymbolInfo) Equal(right Object) bool

func (*SymbolInfo) IsFalsy

func (s *SymbolInfo) IsFalsy() bool

func (*SymbolInfo) ToString

func (s *SymbolInfo) ToString() string

func (*SymbolInfo) Type

func (s *SymbolInfo) Type() ObjectType

type SymbolScope

type SymbolScope uint8

SymbolScope represents a symbol scope.

const (
	ScopeGlobal SymbolScope = iota + 1
	ScopeLocal
	ScopeBuiltin
	ScopeFree
)

List of symbol scopes

func (SymbolScope) String

func (s SymbolScope) String() string

type SymbolTable

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

SymbolTable represents a symbol table.

func NewSymbolTable

func NewSymbolTable(builtins *Builtins) *SymbolTable

NewSymbolTable creates new symbol table object.

func (*SymbolTable) Builtins

func (st *SymbolTable) Builtins() *Builtins

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

func (st *SymbolTable) NamedParams() NamedParams

NamedParams returns named parameters for the scope.

func (*SymbolTable) NextIndex

func (st *SymbolTable) NextIndex() int

NextIndex returns the next symbol index.

func (*SymbolTable) Params

func (st *SymbolTable) Params() Params

Params returns 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) SetNamedParams

func (st *SymbolTable) SetNamedParams(params ...*NamedParam) (err error)

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

func (*SymbolTable) SetParams

func (st *SymbolTable) SetParams(varParams bool, params []string, types []ParamType) (err 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 SyncDict

type SyncDict struct {
	Value Dict
	// contains filtered or unexported fields
}

SyncDict represents map of objects and implements Object interface.

func ToSyncMap

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

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

func (*SyncDict) BinaryOp

func (o *SyncDict) BinaryOp(vm *VM, tok token.Token, right Object) (Object, error)

BinaryOp implements Object interface.

func (*SyncDict) Copy

func (o *SyncDict) Copy() Object

Copy implements Copier interface.

func (*SyncDict) DeepCopy

func (o *SyncDict) DeepCopy(vm *VM) (v Object, err error)

DeepCopy implements DeepCopier interface.

func (*SyncDict) Equal

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

Equal implements Object interface.

func (*SyncDict) Format

func (o *SyncDict) Format(f fmt.State, verb rune)

func (*SyncDict) Get

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

Get returns Object in map if exists.

func (*SyncDict) IndexDelete

func (o *SyncDict) IndexDelete(vm *VM, key Object) error

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

func (*SyncDict) IndexGet

func (o *SyncDict) IndexGet(vm *VM, index Object) (Object, error)

IndexGet implements Object interface.

func (*SyncDict) IndexSet

func (o *SyncDict) IndexSet(vm *VM, index, value Object) error

IndexSet implements Object interface.

func (*SyncDict) IsFalsy

func (o *SyncDict) IsFalsy() bool

IsFalsy implements Object interface.

func (*SyncDict) Items

func (o *SyncDict) Items(vm *VM) (KeyValueArray, error)

func (*SyncDict) Iterate

func (o *SyncDict) Iterate(_ *VM, na *NamedArgs) Iterator

func (*SyncDict) Keys

func (o *SyncDict) Keys() Array

func (*SyncDict) Length

func (o *SyncDict) Length() int

Length returns the number of items in the dict.

func (*SyncDict) Lock

func (o *SyncDict) Lock()

Lock locks the underlying mutex for writing.

func (*SyncDict) RLock

func (o *SyncDict) RLock()

RLock locks the underlying mutex for reading.

func (*SyncDict) RUnlock

func (o *SyncDict) RUnlock()

RUnlock unlocks the underlying mutex for reading.

func (*SyncDict) ToString

func (o *SyncDict) ToString() string

func (*SyncDict) Type

func (o *SyncDict) Type() ObjectType

func (*SyncDict) Unlock

func (o *SyncDict) Unlock()

Unlock unlocks the underlying mutex for writing.

func (*SyncDict) Values

func (o *SyncDict) Values() Array

type SyncIterator

type SyncIterator struct {
	*Iteration
	// contains filtered or unexported fields
}

SyncIterator represents an iterator for the SyncDict.

func (*SyncIterator) NextIteration

func (it *SyncIterator) NextIteration(vm *VM, state *IteratorState) (err error)

func (*SyncIterator) StartIteration

func (it *SyncIterator) StartIteration(vm *VM) (state *IteratorState, err error)

type ToArrayAppenderObject

type ToArrayAppenderObject interface {
	Object
	AppendToArray(arr *Array)
}

type ToIterfaceConverter

type ToIterfaceConverter interface {
	ToInterface() any
}

type ToIterfaceVMConverter

type ToIterfaceVMConverter interface {
	ToInterface(*VM) any
}

type ToWriter

type ToWriter interface {
	Object
	WriteTo(vm *VM, w io.Writer) (n int64, err error)
}

type Type

type Type struct {
	TypeName string
	Parent   ObjectType

	Constructor CallerObject
	// contains filtered or unexported fields
}

func (*Type) AddCallerMethod

func (t *Type) AddCallerMethod(vm *VM, types MultipleObjectTypes, handler CallerObject, override bool) error

func (*Type) Call

func (t *Type) Call(c Call) (_ Object, err error)

func (*Type) Caller

func (t *Type) Caller() CallerObject

func (*Type) CallerMethods

func (t *Type) CallerMethods() *MethodArgType

func (*Type) CallerOf

func (t *Type) CallerOf(args Args) (co CallerObject, ok bool)

func (*Type) CallerOfTypes

func (t *Type) CallerOfTypes(types []ObjectType) (co CallerObject, validate bool)

func (*Type) Equal

func (t *Type) Equal(right Object) bool

func (Type) Fields

func (Type) Fields() Dict

func (*Type) GetMethod

func (t *Type) GetMethod(types []ObjectType) (co CallerObject)

func (Type) Getters

func (Type) Getters() Dict

func (*Type) HasCallerMethods

func (t *Type) HasCallerMethods() bool

func (*Type) IsChildOf

func (t *Type) IsChildOf(ot ObjectType) bool

func (*Type) IsFalsy

func (t *Type) IsFalsy() bool

func (Type) Methods

func (Type) Methods() Dict

func (Type) Name

func (t Type) Name() string

func (Type) New

func (Type) New(*VM, Dict) (Object, error)

func (Type) Setters

func (Type) Setters() Dict

func (*Type) ToString

func (t *Type) ToString() string

func (*Type) Type

func (t *Type) Type() ObjectType

func (*Type) WithConstructor

func (t *Type) WithConstructor(handler CallerObject) *Type

func (*Type) WithMethod

func (t *Type) WithMethod(types MultipleObjectTypes, handler CallerObject, override bool) *Type

type TypeAssertion

type TypeAssertion struct {
	Types    []ObjectType
	Handlers TypeAssertionHandlers
}

func NewTypeAssertion

func NewTypeAssertion(handlers TypeAssertionHandlers, types ...ObjectType) *TypeAssertion

func TypeAssertionFromTypes

func TypeAssertionFromTypes(types ...ObjectType) *TypeAssertion

func (*TypeAssertion) Accept

func (a *TypeAssertion) Accept(value Object) (expectedNames string)

func (*TypeAssertion) AcceptHandler

func (a *TypeAssertion) AcceptHandler(name string, handler TypeAssertionHandler) *TypeAssertion

func (*TypeAssertion) AcceptType

func (a *TypeAssertion) AcceptType(value ObjectType) (expectedNames string)

type TypeAssertionHandler

type TypeAssertionHandler func(v Object) bool

type TypeAssertionHandlers

type TypeAssertionHandlers map[string]TypeAssertionHandler

type Uint

type Uint uint64

Uint represents unsigned integer values and implements Object interface.

func ToUint

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

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

func (Uint) BinaryOp

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

BinaryOp implements Object interface.

func (Uint) Equal

func (o Uint) Equal(right Object) bool

Equal implements Object interface.

func (Uint) Format

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

Format implements fmt.Formatter interface.

func (Uint) IsFalsy

func (o Uint) IsFalsy() bool

IsFalsy implements Object interface.

func (Uint) ToString

func (o Uint) ToString() string

func (Uint) Type

func (o Uint) Type() ObjectType

type UserDataStorage

type UserDataStorage interface {
	Object
	UserData() Indexer
}

type VM

type VM struct {
	StdOut, StdErr *StackWriter
	StdIn          *StackReader
	ObjectToWriter ObjectToWriter

	*SetupOpts
	// 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

func (vm *VM) Aborted() bool

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

func (*VM) AddCallerMethod

func (vm *VM) AddCallerMethod(co CallerObject, types MultipleObjectTypes, caller CallerObject) error

func (*VM) AddCallerMethodOverride

func (vm *VM) AddCallerMethodOverride(co CallerObject, types MultipleObjectTypes, override bool, caller CallerObject) error

func (*VM) Clear

func (vm *VM) Clear() *VM

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

func (*VM) GetGlobals

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

func (vm *VM) GetSymbolValue(symbol *SymbolInfo) (value Object, err error)

func (*VM) Init

func (vm *VM) Init() *VM

func (*VM) Read

func (vm *VM) Read(b []byte) (int, error)

func (*VM) Run

func (vm *VM) Run(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,
	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) RunCompiledFunctionOpts

func (vm *VM) RunCompiledFunctionOpts(
	f *CompiledFunction,
	opts *RunOpts,
) (Object, error)

RunCompiledFunctionOpts 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) RunOpts

func (vm *VM) RunOpts(opts *RunOpts) (Object, error)

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

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.

func (*VM) Setup

func (vm *VM) Setup(opts SetupOpts) *VM

func (*VM) ToInterface

func (vm *VM) ToInterface(v Object) any

func (*VM) ToInterfaceArray

func (vm *VM) ToInterfaceArray(v Array) (ret []any)

func (*VM) ToObject

func (vm *VM) ToObject(v any) (Object, error)

func (*VM) ToObjectArray

func (vm *VM) ToObjectArray(v []any) (ret Array, err error)

func (*VM) Write

func (vm *VM) Write(b []byte) (int, error)

type VMCaller

type VMCaller interface {
	Call() (Object, error)
	Close()
	Callee() CallerObject
}

type ValuesGetter

type ValuesGetter interface {
	Object
	Values() (arr Array)
}

ValuesGetter is an interface for returns values.

type ValuesIterator

type ValuesIterator interface {
	Iterator
	Values() Array
}

type Writer

type Writer interface {
	Object
	io.Writer
	GoWriter() io.Writer
}

func NewTypedWriter

func NewTypedWriter(w io.Writer, typ ObjectType) Writer

func NewWriter

func NewWriter(w io.Writer) Writer

type Zeroer

type Zeroer interface {
	IsZero() bool
}

Directories

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

Jump to

Keyboard shortcuts

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