gad

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Jul 7, 2026 License: MIT Imports: 48 Imported by: 6

README

Gad logo

The Gad Programming Language

Go Reference Go Report Card Gad Test Gad Dev Test Maintainability

The name Gad honors the biblical patriarch known for his fierce warrior spirit, speed, and frontline resilience. Mirroring the Hebrew meaning of Gad ("good fortune"), this project aims to bring productivity, success, and high-performance capabilities to developers. Engineered as a fast, dynamic scripting language, Gad is designed to be deeply embedded into native Go applications or run over the web via WebAssembly (WASM). It compiles down to efficient bytecode executed on a custom, stack-based VM. Just like the Tribe of Gad—celebrated for being swift as gazelles and unyielding in battle—this language is built to be lightweight, agile, and robust enough to handle complex, real-time evaluation challenges in production environments.

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

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(int(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.
  • match expression and statement (PHP 8 like).
  • defer / defer_ok / defer_err (function) and deferb* (block-scoped) deferred handlers, with $ret / $err access and recovery.
  • or error-fallback operator (z := x() or fallback).
  • Array and dict comprehensions ([e for x in it if c], {k: v for ...}).
  • Array and dict spread/merge literals ([1, *a, *b], {a: 1, *b}).
  • Dict and MixedParams destructuring assignment.
  • /regex/ literals backed by a built-in regexp type (match / find / replace).
  • 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.

Language additions

A few of the syntax additions over a Go-like base:

// or: error fallback (re-throws if the fallback is itself an error)
z := mayThrow() or 2
y := 1 + (mayThrow() or 10)

// match (PHP 8 like) — no parens; arms may list several conditions (OR);
// no matching arm (and no else) yields nil
label := match n {
    1, 2: "one or two"
    3:    "three",
    else: "other"
}
match n { 1 { return "one" }, else { return "other" } }

// comprehensions; dict keys are static by default, computed with [..],
// and `_` is the dict being built
squares := [i * i for i in [1, 2, 3] if i > 1]
m := {x: 10, [i]: i * i, z: (_.z ?? 0) + i for i in [1, 2, 3]}

// spread / merge literals (a leading spread yields a fresh copy)
all := [1, *a, 4, *b]
merged := {a: 1, *b, c: 2, *d}

// destructuring: dict and MixedParams
(;a, _b:b, r=2, **other) := {a: 2, b: 3, x: 4}     // a=2, _b=3, r=2, other={x:4}
x := (1, 2, *[3, 4]; c=5, **{d:6, e:7})
(a, b, **pos_rest; c, p:d, r=2, **named_rest) := x

// defer with $ret/$err (recover by clearing $err); deferb runs at block exit
f := func() {
    defer_err { $ret = "recovered: " + str($err); $err = nil }
    throw "boom"
}

// regexp literals and replacement (| yields a replacer; composes with .|)
re := /(\d+)-(\d+)/
re.match("12-34")                 // true
re.replace("12-34", "$2/$1")      // "34/12"
"hello world".|(/o/ | "0")        // "hell0 w0rld"

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

CLI tools

The gad binary is organised as subcommands:

Command Purpose
gad run Run a script/stdin (or a .gadt/--template template), or the REPL.
gad fmt Format Gad source files in place.
gad debug Debug a script — interactive REPL or --dap for editors.
gad ide Start a local web IDE (file tree, tabs, format/run/debug).

Gad also has a template / mixed mode ({% … %} code, {%= … %} values, begin … end blocks, whitespace trim markers) — see doc/templates.md.

Samples & the web IDE

The samples/ directory is a guided tour of the language and the standard library. Open it in the bundled web IDE:

make ide                 # serves the samples workspace in your browser
# or: gad ide samples    # or: gad ide path/to/your/project

The IDE offers multi-file tabs, formatting, running and full debugging (breakpoints, stepping, call stack and locals), with per-file run/debug dialogs (arguments, builtin-module toggles, output capture) and settings stored in the workspace .gad.yaml. See samples/README.md.

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
`

    builtins := gad.NewBuiltins()
    st := gad.NewSymbolTable(builtins.NameSet)
    _, bc, err := gad.Compile(st, []byte(script), gad.CompileOptions{})
    if err != nil {
        panic(err)
    }

    ret, err := gad.NewVM(builtins.Build(), bc).RunOpts(&gad.RunOpts{
        Globals: gad.Dict{"multiplier": gad.Int(2)},
        Args:    gad.Args{gad.Array{gad.Int(1), gad.Int(2), gad.Int(3), gad.Int(4)}},
    })
    if err != nil {
        panic(err)
    }
    fmt.Println(ret) // [2, 4, 6, 8]
}

Documentation

Go Dev Conventions

Conventions for contributing Go code to the runtime.

Registering a builtin function

Build a builtin function with the fluent NewBuiltinFunction constructor, declaring its module and its parameter name/type pairs — do not hand-populate the struct fields:

fn := NewBuiltinFunction("binOpAdd", func(c Call) (Object, error) {
    // ...
}).WithModule(gadModuleSpec).WithParamsPairs("left", TAny, "right", TAny)

WithModule qualifies the function's name (e.g. gad.binOpAdd) and WithParamsPairs declares the parameters as alternating name, Type values, so the signature appears in repr(fn; indent) and drives argument dispatch.

LICENSE

Gad is licensed under the MIT License — see LICENSE for the full text. You are free to use, copy, modify and distribute it, including in commercial and closed-source projects, provided the copyright and license notice is retained.

Gad includes code derived from third-party projects, each under its own license:

Acknowledgements

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

Documentation

Overview

Package time provides time module for measuring and displaying time for Gad script language. It wraps ToInterface's time package functionalities. Note that: Gad's int values are converted to ToInterface's time.Duration values.

Index

Examples

Constants

View Source
const (
	// AttrName is a special attribute injected into modules to identify
	// the modules by name.
	AttrName = "@name"
	// AttrFile is a special attribute injected into modules to identify
	// the module file path.
	AttrFile = "@file"
	// AttrParams is a special attribute injected into modules to identify
	// the module params.
	AttrParams = "@params"
)
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 (
	PrintStateOptionIndent           = "indent"
	PrintStateOptionMaxDepth         = "maxDepth"
	PrintStateOptionTrimEmbedPath    = "trimEmbedPath"
	PrintStateOptionRaw              = "raw"
	PrintStateOptionZeros            = "zeros"
	PrintStateOptionAnonymous        = "anonymous"
	PrintStateOptionSortKeys         = "sortKeys"
	PrintStateOptionIndexes          = "indexes"
	PrintStateOptionTypesAsFullNames = "typesAsFullNames"
	PrintStateOptionRepr             = "repr"
	PrintStateOptionBytesToHex       = "bytesToHex"
	PrintStateOptionQuoteStr         = "quoteStr"
)
View Source
const (
	MainName = parser.MainName
)
View Source
const ObjectMethodsGetterFieldName = "__methods__"
View Source
const PrintLoop = repr.QuotePrefix + "↶" + repr.QuoteSufix
View Source
const TestRegistryPrefix = "__gadTest_"

TestRegistryPrefix marks the top-level const bindings that `test`/`bench` statements lower to. The `gad test` runner discovers them by this prefix. Each binds a `[kind, name, func(t){…}, doc]` array.

Variables

View Source
var (
	TAny                         = NewType("any")
	TModule                      = NewType("Module")
	TStaticModule                = NewType("ModuleSpec")
	TSymbol                      = NewType("Symbol", TAny)
	TIterationStateFlag          = NewType("IterationStateFlag", TAny)
	IterationStop                = NewType("IterationStop", TIterationStateFlag)
	IterationSkip                = NewType("IterationSkip", TIterationStateFlag)
	TBase                        = NewType("Base", TAny)
	TClass                       = NewType("Class", TBase)
	TClassConstructor            = NewType("ClassConstructor", TBase)
	TClassInitiator              = NewType("ClassInitiator", TBase)
	TClassProperty               = NewType("ClassProperty", TBase)
	TClassMethod                 = NewType("ClassMethod", TBase)
	TClassField                  = NewType("ClassField", TBase)
	TClassInstanceMethod         = NewType("ClassInstanceMethod", TBase)
	TClassInstancePropertyGetter = NewType("ClassInstancePropertyGetter", TBase)
	TClassInstancePropertySetter = NewType("ClassInstancePropertySetter", TBase)
	TEmbedded                    = NewType("Embedded", TBase)
	TEmbeddedFS                  = NewType("EmbeddedFS", TBase)
	TIterator                    = NewType("Iterator", TAny)
	TIterabler                   = NewType("Iterabler", TAny)
	TNilIterator                 = NewType("NilIterator", TIterator)
	TStateIterator               = NewType("StateIterator", TIterator)
	TStrIterator                 = NewType("StrIterator", TIterator)
	TRawStrIterator              = NewType("RawStrIterator", TIterator)
	TArrayIterator               = NewType("ArrayIterator", TIterator)
	TDictIterator                = NewType("DictIterator", TIterator)
	TBytesIterator               = NewType("BytesIterator", TIterator)
	TKeyValueArrayIterator       = NewType("KeyValueArrayIterator", TIterator)
	TKeyValueArraysIterator      = NewType("KeyValueArraysIterator", TIterator)
	TArgsIterator                = NewType("ArgsIterator", TIterator)
	TReflectArrayIterator        = NewType("ReflectArrayIterator", TIterator)
	TReflectMapIterator          = NewType("ReflectMapIterator", TIterator)
	TReflectStructIterator       = NewType("ReflectStructIterator", TIterator)
	TKeysIterator                = NewType("KeysIterator", TIterator)
	TValuesIterator              = NewType("ValuesIterator", TIterator)
	TEnumerateIterator           = NewType("EnumerateIterator", TIterator)
	TItemsIterator               = NewType("ItemsIterator", TIterator)
	TCallbackIterator            = NewType("CallbackIterator", TIterator)
	TEachIterator                = NewType("EachIterator", TIterator)
	TMapIterator                 = NewType("MapIterator", TIterator)
	TFilterIterator              = NewType("FilterIterator", TIterator)
	TZipIterator                 = NewType("ZipIterator", TIterator)
	TPipedInvokeIterator         = NewType("PipedInvokeIterator", TIterator)
	TEmbeddedNodeEntriesIterator = NewType("EmbeddedNodeEntries", TIterator)
	TEnum                        = NewType("Enum", TIterator)
)
View Source
var (
	NewFlagFunc = funcPORO(func(arg Object) Object {
		return Flag(!arg.IsFalsy())
	})

	NewBoolFunc = funcPORO(func(arg Object) Object {
		return Bool(!arg.IsFalsy())
	})

	NewIntFunc = funcPi64RO(func(v int64) Object {
		return Int(v)
	})

	NewUintFunc = funcPu64RO(func(v uint64) Object {
		return Uint(v)
	})

	NewFloatFunc = funcPf64RO(func(v float64) Object {
		return Float(v)
	})

	NewDecimalFunc = funcPpVM_OROe(func(vm *VM, v Object) (Object, error) {
		return Decimal(decimal.Zero).BinOpAdd(vm, v)
	})

	NewCharFunc = funcPOROe(func(arg Object) (Object, error) {
		v, ok := ToChar(arg)
		if ok && v != utf8.RuneError {
			return v, nil
		}
		if v == utf8.RuneError || arg == Nil {
			return Nil, nil
		}
		return Nil, NewArgumentTypeError(
			"1st",
			"numeric|string|bool",
			arg.Type().Name(),
		)
	})
)
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"}

	// ErrNotLengther is an error where an Object is not lengther.
	ErrNotLengther = &Error{Name: "NotLengther"}

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

	// ErrCall is an error where call Object
	ErrCall = &Error{Name: "ErrCall"}

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

	// ErrIncompatibleAssign is an error where incompatible assign.
	ErrIncompatibleAssign = &Error{Name: "ErrIncompatibleAssign"}

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

	// ErrNoMethodFound is an error where no method found.
	ErrNoMethodFound = &Error{Name: "ErrNoMethodFound"}

	// ErrConstructorRecursiveCall is an error where call recursive constructor.
	ErrConstructorRecursiveCall = &Error{Name: "ErrConstructorRecursiveCall"}

	// ErrConstructorMethodFound is an error where no constructor method found.
	ErrConstructorMethodFound = &Error{Name: "ErrConstructorMethodFound"}

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

	// ErrArgument represents a argument error.
	ErrArgument = &Error{Name: "ArgumentError"}

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

	// ErrNotWriteable represents a not writeable type error.
	ErrNotWriteable = &Error{Name: "ErrNotWriteable"}

	// ErrDefineClass represents an error for define class.
	ErrDefineClass = &Error{Name: "ErrDefineClass"}

	// ErrNewClassInstance represents an error for create new ClassInstance.
	ErrNewClassInstance = &Error{Name: "ErrNewClassInstance"}

	// ErrClassInstanceInitialized represents an error for initialized ClassInstance.
	ErrClassInstanceInitialized = &Error{Name: "ErrClassInstanceInitialized"}

	// ErrClassInstanceProperty represents an error of ClassInstance property.
	ErrClassInstanceProperty = &Error{Name: "ErrClassInstanceProperty"}

	// ErrClassPropertyChange represents an error on change ClassProperty.
	ErrClassPropertyChange = &Error{Name: "ErrClassPropertyChange"}

	// ErrClassPropertyRegister represents an error on change ClassProperty.
	ErrClassPropertyRegister = &Error{Name: "ErrClassPropertyRegister"}

	// ErrClassMethodRegister represents an error on register method.
	ErrClassMethodRegister = &Error{Name: "ErrClassMethodRegister"}

	// ErrEmbedded represents an embeddedNode errors
	ErrEmbedded = &Error{Name: "ErrEmbeddedNode"}

	// ErrProp represents an error of Prop.
	ErrProp = &Error{Name: "ErrProp"}
)
View Source
var (
	ReprQuote      = repr.Quote
	ReprQuoteTyped = repr.QuoteTyped
)
View Source
var (
	TInterfaceField  = NewBuiltinObjType("InterfaceField")
	TInterfaceProp   = NewBuiltinObjType("InterfaceProp")
	TInterfaceMethod = NewBuiltinObjType("InterfaceMethod")
)

Object types for the interface members. They are internal representations carried inside an Interface constant, not user-constructible.

View Source
var BuiltinObjects = BuiltinObjectsMap{

	BuiltinMakeArray: &BuiltinFunction{
		FuncName:              ":makeArray",
		Value:                 funcPiOROe(BuiltinMakeArrayFunc),
		AcceptMethodsDisabled: true,
	},

	BuiltinMakeArrayRest: &BuiltinFunction{
		FuncName:              ":makeArrayRest",
		Value:                 funcPiOROe(BuiltinMakeArrayRestFunc),
		AcceptMethodsDisabled: true,
	},
	BuiltinBinaryOperator: &BuiltinFunction{
		FuncName: "binOp",
		Value:    BuiltinBinaryOperatorFunc,
	},
	BuiltinSelfAssignOperator: &BuiltinFunction{
		FuncName: "selfAssignOp",
		Value:    BuiltinSelfAssignOperatorFunc,
	},
	BuiltinUnaryOperator: &BuiltinFunction{
		FuncName: "unOp",
		Value:    BuiltinUnaryOperatorFunc,
	},
	BuiltinEnter: &BuiltinFunction{
		FuncName: "enter",
		Value:    BuiltinEnterFunc,
	},
	BuiltinExit: &BuiltinFunction{
		FuncName: "exit",
		Value:    BuiltinExitFunc,
	},
	BuiltinCast: &BuiltinFunction{
		FuncName: "cast",
		Value:    BuiltinCastFunc,
	},
	BuiltinChars: &BuiltinFunction{
		FuncName: "chars",
		Value:    funcPOROe(BuiltinCharsFunc),
	},
	BuiltinAppend: &BuiltinFunction{
		FuncName: "append",
		Value:    BuiltinAppendFunc,
	},
	BuiltinDelete: &BuiltinFunction{
		FuncName: "delete",
		Value:    BuiltinDeleteFunc,
	},
	BuiltinCopy: &BuiltinFunction{
		FuncName: "copy",
		Value:    BuiltinCopyFunc,
	},
	BuiltinDeepCopy: &BuiltinFunction{
		FuncName: "dcopy",
		Value:    BuiltinDeepCopyFunc,
	},
	BuiltinRepeat: &BuiltinFunction{
		FuncName: "repeat",
		Value:    funcPOiROe(BuiltinRepeatFunc),
	},
	BuiltinContains: &BuiltinFunction{
		FuncName: "contains",
		Value:    funcPOOROe(BuiltinContainsFunc),
	},
	BuiltinLen: &BuiltinFunction{
		FuncName: "len",
		Value:    BuiltinLenFunc,
		Header: NewFunctionHeader().
			WithParams(func(np func(name string) *ParamBuilder) {
				np("val").Usage("The value")
			}).
			WithNamedParams(func(np func(name string) *NamedParamBuilder) {
				np("check").
					Type(TFlag).
					Usage("When Yes and value not implements LengthGetter interface return error ErrNotLengther, otherwise return 0.")
			}),
	},
	BuiltinCap: &BuiltinFunction{
		FuncName: "cap",
		Value:    funcPORO(BuiltinCapFunc),
	},
	BuiltinSort: &BuiltinFunction{
		FuncName: "sort",
		Value:    funcPpVM_OCo_less_ROe(BuiltinSortFunc),
	},
	BuiltinSortReverse: &BuiltinFunction{
		FuncName: "sortReverse",
		Value:    funcPpVM_OCo_less_ROe(BuiltinSortReverseFunc),
	},
	BuiltinTypeName: &BuiltinFunction{
		FuncName:              "typeName",
		Value:                 funcPORO(BuiltinTypeNameFunc),
		AcceptMethodsDisabled: true,
	},
	BuiltinPrint: &BuiltinFunction{
		FuncName: "print",
		Value:    BuiltinPrintFunc,
	},
	BuiltinPrintf: &BuiltinFunction{
		FuncName: "printf",
		Value:    BuiltinPrintfFunc,
	},
	BuiltinPrintln: &BuiltinFunction{
		FuncName: "println",
		Value:    BuiltinPrintlnFunc,
	},
	BuiltinSprintf: &BuiltinFunction{
		FuncName:              "sprintf",
		Value:                 BuiltinSprintfFunc,
		AcceptMethodsDisabled: true,
	},
	BuiltinRepr: &BuiltinFunction{
		FuncName: "repr",
		Value:    BuiltinReprFunc,
	},
	BuiltinNamedParamTypeCheck: &BuiltinFunction{
		FuncName:              "namedParamTypeCheck",
		Value:                 BuiltinNamedParamTypeCheckFunc,
		AcceptMethodsDisabled: true,
	},
	BuiltinIs: &BuiltinFunction{
		FuncName:              "is",
		Value:                 BuiltinIsFunc,
		AcceptMethodsDisabled: true,
		Usage:                 ``,
	},
	BuiltinIsError: &BuiltinFunction{
		FuncName:              "isError",
		Value:                 BuiltinIsErrorFunc,
		AcceptMethodsDisabled: true,
	},
	BuiltinIsInt: &BuiltinFunction{
		FuncName:              "isInt",
		Value:                 funcPORO(BuiltinIsIntFunc),
		AcceptMethodsDisabled: true,
	},
	BuiltinIsUint: &BuiltinFunction{
		FuncName:              "isUint",
		Value:                 funcPORO(BuiltinIsUintFunc),
		AcceptMethodsDisabled: true,
	},
	BuiltinIsFloat: &BuiltinFunction{
		FuncName:              "isFloat",
		Value:                 funcPORO(BuiltinIsFloatFunc),
		AcceptMethodsDisabled: true,
	},
	BuiltinIsChar: &BuiltinFunction{
		FuncName:              "isChar",
		Value:                 funcPORO(BuiltinIsCharFunc),
		AcceptMethodsDisabled: true,
	},
	BuiltinIsBool: &BuiltinFunction{
		FuncName:              "isBool",
		Value:                 funcPORO(BuiltinIsBoolFunc),
		AcceptMethodsDisabled: true,
	},
	BuiltinIsStr: &BuiltinFunction{
		FuncName:              "isStr",
		Value:                 funcPORO(BuiltinIsStrFunc),
		AcceptMethodsDisabled: true,
	},
	BuiltinIsRawStr: &BuiltinFunction{
		FuncName:              "isRawStr",
		Value:                 funcPORO(BuiltinIsRawStrFunc),
		AcceptMethodsDisabled: true,
	},
	BuiltinIsBytes: &BuiltinFunction{
		FuncName:              "isBytes",
		Value:                 funcPORO(BuiltinIsBytesFunc),
		AcceptMethodsDisabled: true,
	},
	BuiltinIsDict: &BuiltinFunction{
		FuncName:              "isDict",
		Value:                 funcPORO(BuiltinIsDictFunc),
		AcceptMethodsDisabled: true,
	},
	BuiltinIsSyncDict: &BuiltinFunction{
		FuncName:              "isSyncDict",
		Value:                 funcPORO(BuiltinIsSyncDictFunc),
		AcceptMethodsDisabled: true,
	},
	BuiltinIsArray: &BuiltinFunction{
		FuncName:              "isArray",
		Value:                 funcPORO(BuiltinIsArrayFunc),
		AcceptMethodsDisabled: true,
	},
	BuiltinIsNil: &BuiltinFunction{
		FuncName:              "isNil",
		Value:                 funcPORO(BuiltinIsNilFunc),
		AcceptMethodsDisabled: true,
	},
	BuiltinIsFunction: &BuiltinFunction{
		FuncName:              "isFunction",
		Value:                 funcPORO(BuiltinIsFunctionFunc),
		AcceptMethodsDisabled: true,
	},
	BuiltinIsCallable: &BuiltinFunction{
		FuncName: "isCallable",
		Value:    funcPORO(BuiltinIsCallableFunc),
	},
	BuiltinIsIterable: &BuiltinFunction{
		FuncName: "isIterable",
		Value:    funcPpVM_ORO(BuiltinIsIterableFunc),
	},
	BuiltinIsIterator: &BuiltinFunction{
		FuncName: "isIterator",
		Value:    funcPORO(BuiltinIsIteratorFunc),
	},
	BuiltinImplements: &BuiltinFunction{
		FuncName: "implements",
		Value:    BuiltinImplementsFunc,
	},
	BuiltinStdIO: &BuiltinFunction{
		FuncName: "stdio",
		Value:    BuiltinStdIOFunc,
	},
	BuiltinWrap: &BuiltinFunction{
		FuncName: "wrap",
		Value:    BuiltinWrapFunc,
	},
	BuiltinNewClass: &BuiltinFunction{
		FuncName:              "Class",
		Value:                 NewClassFunc,
		AcceptMethodsDisabled: true,
	},
	BuiltinTypeOf: &BuiltinFunction{
		FuncName:              "typeof",
		Value:                 BuiltinTypeOfFunc,
		AcceptMethodsDisabled: true,
	},
	BuiltinAddMethod: &BuiltinFunction{
		FuncName:              "addMethod",
		Value:                 BuiltinAddMethodFunc,
		AcceptMethodsDisabled: true,
	},
	BuiltinMethodFromArgs: &BuiltinFunction{
		FuncName:              "methodFromArgs",
		Value:                 BuiltinMethodFromArgsFunc,
		AcceptMethodsDisabled: true,
	},
	BuiltinRawCaller: &BuiltinFunction{
		FuncName:              "rawCaller",
		Value:                 BuiltinRawCallerFunc,
		AcceptMethodsDisabled: true,
	},
	BuiltinVMPushWriter: &BuiltinFunction{
		FuncName:              "vmPushWriter",
		Value:                 BuiltinPushWriterFunc,
		AcceptMethodsDisabled: true,
	},
	BuiltinVMPopWriter: &BuiltinFunction{
		FuncName: "vmPopWriter",
		Value:    BuiltinPopWriterFunc,
	},
	BuiltinOBStart: &BuiltinFunction{
		FuncName:              "obstart",
		Value:                 BuiltinOBStartFunc,
		AcceptMethodsDisabled: true,
	},
	BuiltinOBEnd: &BuiltinFunction{
		FuncName:              "obend",
		Value:                 BuiltinOBEndFunc,
		AcceptMethodsDisabled: true,
	},
	BuiltinFlush: &BuiltinFunction{
		FuncName: "flush",
		Value:    BuiltinFlushFunc,
	},
	BuiltinUserData: &BuiltinFunction{
		FuncName: "userData",
		Value:    BuiltinUserDataFunc,
	},
	BuiltinClose: &BuiltinFunction{
		FuncName: "close",
		Value:    BuiltinCloseFunc,
	},
	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{

	"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,
	"close":               BuiltinClose,
	"read":                BuiltinRead,
	"write":               BuiltinWrite,
	"print":               BuiltinPrint,
	"printf":              BuiltinPrintf,
	"println":             BuiltinPrintln,
	"sprintf":             BuiltinSprintf,
	"stdio":               BuiltinStdIO,
	"wrap":                BuiltinWrap,
	"Class":               BuiltinNewClass,
	"typeof":              BuiltinTypeOf,
	"addMethod":           BuiltinAddMethod,
	"rawCaller":           BuiltinRawCaller,
	"repr":                BuiltinRepr,
	"userData":            BuiltinUserData,
	"namedParamTypeCheck": BuiltinNamedParamTypeCheck,
	"toArray":             BuiltinToArray,

	"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,
	"implements": BuiltinImplements,

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

	":makeArray":     BuiltinMakeArray,
	":makeArrayRest": BuiltinMakeArrayRest,
	"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 CalendarDateType = NewBuiltinObjType("calendarDate").WithNew(NewCalendarDateFunc)

CalendarDateType is the object type of CalendarDate values (the gad `calendarDate` type). It is callable as a constructor: CalendarDate(uint|int) from a YYYYMMDD integer, or CalendarDate(str) parsing "YYYYMMDD"/"YYYY-MM-DD". See also strToDate.

View Source
var CalendarTimeType = NewBuiltinObjType("calendarTime").WithNew(NewCalendarTimeFunc)

CalendarTimeType is the object type of CalendarTime values (the gad `calendarTime` type). It is callable as a constructor: CalendarTime(uint|int) from a nanosecond count, or CalendarTime(str) parsing a zone-less timestamp. See also strToCalendarTime.

View Source
var DecimalZero = Decimal(decimal.Zero)
View Source
var DefaultStaticTypes = NewStaticTypes()
View Source
var DiscardWriter = NewWriter(io.Discard)
View Source
var DurationType = NewBuiltinObjType("duration").WithNew(NewDurationFunc)

DurationType is the object type of Duration values (the gad `duration` type). It is callable as a constructor: Duration(int) from a nanosecond count, or Duration(str) parsing a Go duration string ("1h30m"). See also strToDuration.

View Source
var EmptyNamedArgs = &NamedArgs{ro: true}
View Source
var MethodTable = map[string]func(*Time, *Call) (Object, error){
	"Add": func(o *Time, c *Call) (Object, error) {
		if err := c.Args.CheckLen(1); err != nil {
			return Nil, err
		}
		d, ok := ToGoInt64(c.Args.Get(0))
		if !ok {
			return TimeNewArgTypeErr("1st", "int", c.Args.Get(0).Type().Name())
		}
		return TimeAdd(o, d), nil
	},
	"Sub": func(o *Time, c *Call) (Object, error) {
		if err := c.Args.CheckLen(1); err != nil {
			return Nil, err
		}
		t2, ok := ToTime(c.Args.Get(0))
		if !ok {
			return TimeNewArgTypeErr("1st", "time", c.Args.Get(0).Type().Name())
		}
		return TimeSub(o, t2), nil
	},
	"AddDate": func(o *Time, c *Call) (Object, error) {
		if err := c.Args.CheckLen(3); err != nil {
			return Nil, err
		}
		year, ok := ToGoInt(c.Args.Get(0))
		if !ok {
			return TimeNewArgTypeErr("1st", "int", c.Args.Get(0).Type().Name())
		}
		month, ok := ToGoInt(c.Args.Get(1))
		if !ok {
			return TimeNewArgTypeErr("2nd", "int", c.Args.Get(1).Type().Name())
		}
		day, ok := ToGoInt(c.Args.Get(2))
		if !ok {
			return TimeNewArgTypeErr("3rd", "int", c.Args.Get(2).Type().Name())
		}
		return TimeAddDate(o, year, month, day), nil
	},
	"After": func(o *Time, c *Call) (Object, error) {
		if err := c.Args.CheckLen(1); err != nil {
			return Nil, err
		}
		t2, ok := ToTime(c.Args.Get(0))
		if !ok {
			return TimeNewArgTypeErr("1st", "time", c.Args.Get(0).Type().Name())
		}
		return TimeAfter(o, t2), nil
	},
	"Before": func(o *Time, c *Call) (Object, error) {
		if err := c.Args.CheckLen(1); err != nil {
			return Nil, err
		}
		t2, ok := ToTime(c.Args.Get(0))
		if !ok {
			return TimeNewArgTypeErr("1st", "time", c.Args.Get(0).Type().Name())
		}
		return TimeBefore(o, t2), nil
	},
	"Format": func(o *Time, c *Call) (Object, error) {
		if err := c.Args.CheckLen(1); err != nil {
			return Nil, err
		}
		format, ok := ToGoString(c.Args.Get(0))
		if !ok {
			return TimeNewArgTypeErr("1st", "str", c.Args.Get(0).Type().Name())
		}
		return TimeFormat(o, format), nil
	},
	"AppendFormat": func(o *Time, c *Call) (Object, error) {
		if err := c.Args.CheckLen(2); err != nil {
			return Nil, err
		}
		b, ok := ToGoByteSlice(c.Args.Get(0))
		if !ok {
			return TimeNewArgTypeErr("1st", "bytes", c.Args.Get(0).Type().Name())
		}
		format, ok := ToGoString(c.Args.Get(1))
		if !ok {
			return TimeNewArgTypeErr("2nd", "str", c.Args.Get(1).Type().Name())
		}
		return TimeAppendFormat(o, b, format), nil
	},
	"In": func(o *Time, c *Call) (Object, error) {
		if err := c.Args.CheckLen(1); err != nil {
			return Nil, err
		}
		loc, ok := ToLocation(c.Args.Get(0))
		if !ok {
			return TimeNewArgTypeErr("1st", "Location", c.Args.Get(0).Type().Name())
		}
		return TimeIn(o, loc), nil
	},
	"Round": func(o *Time, c *Call) (Object, error) {
		if err := c.Args.CheckLen(1); err != nil {
			return Nil, err
		}
		d, ok := ToGoInt64(c.Args.Get(0))
		if !ok {
			return TimeNewArgTypeErr("1st", "int", c.Args.Get(0).Type().Name())
		}
		return TimeRound(o, d), nil
	},
	"Truncate": func(o *Time, c *Call) (Object, error) {
		if err := c.Args.CheckLen(1); err != nil {
			return Nil, err
		}
		d, ok := ToGoInt64(c.Args.Get(0))
		if !ok {
			return TimeNewArgTypeErr("1st", "int", c.Args.Get(0).Type().Name())
		}
		return TimeTruncate(o, d), nil
	},

	"trunc": func(o *Time, c *Call) (Object, error) {
		unit, err := truncateUnitArg(*c)
		if err != nil {
			return Nil, err
		}
		t, err := truncateTimeUnit(o.Value, unit)
		if err != nil {
			return Nil, err
		}
		return &Time{Value: t}, nil
	},

	"round": func(o *Time, c *Call) (Object, error) {
		unit, err := truncateUnitArg(*c)
		if err != nil {
			return Nil, err
		}
		t, err := roundTimeUnit(o.Value, unit)
		if err != nil {
			return Nil, err
		}
		return &Time{Value: t}, nil
	},
	"Equal": func(o *Time, c *Call) (Object, error) {
		if err := c.Args.CheckLen(1); err != nil {
			return Nil, err
		}
		t2, ok := ToTime(c.Args.Get(0))
		if !ok {
			return TimeNewArgTypeErr("1st", "time", c.Args.Get(0).Type().Name())
		}
		return TimeEqual(o, t2), nil
	},
	"Date": func(o *Time, c *Call) (Object, error) {
		if err := c.Args.CheckLen(0); err != nil {
			return Nil, err
		}
		y, m, d := o.Value.Date()
		return Dict{"year": Int(y), "month": Int(m),
			"day": Int(d)}, nil
	},
	"Clock": func(o *Time, c *Call) (Object, error) {
		if err := c.Args.CheckLen(0); err != nil {
			return Nil, err
		}
		h, m, s := o.Value.Clock()
		return Dict{"hour": Int(h), "minute": Int(m),
			"second": Int(s)}, nil
	},
	"UTC": func(o *Time, c *Call) (Object, error) {
		if err := c.Args.CheckLen(0); err != nil {
			return Nil, err
		}
		return &Time{Value: o.Value.UTC()}, nil
	},
	"Unix": func(o *Time, c *Call) (Object, error) {
		if err := c.Args.CheckLen(0); err != nil {
			return Nil, err
		}
		return Int(o.Value.Unix()), nil
	},
	"UnixNano": func(o *Time, c *Call) (Object, error) {
		if err := c.Args.CheckLen(0); err != nil {
			return Nil, err
		}
		return Int(o.Value.UnixNano()), nil
	},
	"Year": func(o *Time, c *Call) (Object, error) {
		if err := c.Args.CheckLen(0); err != nil {
			return Nil, err
		}
		return Int(o.Value.Year()), nil
	},
	"Month": func(o *Time, c *Call) (Object, error) {
		if err := c.Args.CheckLen(0); err != nil {
			return Nil, err
		}
		return Int(o.Value.Month()), nil
	},
	"Day": func(o *Time, c *Call) (Object, error) {
		if err := c.Args.CheckLen(0); err != nil {
			return Nil, err
		}
		return Int(o.Value.Day()), nil
	},
	"Hour": func(o *Time, c *Call) (Object, error) {
		if err := c.Args.CheckLen(0); err != nil {
			return Nil, err
		}
		return Int(o.Value.Hour()), nil
	},
	"Minute": func(o *Time, c *Call) (Object, error) {
		if err := c.Args.CheckLen(0); err != nil {
			return Nil, err
		}
		return Int(o.Value.Minute()), nil
	},
	"Second": func(o *Time, c *Call) (Object, error) {
		if err := c.Args.CheckLen(0); err != nil {
			return Nil, err
		}
		return Int(o.Value.Second()), nil
	},
	"Nanosecond": func(o *Time, c *Call) (Object, error) {
		if err := c.Args.CheckLen(0); err != nil {
			return Nil, err
		}
		return Int(o.Value.Nanosecond()), nil
	},

	"ns": func(o *Time, c *Call) (Object, error) {
		if err := c.Args.CheckLen(0); err != nil {
			return Nil, err
		}
		return Int(o.Value.Nanosecond()), nil
	},
	"IsZero": func(o *Time, c *Call) (Object, error) {
		if err := c.Args.CheckLen(0); err != nil {
			return Nil, err
		}
		return Bool(o.Value.IsZero()), nil
	},
	"Local": func(o *Time, c *Call) (Object, error) {
		if err := c.Args.CheckLen(0); err != nil {
			return Nil, err
		}
		return &Time{Value: o.Value.Local()}, nil
	},
	"Location": func(o *Time, c *Call) (Object, error) {
		if err := c.Args.CheckLen(0); err != nil {
			return Nil, err
		}
		return &Location{Value: o.Value.Location()}, nil
	},
	"YearDay": func(o *Time, c *Call) (Object, error) {
		if err := c.Args.CheckLen(0); err != nil {
			return Nil, err
		}
		return Int(o.Value.YearDay()), nil
	},
	"Weekday": func(o *Time, c *Call) (Object, error) {
		if err := c.Args.CheckLen(0); err != nil {
			return Nil, err
		}
		return Int(o.Value.Weekday()), nil
	},
	"ISOWeek": func(o *Time, c *Call) (Object, error) {
		if err := c.Args.CheckLen(0); err != nil {
			return Nil, err
		}
		y, w := o.Value.ISOWeek()
		return Dict{"year": Int(y), "week": Int(w)}, nil
	},
	"Zone": func(o *Time, c *Call) (Object, error) {
		if err := c.Args.CheckLen(0); err != nil {
			return Nil, err
		}
		name, offset := o.Value.Zone()
		return Dict{"name": Str(name), "offset": Int(offset)}, nil
	},
}
View Source
var NaN = Float(math.NaN())
View Source
var OpcodeNames = [...]string{
	OpNoOp:              "NOOP",
	OpConstant:          "CONSTANT",
	OpCall:              "CALL",
	OpGetGlobal:         "GETGLOBAL",
	OpSetGlobal:         "SETGLOBAL",
	OpGetLocal:          "GETLOCAL",
	OpSetLocal:          "SETLOCAL",
	OpGetBuiltin:        "GETBUILTIN",
	OpBinary:            "BINARY",
	OpUnary:             "UNARY",
	OpSelfAssign:        "SELFASSIGN",
	OpEqual:             "EQUAL",
	OpNotEqual:          "NOTEQUAL",
	OpJump:              "JUMP",
	OpJumpFalsy:         "JUMPFALSY",
	OpAndJump:           "ANDJUMP",
	OpOrJump:            "ORJUMP",
	OpDict:              "DICT",
	OpArray:             "ARRAY",
	OpSliceIndex:        "SLICEINDEX",
	OpGetIndex:          "GETINDEX",
	OpSetIndex:          "SETINDEX",
	OpNil:               "NIL",
	OpStdIn:             "STDIN",
	OpStdOut:            "STDOUT",
	OpStdErr:            "STDERR",
	OpDotName:           "DOTNAME",
	OpDotFile:           "DOTFILE",
	OpIsMain:            "ISMAIN",
	OpNotIsMain:         "NOTISMAIN",
	OpModule:            "MODULE",
	OpGlobals:           "GLOBALS",
	OpPop:               "POP",
	OpGetFree:           "GETFREE",
	OpSetFree:           "SETFREE",
	OpGetLocalPtr:       "GETLOCALPTR",
	OpGetFreePtr:        "GETFREEPTR",
	OpClosure:           "CLOSURE",
	OpIterInit:          "ITERINIT",
	OpIterNext:          "ITERNEXT",
	OpIterNextElse:      "ITERNEXTELSE",
	OpIterKey:           "ITERKEY",
	OpIterValue:         "ITERVALUE",
	OpLoadModule:        "LOADMODULE",
	OpInitModule:        "INITMODULE",
	OpReturn:            "RETURN",
	OpSetReturn:         "SETRETURN",
	OpSetReturnModule:   "SETRETURNMODULE",
	OpSetupTry:          "SETUPTRY",
	OpSetupCatch:        "SETUPCATCH",
	OpSetupFinally:      "SETUPFINALLY",
	OpThrow:             "THROW",
	OpFinalizer:         "FINALIZER",
	OpDefineLocal:       "DEFINELOCAL",
	OpTrue:              "TRUE",
	OpFalse:             "FALSE",
	OpYes:               "YES",
	OpNo:                "NO",
	OpCallName:          "CALLNAME",
	OpJumpNil:           "JUMPNIL",
	OpJumpNotNil:        "JUMPNOTNIL",
	OpKeyValueArray:     "KVARRAY",
	OpKeyValue:          "KV",
	OpCallee:            "CALLEE",
	OpArgs:              "ARGS",
	OpNamedArgs:         "NAMEDARGS",
	OpIsNil:             "ISNIL",
	OpNotIsNil:          "NOTISNIL",
	OpNamedParamsVar:    "NAMEDPARAMSVAR",
	OpNamedParamValue:   "NPARAMVALUE",
	OpComputedValue:     "COMPUTEDVALUE",
	OpAddMethod:         "ADDMETHOD",
	OpExtendModule:      "EXTENDMODULE",
	OpToRawStr:          "TORAWSTR",
	OpAddMethodOverride: "ADDMETHODOVERRIDE",
	OpAssign:            "ASSIGN",
}

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},
	OpBinary:            {1},
	OpUnary:             {1},
	OpSelfAssign:        {1},
	OpEqual:             {},
	OpNotEqual:          {},
	OpIsNil:             {},
	OpNotIsNil:          {},
	OpJump:              {2},
	OpJumpFalsy:         {2},
	OpAndJump:           {2},
	OpOrJump:            {2},
	OpDict:              {2},
	OpArray:             {2},
	OpSliceIndex:        {},
	OpGetIndex:          {1},
	OpSetIndex:          {},
	OpNil:               {},
	OpStdIn:             {},
	OpStdOut:            {},
	OpStdErr:            {},
	OpDotName:           {},
	OpDotFile:           {},
	OpIsMain:            {},
	OpNotIsMain:         {},
	OpModule:            {},
	OpGlobals:           {},
	OpPop:               {},
	OpGetFree:           {1},
	OpSetFree:           {1},
	OpGetLocalPtr:       {1},
	OpGetFreePtr:        {1},
	OpClosure:           {2, 1},
	OpIterInit:          {},
	OpIterNext:          {},
	OpIterNextElse:      {2, 2},
	OpIterKey:           {},
	OpIterValue:         {},
	OpLoadModule:        {2},
	OpInitModule:        {1, 1},
	OpSetReturn:         {1},
	OpSetReturnModule:   {},
	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},
	OpNamedParamsVar:    {},
	OpNamedParamValue:   {},
	OpComputedValue:     {},
	OpAddMethod:         {1, 1},
	OpExtendModule:      {},
	OpToRawStr:          {},
	OpAddMethodOverride: {1, 1},
	OpAssign:            {},
}

OpcodeOperands is the number of operands.

RangeType is the builtin `Range` object type. The `Range(from, to; step)` constructor and the `..` operator both produce *Range values.

TFunctionHeader is the builtin `FuncHeaderObject` object type.

View Source
var TInterface = RegisterBuiltinType(BuiltinInterface, "Interface", Interface{}, nil)

TInterface is the builtin `Interface` object type. It has no constructor.

TMethodInterface is the builtin `MethodInterface` object type.

View Source
var (
	TOperator = NewType("Operator", TBase)
)

TProp is the builtin `Prop` object type.

View Source
var TimeLocationType = NewBuiltinObjType("Location").WithNew(NewLocationFunc)
View Source
var TimeModuleSpec = NewModuleSpecFromName("time")

TimeModuleSpec is the module spec shared by the builtin `time` namespace members and the importable time module.

View Source
var TimeType = NewBuiltinObjType("time").WithNew(NewTimeFunc)
View Source
var Types = map[reflect.Type]ObjectType{}

Functions

func AddMethodT added in v0.0.2

func AddMethodT[T Object](target T, method ...TypedCallerObjectWithParamTypes) T

func AddressOf added in v0.0.2

func AddressOf(obj Object) unsafe.Pointer

func ArrayToString

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

func ArrayToStringBraces added in v0.0.2

func ArrayToStringBraces(lb, rb string, len int, get func(i int) Object) string

func Callable

func Callable(o Object) (ok bool)

func CloserFrom

func CloserFrom(o Object) (r io.Closer)

func Copy

func Copy[T Object](o T) T

func DeepCopy

func DeepCopy[T Object](vm *VM, o T) (_ T, err error)

func Filterable

func Filterable(obj Object) bool

func FormatInstructions

func FormatInstructions(builtins *Builtins, constants Array, b []byte, posOffset int) []string

FormatInstructions returns string representation of bytecode instructions.

func FormatReturnVars added in v0.0.2

func FormatReturnVars(vars ReturnVars) string

func GoTimeArg added in v0.0.2

func GoTimeArg(arg *Arg) (get func() *Time)

func IsAssignableTo added in v0.0.2

func IsAssignableTo(typ, refType ObjectType) (ok bool)

func IsFunction added in v0.0.2

func IsFunction(o Object) (ok bool)

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 IsNil

func IsNil(value any) bool

func IsObjector

func IsObjector(obj Object) (ok bool)

func IsPrimitive

func IsPrimitive(obj Object) bool

func IsType

func IsType(obj Object) (ok bool)

func IsTypeAssignableTo

func IsTypeAssignableTo(a ObjectType, b TypeAssigner) bool

func ItemsOfCb

func ItemsOfCb(vm *VM, na *NamedArgs, cb func(kv *KeyValue) error, o ...Object) (err error)

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 MethodInterfaceImplements added in v0.0.2

func MethodInterfaceImplements(vm *VM, value Object, ifaces ...*MethodInterface) (bool, error)

MethodInterfaceImplements reports whether value (a callable) structurally satisfies every header of the given method interface(s) — the same match used by the `implements` builtin. A non-callable value never implements.

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 ObjectsStrW

func ObjectsStrW(w io.Writer, vm *VM, len int, get func(i int) Object) (err error)

func Print

func Print(state *PrinterState, o ...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 Readable

func Readable(o Object) (ok bool)

func Reducable

func Reducable(obj Object) bool

func ReprTypeName added in v0.0.2

func ReprTypeName(o Object) (name string)

func SplitCaller added in v0.0.2

func SplitCaller(vm *VM, caller Object, cb func(co CallerObject, types ParamsTypes) error, fallback ...func(co CallerObject) error) (err error)

func TestBytecodesEqual

func TestBytecodesEqual(t *testing.T,
	expected, got *Bytecode, checkSourceMap bool, opt ...*TestBytecodesEqualOptions)

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 ToRawStrW

func ToRawStrW(w io.Writer, vm *VM, o Object) (err error)

func ToStrW

func ToStrW(w io.Writer, vm *VM, o Object) (err error)

func ToWritable

func ToWritable(obj Object) bool

func TranspileOptions

func TranspileOptions() *node.TranspileOptions

func TypeAssignerFullName added in v0.0.2

func TypeAssignerFullName(t TypeAssigner) string

TypeAssignerFullName returns a fully-qualified display name for a type assigner, falling back to TypeAssignerName.

func TypeAssignerName added in v0.0.2

func TypeAssignerName(t TypeAssigner) string

TypeAssignerName returns a display name for a type assigner (an ObjectType's Name, a meti/interface's Name, else its ToString).

func TypeAssigners added in v0.0.2

func TypeAssigners(t ObjectType, cb func(t ObjectType) any) (ret any)

func TypeToString

func TypeToString(typeName string) string

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

func Writeable

func Writeable(o Object) (ok bool)

Types

type Adder

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

type Appender

type Appender interface {
	Object
	AppendObjects(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 ArgValue

type ArgValue struct {
	Arg   Arg
	Value any
}

type Args

type Args []Array

func (Args) Array

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

func (Args) BinOpGreater added in v0.0.2

func (o Args) BinOpGreater(_ *VM, right Object) (Object, error)

func (Args) BinOpGreaterEq added in v0.0.2

func (o Args) BinOpGreaterEq(_ *VM, right Object) (Object, error)

func (Args) BinOpLess added in v0.0.2

func (o Args) BinOpLess(_ *VM, right Object) (Object, error)

Args compares by length against another Args, and orders after nil; these implement the comparison ObjectWith{Op}BinOperator interfaces.

func (Args) BinOpLessEq added in v0.0.2

func (o Args) BinOpLessEq(_ *VM, 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) DestructureRangeVar added in v0.0.2

func (o Args) DestructureRangeVar(maxVar int, dst ...*Arg) (other Array, err error)

DestructureRangeVar 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) DestructureTo

func (o Args) DestructureTo(dst ...ArgValue) (err error)

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) DestructureVarMinCb added in v0.0.2

func (o Args) DestructureVarMinCb(min int, otherCb func(i int, arg Object) error, dst ...*Arg) (err error)

DestructureVarMinCb shifts argument and set value to dst, and returns left arguments. If the number of arguments is less then to called args length + min, it returns an error. If type check of arg is fails, returns ArgumentTypeError. If has more args, call otherCb.

func (Args) DestructureVarRangeCb added in v0.0.2

func (o Args) DestructureVarRangeCb(min, max int, otherCb func(i int, arg Object) error, dst ...*Arg) (err error)

DestructureVarRangeCb shifts argument and set value to dst, and returns left arguments. If the number of arguments is less then to called args length + min, it returns an error. If type check of arg is fails, returns ArgumentTypeError. If has more args, call otherCb.

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

func (o Args) Items(_ *VM, cb ItemsGetterCallback) (err error)

func (Args) Iterate

func (o Args) Iterate(vm *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) Types

func (o Args) Types() (types ObjectTypeArray)

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

func (o Args) WalkE(cb func(i int, arg Object) error) (err error)

WalkE 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 ConvertToArray

func ConvertToArray(vm *VM, o ...Object) (ret Array, err error)

ConvertToArray convert objects to Array. If success return then, otherwise return error.

func MustConvertToArray

func MustConvertToArray(vm *VM, o ...Object) Array

MustConvertToArray convert objects to Array and return then if success, otherwise panics.

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

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

func (Array) AppendObjects

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

func (Array) AppendToArray

func (o Array) AppendToArray(arr Array) Array

func (Array) BinOpAdd added in v0.0.2

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

BinOpAdd appends right to the array (ObjectWithAddBinOperator): an iterable extends it, any other value (including strings) is appended as one element.

func (Array) BinOpGreater added in v0.0.2

func (o Array) BinOpGreater(_ *VM, right Object) (Object, error)

func (Array) BinOpGreaterEq added in v0.0.2

func (o Array) BinOpGreaterEq(_ *VM, right Object) (Object, error)

func (Array) BinOpIn added in v0.0.2

func (o Array) BinOpIn(_ *VM, v Object) (Object, error)

Contains reports whether v equals an element of the array (`v in array`). BinOpIn implements the `in` operator (ObjectWithInBinOperator): reports whether v is an element of o.

func (Array) BinOpLess added in v0.0.2

func (o Array) BinOpLess(_ *VM, right Object) (Object, error)

An array orders after nil and is otherwise not comparable.

func (Array) BinOpLessEq added in v0.0.2

func (o Array) BinOpLessEq(_ *VM, right Object) (Object, error)

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, cb ItemsGetterCallback) (err error)

func (Array) Iterate

func (o Array) Iterate(vm *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) Print

func (o Array) Print(state *PrinterState) (err error)

func (Array) PrintObject added in v0.0.2

func (o Array) PrintObject(state *PrinterState, obj Object) (err error)

func (Array) SelfAssignOpAdd added in v0.0.2

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

SelfAssignOpAdd handles `arr += v`: append the single value v.

func (Array) SelfAssignOpInc added in v0.0.2

func (o Array) SelfAssignOpInc(vm *VM, value Object) (Object, error)

SelfAssignOpInc handles `arr ++= v`: append the elements of v (spread).

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 BinaryOperatorType

type BinaryOperatorType token.Token

func (BinaryOperatorType) AssignTo added in v0.0.2

func (b BinaryOperatorType) AssignTo(_ *VM, obj Object, to TypeAssigner) (Object, error)

func (BinaryOperatorType) Call

func (BinaryOperatorType) CanAssign added in v0.0.2

func (b BinaryOperatorType) CanAssign(obj Object) (bool, error)

func (BinaryOperatorType) Equal

func (b BinaryOperatorType) Equal(right Object) bool

func (BinaryOperatorType) Fields

func (BinaryOperatorType) Fields() Dict

func (BinaryOperatorType) FullName added in v0.0.2

func (b BinaryOperatorType) FullName() string

func (BinaryOperatorType) GadObjectType added in v0.0.2

func (BinaryOperatorType) GadObjectType()

func (BinaryOperatorType) Getters

func (BinaryOperatorType) Getters() Dict

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

func (BinaryOperatorType) Setters() Dict

func (BinaryOperatorType) String

func (b BinaryOperatorType) String() string

func (BinaryOperatorType) ToString

func (b BinaryOperatorType) ToString() string

func (BinaryOperatorType) Token

func (b BinaryOperatorType) Token() token.Token

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) BinOpAdd added in v0.0.2

func (o Bool) BinOpAdd(vm *VM, right Object) (Object, error)

A Bool behaves as 0/1 in arithmetic, with the result type following the numeric right operand (Int or Uint). These implement the per-operator ObjectWith{Op}BinOperator interfaces.

func (Bool) BinOpAnd added in v0.0.2

func (o Bool) BinOpAnd(vm *VM, right Object) (Object, error)

func (Bool) BinOpAndNot added in v0.0.2

func (o Bool) BinOpAndNot(vm *VM, right Object) (Object, error)

func (Bool) BinOpGreater added in v0.0.2

func (o Bool) BinOpGreater(vm *VM, right Object) (Object, error)

func (Bool) BinOpGreaterEq added in v0.0.2

func (o Bool) BinOpGreaterEq(vm *VM, right Object) (Object, error)

func (Bool) BinOpLess added in v0.0.2

func (o Bool) BinOpLess(vm *VM, right Object) (Object, error)

func (Bool) BinOpLessEq added in v0.0.2

func (o Bool) BinOpLessEq(vm *VM, right Object) (Object, error)

func (Bool) BinOpMul added in v0.0.2

func (o Bool) BinOpMul(vm *VM, right Object) (Object, error)

func (Bool) BinOpOr added in v0.0.2

func (o Bool) BinOpOr(vm *VM, right Object) (Object, error)

func (Bool) BinOpQuo added in v0.0.2

func (o Bool) BinOpQuo(vm *VM, right Object) (Object, error)

func (Bool) BinOpRem added in v0.0.2

func (o Bool) BinOpRem(vm *VM, right Object) (Object, error)

func (Bool) BinOpSame added in v0.0.2

func (o Bool) BinOpSame(_ *VM, right Object) (Object, error)

func (Bool) BinOpShl added in v0.0.2

func (o Bool) BinOpShl(vm *VM, right Object) (Object, error)

func (Bool) BinOpShr added in v0.0.2

func (o Bool) BinOpShr(vm *VM, right Object) (Object, error)

func (Bool) BinOpSub added in v0.0.2

func (o Bool) BinOpSub(vm *VM, right Object) (Object, error)

func (Bool) BinOpXor added in v0.0.2

func (o Bool) BinOpXor(vm *VM, right Object) (Object, error)

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

func (Bool) UnOpAdd added in v0.0.2

func (o Bool) UnOpAdd(*VM) (Object, error)

func (Bool) UnOpSub added in v0.0.2

func (o Bool) UnOpSub(*VM) (Object, error)

func (Bool) UnOpXor added in v0.0.2

func (o Bool) UnOpXor(*VM) (Object, error)

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) Print added in v0.0.2

func (o *Buffer) Print(state *PrinterState) error

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

func (*Buffer) WriteTo added in v0.0.2

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

type BuiltinCompilableModule added in v0.0.2

type BuiltinCompilableModule struct {
	Compile BuiltinCompileModuleFunc
}

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

func (*BuiltinCompilableModule) Import added in v0.0.2

func (m *BuiltinCompilableModule) Import(_ context.Context, module *ModuleSpec) (any, string, error)

Import returns an immutable map for the module.

type BuiltinCompileModuleContext added in v0.0.2

type BuiltinCompileModuleContext struct {
	Node     ast.Node
	Compiler *Compiler
	FileSet  *source.FileSet
	Spec     *ModuleSpec
}

func (*BuiltinCompileModuleContext) Compile added in v0.0.2

func (c *BuiltinCompileModuleContext) Compile(smts node.Stmts) error

func (*BuiltinCompileModuleContext) SetFileData added in v0.0.2

func (c *BuiltinCompileModuleContext) SetFileData(data []byte) *source.File

type BuiltinCompileModuleFunc added in v0.0.2

type BuiltinCompileModuleFunc func(ctx *BuiltinCompileModuleContext) (*Bytecode, error)

type BuiltinFunction

type BuiltinFunction struct {
	ObjectImpl
	// Module qualifies the function's name (e.g. gad.binOpAdd) and scopes it to
	// a builtin namespace; set with WithModule.
	Module *ModuleSpec
	// FuncName is the function's (unqualified) name, used in repr and errors.
	FuncName string
	// Value is the Go handler invoked on each call.
	Value func(Call) (Object, error)
	// Header declares the parameter signature (names/types); it drives argument
	// dispatch and appears in repr. Set it via WithParams/WithParamsPairs.
	Header *FunctionHeader
	// AcceptMethodsDisabled prevents the function from being promoted to a
	// method-bearing builtin (no `met`/AddMethod overloads allowed).
	AcceptMethodsDisabled bool
	// Usage is optional Markdown documentation shown by Doc().
	Usage string
}

BuiltinFunction is a runtime-provided callable registered in the builtins table (see BuiltinObjects / BuiltinsMap). It behaves like Function but is part of the interpreter's standard environment rather than user code. Build one with NewBuiltinFunction and the fluent With* options:

fn := NewBuiltinFunction("binOpAdd", func(c Call) (Object, error) { … }).
	WithModule(gadModuleSpec).WithParamsPairs("left", TAny, "right", TAny)

A BuiltinFunction holds a single handler; to accept typed method overloads (via `met`/AddMethod) it is promoted to a BuiltinFunctionWithMethods.

func NewBuiltinFunction

func NewBuiltinFunction(name string, value func(Call) (Object, error), opt ...BuiltinFunctionOption) *BuiltinFunction

func (*BuiltinFunction) Call

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

func (*BuiltinFunction) Copy

func (f *BuiltinFunction) Copy() Object

Copy implements Copier interface.

func (*BuiltinFunction) Doc added in v0.0.2

func (f *BuiltinFunction) Doc() string

func (*BuiltinFunction) Equal

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

Equal implements Object interface.

func (*BuiltinFunction) IsFalsy

func (*BuiltinFunction) IsFalsy() bool

IsFalsy implements Object interface.

func (*BuiltinFunction) MethodsDisabled

func (f *BuiltinFunction) MethodsDisabled() bool

func (*BuiltinFunction) Name

func (f *BuiltinFunction) Name() string

func (*BuiltinFunction) ParamTypes

func (f *BuiltinFunction) ParamTypes() ParamsTypes

func (*BuiltinFunction) ReturnVars added in v0.0.2

func (f *BuiltinFunction) ReturnVars() ReturnVars

func (*BuiltinFunction) String added in v0.0.2

func (f *BuiltinFunction) String() string

func (*BuiltinFunction) ToString

func (f *BuiltinFunction) ToString() string

func (*BuiltinFunction) Type

func (*BuiltinFunction) Type() ObjectType

func (*BuiltinFunction) WithHeader added in v0.0.2

func (f *BuiltinFunction) WithHeader(do func(h *FunctionHeader)) *BuiltinFunction

func (*BuiltinFunction) WithModule added in v0.0.2

func (f *BuiltinFunction) WithModule(module *ModuleSpec) *BuiltinFunction

func (*BuiltinFunction) WithParams added in v0.0.2

func (f *BuiltinFunction) WithParams(builder func(newParam func(name string) *ParamBuilder)) *BuiltinFunction

func (*BuiltinFunction) WithParamsPairs added in v0.0.2

func (f *BuiltinFunction) WithParamsPairs(nameAndType ...any) *BuiltinFunction

type BuiltinFunctionOption added in v0.0.2

type BuiltinFunctionOption func(f *BuiltinFunction)

func BuiltinFunctionWithHeader added in v0.0.2

func BuiltinFunctionWithHeader(do func(h *FunctionHeader)) BuiltinFunctionOption

func BuiltinFunctionWithModule added in v0.0.2

func BuiltinFunctionWithModule(module *ModuleSpec) BuiltinFunctionOption

type BuiltinFunctionWithMethods added in v0.0.2

type BuiltinFunctionWithMethods struct {
	*FuncSpec

	Module *ModuleSpec
	// contains filtered or unexported fields
}

func NewBuiltinFunctionWithMethods added in v0.0.2

func NewBuiltinFunctionWithMethods(name string, module *ModuleSpec) *BuiltinFunctionWithMethods

func (BuiltinFunctionWithMethods) Copy added in v0.0.2

func (*BuiltinFunctionWithMethods) Equal added in v0.0.2

func (f *BuiltinFunctionWithMethods) Equal(right Object) bool

func (*BuiltinFunctionWithMethods) FullName added in v0.0.2

func (f *BuiltinFunctionWithMethods) FullName() string

func (*BuiltinFunctionWithMethods) FuncSpecName added in v0.0.2

func (f *BuiltinFunctionWithMethods) FuncSpecName() string

func (*BuiltinFunctionWithMethods) GetModule added in v0.0.2

func (f *BuiltinFunctionWithMethods) GetModule() *ModuleSpec

func (*BuiltinFunctionWithMethods) Name added in v0.0.2

func (*BuiltinFunctionWithMethods) Print added in v0.0.2

func (f *BuiltinFunctionWithMethods) Print(state *PrinterState) (err error)

func (*BuiltinFunctionWithMethods) String added in v0.0.2

func (f *BuiltinFunctionWithMethods) String() string

func (*BuiltinFunctionWithMethods) ToString added in v0.0.2

func (f *BuiltinFunctionWithMethods) ToString() string

func (*BuiltinFunctionWithMethods) Type added in v0.0.2

type BuiltinInitModule added in v0.0.2

type BuiltinInitModule struct {
	Init ModuleInitFunc
}

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

func (*BuiltinInitModule) Import added in v0.0.2

func (m *BuiltinInitModule) Import(_ context.Context, module *ModuleSpec) (any, string, error)

Import returns an immutable map for the module.

type BuiltinModule

type BuiltinModule struct {
	Attrs Dict
	// contains filtered or unexported fields
}

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

func (*BuiltinModule) Import

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

Import returns an immutable map for the module.

func (*BuiltinModule) InitFunc added in v0.0.2

func (m *BuiltinModule) InitFunc() ModuleInitFunc

type BuiltinObjType

type BuiltinObjType struct {
	Module *ModuleSpec

	*FuncSpec
	// contains filtered or unexported fields
}

func NewBuiltinObjType

func NewBuiltinObjType(name string) *BuiltinObjType

func RegisterBuiltinType

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

func (*BuiltinObjType) AssignTo added in v0.0.2

func (t *BuiltinObjType) AssignTo(_ *VM, obj Object, to TypeAssigner) (Object, error)

func (*BuiltinObjType) BuiltinType added in v0.0.2

func (t *BuiltinObjType) BuiltinType() BuiltinType

func (*BuiltinObjType) CanAssign added in v0.0.2

func (t *BuiltinObjType) CanAssign(obj Object) (bool, error)

func (BuiltinObjType) Copy added in v0.0.2

func (t BuiltinObjType) Copy() Object

func (*BuiltinObjType) Equal

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

func (*BuiltinObjType) Fields

func (t *BuiltinObjType) Fields() Dict

func (*BuiltinObjType) FullName added in v0.0.2

func (t *BuiltinObjType) FullName() string

FullName returns the type's display name, qualified with its module when it belongs to one (e.g. `time.Time`, `time.Location`). Standalone types (int, str, …) render by their bare name.

func (*BuiltinObjType) FuncSpecName added in v0.0.2

func (t *BuiltinObjType) FuncSpecName() string

func (*BuiltinObjType) GadObjectType added in v0.0.2

func (t *BuiltinObjType) GadObjectType()

func (*BuiltinObjType) GetModule added in v0.0.2

func (t *BuiltinObjType) GetModule() *ModuleSpec

func (*BuiltinObjType) Getters

func (t *BuiltinObjType) Getters() Dict

func (*BuiltinObjType) IsFalsy

func (t *BuiltinObjType) IsFalsy() bool

func (*BuiltinObjType) Methods

func (t *BuiltinObjType) Methods() Dict

func (*BuiltinObjType) Name

func (t *BuiltinObjType) Name() string

func (*BuiltinObjType) Print added in v0.0.2

func (t *BuiltinObjType) Print(state *PrinterState) (err error)

func (*BuiltinObjType) ReprTypeName added in v0.0.2

func (t *BuiltinObjType) ReprTypeName() string

func (*BuiltinObjType) SetModule added in v0.0.2

func (t *BuiltinObjType) SetModule(m *ModuleSpec)

func (*BuiltinObjType) Setters

func (t *BuiltinObjType) Setters() Dict

func (*BuiltinObjType) String

func (t *BuiltinObjType) String() string

func (*BuiltinObjType) ToString

func (t *BuiltinObjType) ToString() string

func (*BuiltinObjType) Type

func (t *BuiltinObjType) Type() ObjectType

func (*BuiltinObjType) TypeKey added in v0.0.2

func (t *BuiltinObjType) TypeKey() BuiltinObjTypeKey

func (*BuiltinObjType) WithNew added in v0.0.2

type BuiltinObjTypeKey added in v0.0.2

type BuiltinObjTypeKey BuiltinType
var (
	TNil,
	TFlag,
	TBool,
	TInt,
	TUint,
	TFloat,
	TDecimal,
	TChar,
	TRawStr,
	TStr,
	TTypedIdent,
	TBytes,
	TBuffer,
	TArray,
	TDict,
	TSyncDict,
	TKeyValue,
	TKeyValueArray,
	TRegexp,
	TRegexpStrsResult,
	TRegexpStrsSliceResult,
	TRegexpBytesResult,
	TRegexpBytesSliceResult,
	TMixedParams,
	TError,
	TPrinterState,
	TFunc,
	TComputedValue,
	TBuiltinFunction,
	TCallWrapper,
	TCompiledFunction,
	TFunction,
	TKeyValueArrays,
	TArgs,
	TNamedArgs,
	TObjectPtr,
	TReader,
	TWriter,
	TDiscardWriter,
	TObjectTypeArray,
	TReflectMethod,
	TIndexGetProxy BuiltinObjTypeKey
)

func (BuiltinObjTypeKey) AssignTo added in v0.0.2

func (b BuiltinObjTypeKey) AssignTo(_ *VM, obj Object, to TypeAssigner) (Object, error)

func (BuiltinObjTypeKey) BType added in v0.0.2

func (b BuiltinObjTypeKey) BType() BuiltinType

func (BuiltinObjTypeKey) Call added in v0.0.2

func (b BuiltinObjTypeKey) Call(c Call) (Object, error)

func (BuiltinObjTypeKey) CanAssign added in v0.0.2

func (b BuiltinObjTypeKey) CanAssign(obj Object) (bool, error)

func (BuiltinObjTypeKey) Equal added in v0.0.2

func (b BuiltinObjTypeKey) Equal(right Object) bool

func (BuiltinObjTypeKey) FullName added in v0.0.2

func (b BuiltinObjTypeKey) FullName() string

func (BuiltinObjTypeKey) GadObjectType added in v0.0.2

func (BuiltinObjTypeKey) GadObjectType()

func (BuiltinObjTypeKey) IsFalsy added in v0.0.2

func (b BuiltinObjTypeKey) IsFalsy() bool

func (BuiltinObjTypeKey) Name added in v0.0.2

func (b BuiltinObjTypeKey) Name() string

func (BuiltinObjTypeKey) Print added in v0.0.2

func (b BuiltinObjTypeKey) Print(state *PrinterState) error

func (BuiltinObjTypeKey) String added in v0.0.2

func (b BuiltinObjTypeKey) String() string

func (BuiltinObjTypeKey) ToString added in v0.0.2

func (b BuiltinObjTypeKey) ToString() string

func (BuiltinObjTypeKey) Type added in v0.0.2

func (b BuiltinObjTypeKey) Type() ObjectType

type BuiltinObjectsMap

type BuiltinObjectsMap map[BuiltinType]Object

func (BuiltinObjectsMap) AddMethod added in v0.0.2

func (BuiltinObjectsMap) Append

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

type BuiltinType

type BuiltinType uint16

BuiltinType represents a builtin type

const (
	BuiltinTypesBegin_ BuiltinType = iota
	// types
	BuiltinNil
	BuiltinAny
	BuiltinFlag
	BuiltinBool
	BuiltinInt
	BuiltinUint
	BuiltinFloat
	BuiltinDecimal
	BuiltinChar
	BuiltinRawStr
	BuiltinStr
	BuiltinBytes
	BuiltinArray
	BuiltinDict
	BuiltinSyncDic
	BuiltinKeyValue
	BuiltinKeyValueArray
	BuiltinError
	BuiltinBuffer
	BuiltinRegexp
	BuiltinRegexpStrsResult
	BuiltinRegexpStrsSliceResult
	BuiltinRegexpBytesResult
	BuiltinRegexpBytesSliceResult
	BuiltinIterator
	BuiltinZipIterator
	BuiltinMixedParams
	BuiltinPrinterState
	BuiltinTypedIdent
	BuiltinFunc
	BuiltinComputedValue
	// BuiltinProp is the builtin object type for getter/setter properties.
	BuiltinProp
	// BuiltinFunctionHeader is the builtin object type for func-header values.
	BuiltinFunctionHeader
	// BuiltinMethodInterface is the builtin object type for method interfaces.
	BuiltinMethodInterface
	// BuiltinInterface is the builtin object type for `interface { … }` values.
	BuiltinInterface
	BuiltinTypesEnd_

	BuiltinStaticTypesStart_
	BuiltinStaticTypeBuiltinFunction
	BuiltinStaticTypeCallWrapper
	BuiltinStaticTypeCompiledFunction
	BuiltinStaticTypeFunction
	BuiltinStaticTypeKeyValueArrays
	BuiltinStaticTypeArgs
	BuiltinStaticTypeNamedArgs
	BuiltinStaticTypeObjectPtr
	BuiltinStaticTypeReader
	BuiltinStaticTypeWriter
	BuiltinStaticTypeDiscardWriter
	BuiltinStaticTypeObjectTypeArray
	BuiltinStaticTypeReflectMethod
	BuiltinStaticTypeIndexGetProxy
	BuiltinRange
	BuiltinStaticTypesEnd_

	BuiltinFunctionsBegin_
	BuiltinBinaryOperator
	BuiltinSelfAssignOperator
	BuiltinUnaryOperator
	BuiltinEnter
	BuiltinExit
	BuiltinRepr
	BuiltinCast
	BuiltinAppend
	BuiltinDelete
	BuiltinCopy
	BuiltinDeepCopy
	BuiltinRepeat
	BuiltinContains
	BuiltinLen
	BuiltinSort
	BuiltinSortReverse
	BuiltinFilter
	BuiltinMap
	BuiltinEach
	BuiltinReduce
	BuiltinTypeName
	BuiltinChars
	BuiltinClose
	BuiltinRead
	BuiltinWrite
	BuiltinPrint
	BuiltinPrintf
	BuiltinPrintln
	BuiltinSprintf
	BuiltinStdIO
	BuiltinWrap
	BuiltinNewClass
	BuiltinTypeOf
	BuiltinAddMethod
	BuiltinRawCaller
	BuiltinMakeArray
	BuiltinMakeArrayRest
	BuiltinCap
	BuiltinIterate
	BuiltinKeys
	BuiltinValues
	BuiltinItems
	BuiltinCollect
	BuiltinEnumerate
	BuiltinIteratorInput
	BuiltinVMPushWriter
	BuiltinVMPopWriter
	BuiltinOBStart
	BuiltinOBEnd
	BuiltinFlush
	BuiltinUserData
	BuiltinNamedParamTypeCheck
	BuiltinToArray

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

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

	BuiltinConstantsBegin_
	BuiltinDiscardWriter
	BuiltinConstantsEnd_

	// Builtin module namespaces (stdlib modules exposed without `import`).
	GroupBuiltinModulesBegin
	BuiltinModuleBase64
	BuiltinModuleStrings
	BuiltinModuleTime
	BuiltinModuleFmt
	BuiltinModuleGad
	GroupBuiltinModulesEnd

	GroupBuiltinBinaryOperatorsBegin
	BuiltinBinaryOperatorAdd
	BuiltinBinaryOperatorSub
	BuiltinBinaryOperatorMul
	BuiltinBinaryOperatorPow
	BuiltinBinaryOperatorQuo
	BuiltinBinaryOperatorRem
	BuiltinBinaryOperatorAnd
	BuiltinBinaryOperatorOr
	BuiltinBinaryOperatorXor
	BuiltinBinaryOperatorShl
	BuiltinBinaryOperatorShr
	BuiltinBinaryOperatorAndNot
	BuiltinBinaryOperatorLAnd
	BuiltinBinaryOperatorEqual
	BuiltinBinaryOperatorNotEqual
	BuiltinBinaryOperatorLess
	BuiltinBinaryOperatorGreater
	BuiltinBinaryOperatorLessEq
	BuiltinBinaryOperatorGreaterEq
	BuiltinBinaryOperatorTilde
	BuiltinBinaryOperatorDoubleTilde
	BuiltinBinaryOperatorTripleTilde
	BuiltinBinaryOperatorDotDot
	BuiltinBinaryOperatorTripleLess
	BuiltinBinaryOperatorTripleGreater
	BuiltinBinaryOperatorDoubleMod
	BuiltinBinaryOperatorLambda
	BuiltinBinaryOperatorSame
	BuiltinBinaryOperatorNotSame
	BuiltinBinaryOperatorInc
	BuiltinBinaryOperatorDec
	BuiltinBinaryOperatorIn
	BuiltinBinaryOperatorAin
	GroupBuiltinBinaryOperatorsEnd

	GroupBuiltinSelfAssignOperatorsBegin
	BuiltinSelfAssignOperatorAdd
	BuiltinSelfAssignOperatorInc
	BuiltinSelfAssignOperatorSub
	BuiltinSelfAssignOperatorDec
	BuiltinSelfAssignOperatorMul
	BuiltinSelfAssignOperatorPow
	BuiltinSelfAssignOperatorQuo
	BuiltinSelfAssignOperatorRem
	BuiltinSelfAssignOperatorAnd
	BuiltinSelfAssignOperatorOr
	BuiltinSelfAssignOperatorXor
	BuiltinSelfAssignOperatorShl
	BuiltinSelfAssignOperatorShr
	BuiltinSelfAssignOperatorTripleLess
	BuiltinSelfAssignOperatorTripleGreater
	BuiltinSelfAssignOperatorDoubleMod
	BuiltinSelfAssignOperatorAndNot
	BuiltinSelfAssignOperatorLOr
	GroupBuiltinSelfAssignOperatorsEnd

	GroupBuiltinUnaryOperatorsBegin
	BuiltinUnaryOperatorNot
	BuiltinUnaryOperatorSub
	BuiltinUnaryOperatorAdd
	BuiltinUnaryOperatorXor
	BuiltinUnaryOperatorInc
	BuiltinUnaryOperatorDec
	GroupBuiltinUnaryOperatorsEnd

	BuiltinEnd_
)

Builtins

func NewBuiltinType

func NewBuiltinType() (t BuiltinType)

func (BuiltinType) String

func (t BuiltinType) String() string

type Builtins

type Builtins struct {
	Objects BuiltinObjectsMap
	NameSet BuiltinsNameSet
	// contains filtered or unexported fields
}

func NewBuiltins

func NewBuiltins() *Builtins

func (*Builtins) AppendMap

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

func (*Builtins) ArgsInvoker

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

func (*Builtins) Build added in v0.0.2

func (b *Builtins) Build() (s *StaticBuiltins)

func (*Builtins) Call

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

func (*Builtins) Caller

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

func (*Builtins) Get

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

func (*Builtins) Invoker

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

func (*Builtins) Set

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

func (*Builtins) SetType

func (b *Builtins) SetType(typ ObjectType) *Builtins

type BuiltinsNameSet added in v0.0.2

type BuiltinsNameSet map[string]BuiltinType

type Bytecode

type Bytecode struct {
	FileSet    *source.FileSet
	Main       *CompiledFunction
	Constants  Array
	Modules    []*ModuleSpec
	NumModules int
}

Bytecode holds the compiled functions and constants.

func Compile

func Compile(st *SymbolTable, script []byte, opts CompileOptions) (pf *parser.File, bc *Bytecode, err error)

Compile compiles given script to Bytecode.

func CompileFile added in v0.0.2

func CompileFile(st *SymbolTable, module *ModuleSpec, pf *parser.File, opts CompileOptions) (bc *Bytecode, err error)

CompileFile compiles given module file to Bytecode.

func CompileModule added in v0.0.2

func CompileModule(st *SymbolTable, module *ModuleSpec, script []byte, opts CompileOptions) (pf *parser.File, bc *Bytecode, err error)

CompileModule compiles given module script to Bytecode.

func (*Bytecode) Fprint

func (bc *Bytecode) Fprint(builtins *Builtins, 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) BinOpAdd added in v0.0.2

func (o Bytes) BinOpAdd(_ *VM, right Object) (Object, error)

BinOpAdd appends Bytes or a Str to the bytes (ObjectWithAddBinOperator).

func (Bytes) BinOpGreater added in v0.0.2

func (o Bytes) BinOpGreater(_ *VM, right Object) (Object, error)

func (Bytes) BinOpGreaterEq added in v0.0.2

func (o Bytes) BinOpGreaterEq(_ *VM, right Object) (Object, error)

func (Bytes) BinOpIn added in v0.0.2

func (o Bytes) BinOpIn(_ *VM, v Object) (Object, error)

Contains reports whether v (a byte-valued number/char in 0..255) is present in the bytes (`v in bytes`). BinOpIn implements the `in` operator (ObjectWithInBinOperator): reports whether the byte value v is present in o.

func (Bytes) BinOpLess added in v0.0.2

func (o Bytes) BinOpLess(_ *VM, right Object) (Object, error)

func (Bytes) BinOpLessEq added in v0.0.2

func (o Bytes) BinOpLessEq(_ *VM, right Object) (Object, error)

func (Bytes) BinOpSame added in v0.0.2

func (o Bytes) BinOpSame(_ *VM, right Object) (Object, error)

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) 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) Print added in v0.0.2

func (o Bytes) Print(state *PrinterState) (err error)

func (Bytes) ToString

func (o Bytes) ToString() string

func (Bytes) ToStringF added in v0.0.2

func (o Bytes) ToStringF(w io.Writer) (err error)

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 CalendarDate added in v0.0.2

type CalendarDate uint

CalendarDate is a calendar date encoded as the unsigned integer YYYYMMDD (e.g. 20260131 for 2026-01-31); it mirrors a Go uint and is one of the time module's value types.

func CalendarDateFromTime added in v0.0.2

func CalendarDateFromTime(t time.Time) CalendarDate

CalendarDateFromTime returns the CalendarDate (YYYYMMDD) part of t.

func NewCalendarDate added in v0.0.2

func NewCalendarDate(year, month, day int) CalendarDate

NewCalendarDate builds a CalendarDate from its year, month and day components.

func (CalendarDate) BinOpAdd added in v0.0.2

func (o CalendarDate) BinOpAdd(_ *VM, right Object) (Object, error)

BinaryOp supports duration arithmetic, date difference and ordered comparisons:

  • `calendarDate ± duration` -> calendarDate when the result lands on midnight (a whole number of days), otherwise calendarTime
  • `calendarDate - calendarDate` -> duration
  • ordered comparisons -> bool (the YYYYMMDD encoding is monotonic)

func (CalendarDate) BinOpGreater added in v0.0.2

func (o CalendarDate) BinOpGreater(_ *VM, right Object) (Object, error)

func (CalendarDate) BinOpGreaterEq added in v0.0.2

func (o CalendarDate) BinOpGreaterEq(_ *VM, right Object) (Object, error)

func (CalendarDate) BinOpLess added in v0.0.2

func (o CalendarDate) BinOpLess(_ *VM, right Object) (Object, error)

func (CalendarDate) BinOpLessEq added in v0.0.2

func (o CalendarDate) BinOpLessEq(_ *VM, right Object) (Object, error)

func (CalendarDate) BinOpSub added in v0.0.2

func (o CalendarDate) BinOpSub(_ *VM, right Object) (Object, error)

func (CalendarDate) CallName added in v0.0.2

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

CallName dispatches the date accessor methods.

func (CalendarDate) Day added in v0.0.2

func (o CalendarDate) Day() int

func (CalendarDate) Equal added in v0.0.2

func (o CalendarDate) Equal(right Object) bool

Equal implements Object. A CalendarDate equals another CalendarDate or a uint/int with the same YYYYMMDD value.

func (CalendarDate) IsFalsy added in v0.0.2

func (o CalendarDate) IsFalsy() bool

IsFalsy reports whether the date is the zero value.

func (CalendarDate) MarshalJSON added in v0.0.2

func (o CalendarDate) MarshalJSON() ([]byte, error)

MarshalJSON encodes the date as the JSON string "YYYY-MM-DD".

func (CalendarDate) Month added in v0.0.2

func (o CalendarDate) Month() int

func (CalendarDate) Print added in v0.0.2

func (o CalendarDate) Print(s *PrinterState) error

Print writes the date (Printabler); without it the printer's reflection fallback would recurse on this named-uint Object.

func (CalendarDate) Time added in v0.0.2

func (o CalendarDate) Time(loc *time.Location) time.Time

Time returns midnight of this date in the given location (UTC when nil).

func (CalendarDate) ToString added in v0.0.2

func (o CalendarDate) ToString() string

ToString renders the date as YYYY-MM-DD.

func (CalendarDate) Type added in v0.0.2

func (CalendarDate) Type() ObjectType

func (CalendarDate) UnOpDec added in v0.0.2

func (o CalendarDate) UnOpDec(*VM) (Object, error)

func (CalendarDate) UnOpInc added in v0.0.2

func (o CalendarDate) UnOpInc(*VM) (Object, error)

func (CalendarDate) Year added in v0.0.2

func (o CalendarDate) Year() int

type CalendarTime added in v0.0.2

type CalendarTime uint64

CalendarTime is a zone-less wall-clock timestamp stored as the number of nanoseconds since the Unix epoch (interpreted as UTC wall clock). Unlike *Time it carries no location; it mirrors a Go uint64 and is one of the time module's value types. Instants before 1970-01-01 are not representable.

func CalendarTimeFromTime added in v0.0.2

func CalendarTimeFromTime(t time.Time) CalendarTime

CalendarTimeFromTime returns the zone-less CalendarTime of t (its wall-clock fields are kept; the zone is dropped).

func NewCalendarTime added in v0.0.2

func NewCalendarTime(year, month, day, hour, min, sec, nsec int) CalendarTime

NewCalendarTime builds a CalendarTime from its components (UTC wall clock).

func (CalendarTime) BinOpAdd added in v0.0.2

func (o CalendarTime) BinOpAdd(_ *VM, right Object) (Object, error)

BinaryOp supports duration arithmetic and ordered comparisons:

  • `calendarTime ± int|duration` -> calendarTime (the int is nanoseconds)
  • `calendarTime - calendarTime` -> duration
  • `calendarTime <|<=|>|>= calendarTime` -> bool

func (CalendarTime) BinOpGreater added in v0.0.2

func (o CalendarTime) BinOpGreater(_ *VM, right Object) (Object, error)

func (CalendarTime) BinOpGreaterEq added in v0.0.2

func (o CalendarTime) BinOpGreaterEq(_ *VM, right Object) (Object, error)

func (CalendarTime) BinOpLess added in v0.0.2

func (o CalendarTime) BinOpLess(_ *VM, right Object) (Object, error)

func (CalendarTime) BinOpLessEq added in v0.0.2

func (o CalendarTime) BinOpLessEq(_ *VM, right Object) (Object, error)

func (CalendarTime) BinOpSub added in v0.0.2

func (o CalendarTime) BinOpSub(_ *VM, right Object) (Object, error)

func (CalendarTime) CallName added in v0.0.2

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

CallName dispatches the calendar-time accessor methods.

func (CalendarTime) Date added in v0.0.2

func (o CalendarTime) Date() CalendarDate

Date returns the calendar date (YYYYMMDD) part of this timestamp.

func (CalendarTime) Day added in v0.0.2

func (o CalendarTime) Day() int

func (CalendarTime) Equal added in v0.0.2

func (o CalendarTime) Equal(right Object) bool

Equal implements Object. A CalendarTime equals another CalendarTime or a uint/int holding the same nanosecond count.

func (CalendarTime) Hour added in v0.0.2

func (o CalendarTime) Hour() int

func (CalendarTime) IsFalsy added in v0.0.2

func (o CalendarTime) IsFalsy() bool

IsFalsy reports whether the timestamp is the zero value.

func (CalendarTime) MarshalJSON added in v0.0.2

func (o CalendarTime) MarshalJSON() ([]byte, error)

MarshalJSON encodes the timestamp as a JSON string "YYYY-MM-DD HH:MM:SS".

func (CalendarTime) Minute added in v0.0.2

func (o CalendarTime) Minute() int

func (CalendarTime) Month added in v0.0.2

func (o CalendarTime) Month() int

func (CalendarTime) Nanosecond added in v0.0.2

func (o CalendarTime) Nanosecond() int

func (CalendarTime) Print added in v0.0.2

func (o CalendarTime) Print(s *PrinterState) error

Print writes the timestamp (Printabler); without it the printer's reflection fallback would recurse on this named-uint64 Object.

func (CalendarTime) Second added in v0.0.2

func (o CalendarTime) Second() int

func (CalendarTime) Time added in v0.0.2

func (o CalendarTime) Time(loc *time.Location) time.Time

Time returns this wall time in the given location (UTC when nil).

func (CalendarTime) ToString added in v0.0.2

func (o CalendarTime) ToString() string

ToString renders the timestamp as "YYYY-MM-DD HH:MM:SS[.fraction]".

func (CalendarTime) Type added in v0.0.2

func (CalendarTime) Type() ObjectType

func (CalendarTime) UnOpDec added in v0.0.2

func (o CalendarTime) UnOpDec(*VM) (Object, error)

func (CalendarTime) UnOpInc added in v0.0.2

func (o CalendarTime) UnOpInc(*VM) (Object, error)

func (CalendarTime) Year added in v0.0.2

func (o CalendarTime) Year() int

type Call

type Call struct {
	VM        *VM
	Args      Args
	NamedArgs NamedArgs
	SafeArgs  bool
	Context   context.Context
}

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

func (*Call) Params added in v0.0.2

func (c *Call) Params() *MixedParams

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) Name added in v0.0.2

func (i *CallWrapper) Name() string

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.

func FuncPTLRO added in v0.0.2

func FuncPTLRO(fn func(*Time, *Location) Object) CallableFunc

FuncPTLRO is a generated function to make CallableFunc. Source: FuncPTLRO(t *Time, loc *Location) (ret Object)

func FuncPTRO added in v0.0.2

func FuncPTRO(fn func(*Time) Object) CallableFunc

FuncPTRO is a generated function to make CallableFunc. Source: FuncPTRO(t *Time) (ret Object)

func FuncPTTRO added in v0.0.2

func FuncPTTRO(fn func(*Time, *Time) Object) CallableFunc

FuncPTTRO is a generated function to make CallableFunc. Source: FuncPTTRO(t1 *Time, t2 *Time) (ret Object)

func FuncPTb2sRO added in v0.0.2

func FuncPTb2sRO(fn func(*Time, []byte, string) Object) CallableFunc

FuncPTb2sRO is a generated function to make CallableFunc. Source: FuncPTb2sRO(t *Time, b []byte, s string) (ret Object)

func FuncPTi64RO added in v0.0.2

func FuncPTi64RO(fn func(*Time, int64) Object) CallableFunc

FuncPTi64RO is a generated function to make CallableFunc. Source: FuncPTi64RO(t *Time, d int64) (ret Object)

func FuncPTiiiRO added in v0.0.2

func FuncPTiiiRO(fn func(*Time, int, int, int) Object) CallableFunc

FuncPTiiiRO is a generated function to make CallableFunc. Source: FuncPTiiiRO(t *Time, i1 int, i2 int, i3 int) (ret Object)

func FuncPTsRO added in v0.0.2

func FuncPTsRO(fn func(*Time, string) Object) CallableFunc

FuncPTsRO is a generated function to make CallableFunc. Source: FuncPTsRO(t *Time, s string) (ret Object)

type CallerMethod

type CallerMethod struct {
	CallerObject
	ToStringDetailFunc func(m *CallerMethod) string
	// contains filtered or unexported fields
}

func NewCallerMethod added in v0.0.2

func NewCallerMethod(target Object, callerObject CallerObject) *CallerMethod

func (*CallerMethod) Caller

func (o *CallerMethod) Caller() CallerObject

func (*CallerMethod) IndexGet added in v0.0.2

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

func (*CallerMethod) String

func (o *CallerMethod) String() string

func (*CallerMethod) StringTarget added in v0.0.2

func (o *CallerMethod) StringTarget(targets bool) string

func (*CallerMethod) Target added in v0.0.2

func (o *CallerMethod) Target() Object

type CallerMethodDefinition

type CallerMethodDefinition struct {
	Handler  CallerObject
	Types    ParamsTypes
	Override bool
}

type CallerObject

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

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

func YieldCallDone added in v0.0.2

func YieldCallDone(callerObject CallerObject, c *Call, done func()) CallerObject

type CallerObjectWithVMParamTypes added in v0.0.2

type CallerObjectWithVMParamTypes interface {
	CallerObject
	ParamTypes(vm *VM) (ParamsTypes, error)
}

CallerObjectWithVMParamTypes 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 CanCloser

type CanCloser interface {
	CanClose() 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 CanIterationDoner

type CanIterationDoner interface {
	CanIterationDone() 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) BinOpAdd added in v0.0.2

func (o Char) BinOpAdd(vm *VM, right Object) (Object, error)

func (Char) BinOpAnd added in v0.0.2

func (o Char) BinOpAnd(vm *VM, right Object) (Object, error)

func (Char) BinOpAndNot added in v0.0.2

func (o Char) BinOpAndNot(vm *VM, right Object) (Object, error)

func (Char) BinOpGreater added in v0.0.2

func (o Char) BinOpGreater(vm *VM, right Object) (Object, error)

func (Char) BinOpGreaterEq added in v0.0.2

func (o Char) BinOpGreaterEq(vm *VM, right Object) (Object, error)

func (Char) BinOpLess added in v0.0.2

func (o Char) BinOpLess(vm *VM, right Object) (Object, error)

func (Char) BinOpLessEq added in v0.0.2

func (o Char) BinOpLessEq(vm *VM, right Object) (Object, error)

func (Char) BinOpMul added in v0.0.2

func (o Char) BinOpMul(vm *VM, right Object) (Object, error)

func (Char) BinOpOr added in v0.0.2

func (o Char) BinOpOr(vm *VM, right Object) (Object, error)

func (Char) BinOpQuo added in v0.0.2

func (o Char) BinOpQuo(vm *VM, right Object) (Object, error)

func (Char) BinOpRem added in v0.0.2

func (o Char) BinOpRem(vm *VM, right Object) (Object, error)

func (Char) BinOpSame added in v0.0.2

func (o Char) BinOpSame(_ *VM, right Object) (Object, error)

func (Char) BinOpShl added in v0.0.2

func (o Char) BinOpShl(vm *VM, right Object) (Object, error)

func (Char) BinOpShr added in v0.0.2

func (o Char) BinOpShr(vm *VM, right Object) (Object, error)

func (Char) BinOpSub added in v0.0.2

func (o Char) BinOpSub(vm *VM, right Object) (Object, error)

func (Char) BinOpXor added in v0.0.2

func (o Char) BinOpXor(vm *VM, right Object) (Object, error)

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

func (Char) UnOpAdd added in v0.0.2

func (o Char) UnOpAdd(*VM) (Object, error)

func (Char) UnOpDec added in v0.0.2

func (o Char) UnOpDec(*VM) (Object, error)

func (Char) UnOpInc added in v0.0.2

func (o Char) UnOpInc(*VM) (Object, error)

func (Char) UnOpSub added in v0.0.2

func (o Char) UnOpSub(*VM) (Object, error)

func (Char) UnOpXor added in v0.0.2

func (o Char) UnOpXor(*VM) (Object, error)

type ClasPropertySetter added in v0.0.2

type ClasPropertySetter struct {
	Handler    CallerObject
	ValueTypes ObjectTypes
	// contains filtered or unexported fields
}

func (*ClasPropertySetter) ToParamTypes added in v0.0.2

func (s *ClasPropertySetter) ToParamTypes() (t ParamsTypes)

type Class added in v0.0.2

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

Class is a user-defined type created with the `Class(name; …)` builtin. It is an ObjectType (so values can be type-checked against it) and is itself callable: calling a Class constructs a ClassInstance via its constructor.

A class owns its fields (with defaults), methods, getter/setter properties and new-handlers, plus a list of parent classes for inheritance. It is assembled by NewClass followed by Define (which reads the `fields`/`methods`/ `properties`/`new`/`extends` named args); members can also be added incrementally via AddField/AddMethod/AddProperty and the `met`/`prop` syntax.

func NewClass added in v0.0.2

func NewClass(name string, module *ModuleSpec) (t *Class)

NewClass returns an empty Class with the given name and defining module, its constructor wired to Construct. Members are added afterwards via Define or the AddField/AddMethod/AddProperty helpers.

func (*Class) AddCallerMethod added in v0.0.2

func (t *Class) AddCallerMethod(_ *VM, types ParamsTypes, handler CallerObject, override bool, onAdd func(tcm *TypedCallerMethod) error) (err error)

func (*Class) AddField added in v0.0.2

func (t *Class) AddField(field ...*ClassField) error

func (*Class) AddMethod added in v0.0.2

func (t *Class) AddMethod(name string) (_ *ClassMethod, err error)

func (*Class) AddMethodByTypes added in v0.0.2

func (t *Class) AddMethodByTypes(vm *VM, argTypes ParamsTypes, handler CallerObject, override bool, onAdd func(method *TypedCallerMethod) error) error

func (*Class) AddMethodIndex added in v0.0.2

func (t *Class) AddMethodIndex(c Call) (ret Object, err error)

func (*Class) AddProperty added in v0.0.2

func (t *Class) AddProperty(name string, f *Func) (err error)

func (*Class) AssignTo added in v0.0.2

func (t *Class) AssignTo(_ *VM, obj Object, to TypeAssigner) (Object, error)

func (*Class) BinOpGreater added in v0.0.2

func (t *Class) BinOpGreater(_ *VM, right Object) (Object, error)

func (*Class) BinOpGreaterEq added in v0.0.2

func (t *Class) BinOpGreaterEq(_ *VM, right Object) (Object, error)

func (*Class) BinOpLess added in v0.0.2

func (t *Class) BinOpLess(_ *VM, right Object) (Object, error)

A class compares as greater than nil and is otherwise not comparable, so `class < nil` / `class <= nil` are false and `class > nil` / `class >= nil` are true; any other operand is unsupported.

func (*Class) BinOpLessEq added in v0.0.2

func (t *Class) BinOpLessEq(_ *VM, right Object) (Object, error)

func (*Class) Call added in v0.0.2

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

Call constructs a new instance. Calling a Class value (`MyClass(…)`, in the VM or from Go via Class.Call(Call{VM: vm, …})) allocates an uninitialised instance, wraps it in a ClassInitiator and dispatches to the matching constructor, which receives the initiator as its `new` first parameter. The constructor body builds the instance with a `new(; fields)` super-call (see ClassInitiator.Call).

func (*Class) CallAddFields added in v0.0.2

func (t *Class) CallAddFields(call Call) (err error)

func (*Class) CallAddMethods added in v0.0.2

func (t *Class) CallAddMethods(call Call) (err error)

func (*Class) CallAddNewHandlers added in v0.0.2

func (t *Class) CallAddNewHandlers(c Call) (err error)

func (*Class) CallAddProperties added in v0.0.2

func (t *Class) CallAddProperties(call Call) (err error)

func (*Class) CallAddProperty added in v0.0.2

func (t *Class) CallAddProperty(c Call) (ret Object, err error)

func (*Class) CallExtends added in v0.0.2

func (t *Class) CallExtends(c Call) (err error)

func (*Class) CallFieldsOf added in v0.0.2

func (t *Class) CallFieldsOf(c Call) (ret Object, err error)

func (*Class) CallGetProperty added in v0.0.2

func (t *Class) CallGetProperty(c Call) (ret Object, err error)

func (*Class) CallName added in v0.0.2

func (t *Class) CallName(name string, c Call) (ret Object, err error)

func (*Class) CallerMethodDefault added in v0.0.2

func (t *Class) CallerMethodDefault() CallerObject

CallerMethodDefault returns the constructor's default caller, if any.

func (*Class) CallerMethodOfArgsTypes added in v0.0.2

func (t *Class) CallerMethodOfArgsTypes(types ObjectTypeArray) CallerObject

CallerMethodOfArgsTypes resolves a constructor method from argument types.

func (*Class) CallerMethodWithValidationCheckOfArgs added in v0.0.2

func (t *Class) CallerMethodWithValidationCheckOfArgs(args Args) (CallerObject, bool)

CallerMethodWithValidationCheckOfArgs resolves a constructor method from args.

func (*Class) CallerMethodWithValidationCheckOfArgsTypes added in v0.0.2

func (t *Class) CallerMethodWithValidationCheckOfArgsTypes(types ObjectTypeArray) (CallerObject, bool)

CallerMethodWithValidationCheckOfArgsTypes resolves a constructor method from argument types.

func (*Class) CallerMethods added in v0.0.2

func (t *Class) CallerMethods() *MethodArgType

CallerMethods returns the constructor's method tree.

func (*Class) CanAssign added in v0.0.2

func (t *Class) CanAssign(obj Object) (ok bool, err error)

func (*Class) Construct added in v0.0.2

func (t *Class) Construct(c Call) (o Object, err error)

Construct re-initialises an already-allocated `this` instance (passed as the first argument) from the call's named args. It backs `instance.@new` and `MyClass.new(this; …)`.

func (*Class) Constructor added in v0.0.2

func (t *Class) Constructor() *ClassConstructor

func (*Class) DeclaresField added in v0.0.2

func (t *Class) DeclaresField(name string) bool

DeclaresField reports whether the class or one of its (transitive) parents declares a field named name.

func (*Class) Define added in v0.0.2

func (t *Class) Define(c Call) (err error)

Define populates the class from the call's named args: `new` (constructor handler(s)), `fields` (a KeyValueArray of field specs), `methods`, `properties` and `extends` (parent classes). Each recognised arg runs its corresponding CallAdd* helper. Unrecognised named args are rejected (ErrUnexpectedNamedArg), so callers that handle some args themselves must consume those first (see NewClassFunc / NamedArgs.GetDoCheck).

func (*Class) Equal added in v0.0.2

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

Equal implements Object interface.

func (*Class) Extends added in v0.0.2

func (t *Class) Extends(parent *Class, alias string) *Class

func (*Class) Fields added in v0.0.2

func (t *Class) Fields() (d Dict)

func (*Class) FullName added in v0.0.2

func (t *Class) FullName() string

func (Class) GadObjectType added in v0.0.2

func (Class) GadObjectType()

func (*Class) GetFuncSpec added in v0.0.2

func (t *Class) GetFuncSpec() *FuncSpec

GetFuncSpec exposes the constructor's dispatcher.

func (*Class) GetIndexMethod added in v0.0.2

func (t *Class) GetIndexMethod(_ *VM, index Object) (ret Object, err error)

func (*Class) GetProperty added in v0.0.2

func (t *Class) GetProperty(name string) *ClassProperty

func (*Class) HasCallerMethods added in v0.0.2

func (t *Class) HasCallerMethods() bool

HasCallerMethods reports whether the constructor has registered methods.

func (*Class) IndexGet added in v0.0.2

func (t *Class) IndexGet(vm *VM, index Object) (value Object, err error)

func (*Class) IsChildOf added in v0.0.2

func (t *Class) IsChildOf(p ObjectType) bool

func (Class) IsFalsy added in v0.0.2

func (Class) IsFalsy() bool

func (*Class) Methods added in v0.0.2

func (t *Class) Methods() (d Dict)

func (*Class) Module added in v0.0.2

func (t *Class) Module() *ModuleSpec

func (*Class) Name added in v0.0.2

func (t *Class) Name() string

func (*Class) New added in v0.0.2

func (t *Class) New(c Call) (*ClassInstance, error)

New constructs an instance of t, initialising its fields from the given dict (defaults fill the rest). It is the Go-side entry point for creating an instance; from Gad, calling the class invokes Call/Construct. New constructs an instance of t, running any matching custom constructor. It is a typed wrapper over Call usable from Go (inside or outside the VM loop):

inst, err := cls.New(Call{VM: vm, Args: Args{Array{a, b}}})

func (*Class) NewInstance added in v0.0.2

func (t *Class) NewInstance() (o *ClassInstance)

NewInstance allocates an uninitialised instance of t (its fields are not yet populated; call Init or use NewInstanceWithFields).

func (*Class) NewInstanceWithFields added in v0.0.2

func (t *Class) NewInstanceWithFields(vm *VM, fields Dict) (*ClassInstance, error)

NewInstanceWithFields allocates an instance of t and runs Init with the given field values (applying defaults and inherited fields).

func (*Class) Parents added in v0.0.2

func (t *Class) Parents() (r Array)

func (*Class) Print added in v0.0.2

func (t *Class) Print(state *PrinterState) error

func (*Class) Properties added in v0.0.2

func (t *Class) Properties() (d Dict)

func (*Class) RawFields added in v0.0.2

func (t *Class) RawFields() (r []*ClassField)

func (*Class) RawParents added in v0.0.2

func (t *Class) RawParents() []*ClassParent

func (*Class) Repr added in v0.0.2

func (t *Class) Repr() string

func (*Class) String added in v0.0.2

func (t *Class) String() string

func (*Class) ToString added in v0.0.2

func (t *Class) ToString() string

func (*Class) Type added in v0.0.2

func (t *Class) Type() ObjectType

func (*Class) Walk added in v0.0.2

func (t *Class) Walk(cb func(parent *Class) (mode utils.WalkMode))

type ClassConstructor added in v0.0.2

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

ClassConstructor is a Class's constructor: a callable FuncSpec holding the user `new` handler overloads plus the default handler (Class.Construct). It is invoked when a Class is called to build an instance.

func (*ClassConstructor) AddMethodByTypes added in v0.0.2

func (c *ClassConstructor) AddMethodByTypes(vm *VM, argTypes ParamsTypes, handler CallerObject, override bool, onAdd func(method *TypedCallerMethod) error) error

func (*ClassConstructor) Call added in v0.0.2

func (c *ClassConstructor) Call(c2 Call) (Object, error)

func (*ClassConstructor) Equal added in v0.0.2

func (c *ClassConstructor) Equal(right Object) bool

func (*ClassConstructor) FullName added in v0.0.2

func (c *ClassConstructor) FullName() string

func (*ClassConstructor) FuncSpecName added in v0.0.2

func (c *ClassConstructor) FuncSpecName() string

func (*ClassConstructor) GetFuncSpec added in v0.0.2

func (c *ClassConstructor) GetFuncSpec() *FuncSpec

GetFuncSpec exposes the constructor's dispatcher so helpers such as gad.methodFromArgs can resolve a registered constructor by argument types.

func (*ClassConstructor) GetModule added in v0.0.2

func (c *ClassConstructor) GetModule() *ModuleSpec

func (*ClassConstructor) IsFalsy added in v0.0.2

func (c *ClassConstructor) IsFalsy() bool

func (*ClassConstructor) Name added in v0.0.2

func (c *ClassConstructor) Name() string

func (*ClassConstructor) Print added in v0.0.2

func (c *ClassConstructor) Print(state *PrinterState) (err error)

func (*ClassConstructor) String added in v0.0.2

func (c *ClassConstructor) String() string

func (*ClassConstructor) ToString added in v0.0.2

func (c *ClassConstructor) ToString() string

func (*ClassConstructor) Type added in v0.0.2

func (c *ClassConstructor) Type() ObjectType

type ClassField added in v0.0.2

type ClassField struct {
	Name  string
	Types ObjectTypes

	Value Object
	// contains filtered or unexported fields
}

ClassField is a declared field of a Class: its Name, optional accepted Types, positional index within the instance, and default Value (an initialiser or nil when the field has no default).

func (*ClassField) Equal added in v0.0.2

func (f *ClassField) Equal(right Object) bool

func (*ClassField) IsFalsy added in v0.0.2

func (f *ClassField) IsFalsy() bool

func (*ClassField) Print added in v0.0.2

func (f *ClassField) Print(state *PrinterState) (err error)

func (*ClassField) ReprTypeName added in v0.0.2

func (f *ClassField) ReprTypeName() string

func (*ClassField) String added in v0.0.2

func (f *ClassField) String() string

func (*ClassField) ToString added in v0.0.2

func (f *ClassField) ToString() string

func (*ClassField) Type added in v0.0.2

func (f *ClassField) Type() ObjectType

type ClassGoMethod added in v0.0.2

type ClassGoMethod struct {
	Name     string
	Handlers []*ClassGoMethodHandler
}

type ClassGoMethodHandler added in v0.0.2

type ClassGoMethodHandler struct {
	Handler    CallerObject
	ParamTypes ParamsTypes
}

type ClassInitiator added in v0.0.2

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

ClassInitiator wraps the in-progress ClassInstance during construction. It is passed to every constructor as the `new` first parameter and is itself callable: a `new(; fields)` super-call dispatches to the matching constructor (or, when it re-enters the running one, to the default) to build the instance. newCallStack tracks the active constructor chain so that super-call recursion terminates at the default constructor.

func (*ClassInitiator) Call added in v0.0.2

func (in *ClassInitiator) Call(c Call) (_ Object, err error)

Call dispatches to the matching constructor, passing the initiator as the `new` first argument. A super-call back into the running constructor falls to the default constructor (which initialises the instance), so construction terminates. It returns the constructed instance.

func (*ClassInitiator) Equal added in v0.0.2

func (in *ClassInitiator) Equal(right Object) bool

func (*ClassInitiator) IsFalsy added in v0.0.2

func (in *ClassInitiator) IsFalsy() bool

func (*ClassInitiator) Name added in v0.0.2

func (in *ClassInitiator) Name() string

func (*ClassInitiator) ToString added in v0.0.2

func (in *ClassInitiator) ToString() string

func (*ClassInitiator) Type added in v0.0.2

func (in *ClassInitiator) Type() ObjectType

type ClassInstance added in v0.0.2

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

ClassInstance is a live object of a Class. It holds the instance's field values (fields), one ClassInstance per parent class (parents, keyed by the parent alias) and a back-reference to its class. It implements the Object interface and dispatches method, property and field access through its class.

func (*ClassInstance) AssignTo added in v0.0.2

func (o *ClassInstance) AssignTo(_ *VM, obj Object, to TypeAssigner) (Object, error)

AssignTo makes *ClassInstance a TypeAssigner: obj is assignable to `to` when the instance's class (or one of its parents) is the target type. Returns obj unchanged (unlike CastTo, which returns the up-cast instance).

func (*ClassInstance) BinOpIn added in v0.0.2

func (o *ClassInstance) BinOpIn(_ *VM, v Object) (Object, error)

BinOpIn implements the `in` operator (ObjectWithInBinOperator): reports whether v names a property or a field of the instance, including fields inherited from parent instances. Membership is checked structurally, without invoking any property getter.

func (*ClassInstance) Call added in v0.0.2

func (o *ClassInstance) Call(Call) (Object, error)

Call on an instance is not a constructor entry point: instances are built via Class.Call / ClassInitiator. Calling a live instance is therefore an error.

func (*ClassInstance) CallName added in v0.0.2

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

func (*ClassInstance) CallPrint added in v0.0.2

func (o *ClassInstance) CallPrint(c Call) (err error)

func (*ClassInstance) Cast added in v0.0.2

func (*ClassInstance) CastTo added in v0.0.2

func (o *ClassInstance) CastTo(_ *VM, t ObjectType) (Object, error)

func (*ClassInstance) Copy added in v0.0.2

func (o *ClassInstance) Copy() Object

Copy implements Copier interface.

func (ClassInstance) CopyInstance added in v0.0.2

func (o ClassInstance) CopyInstance() *ClassInstance

CopyInstance copy this instance.

func (*ClassInstance) DeepCopy added in v0.0.2

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

DeepCopy implements DeepCopier interface.

func (ClassInstance) DeepCopyInstance added in v0.0.2

func (o ClassInstance) DeepCopyInstance(vm *VM) (_ *ClassInstance, err error)

DeepCopyInstance deep copy this instance.

func (*ClassInstance) Equal added in v0.0.2

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

Equal implements Object interface.

func (*ClassInstance) Fields added in v0.0.2

func (o *ClassInstance) Fields() Dict

func (*ClassInstance) GetFieldValue added in v0.0.2

func (o *ClassInstance) GetFieldValue(vm *VM, name string) (Object, error)

func (*ClassInstance) GetMethod added in v0.0.2

func (o *ClassInstance) GetMethod(name string) CallerObject

func (*ClassInstance) GetPropertyGetter added in v0.0.2

func (o *ClassInstance) GetPropertyGetter(name string) (handler CallerObject, valid bool)

func (*ClassInstance) GetPropertySetter added in v0.0.2

func (o *ClassInstance) GetPropertySetter(name string, typ ObjectType) (handler CallerObject, valid bool)

func (*ClassInstance) IndexGet added in v0.0.2

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

IndexGet implements Object interface.

func (*ClassInstance) IndexSet added in v0.0.2

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

IndexSet implements Object interface.

func (*ClassInstance) Init added in v0.0.2

func (o *ClassInstance) Init(vm *VM, fields Dict) (err error)

func (*ClassInstance) Instances added in v0.0.2

func (o *ClassInstance) Instances() func(yield func(instance *ClassInstance) bool)

func (*ClassInstance) IsFalsy added in v0.0.2

func (o *ClassInstance) IsFalsy() bool

IsFalsy implements Object interface.

func (*ClassInstance) Items added in v0.0.2

func (o *ClassInstance) Items(vm *VM, cb ItemsGetterCallback) (err error)

func (*ClassInstance) Keys added in v0.0.2

func (o *ClassInstance) Keys() Array

func (*ClassInstance) Methods added in v0.0.2

func (o *ClassInstance) Methods() *IndexGetProxy

func (*ClassInstance) Name added in v0.0.2

func (o *ClassInstance) Name() string

func (*ClassInstance) Parent added in v0.0.2

func (o *ClassInstance) Parent(name string) *ClassInstance

func (*ClassInstance) Parents added in v0.0.2

func (o *ClassInstance) Parents() (d Dict)

func (*ClassInstance) Print added in v0.0.2

func (o *ClassInstance) Print(state *PrinterState) error

func (*ClassInstance) ReprTypeName added in v0.0.2

func (o *ClassInstance) ReprTypeName() string

func (*ClassInstance) ResolveField added in v0.0.2

func (o *ClassInstance) ResolveField(name string) (inst *ClassInstance)

func (*ClassInstance) ResolveMethod added in v0.0.2

func (o *ClassInstance) ResolveMethod(name string) (inst *ClassInstance, m *ClassMethod)

func (*ClassInstance) ResolveProperty added in v0.0.2

func (o *ClassInstance) ResolveProperty(name string) (inst *ClassInstance, p *ClassProperty)

func (*ClassInstance) SetFieldValue added in v0.0.2

func (o *ClassInstance) SetFieldValue(vm *VM, name string, value Object) error

func (*ClassInstance) ToDict added in v0.0.2

func (o *ClassInstance) ToDict() (d Dict)

func (*ClassInstance) ToString added in v0.0.2

func (o *ClassInstance) ToString() string

func (*ClassInstance) Type added in v0.0.2

func (o *ClassInstance) Type() ObjectType

func (*ClassInstance) Values added in v0.0.2

func (o *ClassInstance) Values() Array

func (*ClassInstance) WalkInstances added in v0.0.2

func (o *ClassInstance) WalkInstances(cb func(path []*ClassInstance, instance *ClassInstance) (mode utils.WalkMode))

func (*ClassInstance) WalkProperty added in v0.0.2

func (o *ClassInstance) WalkProperty(name string, f func(inst *ClassInstance, p *ClassProperty) (next bool))

type ClassInstanceMethod added in v0.0.2

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

ClassInstanceMethod is a ClassMethod bound to a receiver instance. Calling it prepends `this` to the arguments and dispatches to the method's typed overloads.

func (*ClassInstanceMethod) Call added in v0.0.2

func (m *ClassInstanceMethod) Call(c Call) (Object, error)

func (*ClassInstanceMethod) Equal added in v0.0.2

func (m *ClassInstanceMethod) Equal(right Object) bool

func (*ClassInstanceMethod) FullName added in v0.0.2

func (m *ClassInstanceMethod) FullName() string

func (*ClassInstanceMethod) FuncSpecName added in v0.0.2

func (m *ClassInstanceMethod) FuncSpecName() string

func (*ClassInstanceMethod) IsFalsy added in v0.0.2

func (m *ClassInstanceMethod) IsFalsy() bool

func (*ClassInstanceMethod) Name added in v0.0.2

func (m *ClassInstanceMethod) Name() string

func (*ClassInstanceMethod) Print added in v0.0.2

func (m *ClassInstanceMethod) Print(state *PrinterState) (err error)

func (*ClassInstanceMethod) String added in v0.0.2

func (m *ClassInstanceMethod) String() string

func (*ClassInstanceMethod) ToString added in v0.0.2

func (m *ClassInstanceMethod) ToString() string

func (*ClassInstanceMethod) Type added in v0.0.2

func (m *ClassInstanceMethod) Type() ObjectType

type ClassInstancePropertyGetter added in v0.0.2

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

ClassInstancePropertyGetter is a ClassProperty's getter bound to a receiver instance. h is the resolved zero-arg `(this)` getter overload; calling the getter (or indexing into it) invokes h with `this`.

func (*ClassInstancePropertyGetter) Call added in v0.0.2

func (*ClassInstancePropertyGetter) Equal added in v0.0.2

func (m *ClassInstancePropertyGetter) Equal(right Object) bool

func (*ClassInstancePropertyGetter) IndexGet added in v0.0.2

func (m *ClassInstancePropertyGetter) IndexGet(vm *VM, index Object) (value Object, err error)

func (*ClassInstancePropertyGetter) IsFalsy added in v0.0.2

func (m *ClassInstancePropertyGetter) IsFalsy() bool

func (*ClassInstancePropertyGetter) Name added in v0.0.2

func (*ClassInstancePropertyGetter) Print added in v0.0.2

func (m *ClassInstancePropertyGetter) Print(state *PrinterState) (err error)

func (*ClassInstancePropertyGetter) String added in v0.0.2

func (m *ClassInstancePropertyGetter) String() string

func (*ClassInstancePropertyGetter) ToString added in v0.0.2

func (m *ClassInstancePropertyGetter) ToString() string

func (*ClassInstancePropertyGetter) Type added in v0.0.2

type ClassInstancePropertySetter added in v0.0.2

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

ClassInstancePropertySetter is a ClassProperty's setter bound to a receiver instance. Its Set method dispatches to the matching `(this, value)` setter overload, using vm for the call.

func (*ClassInstancePropertySetter) Equal added in v0.0.2

func (m *ClassInstancePropertySetter) Equal(right Object) bool

func (*ClassInstancePropertySetter) IndexGet added in v0.0.2

func (m *ClassInstancePropertySetter) IndexGet(vm *VM, index Object) (value Object, err error)

func (*ClassInstancePropertySetter) IsFalsy added in v0.0.2

func (m *ClassInstancePropertySetter) IsFalsy() bool

func (*ClassInstancePropertySetter) Name added in v0.0.2

func (*ClassInstancePropertySetter) Print added in v0.0.2

func (m *ClassInstancePropertySetter) Print(state *PrinterState) (err error)

func (*ClassInstancePropertySetter) Set added in v0.0.2

func (m *ClassInstancePropertySetter) Set(v Object) (err error)

func (*ClassInstancePropertySetter) String added in v0.0.2

func (m *ClassInstancePropertySetter) String() string

func (*ClassInstancePropertySetter) ToString added in v0.0.2

func (m *ClassInstancePropertySetter) ToString() string

func (*ClassInstancePropertySetter) Type added in v0.0.2

type ClassMethod added in v0.0.2

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

ClassMethod is a named method of a Class: a callable FuncSpec that may carry several typed overloads. On an instance it is bound as a ClassInstanceMethod (with `this` prepended).

func NewClassMethod added in v0.0.2

func NewClassMethod(name string, class *Class) *ClassMethod

func (*ClassMethod) AddMethodByTypes added in v0.0.2

func (m *ClassMethod) AddMethodByTypes(vm *VM, argTypes ParamsTypes, handler CallerObject, override bool, onAdd func(method *TypedCallerMethod) error) error

func (*ClassMethod) Call added in v0.0.2

func (m *ClassMethod) Call(c Call) (Object, error)

func (*ClassMethod) Equal added in v0.0.2

func (m *ClassMethod) Equal(right Object) bool

func (*ClassMethod) FullName added in v0.0.2

func (m *ClassMethod) FullName() string

func (*ClassMethod) FuncSpecName added in v0.0.2

func (m *ClassMethod) FuncSpecName() string

func (*ClassMethod) GetFuncSpec added in v0.0.2

func (m *ClassMethod) GetFuncSpec() *FuncSpec

GetFuncSpec exposes the method's dispatcher so helpers such as gad.methodFromArgs can resolve a registered method by argument types.

func (*ClassMethod) IsFalsy added in v0.0.2

func (m *ClassMethod) IsFalsy() bool

func (*ClassMethod) Name added in v0.0.2

func (m *ClassMethod) Name() string

func (*ClassMethod) NewInstance added in v0.0.2

func (m *ClassMethod) NewInstance(this *ClassInstance) *ClassInstanceMethod

func (*ClassMethod) Print added in v0.0.2

func (m *ClassMethod) Print(state *PrinterState) (err error)

func (*ClassMethod) ReprTypeName added in v0.0.2

func (m *ClassMethod) ReprTypeName() string

func (*ClassMethod) String added in v0.0.2

func (m *ClassMethod) String() string

func (*ClassMethod) ToString added in v0.0.2

func (m *ClassMethod) ToString() string

func (*ClassMethod) Type added in v0.0.2

func (m *ClassMethod) Type() ObjectType

type ClassParent added in v0.0.2

type ClassParent struct {
	Alias string
	Type  *Class
}

ClassParent is one entry in a class's inheritance list: a parent Class and the Alias under which its members are reachable (defaults to the parent's name).

type ClassProperty added in v0.0.2

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

ClassProperty is a computed property of a Class (declared with `prop`): a named getter/setter backed by a FuncSpec, whose overloads distinguish the zero-arg getter `(this)` from the typed setters `(this, value)`.

func NewClassProperty added in v0.0.2

func NewClassProperty(class *Class, name string) *ClassProperty

NewClassProperty returns an empty property named name on class, ready for getter/setter overloads to be added to its FuncSpec.

func (*ClassProperty) Add added in v0.0.2

func (p *ClassProperty) Add(handler CallerObject, argTypes ParamsTypes) (err error)

func (*ClassProperty) AddGetter added in v0.0.2

func (p *ClassProperty) AddGetter(v Object, thisType ParamTypes, override bool, onAdd func(method *TypedCallerMethod) error) (err error)

func (*ClassProperty) AddMethodByTypes added in v0.0.2

func (p *ClassProperty) AddMethodByTypes(vm *VM, argTypes ParamsTypes, handler CallerObject, override bool, onAdd func(method *TypedCallerMethod) error) error

func (*ClassProperty) AddSetter added in v0.0.2

func (p *ClassProperty) AddSetter(v Object, thisType, valueType ParamTypes, override bool, onAdd func(method *TypedCallerMethod) error) (err error)

func (*ClassProperty) Call added in v0.0.2

func (p *ClassProperty) Call(c Call) (Object, error)

Call dispatches to the matching getter or setter.

func (*ClassProperty) CallerMethodDefault added in v0.0.2

func (p *ClassProperty) CallerMethodDefault() CallerObject

CallerMethodDefault returns the accessor default caller, if any.

func (*ClassProperty) CallerMethodOfArgsTypes added in v0.0.2

func (p *ClassProperty) CallerMethodOfArgsTypes(types ObjectTypeArray) CallerObject

CallerMethodOfArgsTypes resolves an accessor from argument types.

func (*ClassProperty) CallerMethodWithValidationCheckOfArgs added in v0.0.2

func (p *ClassProperty) CallerMethodWithValidationCheckOfArgs(args Args) (CallerObject, bool)

CallerMethodWithValidationCheckOfArgs resolves an accessor from args.

func (*ClassProperty) CallerMethodWithValidationCheckOfArgsTypes added in v0.0.2

func (p *ClassProperty) CallerMethodWithValidationCheckOfArgsTypes(types ObjectTypeArray) (CallerObject, bool)

CallerMethodWithValidationCheckOfArgsTypes resolves an accessor from argument types.

func (*ClassProperty) CallerMethods added in v0.0.2

func (p *ClassProperty) CallerMethods() *MethodArgType

CallerMethods returns the getter/setter method tree.

func (ClassProperty) Clone added in v0.0.2

func (p ClassProperty) Clone() *ClassProperty

func (*ClassProperty) Equal added in v0.0.2

func (p *ClassProperty) Equal(right Object) bool

func (*ClassProperty) FullName added in v0.0.2

func (p *ClassProperty) FullName() string

func (*ClassProperty) FuncSpecName added in v0.0.2

func (p *ClassProperty) FuncSpecName() string

func (*ClassProperty) GetFuncSpec added in v0.0.2

func (p *ClassProperty) GetFuncSpec() *FuncSpec

GetFuncSpec exposes the property's getter/setter dispatcher so helpers such as gad.methodFromArgs can resolve a registered accessor by argument types.

func (*ClassProperty) GetModule added in v0.0.2

func (p *ClassProperty) GetModule() *ModuleSpec

func (*ClassProperty) HasCallerMethods added in v0.0.2

func (p *ClassProperty) HasCallerMethods() bool

HasCallerMethods reports whether any getter/setter is registered.

func (*ClassProperty) IsFalsy added in v0.0.2

func (p *ClassProperty) IsFalsy() bool

func (*ClassProperty) Name added in v0.0.2

func (p *ClassProperty) Name() string

func (*ClassProperty) NewGetter added in v0.0.2

func (*ClassProperty) NewSetter added in v0.0.2

func (p *ClassProperty) NewSetter(vm *VM, this *ClassInstance) *ClassInstancePropertySetter

func (*ClassProperty) Print added in v0.0.2

func (p *ClassProperty) Print(state *PrinterState) (err error)

func (*ClassProperty) ReprTypeName added in v0.0.2

func (p *ClassProperty) ReprTypeName() string

func (*ClassProperty) String added in v0.0.2

func (p *ClassProperty) String() string

func (*ClassProperty) ToString added in v0.0.2

func (p *ClassProperty) ToString() string

func (*ClassProperty) Type added in v0.0.2

func (p *ClassProperty) Type() ObjectType

func (*ClassProperty) VMAdd added in v0.0.2

func (p *ClassProperty) VMAdd(vm *VM, v Object) error

type CollectableIterator

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

type CompilableImporter

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

type CompileOptions

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

type CompileStack

type CompileStack []ast.Node

func (CompileStack) Up

func (s CompileStack) Up(n int) ast.Node

type CompiledFunction

type CompiledFunction struct {
	FuncName string

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

	Params Params

	NamedParams NamedParams

	ReturnVars ReturnVars

	// NamedParamsMap is a map of NamedParams with index
	// this value allow to perform named args validation.
	NamedParamsMap map[string]int

	// LocalNames holds debug names for local slots (slot index -> name), used by
	// the debugger to label locals. It is populated by the compiler and may be
	// nil (e.g. for hand-built functions); it round-trips through the encoder.
	LocalNames []string
	// 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) 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(builtins *Builtins, w io.Writer, bc *Bytecode)

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

func (*CompiledFunction) FprintLP

func (o *CompiledFunction) FprintLP(builtins *Builtins, constants Array, linePrefix string, w io.Writer)

FprintLP writes constants and instructions to given Writer in a human readable form with line prefix.

func (*CompiledFunction) FullName added in v0.0.2

func (o *CompiledFunction) FullName() string

func (*CompiledFunction) GetModule added in v0.0.2

func (o *CompiledFunction) GetModule() *ModuleSpec

func (*CompiledFunction) GetReturnVars added in v0.0.2

func (o *CompiledFunction) GetReturnVars() ReturnVars

func (*CompiledFunction) HasStructuralParamTypes added in v0.0.2

func (o *CompiledFunction) HasStructuralParamTypes() bool

HasStructuralParamTypes reports whether any parameter is typed by a structural type literal (meti/interface), i.e. a type symbol resolved from a bytecode constant (ScopeConstant). Such params cannot be matched by identity in the dispatch tree, so a match against them must always be validated by value.

func (*CompiledFunction) HeaderString added in v0.0.2

func (o *CompiledFunction) HeaderString() string

func (*CompiledFunction) IsFalsy

func (*CompiledFunction) IsFalsy() bool

IsFalsy implements Object interface.

func (*CompiledFunction) Name

func (o *CompiledFunction) Name() string

func (*CompiledFunction) ParamTypes

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

func (*CompiledFunction) Print added in v0.0.2

func (o *CompiledFunction) Print(state *PrinterState) error

func (*CompiledFunction) SetModule added in v0.0.2

func (o *CompiledFunction) SetModule(m *ModuleSpec)

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)

func (*CompiledFunction) WithNamedParams added in v0.0.2

func (o *CompiledFunction) WithNamedParams(names ...string) *CompiledFunction

func (*CompiledFunction) WithParams

func (o *CompiledFunction) WithParams(names ...string) *CompiledFunction

type Compiler

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

Compiler compiles the AST into a bytecode.

func NewCompiler

func NewCompiler(st *SymbolTable, module *ModuleSpec, file *source.File, opts CompileOptions) *Compiler

NewCompiler creates a new Compiler object.

func (*Compiler) BaseEmbedMap

func (c *Compiler) BaseEmbedMap() *EmbeddedMap

func (*Compiler) BaseModuleMap

func (c *Compiler) BaseModuleMap() *ModuleMap

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 *ModuleStmt) (err error)

func (*Compiler) Errorf added in v0.0.2

func (c *Compiler) Errorf(
	nd ast.Node,
	format string,
	args ...any,
) error

func (*Compiler) Options added in v0.0.2

func (c *Compiler) Options() *CompileOptions

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 *source.FileSet
	Node    ast.Node
	Err     error
}

CompilerError represents a compiler error.

func (*CompilerError) Error

func (e *CompilerError) Error() string

func (*CompilerError) Format

func (e *CompilerError) Format(f fmt.State, verb rune)

func (*CompilerError) Unwrap

func (e *CompilerError) Unwrap() error

type CompilerOptions

type CompilerOptions struct {
	Context             context.Context
	EmbededdMap         *EmbeddedMap
	ModuleMap           *ModuleMap
	ModuleFile          string
	Constants           []Object
	Trace               io.Writer
	TraceParser         bool
	TraceCompiler       bool
	TraceOptimizer      bool
	OptimizerMaxCycle   int
	OptimizeConst       bool
	OptimizeExpr        bool
	MixedWriteFunction  node.Expr
	MixedExprToTextFunc node.Expr
	FallbackFunc        func(c *Compiler, nd ast.Node) error
	// contains filtered or unexported fields
}

CompilerOptions represents customizable options for Compile().

type ComputedValue added in v0.0.2

type ComputedValue struct {
	CallerObject CallerObject
}

func (*ComputedValue) Call added in v0.0.2

func (v *ComputedValue) Call(c Call) (Object, error)

func (*ComputedValue) Equal added in v0.0.2

func (v *ComputedValue) Equal(right Object) bool

func (*ComputedValue) IsFalsy added in v0.0.2

func (v *ComputedValue) IsFalsy() bool

func (*ComputedValue) Name added in v0.0.2

func (v *ComputedValue) Name() string

func (*ComputedValue) Print added in v0.0.2

func (v *ComputedValue) Print(state *PrinterState) error

func (*ComputedValue) ReprTypeName added in v0.0.2

func (v *ComputedValue) ReprTypeName() string

func (*ComputedValue) String added in v0.0.2

func (v *ComputedValue) String() string

func (*ComputedValue) ToString added in v0.0.2

func (v *ComputedValue) ToString() string

func (ComputedValue) Type added in v0.0.2

func (ComputedValue) Type() ObjectType

type Copier

type Copier interface {
	Object
	Copy() Object
}

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

type DebugFrame added in v0.0.2

type DebugFrame struct {
	FuncName   string
	Pos        source.FilePos
	Locals     []Object
	LocalNames []string
}

DebugFrame describes one active call frame for the debugger's stack view, including that frame's local values and their debug names.

type DebugStepper added in v0.0.2

type DebugStepper interface {
	// Step is called with the VM positioned at the instruction about to run.
	Step(vm *VM)
}

DebugStepper is invoked before each instruction executes when the VM runs in debug mode (see VM.SetDebugger). Implementations typically block inside Step to pause execution (breakpoints, single-stepping) and inspect state through the VM's Debug* accessors.

The debug execution loop (loopDebug) is generated from the production loop by cmd/update-delve, so the two never drift; the production loop has no per-instruction hook and is unaffected.

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) BinOpAdd added in v0.0.2

func (o Decimal) BinOpAdd(_ *VM, right Object) (Object, error)

func (Decimal) BinOpGreater added in v0.0.2

func (o Decimal) BinOpGreater(_ *VM, right Object) (Object, error)

func (Decimal) BinOpGreaterEq added in v0.0.2

func (o Decimal) BinOpGreaterEq(_ *VM, right Object) (Object, error)

func (Decimal) BinOpLess added in v0.0.2

func (o Decimal) BinOpLess(_ *VM, right Object) (Object, error)

func (Decimal) BinOpLessEq added in v0.0.2

func (o Decimal) BinOpLessEq(_ *VM, right Object) (Object, error)

func (Decimal) BinOpMul added in v0.0.2

func (o Decimal) BinOpMul(_ *VM, right Object) (Object, error)

func (Decimal) BinOpPow added in v0.0.2

func (o Decimal) BinOpPow(_ *VM, right Object) (Object, error)

func (Decimal) BinOpQuo added in v0.0.2

func (o Decimal) BinOpQuo(_ *VM, right Object) (Object, error)

func (Decimal) BinOpSame added in v0.0.2

func (o Decimal) BinOpSame(_ *VM, right Object) (Object, error)

func (Decimal) BinOpSub added in v0.0.2

func (o Decimal) BinOpSub(_ *VM, right Object) (Object, error)

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

func (o Decimal) ToGo() decimal.Decimal

func (Decimal) ToInterface

func (o Decimal) ToInterface() any

func (Decimal) ToString

func (o Decimal) ToString() string

func (Decimal) Type

func (o Decimal) Type() ObjectType

func (Decimal) UnOpDec added in v0.0.2

func (o Decimal) UnOpDec(*VM) (Object, error)

func (Decimal) UnOpInc added in v0.0.2

func (o Decimal) UnOpInc(*VM) (Object, error)

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 Base64Module added in v0.0.2

func Base64Module() Dict

Base64Module returns the `base64` builtin namespace. It is shared (not copied) and is also used by the stdlib `encoding/base64` importable module.

func ConvertToDict

func ConvertToDict(vm *VM, o ...Object) (ret Dict, err error)

ConvertToDict convert objects to Dict. If success return then, otherwise return error.

func FmtModule added in v0.0.2

func FmtModule() Dict

FmtModule returns the `fmt` builtin namespace (Print/Printf/Sprint/Scan…). It is also used by the stdlib `fmt` importable module.

func GadModule added in v0.0.2

func GadModule() Dict

GadModule returns the `gad` builtin namespace (the operator functions).

func MustConvertToDict

func MustConvertToDict(vm *VM, o ...Object) Dict

MustConvertToDict convert objects to Dict and return then if success, otherwise panics.

func StringsModule added in v0.0.2

func StringsModule() Dict

StringsModule returns the `strings` builtin namespace. It is also used by the stdlib `strings` importable module.

func TimeModule added in v0.0.2

func TimeModule() Dict

TimeModule returns the `time` builtin namespace. It is also used by the stdlib `time` importable module.

func ToDict

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

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

func (Dict) Backup

func (o Dict) Backup(key string) func()

Backup returns a handle function to restores key value.

func (Dict) BinOpAdd added in v0.0.2

func (o Dict) BinOpAdd(vm *VM, right Object) (Object, error)

BinOpAdd merges right's entries into the dict (ObjectWithAddBinOperator).

func (Dict) BinOpGreater added in v0.0.2

func (o Dict) BinOpGreater(_ *VM, right Object) (Object, error)

func (Dict) BinOpGreaterEq added in v0.0.2

func (o Dict) BinOpGreaterEq(_ *VM, right Object) (Object, error)

func (Dict) BinOpIn added in v0.0.2

func (o Dict) BinOpIn(_ *VM, v Object) (Object, error)

Contains reports whether v is a key of the dict (`v in dict`). BinOpIn implements the `in` operator (ObjectWithInBinOperator): reports whether v is a key of o.

func (Dict) BinOpLess added in v0.0.2

func (o Dict) BinOpLess(_ *VM, right Object) (Object, error)

A dict orders after nil and is otherwise not comparable.

func (Dict) BinOpLessEq added in v0.0.2

func (o Dict) BinOpLessEq(_ *VM, right Object) (Object, error)

func (Dict) BinOpSub added in v0.0.2

func (o Dict) BinOpSub(vm *VM, right Object) (Object, error)

BinOpSub removes the keys in right from the dict (ObjectWithSubBinOperator).

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

func (o Dict) Get(key string) (r Object)

Get gets object by key. Return then if exists or Nil.

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, cb ItemsGetterCallback) (err error)

func (Dict) Iterate

func (o Dict) Iterate(vm *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) Print

func (o Dict) Print(state *PrinterState) (err error)

Print prints object writing output to out writer. Options: - anonymous flag: include anonymous fields. - zeros flag: include zero fields. - sortKeys int = 0: fields sorting. 1: ASC, 2: DESC.

func (Dict) PrintObject added in v0.0.2

func (o Dict) PrintObject(state *PrinterState, dot Object) (err error)

func (Dict) Set

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

func (Dict) SortedKeys

func (o Dict) SortedKeys() Array

func (Dict) ToDict added in v0.0.2

func (o Dict) ToDict() Dict

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 added in v0.0.2

func (o Dict) ToKeyValueArray() (arr KeyValueArray)

func (Dict) ToNamedArgs

func (o Dict) ToNamedArgs() *NamedArgs

func (Dict) ToString

func (o Dict) ToString() string

func (Dict) Type

func (o Dict) Type() ObjectType

func (Dict) UpdateIndexSetter added in v0.0.2

func (o Dict) UpdateIndexSetter(out StringIndexSetter)

func (Dict) Values

func (o Dict) Values() Array

type Duration added in v0.0.2

type Duration time.Duration

Duration is a span of time with nanosecond precision; it mirrors Go's time.Duration and is one of the time module's value types.

func (Duration) BinOpAdd added in v0.0.2

func (o Duration) BinOpAdd(_ *VM, right Object) (Object, error)

BinaryOp supports duration arithmetic and comparison:

  • `duration ± duration` -> duration
  • `duration * int` -> duration (scale)
  • `duration / int` -> duration (scale)
  • `duration / duration` -> float (ratio)
  • `duration % int|duration` -> duration (remainder)
  • ordered comparisons -> bool

The operators accept a Duration or an Int (taken as a nanosecond count).

func (Duration) BinOpGreater added in v0.0.2

func (o Duration) BinOpGreater(_ *VM, right Object) (Object, error)

func (Duration) BinOpGreaterEq added in v0.0.2

func (o Duration) BinOpGreaterEq(_ *VM, right Object) (Object, error)

func (Duration) BinOpLess added in v0.0.2

func (o Duration) BinOpLess(_ *VM, right Object) (Object, error)

func (Duration) BinOpLessEq added in v0.0.2

func (o Duration) BinOpLessEq(_ *VM, right Object) (Object, error)

func (Duration) BinOpMul added in v0.0.2

func (o Duration) BinOpMul(_ *VM, right Object) (Object, error)

func (Duration) BinOpQuo added in v0.0.2

func (o Duration) BinOpQuo(_ *VM, right Object) (Object, error)

func (Duration) BinOpRem added in v0.0.2

func (o Duration) BinOpRem(_ *VM, right Object) (Object, error)

func (Duration) BinOpSub added in v0.0.2

func (o Duration) BinOpSub(_ *VM, right Object) (Object, error)

func (Duration) CallName added in v0.0.2

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

CallName dispatches the duration methods (Go time.Duration accessors).

func (Duration) Equal added in v0.0.2

func (o Duration) Equal(right Object) bool

Equal implements Object. A Duration equals another Duration or an int with the same nanosecond count.

func (Duration) IsFalsy added in v0.0.2

func (o Duration) IsFalsy() bool

IsFalsy reports whether the duration is zero.

func (Duration) MarshalJSON added in v0.0.2

func (o Duration) MarshalJSON() ([]byte, error)

MarshalJSON encodes the duration as a JSON string, e.g. "1h30m0s".

func (Duration) Print added in v0.0.2

func (o Duration) Print(s *PrinterState) error

Print writes the duration (Printabler); without it the printer's reflection fallback would recurse on this named-int Object.

func (Duration) ToString added in v0.0.2

func (o Duration) ToString() string

ToString renders the duration like Go does, e.g. "1h30m0s".

func (Duration) Type added in v0.0.2

func (Duration) Type() ObjectType

func (Duration) UnOpAdd added in v0.0.2

func (o Duration) UnOpAdd(*VM) (Object, error)

func (Duration) UnOpSub added in v0.0.2

func (o Duration) UnOpSub(*VM) (Object, error)

type Embedded added in v0.0.2

type Embedded struct {
	ReaderFactory EmbeddedReaderFactory
	Name          string
	Entries       map[string]*Embedded
	Parent        *Embedded
	ModTime       time.Time
	Mode          os.FileMode
	AbsPath       string
}

func (*Embedded) Dirs added in v0.0.2

func (n *Embedded) Dirs(recursive bool) (ret []*Embedded)

func (*Embedded) Equal added in v0.0.2

func (n *Embedded) Equal(right Object) bool

func (*Embedded) FS added in v0.0.2

func (n *Embedded) FS() (*EmbeddedNodeFS, error)

func (*Embedded) Files added in v0.0.2

func (n *Embedded) Files(recursive bool) (ret []*Embedded)

func (*Embedded) FullPath added in v0.0.2

func (n *Embedded) FullPath() string

func (*Embedded) Get added in v0.0.2

func (n *Embedded) Get(pth string) (e *Embedded, err error)

func (*Embedded) GetNode added in v0.0.2

func (n *Embedded) GetNode(name string) *Embedded

func (*Embedded) IndexGet added in v0.0.2

func (n *Embedded) IndexGet(vm *VM, index Object) (value Object, err error)

func (*Embedded) IsDir added in v0.0.2

func (n *Embedded) IsDir() bool

func (*Embedded) IsFalsy added in v0.0.2

func (n *Embedded) IsFalsy() bool

func (*Embedded) JoinToArray added in v0.0.2

func (n *Embedded) JoinToArray() (ret []*Embedded)

func (*Embedded) Path added in v0.0.2

func (n *Embedded) Path() string

func (*Embedded) Print added in v0.0.2

func (n *Embedded) Print(state *PrinterState) (err error)

func (*Embedded) Read added in v0.0.2

func (n *Embedded) Read() (b []byte, err error)

func (*Embedded) Reader added in v0.0.2

func (n *Embedded) Reader() (r io.ReadSeeker, err error)

func (*Embedded) Size added in v0.0.2

func (n *Embedded) Size() (_ int64, err error)

func (*Embedded) SortedNames added in v0.0.2

func (n *Embedded) SortedNames() (ret []string)

func (*Embedded) ToBytes added in v0.0.2

func (n *Embedded) ToBytes() (Bytes, error)

func (*Embedded) ToString added in v0.0.2

func (n *Embedded) ToString() string

func (*Embedded) Type added in v0.0.2

func (n *Embedded) Type() ObjectType

func (*Embedded) Walk added in v0.0.2

func (n *Embedded) Walk(cb func(path []string, n *Embedded) error) (err error)

func (*Embedded) WalkR added in v0.0.2

func (n *Embedded) WalkR(recursive bool, cb func(path []string, n *Embedded) error) (err error)

type EmbeddedBytesReaderFactory added in v0.0.2

type EmbeddedBytesReaderFactory []byte

func (EmbeddedBytesReaderFactory) Reader added in v0.0.2

type EmbeddedExtImporter added in v0.0.2

type EmbeddedExtImporter interface {
	EmbeddedImporter
	// Get returns EmbeddedExtImporter instance which will import an embedded file.
	Get(name string) EmbeddedExtImporter
	// Paths returns the unique relative and absolute paths of embedded.
	Paths() (relPath, absPath string, err error)
}

EmbeddedExtImporter wraps methods for a embedded which will be imported dynamically like a file.

type EmbeddedFile added in v0.0.2

type EmbeddedFile Embedded

EmbeddedFile is an importable embed that's written in Gad.

func (EmbeddedFile) Import added in v0.0.2

type EmbeddedFileData added in v0.0.2

type EmbeddedFileData []byte

EmbeddedFileData is an importable embed for data that's written in Gad.

func (EmbeddedFileData) Import added in v0.0.2

type EmbeddedFileImporter added in v0.0.2

type EmbeddedFileImporter struct {
	NameResolver func(cwd, name string) (string, error)
	WorkDir      string
	FileReader   func(string) (data []byte, uri string, err error)
}

EmbeddedFileImporter is an implemention of gad.ExtImporter to import files from file system. It uses absolute paths of module as import names.

type EmbeddedImportOptions added in v0.0.2

type EmbeddedImportOptions struct {
	Sources    []string
	Includes   []string
	Excludes   []string
	IncludesRe []string
	ExcludesRe []string
	ConfigFile string
	Tree       bool
}

type EmbeddedImporter added in v0.0.2

type EmbeddedImporter interface {
	// Import should return either an Object or module source code ([]byte).
	Import(ctx context.Context, relPath string, absPath string, opts *EmbeddedImportOptions) (data *Embedded, err error)
}

EmbeddedImporter interface represents importable embedded instance.

type EmbeddedLimittedReaderFactory added in v0.0.2

type EmbeddedLimittedReaderFactory struct {
	AtReader io.ReaderAt
	Offset   int64
	Limit    int64
}

func (*EmbeddedLimittedReaderFactory) Reader added in v0.0.2

type EmbeddedMap added in v0.0.2

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

EmbeddedMap represents a set of named modules. Use NewEmbedMap to create a new module map.

func NewEmbedMap

func NewEmbedMap() *EmbeddedMap

NewEmbedMap creates a new module map.

func (*EmbeddedMap) Add added in v0.0.2

func (m *EmbeddedMap) Add(name string, module EmbeddedImporter) *EmbeddedMap

Add adds an importable module.

func (*EmbeddedMap) AddFile added in v0.0.2

func (m *EmbeddedMap) AddFile(path string, data []byte) *EmbeddedMap

AddFile adds a source file data.

func (*EmbeddedMap) Copy added in v0.0.2

func (m *EmbeddedMap) Copy() *EmbeddedMap

Copy creates a copy of the module map.

func (*EmbeddedMap) Get added in v0.0.2

func (m *EmbeddedMap) Get(name string) EmbeddedImporter

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

func (*EmbeddedMap) Remove added in v0.0.2

func (m *EmbeddedMap) Remove(name string)

Remove removes a named module.

func (*EmbeddedMap) SetExtImporter added in v0.0.2

func (m *EmbeddedMap) SetExtImporter(im EmbeddedExtImporter) *EmbeddedMap

SetExtImporter sets an ExtImporter to EmbeddedMap, which will be used to embed path dynamically.

type EmbeddedNodeFS added in v0.0.2

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

func (*EmbeddedNodeFS) Equal added in v0.0.2

func (e *EmbeddedNodeFS) Equal(right Object) bool

func (*EmbeddedNodeFS) IndexGet added in v0.0.2

func (e *EmbeddedNodeFS) IndexGet(_ *VM, index Object) (value Object, err error)

func (*EmbeddedNodeFS) IsFalsy added in v0.0.2

func (e *EmbeddedNodeFS) IsFalsy() bool

func (*EmbeddedNodeFS) Iterate added in v0.0.2

func (e *EmbeddedNodeFS) Iterate(_ *VM, na *NamedArgs) Iterator

func (*EmbeddedNodeFS) Print added in v0.0.2

func (e *EmbeddedNodeFS) Print(state *PrinterState) error

func (*EmbeddedNodeFS) ToDict added in v0.0.2

func (e *EmbeddedNodeFS) ToDict() (d Dict)

func (*EmbeddedNodeFS) ToString added in v0.0.2

func (e *EmbeddedNodeFS) ToString() string

func (*EmbeddedNodeFS) Type added in v0.0.2

func (e *EmbeddedNodeFS) Type() ObjectType

type EmbeddedOsFileReaderFactory added in v0.0.2

type EmbeddedOsFileReaderFactory struct{}

func (*EmbeddedOsFileReaderFactory) Reader added in v0.0.2

type EmbeddedReaderFactory added in v0.0.2

type EmbeddedReaderFactory interface {
	Reader(e *Embedded) (io.ReadSeeker, error)
}

type Enum added in v0.0.2

type Enum struct {
	EnumName string
	Values   map[string]*EnumValue
	Module   *ModuleSpec
}

Enum is an ordered, named set of integer constants produced by the `enum` syntax. It is also an ObjectType: each member is an EnumValue whose Type() is the owning Enum. An Enum is immutable after construction, indexable by member name and iterable in declaration order.

func NewEnum added in v0.0.2

func NewEnum(enumName string, module *ModuleSpec) *Enum

NewEnum returns an empty Enum; members are added in order with AddValue.

func (*Enum) AddValue added in v0.0.2

func (e *Enum) AddValue(name string, value Object)

AddValue appends a member with the given name and underlying int/uint value. Its Index is the current member count, so members added in source order keep that order.

func (*Enum) AssignTo added in v0.0.2

func (e *Enum) AssignTo(_ *VM, obj Object, to TypeAssigner) (Object, error)

func (*Enum) Call added in v0.0.2

func (e *Enum) Call(c Call) (Object, error)

func (*Enum) CanAssign added in v0.0.2

func (e *Enum) CanAssign(obj Object) (bool, error)

func (*Enum) CanCall added in v0.0.2

func (e *Enum) CanCall() bool

func (*Enum) Equal added in v0.0.2

func (e *Enum) Equal(right Object) bool

func (*Enum) FullName added in v0.0.2

func (e *Enum) FullName() string

func (*Enum) GadObjectType added in v0.0.2

func (e *Enum) GadObjectType()

func (*Enum) GetModule added in v0.0.2

func (e *Enum) GetModule() *ModuleSpec

func (*Enum) IndexGet added in v0.0.2

func (e *Enum) IndexGet(vm *VM, index Object) (value Object, err error)

func (*Enum) IsFalsy added in v0.0.2

func (e *Enum) IsFalsy() bool

func (*Enum) Iterate added in v0.0.2

func (e *Enum) Iterate(_ *VM, na *NamedArgs) Iterator

func (*Enum) Name added in v0.0.2

func (e *Enum) Name() string

func (*Enum) Print added in v0.0.2

func (e *Enum) Print(state *PrinterState) error

func (*Enum) ReprTypeName added in v0.0.2

func (e *Enum) ReprTypeName() string

func (*Enum) SetModule added in v0.0.2

func (e *Enum) SetModule(m *ModuleSpec)

func (*Enum) String added in v0.0.2

func (e *Enum) String() string

func (*Enum) ToArray added in v0.0.2

func (e *Enum) ToArray() (arr Array)

func (*Enum) ToDict added in v0.0.2

func (e *Enum) ToDict() (d Dict)

func (*Enum) ToString added in v0.0.2

func (e *Enum) ToString() string

func (*Enum) Type added in v0.0.2

func (e *Enum) Type() ObjectType

type EnumValue added in v0.0.2

type EnumValue struct {
	Index int
	Enum  *Enum
	Name  string
	Value Object
}

EnumValue is a single member of an Enum: its declaration Index, owning Enum, Name and the underlying Int/Uint Value. Its members are reachable from Gad as `.name`, `.value`, `.index` and `.enum`.

func (*EnumValue) Equal added in v0.0.2

func (e *EnumValue) Equal(right Object) bool

func (*EnumValue) IndexGet added in v0.0.2

func (e *EnumValue) IndexGet(_ *VM, index Object) (Object, error)

IndexGet exposes the value's members: `name` (the field name), `value` (the underlying int/uint), `index` (declaration order) and `enum` (the owning Enum).

func (*EnumValue) IsFalsy added in v0.0.2

func (e *EnumValue) IsFalsy() bool

func (*EnumValue) IsInt added in v0.0.2

func (e *EnumValue) IsInt() (ok bool)

func (*EnumValue) ToString added in v0.0.2

func (e *EnumValue) ToString() string

func (*EnumValue) Type added in v0.0.2

func (e *EnumValue) Type() ObjectType

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 NewEmbeddedPathIsDir added in v0.0.2

func NewEmbeddedPathIsDir(path string) *Error

NewEmbeddedPathIsDir creates a new ErrEmbedded when path is directory

func NewEmbeddedPathIsNtDir added in v0.0.2

func NewEmbeddedPathIsNtDir(path string) *Error

NewEmbeddedPathIsNtDir creates a new ErrEmbedded when path isn't a directory

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(index string, 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 NewStructPropertyInstanceError added in v0.0.2

func NewStructPropertyInstanceError(propertyName, message string) *Error

NewStructPropertyInstanceError creates a new Error from ErrClassInstanceProperty.

func WrapError

func WrapError(cause error) *Error

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) NewErrorf added in v0.0.2

func (o *Error) NewErrorf(format string, arg ...any) *Error

NewErrorf creates a new Error and sets original Error as its cause which can be unwrapped, using formatable message.

func (*Error) ToString

func (o *Error) ToString() string

func (*Error) Type

func (o *Error) Type() ObjectType

func (*Error) Unwrap

func (o *Error) Unwrap() error

func (*Error) Wrap added in v0.0.2

func (o *Error) Wrap(cause error, msg string) *Error

func (*Error) Wrapf added in v0.0.2

func (o *Error) Wrapf(cause error, format string, arg ...any) *Error

type ErrorHumanizing

type ErrorHumanizing struct {
	Current, Other UpDownLines
}

func (*ErrorHumanizing) Humanize

func (h *ErrorHumanizing) Humanize(out io.Writer, err error)

type Eval

type Eval struct {
	Locals []Object
	*RunOpts
	Opts         CompileOptions
	VM           *VM
	ModulesCache []*Module
	// contains filtered or unexported fields
}

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(builtins *StaticBuiltins, st *SymbolTable, opts CompileOptions, runOpts ...*RunOpts) *Eval

NewEval returns new Eval object.

func (*Eval) Run

func (r *Eval) Run(ctx context.Context, bytecode *Bytecode) (ret Object, err error)

Run Bytecode and returns last value on stack.

func (*Eval) RunScript added in v0.0.2

func (r *Eval) RunScript(ctx context.Context, script []byte) (ret Object, bytecode *Bytecode, err error)

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

func (*Eval) SymbolTable added in v0.0.2

func (r *Eval) SymbolTable() *SymbolTable

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) BinOpAdd added in v0.0.2

func (o Flag) BinOpAdd(vm *VM, right Object) (Object, error)

func (Flag) BinOpAnd added in v0.0.2

func (o Flag) BinOpAnd(vm *VM, right Object) (Object, error)

func (Flag) BinOpAndNot added in v0.0.2

func (o Flag) BinOpAndNot(vm *VM, right Object) (Object, error)

func (Flag) BinOpGreater added in v0.0.2

func (o Flag) BinOpGreater(vm *VM, right Object) (Object, error)

func (Flag) BinOpGreaterEq added in v0.0.2

func (o Flag) BinOpGreaterEq(vm *VM, right Object) (Object, error)

func (Flag) BinOpLess added in v0.0.2

func (o Flag) BinOpLess(vm *VM, right Object) (Object, error)

func (Flag) BinOpLessEq added in v0.0.2

func (o Flag) BinOpLessEq(vm *VM, right Object) (Object, error)

func (Flag) BinOpMul added in v0.0.2

func (o Flag) BinOpMul(vm *VM, right Object) (Object, error)

func (Flag) BinOpOr added in v0.0.2

func (o Flag) BinOpOr(vm *VM, right Object) (Object, error)

func (Flag) BinOpQuo added in v0.0.2

func (o Flag) BinOpQuo(vm *VM, right Object) (Object, error)

func (Flag) BinOpRem added in v0.0.2

func (o Flag) BinOpRem(vm *VM, right Object) (Object, error)

func (Flag) BinOpSame added in v0.0.2

func (o Flag) BinOpSame(_ *VM, right Object) (Object, error)

func (Flag) BinOpShl added in v0.0.2

func (o Flag) BinOpShl(vm *VM, right Object) (Object, error)

func (Flag) BinOpShr added in v0.0.2

func (o Flag) BinOpShr(vm *VM, right Object) (Object, error)

func (Flag) BinOpSub added in v0.0.2

func (o Flag) BinOpSub(vm *VM, right Object) (Object, error)

func (Flag) BinOpXor added in v0.0.2

func (o Flag) BinOpXor(vm *VM, 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

func (Flag) UnOpAdd added in v0.0.2

func (o Flag) UnOpAdd(*VM) (Object, error)

func (Flag) UnOpNot added in v0.0.2

func (o Flag) UnOpNot(*VM) (Object, error)

UnOpNot keeps logical NOT of a Flag a Flag (the universal default would return a Bool).

func (Flag) UnOpXor added in v0.0.2

func (o Flag) UnOpXor(*VM) (Object, error)

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) BinOpAdd added in v0.0.2

func (o Float) BinOpAdd(vm *VM, right Object) (Object, error)

func (Float) BinOpGreater added in v0.0.2

func (o Float) BinOpGreater(vm *VM, right Object) (Object, error)

func (Float) BinOpGreaterEq added in v0.0.2

func (o Float) BinOpGreaterEq(vm *VM, right Object) (Object, error)

func (Float) BinOpLess added in v0.0.2

func (o Float) BinOpLess(vm *VM, right Object) (Object, error)

func (Float) BinOpLessEq added in v0.0.2

func (o Float) BinOpLessEq(vm *VM, right Object) (Object, error)

func (Float) BinOpMul added in v0.0.2

func (o Float) BinOpMul(vm *VM, right Object) (Object, error)

func (Float) BinOpPow added in v0.0.2

func (o Float) BinOpPow(vm *VM, right Object) (Object, error)

func (Float) BinOpQuo added in v0.0.2

func (o Float) BinOpQuo(vm *VM, right Object) (Object, error)

func (Float) BinOpSame added in v0.0.2

func (o Float) BinOpSame(_ *VM, right Object) (Object, error)

func (Float) BinOpSub added in v0.0.2

func (o Float) BinOpSub(vm *VM, right Object) (Object, error)

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

func (Float) UnOpAdd added in v0.0.2

func (o Float) UnOpAdd(*VM) (Object, error)

func (Float) UnOpDec added in v0.0.2

func (o Float) UnOpDec(*VM) (Object, error)

func (Float) UnOpInc added in v0.0.2

func (o Float) UnOpInc(*VM) (Object, error)

func (Float) UnOpSub added in v0.0.2

func (o Float) UnOpSub(*VM) (Object, error)

type FmtScanArg added in v0.0.2

type FmtScanArg interface {
	// Set sets status of scanning. It is set false before scanning and true
	// after scanning if argument is scanned.
	Set(bool)
	// Arg must return either a pointer to a basic ToInterface type or implementations of
	// fmt.Scanner interface.
	Arg() any
	// Value must return scanned, non-nil Gad Object.
	Value() Object
}

FmtScanArg is an interface that wraps methods required to scan argument with scan functions.

type Func added in v0.0.2

type Func struct {
	*FuncSpec
	// contains filtered or unexported fields
}

func NewFunc added in v0.0.2

func NewFunc(name string, module *ModuleSpec) *Func

func (*Func) Equal added in v0.0.2

func (f *Func) Equal(right Object) bool

func (*Func) FullName added in v0.0.2

func (f *Func) FullName() string

func (*Func) FuncSpecName added in v0.0.2

func (f *Func) FuncSpecName() string

func (*Func) GetModule added in v0.0.2

func (f *Func) GetModule() *ModuleSpec

func (*Func) Name added in v0.0.2

func (f *Func) Name() string

func (*Func) Print added in v0.0.2

func (f *Func) Print(state *PrinterState) (err error)

func (*Func) String added in v0.0.2

func (f *Func) String() string

func (*Func) ToString added in v0.0.2

func (f *Func) ToString() string

func (*Func) Type added in v0.0.2

func (f *Func) Type() ObjectType

type FuncHeaderObject added in v0.0.2

type FuncHeaderObject struct {
	FuncName    string
	Params      Array // of *TypedIdent
	NamedParams Array // of *TypedIdent
	Return      Array // of *TypedIdent
	// Module is the module the header was compiled in, used to render a
	// module-qualified FullName. Set from *Compiler.module when a func-header
	// value is compiled to a constant; nil for values built at run time.
	Module *ModuleSpec
}

FuncHeaderObject is a function signature value (see TFunctionHeader).

func (*FuncHeaderObject) Equal added in v0.0.2

func (h *FuncHeaderObject) Equal(right Object) bool

func (*FuncHeaderObject) FullName added in v0.0.2

func (h *FuncHeaderObject) FullName() string

FullName is the header name qualified by its module, e.g. `mod.f`, or just the name when there is no (or an unnamed) module. An anonymous header (no name) has no FullName.

func (*FuncHeaderObject) IndexGet added in v0.0.2

func (h *FuncHeaderObject) IndexGet(_ *VM, index Object) (Object, error)

IndexGet exposes name, params, namedParams and return.

func (*FuncHeaderObject) IsFalsy added in v0.0.2

func (h *FuncHeaderObject) IsFalsy() bool

func (*FuncHeaderObject) Name added in v0.0.2

func (h *FuncHeaderObject) Name() string

func (*FuncHeaderObject) String added in v0.0.2

func (h *FuncHeaderObject) String() string

func (*FuncHeaderObject) ToString added in v0.0.2

func (h *FuncHeaderObject) ToString() string

func (*FuncHeaderObject) Type added in v0.0.2

func (h *FuncHeaderObject) Type() ObjectType

type FuncSpec added in v0.0.2

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

func NewFuncSpec added in v0.0.2

func NewFuncSpec(this FuncWrapper, opt ...FuncSpecOption) *FuncSpec

func (*FuncSpec) AddMethod added in v0.0.2

func (s *FuncSpec) AddMethod(vm *VM, handler CallerObject, override bool, onAdd func(tcm *TypedCallerMethod) error) error

AddMethod Add caller method.

func (*FuncSpec) AddMethodByTypes added in v0.0.2

func (s *FuncSpec) AddMethodByTypes(_ *VM, argTypes ParamsTypes, handler CallerObject, override bool, onAdd func(tcm *TypedCallerMethod) error) error

func (*FuncSpec) Call added in v0.0.2

func (s *FuncSpec) Call(c Call) (Object, error)

func (*FuncSpec) CallerMethodDefault added in v0.0.2

func (s *FuncSpec) CallerMethodDefault() CallerObject

func (*FuncSpec) CallerMethodOfArgsTypes added in v0.0.2

func (s *FuncSpec) CallerMethodOfArgsTypes(types ObjectTypeArray) (co CallerObject)

func (*FuncSpec) CallerMethodWithValidationCheckOfArgs added in v0.0.2

func (s *FuncSpec) CallerMethodWithValidationCheckOfArgs(args Args) (CallerObject, bool)

func (*FuncSpec) CallerMethodWithValidationCheckOfArgsTypes added in v0.0.2

func (s *FuncSpec) CallerMethodWithValidationCheckOfArgsTypes(types ObjectTypeArray) (co CallerObject, validate bool)

func (*FuncSpec) CallerMethods added in v0.0.2

func (s *FuncSpec) CallerMethods() *MethodArgType

func (FuncSpec) CopyWithTarget added in v0.0.2

func (s FuncSpec) CopyWithTarget(target FuncWrapper) *FuncSpec

func (*FuncSpec) GetFuncSpec added in v0.0.2

func (s *FuncSpec) GetFuncSpec() *FuncSpec

func (*FuncSpec) HasCallerMethods added in v0.0.2

func (s *FuncSpec) HasCallerMethods() bool

func (*FuncSpec) IsFalsy added in v0.0.2

func (s *FuncSpec) IsFalsy() bool

func (*FuncSpec) MethodOrDefault added in v0.0.2

func (s *FuncSpec) MethodOrDefault(types ObjectTypeArray) (method *TypedCallerMethod, defaul CallerObject)

func (*FuncSpec) PrintFuncWrapper added in v0.0.2

func (s *FuncSpec) PrintFuncWrapper(state *PrinterState, fo FuncWrapper) (err error)

type FuncSpecOption added in v0.0.2

type FuncSpecOption func(spec *FuncSpec)

func FuncSpectWithDefault added in v0.0.2

func FuncSpectWithDefault(co CallerObject) FuncSpecOption

type FuncWrapper added in v0.0.2

type FuncWrapper interface {
	fmt.Stringer
	Object
	Printabler
	Name() string
	FullName() string
	FuncSpecName() string
}

type Function

type Function struct {
	ObjectImpl
	// FuncName is the function's (unqualified) name, used in repr and errors.
	FuncName string
	// Usage is optional Markdown documentation shown by Doc().
	Usage string
	// Value is the Go handler invoked on each call.
	Value func(Call) (Object, error)
	// ToStringFunc, when set, overrides the default ToString rendering.
	ToStringFunc func() string
	// Header declares the parameter signature (names/types); it drives argument
	// dispatch and appears in repr. Set it via WithParams/WithParamsPairs.
	Header *FunctionHeader

	// Module qualifies the function's name (e.g. mod.greet) and scopes it to a
	// builtin namespace; set with WithModule.
	Module *ModuleSpec
	// contains filtered or unexported fields
}

Function is a Go-implemented callable value: it wraps a Value handler behind the Object/CallerObject interfaces so native Go code can be exposed to Gad scripts. Build one with NewFunction and the fluent With* options rather than populating the fields directly:

fn := NewFunction("greet", func(c Call) (Object, error) { … }).
	WithModule(mod).WithParamsPairs("name", TStr)

func NewFunction added in v0.0.2

func NewFunction(name string, v func(Call) (Object, error), opt ...FunctionOption) *Function

func (*Function) Call

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

func (Function) Copy

func (f Function) Copy() Object

Copy implements Copier interface.

func (*Function) Equal

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

Equal implements Object interface.

func (*Function) GetModule added in v0.0.2

func (f *Function) GetModule() *ModuleSpec

func (*Function) IsFalsy

func (*Function) IsFalsy() bool

IsFalsy implements Object interface.

func (*Function) Name

func (f *Function) Name() string

func (*Function) ParamTypes added in v0.0.2

func (f *Function) ParamTypes() (types ParamsTypes)

func (*Function) ReturnVars added in v0.0.2

func (f *Function) ReturnVars() ReturnVars

func (*Function) SetModule added in v0.0.2

func (f *Function) SetModule(m *ModuleSpec)

func (*Function) String added in v0.0.2

func (f *Function) String() string

func (*Function) ToString

func (f *Function) ToString() string

func (*Function) Type

func (*Function) Type() ObjectType

func (*Function) WithHeader added in v0.0.2

func (f *Function) WithHeader(do func(h *FunctionHeader)) *Function

func (*Function) WithOption added in v0.0.2

func (f *Function) WithOption(opt ...FunctionOption) *Function

func (*Function) WithParams added in v0.0.2

func (f *Function) WithParams(builder func(newParam func(name string) *ParamBuilder)) *Function

func (*Function) WithParamsPairs added in v0.0.2

func (f *Function) WithParamsPairs(nameAndType ...any) *Function

type FunctionHeader

type FunctionHeader struct {
	Params      Params
	NamedParams NamedParams

	ReturnVars ReturnVars
	// contains filtered or unexported fields
}

func NewFunctionHeader added in v0.0.2

func NewFunctionHeader() *FunctionHeader

func (*FunctionHeader) ParamTypes

func (h *FunctionHeader) ParamTypes() ParamsTypes

func (*FunctionHeader) String

func (h *FunctionHeader) String() string

func (*FunctionHeader) WithNamedParams added in v0.0.2

func (h *FunctionHeader) WithNamedParams(builder func(newParam func(name string) *NamedParamBuilder)) *FunctionHeader

func (*FunctionHeader) WithParams added in v0.0.2

func (h *FunctionHeader) WithParams(builder func(newParam func(name string) *ParamBuilder)) *FunctionHeader

func (*FunctionHeader) WithReturnVars added in v0.0.2

func (h *FunctionHeader) WithReturnVars(builder func(ret func(name string, typ ...ObjectType))) *FunctionHeader

type FunctionHeaderParam

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

func (*FunctionHeaderParam) String

func (p *FunctionHeaderParam) String() string

type FunctionOption added in v0.0.2

type FunctionOption func(f *Function)

func FunctionWithModule added in v0.0.2

func FunctionWithModule(spec *ModuleSpec) FunctionOption

func FunctionWithNamedParams added in v0.0.2

func FunctionWithNamedParams(builder func(newParam func(name string) *NamedParamBuilder)) FunctionOption

func FunctionWithParams added in v0.0.2

func FunctionWithParams(builder func(newParam func(name string) *ParamBuilder)) FunctionOption

func FunctionWithUsage added in v0.0.2

func FunctionWithUsage(usage string) FunctionOption

type Importable

type Importable interface {
	// Import should return either an Object or module source code ([]byte).
	Import(ctx context.Context, module *ModuleSpec) (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) BinOpAdd added in v0.0.2

func (o *IndexDeleteProxy) BinOpAdd(vm *VM, right Object) (Object, error)

BinaryOp implements Object interface. BinOpAdd merges an iterable via the proxied index setter.

func (*IndexDeleteProxy) BinOpGreater added in v0.0.2

func (o *IndexDeleteProxy) BinOpGreater(_ *VM, right Object) (Object, error)

func (*IndexDeleteProxy) BinOpGreaterEq added in v0.0.2

func (o *IndexDeleteProxy) BinOpGreaterEq(_ *VM, right Object) (Object, error)

func (*IndexDeleteProxy) BinOpLess added in v0.0.2

func (o *IndexDeleteProxy) BinOpLess(_ *VM, right Object) (Object, error)

func (*IndexDeleteProxy) BinOpLessEq added in v0.0.2

func (o *IndexDeleteProxy) BinOpLessEq(_ *VM, right Object) (Object, error)

func (*IndexDeleteProxy) BinOpSub added in v0.0.2

func (o *IndexDeleteProxy) BinOpSub(vm *VM, right Object) (_ Object, err error)

BinOpSub deletes the keys in right via the proxied delete.

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 {
	GetIndexFunc   func(vm *VM, index Object) (value Object, err error)
	ToStrFunc      func() string
	PrintFunc      func(s *PrinterState) error
	IterateFunc    func(vm *VM, na *NamedArgs) Iterator
	InterfaceValue any
	CallNameFunc   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) Print added in v0.0.2

func (i *IndexGetProxy) Print(state *PrinterState) error

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 IndexMethodAdder added in v0.0.2

type IndexMethodAdder interface {
	AddMethodIndex(c Call) (ret Object, err error)
}

type IndexMethodGetter added in v0.0.2

type IndexMethodGetter interface {
	GetIndexMethod(vm *VM, index Object) (ret Object, err error)
}

type IndexProxy

type IndexProxy struct {
	IndexGetProxy
	IndexSetProxy
}

func (*IndexProxy) BinOpAdd added in v0.0.2

func (o *IndexProxy) BinOpAdd(vm *VM, right Object) (Object, error)

BinOpAdd merges an iterable's entries via the proxied index setter; the comparison operators order the proxy after nil.

func (*IndexProxy) BinOpGreater added in v0.0.2

func (o *IndexProxy) BinOpGreater(_ *VM, right Object) (Object, error)

func (*IndexProxy) BinOpGreaterEq added in v0.0.2

func (o *IndexProxy) BinOpGreaterEq(_ *VM, right Object) (Object, error)

func (*IndexProxy) BinOpLess added in v0.0.2

func (o *IndexProxy) BinOpLess(_ *VM, right Object) (Object, error)

func (*IndexProxy) BinOpLessEq added in v0.0.2

func (o *IndexProxy) BinOpLessEq(_ *VM, right Object) (Object, error)

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 IndexSetterUpdater added in v0.0.2

type IndexSetterUpdater interface {
	UpdateIndexSetter(out StringIndexSetter)
}

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) BinOpAdd added in v0.0.2

func (o Int) BinOpAdd(vm *VM, right Object) (Object, error)

func (Int) BinOpAnd added in v0.0.2

func (o Int) BinOpAnd(vm *VM, right Object) (Object, error)

func (Int) BinOpAndNot added in v0.0.2

func (o Int) BinOpAndNot(vm *VM, right Object) (Object, error)

func (Int) BinOpGreater added in v0.0.2

func (o Int) BinOpGreater(vm *VM, right Object) (Object, error)

func (Int) BinOpGreaterEq added in v0.0.2

func (o Int) BinOpGreaterEq(vm *VM, right Object) (Object, error)

func (Int) BinOpLess added in v0.0.2

func (o Int) BinOpLess(vm *VM, right Object) (Object, error)

func (Int) BinOpLessEq added in v0.0.2

func (o Int) BinOpLessEq(vm *VM, right Object) (Object, error)

func (Int) BinOpMul added in v0.0.2

func (o Int) BinOpMul(vm *VM, right Object) (Object, error)

func (Int) BinOpOr added in v0.0.2

func (o Int) BinOpOr(vm *VM, right Object) (Object, error)

func (Int) BinOpPow added in v0.0.2

func (o Int) BinOpPow(vm *VM, right Object) (Object, error)

func (Int) BinOpQuo added in v0.0.2

func (o Int) BinOpQuo(vm *VM, right Object) (Object, error)

func (Int) BinOpRem added in v0.0.2

func (o Int) BinOpRem(vm *VM, right Object) (Object, error)

func (Int) BinOpSame added in v0.0.2

func (o Int) BinOpSame(_ *VM, right Object) (Object, error)

func (Int) BinOpShl added in v0.0.2

func (o Int) BinOpShl(vm *VM, right Object) (Object, error)

func (Int) BinOpShr added in v0.0.2

func (o Int) BinOpShr(vm *VM, right Object) (Object, error)

func (Int) BinOpSub added in v0.0.2

func (o Int) BinOpSub(vm *VM, right Object) (Object, error)

func (Int) BinOpXor added in v0.0.2

func (o Int) BinOpXor(vm *VM, right Object) (Object, error)

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

func (Int) UnOpAdd added in v0.0.2

func (o Int) UnOpAdd(*VM) (Object, error)

func (Int) UnOpDec added in v0.0.2

func (o Int) UnOpDec(*VM) (Object, error)

func (Int) UnOpInc added in v0.0.2

func (o Int) UnOpInc(*VM) (Object, error)

func (Int) UnOpSub added in v0.0.2

func (o Int) UnOpSub(*VM) (Object, error)

func (Int) UnOpXor added in v0.0.2

func (o Int) UnOpXor(*VM) (Object, error)

type Interface added in v0.0.2

type Interface struct {
	IName   string
	Module  *ModuleSpec       // module the interface was compiled in (for FullName)
	Extends ParamType         // parent interface symbol refs (from `extends { … }`)
	Fields  []*InterfaceField // typed fields
	Props   []*InterfaceProp  // getter/setter properties
	Methods []*InterfaceMethod
}

Interface is the value of an `interface { … }` (see TInterface).

func (*Interface) AssignTo added in v0.0.2

func (i *Interface) AssignTo(vm *VM, obj Object, to TypeAssigner) (Object, error)

AssignTo makes *Interface a TypeAssigner: obj is assignable to the interface `to` when it structurally satisfies it (see CanAssignVM).

func (*Interface) CanAssign added in v0.0.2

func (i *Interface) CanAssign(obj Object) (bool, error)

CanAssign reports whether obj structurally satisfies the interface. It has no VM, so field-type symbols and parent interfaces that need one are skipped; prefer CanAssignVM (used by parameter checking and the `::` operator).

func (*Interface) CanAssignVM added in v0.0.2

func (i *Interface) CanAssignVM(vm *VM, obj Object) (bool, error)

CanAssignVM reports whether obj structurally satisfies the interface: it has every required field (with an assignable type), property and method (whose signatures satisfy the required headers), and satisfies every extended interface. vm resolves field-type symbols, property/method calls and the parent-interface symbols; when nil those VM-dependent checks are relaxed.

func (*Interface) Equal added in v0.0.2

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

func (*Interface) FullName added in v0.0.2

func (i *Interface) FullName() string

FullName is the interface name qualified by its module, or just the name when there is no (or an unnamed) module or the interface is anonymous. FullName returns the module-qualified name `MODULE_NAME.NAME` when the module name is set; otherwise the bare name (or an empty string when unnamed).

func (*Interface) IndexGet added in v0.0.2

func (i *Interface) IndexGet(_ *VM, index Object) (Object, error)

func (*Interface) IsFalsy added in v0.0.2

func (i *Interface) IsFalsy() bool

func (*Interface) Name added in v0.0.2

func (i *Interface) Name() string

func (*Interface) String added in v0.0.2

func (i *Interface) String() string

func (*Interface) ToString added in v0.0.2

func (i *Interface) ToString() string

func (*Interface) Type added in v0.0.2

func (i *Interface) Type() ObjectType

func (*Interface) WithField added in v0.0.2

func (i *Interface) WithField(name string, types ...ObjectType) *Interface

WithField appends a typed field.

func (*Interface) WithGetter added in v0.0.2

func (i *Interface) WithGetter(name string, getter *FuncHeaderObject) *Interface

WithGetter appends a getter property (an InterfaceProp with a Getter).

func (*Interface) WithMethod added in v0.0.2

func (i *Interface) WithMethod(name string, headers ...*FuncHeaderObject) *Interface

WithMethod appends a required method with its overload signatures.

func (*Interface) WithSetter added in v0.0.2

func (i *Interface) WithSetter(name string, setters ...*FuncHeaderObject) *Interface

WithSetter appends a setter property (an InterfaceProp with Setters).

type InterfaceField added in v0.0.2

type InterfaceField struct {
	Iface        *Interface
	Name         string
	TypesSymbols ParamType   // compile-time type symbols
	Types        ObjectTypes // resolved types (when built at run time)
}

InterfaceField is a typed field of an interface (see gad.Param for the type symbol/ObjectType split).

func (*InterfaceField) Equal added in v0.0.2

func (f *InterfaceField) Equal(right Object) bool

func (*InterfaceField) IndexGet added in v0.0.2

func (f *InterfaceField) IndexGet(vm *VM, index Object) (Object, error)

func (*InterfaceField) IsFalsy added in v0.0.2

func (f *InterfaceField) IsFalsy() bool

func (*InterfaceField) ToString added in v0.0.2

func (f *InterfaceField) ToString() string

func (*InterfaceField) Type added in v0.0.2

func (f *InterfaceField) Type() ObjectType

type InterfaceMethod added in v0.0.2

type InterfaceMethod struct {
	Iface   *Interface
	Name    string
	Headers []*FuncHeaderObject
}

InterfaceMethod is a required method of an interface: a name and its overload signatures (like a MethodInterface).

func (*InterfaceMethod) Equal added in v0.0.2

func (m *InterfaceMethod) Equal(right Object) bool

func (*InterfaceMethod) IndexGet added in v0.0.2

func (m *InterfaceMethod) IndexGet(_ *VM, index Object) (Object, error)

func (*InterfaceMethod) IsFalsy added in v0.0.2

func (m *InterfaceMethod) IsFalsy() bool

func (*InterfaceMethod) ToString added in v0.0.2

func (m *InterfaceMethod) ToString() string

func (*InterfaceMethod) Type added in v0.0.2

func (m *InterfaceMethod) Type() ObjectType

type InterfaceProp added in v0.0.2

type InterfaceProp struct {
	Iface   *Interface
	Name    string
	Getter  *FuncHeaderObject   // the getter signature, or nil
	Setters []*FuncHeaderObject // the setter signatures
}

InterfaceProp is a getter and/or setter property of an interface.

func (*InterfaceProp) Equal added in v0.0.2

func (p *InterfaceProp) Equal(right Object) bool

func (*InterfaceProp) IndexGet added in v0.0.2

func (p *InterfaceProp) IndexGet(_ *VM, index Object) (Object, error)

func (*InterfaceProp) IsFalsy added in v0.0.2

func (p *InterfaceProp) IsFalsy() bool

func (*InterfaceProp) ToString added in v0.0.2

func (p *InterfaceProp) ToString() string

func (*InterfaceProp) Type added in v0.0.2

func (p *InterfaceProp) 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) Prepare

func (inv *Invoker) Prepare(f func(vm *VM))

func (*Invoker) PrepareHandlers

func (inv *Invoker) PrepareHandlers() []func(vm *VM)

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

func (*Invoker) WithContext added in v0.0.2

func (inv *Invoker) WithContext(ctx context.Context) *Invoker

WithContext binds a context to the Invoker. When the context is cancelled (for example a deadline from context.WithTimeout, or a context.WithCancel cancel) before the invoked function returns, the whole VM tree is aborted from the root, so the invoked CompiledFunction and every VM it spawned through nested invokers — which all fork into the same root pool — stop, and Invoke returns the context's error (context.DeadlineExceeded / context.Canceled). This is the intended guard against infinite loops and long-running invoked code.

A nil or non-cancellable context (the default, or context.Background) adds no goroutine and no overhead: the callee runs inline as before.

type ItemsGetter

type ItemsGetter interface {
	Object
	Items(vm *VM, cb ItemsGetterCallback) (err error)
}

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

type ItemsGetterCallback

type ItemsGetterCallback func(i int, item *KeyValue) (err error)

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) Print added in v0.0.2

func (it *Iteration) Print(state *PrinterState) 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 IterationDoner

type IterationDoner interface {
	IterationDone(vm *VM) error
}

func ToIterationDoner

func ToIterationDoner(obj any) IterationDoner

type Iterator

type Iterator interface {
	Printabler
	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 Iterators added in v0.0.2

type Iterators []Iterator

func (Iterators) Print added in v0.0.2

func (its Iterators) Print(s *PrinterState) (err error)

type KeyValue

type KeyValue struct {
	K, V Object
}

func (*KeyValue) BinOpGreater added in v0.0.2

func (o *KeyValue) BinOpGreater(vm *VM, right Object) (Object, error)

Greater and GreaterEq both report !IsLess (matching the original behavior).

func (*KeyValue) BinOpGreaterEq added in v0.0.2

func (o *KeyValue) BinOpGreaterEq(vm *VM, right Object) (Object, error)

func (*KeyValue) BinOpLess added in v0.0.2

func (o *KeyValue) BinOpLess(vm *VM, right Object) (Object, error)

A *KeyValue orders after nil and against another *KeyValue by IsLess; these implement the comparison ObjectWith{Op}BinOperator interfaces.

func (*KeyValue) BinOpLessEq added in v0.0.2

func (o *KeyValue) BinOpLessEq(vm *VM, right Object) (Object, error)

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

func (o *KeyValue) Print(state *PrinterState) (err error)

func (*KeyValue) ToString

func (o *KeyValue) ToString() string

func (*KeyValue) Type

func (o *KeyValue) Type() ObjectType

type KeyValueArray

type KeyValueArray []*KeyValue

func ConvertToKeyValueArray

func ConvertToKeyValueArray(vm *VM, o ...Object) (ret KeyValueArray, err error)

ConvertToKeyValueArray convert objects to KeyValueArray. If success return then, otherwise return error.

func MustConvertToKeyValueArray

func MustConvertToKeyValueArray(vm *VM, o ...Object) (ret KeyValueArray)

MustConvertToKeyValueArray convert objects to KeyValueArray and return then if success, otherwise panics.

func (KeyValueArray) AddItems

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

func (*KeyValueArray) Append

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

func (KeyValueArray) AppendArray

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

func (*KeyValueArray) AppendArrayOfPairs added in v0.0.2

func (o *KeyValueArray) AppendArrayOfPairs(arr Array) error

func (KeyValueArray) AppendMap

func (o KeyValueArray) AppendMap(m Dict) KeyValueArray

func (KeyValueArray) AppendObjects

func (o KeyValueArray) AppendObjects(vm *VM, items ...Object) (this Object, err error)

func (KeyValueArray) BinOpAdd added in v0.0.2

func (o KeyValueArray) BinOpAdd(vm *VM, right Object) (Object, error)

BinOpAdd appends right's entries (ObjectWithAddBinOperator); the comparison operators order the array after nil and are otherwise unsupported.

func (KeyValueArray) BinOpGreater added in v0.0.2

func (o KeyValueArray) BinOpGreater(_ *VM, right Object) (Object, error)

func (KeyValueArray) BinOpGreaterEq added in v0.0.2

func (o KeyValueArray) BinOpGreaterEq(_ *VM, right Object) (Object, error)

func (KeyValueArray) BinOpIn added in v0.0.2

func (o KeyValueArray) BinOpIn(_ *VM, v Object) (Object, error)

BinOpIn implements the `in` operator (ObjectWithInBinOperator): reports whether v is a key of the key-value array (`v in kva`).

func (KeyValueArray) BinOpLess added in v0.0.2

func (o KeyValueArray) BinOpLess(_ *VM, right Object) (Object, error)

func (KeyValueArray) BinOpLessEq added in v0.0.2

func (o KeyValueArray) BinOpLessEq(_ *VM, right Object) (Object, error)

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) 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, cb ItemsGetterCallback) (err error)

func (KeyValueArray) Iterate

func (o KeyValueArray) Iterate(vm *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) Print

func (o KeyValueArray) Print(state *PrinterState) (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) ToArray added in v0.0.2

func (o KeyValueArray) ToArray() (arr Array)

func (KeyValueArray) ToString

func (o KeyValueArray) ToString() string

func (KeyValueArray) Type

func (o KeyValueArray) Type() ObjectType

func (KeyValueArray) UpdateIndexSetter added in v0.0.2

func (o KeyValueArray) UpdateIndexSetter(out StringIndexSetter)

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) BinOpGreater added in v0.0.2

func (o KeyValueArrays) BinOpGreater(_ *VM, right Object) (Object, error)

func (KeyValueArrays) BinOpGreaterEq added in v0.0.2

func (o KeyValueArrays) BinOpGreaterEq(_ *VM, right Object) (Object, error)

func (KeyValueArrays) BinOpLess added in v0.0.2

func (o KeyValueArrays) BinOpLess(_ *VM, right Object) (Object, error)

KeyValueArrays orders after nil and is otherwise not comparable.

func (KeyValueArrays) BinOpLessEq added in v0.0.2

func (o KeyValueArrays) BinOpLessEq(_ *VM, right Object) (Object, error)

func (KeyValueArrays) CallName

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

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 *VM, na *NamedArgs) Iterator

func (KeyValueArrays) Length

func (o KeyValueArrays) Length() int

Length implements LengthGetter interface.

func (KeyValueArrays) Print

func (o KeyValueArrays) Print(state *PrinterState) (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 Location added in v0.0.2

type Location struct {
	ObjectImpl
	Value *time.Location
}

Location represents location values and implements Object interface.

func ToLocation added in v0.0.2

func ToLocation(o Object) (ret *Location, ok bool)

ToLocation will try to convert given Object to *Location value.

func (*Location) Equal added in v0.0.2

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

Equal implements Object interface.

func (*Location) IsFalsy added in v0.0.2

func (o *Location) IsFalsy() bool

IsFalsy implements Object interface.

func (*Location) ToString added in v0.0.2

func (o *Location) ToString() string

ToString implements Object interface.

func (*Location) Type added in v0.0.2

func (*Location) Type() ObjectType

type Mapabler

type Mapabler interface {
	Object
	// Map map object.
	// If update, update self object.
	// If len(args) is 1, must a value, otherwise value and key
	Map(c Call, update bool, keyValue Array, handler VMCaller) (Object, error)
}

type MethodAdder added in v0.0.2

type MethodAdder interface {
	// AddCallerMethod add caller method from argument types.
	// the argTypes param is a list of supported types for arguments.
	//
	// Examples:
	//  - fn(str, decimal) => ParamsTypes{{TStr},{TDecimal}}
	//  - fn(str|int, decimal) => ParamsTypes{{TStr,Int},{TDecimal}}
	AddMethodByTypes(vm *VM, argTypes ParamsTypes, handler CallerObject, override bool, onAdd func(method *TypedCallerMethod) error) error
}

type MethodArgType

type MethodArgType struct {
	Type    TypeAssigner
	Method  *TypedCallerMethod
	Var     bool
	Next    Methods
	NextVar Methods
	// contains filtered or unexported fields
}

func (*MethodArgType) Add

func (at *MethodArgType) Add(types ParamsTypes, m *CallerMethod, override bool, onAdd func(tcm *TypedCallerMethod) error) (err error)

func (*MethodArgType) ArgWalk added in v0.0.2

func (at *MethodArgType) ArgWalk(f func(m *MethodArgType) any) (r any)

func (MethodArgType) Copy added in v0.0.2

func (at MethodArgType) Copy() *MethodArgType

func (*MethodArgType) EachMethods added in v0.0.2

func (at *MethodArgType) EachMethods() func(func(i int, m *MethodArgType) bool)

func (*MethodArgType) GetMethod

func (at *MethodArgType) GetMethod(types ObjectTypeArray) *TypedCallerMethod

func (*MethodArgType) IsZero

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

func (*MethodArgType) MethodsWalk added in v0.0.2

func (at *MethodArgType) MethodsWalk(f func(m *MethodArgType) any) (r any)

func (*MethodArgType) NumMethods added in v0.0.2

func (at *MethodArgType) NumMethods() (i int)

func (*MethodArgType) Parents added in v0.0.2

func (at *MethodArgType) Parents() (parents []*MethodArgType)

func (*MethodArgType) Path added in v0.0.2

func (at *MethodArgType) Path() (path []*MethodArgType)

func (*MethodArgType) ToString added in v0.0.2

func (at *MethodArgType) ToString() string

func (*MethodArgType) Walk

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

func (*MethodArgType) WalkSorted

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

type MethodCaller

type MethodCaller interface {
	CallerObject
	MethodAdder

	CallerMethods() *MethodArgType
	// CallerMethodWithValidationCheckOfArgs return a method and validation check flag from args.
	// In same cases this method is most fast then `MethodWithValidationCheckOfArgTypes`
	CallerMethodWithValidationCheckOfArgs(args Args) (method CallerObject, validationCheck bool)
	// CallerMethodWithValidationCheckOfArgsTypes return a method from knowed args types with validation check flag
	CallerMethodWithValidationCheckOfArgsTypes(types ObjectTypeArray) (method CallerObject, validationCheck bool)
	// CallerMethodOfArgsTypes return a method from arguments types whitout validation check flag.
	CallerMethodOfArgsTypes(types ObjectTypeArray) (method CallerObject)
	HasCallerMethods() bool
	// CallerMethodDefault returns default caller Object if exists or nil
	CallerMethodDefault() CallerObject
	Name() string
}

type MethodDefinition

type MethodDefinition struct {
	Args    []ObjectType
	Handler CallerObject
}

type MethodInterface added in v0.0.2

type MethodInterface struct {
	MIName  string
	Headers []*FuncHeaderObject
}

MethodInterface is the value of a method interface (see TMethodInterface): a name and the required function headers.

func (*MethodInterface) AssignTo added in v0.0.2

func (m *MethodInterface) AssignTo(vm *VM, obj Object, to TypeAssigner) (Object, error)

AssignTo makes *MethodInterface a TypeAssigner. As a target it accepts a value that structurally implements it; as a source it matches only an equal interface.

func (*MethodInterface) BinOpAdd added in v0.0.2

func (m *MethodInterface) BinOpAdd(_ *VM, right Object) (Object, error)

BinOpAdd implements `mi + mi2` (ObjectWithAddBinOperator), merging two interfaces.

func (*MethodInterface) BinOpIn added in v0.0.2

func (m *MethodInterface) BinOpIn(_ *VM, v Object) (Object, error)

BinOpIn implements the `in` operator (ObjectWithInBinOperator): reports whether v is one of the interface's function headers (`header in meti`).

func (*MethodInterface) CanAssign added in v0.0.2

func (m *MethodInterface) CanAssign(obj Object) (bool, error)

func (*MethodInterface) CanAssignVM added in v0.0.2

func (m *MethodInterface) CanAssignVM(vm *VM, obj Object) (bool, error)

CanAssignVM reports whether obj (a callable) structurally implements the interface, using vm to resolve the callable's signatures.

func (*MethodInterface) Equal added in v0.0.2

func (m *MethodInterface) Equal(right Object) bool

func (*MethodInterface) HeadersArray added in v0.0.2

func (m *MethodInterface) HeadersArray() Array

HeadersArray returns the headers as an Array of FunctionHeader values.

func (*MethodInterface) IndexGet added in v0.0.2

func (m *MethodInterface) IndexGet(_ *VM, index Object) (Object, error)

IndexGet exposes name and headers.

func (*MethodInterface) IsFalsy added in v0.0.2

func (m *MethodInterface) IsFalsy() bool

func (*MethodInterface) Name added in v0.0.2

func (m *MethodInterface) Name() string

func (*MethodInterface) String added in v0.0.2

func (m *MethodInterface) String() string

func (*MethodInterface) ToString added in v0.0.2

func (m *MethodInterface) ToString() string

func (*MethodInterface) Type added in v0.0.2

func (m *MethodInterface) Type() ObjectType

type Methods

type Methods map[TypeAssigner]*MethodArgType

func (Methods) Copy added in v0.0.2

func (m Methods) Copy() (cp Methods)

func (Methods) IsZero

func (m Methods) IsZero() (ok bool)

func (Methods) Sorted added in v0.0.2

func (m Methods) Sorted(cb func(m *MethodArgType) any) (err any)

func (Methods) Walk

func (m Methods) Walk(cb func(m *TypedCallerMethod) any) (v any)

func (Methods) WalkSorted

func (m Methods) WalkSorted(cb func(m *TypedCallerMethod) any) (v any)

type MixedParams

type MixedParams struct {
	Positional Array
	Named      KeyValueArray
}

func (*MixedParams) Equal

func (m *MixedParams) Equal(right Object) bool

func (*MixedParams) IndexGet

func (m *MixedParams) IndexGet(vm *VM, index Object) (value Object, err error)

func (*MixedParams) IsFalsy

func (m *MixedParams) IsFalsy() bool

func (*MixedParams) Print added in v0.0.2

func (m *MixedParams) Print(state *PrinterState) error

func (*MixedParams) ToDict

func (m *MixedParams) ToDict() (d Dict)

func (*MixedParams) ToString

func (m *MixedParams) ToString() string

func (*MixedParams) Type

func (m *MixedParams) Type() ObjectType

func (*MixedParams) UpdateIndexSetter added in v0.0.2

func (m *MixedParams) UpdateIndexSetter(out StringIndexSetter)

type Module added in v0.0.2

type Module struct {
	Spec   *ModuleSpec
	Data   ModuleData
	Params MixedParams
}

Module represent the module

func NewModule added in v0.0.2

func NewModule(static *ModuleSpec, f ...func(m *Module)) *Module

func (*Module) CanCall added in v0.0.2

func (m *Module) CanCall() bool

func (*Module) CanIterate added in v0.0.2

func (m *Module) CanIterate() bool

func (*Module) Equal added in v0.0.2

func (m *Module) Equal(right Object) bool

func (*Module) File added in v0.0.2

func (m *Module) File() string

func (*Module) IndexGet added in v0.0.2

func (m *Module) IndexGet(vm *VM, index Object) (value Object, err error)

func (*Module) IndexSet added in v0.0.2

func (m *Module) IndexSet(vm *VM, index, value Object) error

func (*Module) IsFalsy added in v0.0.2

func (m *Module) IsFalsy() bool

func (*Module) Items added in v0.0.2

func (m *Module) Items(vm *VM, cb ItemsGetterCallback) (err error)

func (*Module) Iterate added in v0.0.2

func (m *Module) Iterate(vm *VM, na *NamedArgs) Iterator

func (*Module) Keys added in v0.0.2

func (m *Module) Keys() (arr Array)

func (*Module) Length added in v0.0.2

func (m *Module) Length() int

func (*Module) MergeData added in v0.0.2

func (m *Module) MergeData(d Dict)

func (*Module) Name added in v0.0.2

func (m *Module) Name() string

func (*Module) Print added in v0.0.2

func (m *Module) Print(state *PrinterState) (err error)

func (*Module) Set added in v0.0.2

func (m *Module) Set(key string, value Object)

func (*Module) String added in v0.0.2

func (m *Module) String() string

func (*Module) ToDict added in v0.0.2

func (m *Module) ToDict() Dict

func (*Module) ToString added in v0.0.2

func (m *Module) ToString() string

func (*Module) Type added in v0.0.2

func (m *Module) Type() ObjectType

func (*Module) UpdateIndexSetter added in v0.0.2

func (m *Module) UpdateIndexSetter(out StringIndexSetter)

func (*Module) Values added in v0.0.2

func (m *Module) Values() (arr Array)

type ModuleGetter added in v0.0.2

type ModuleGetter interface {
	GetModule() *ModuleSpec
}

type ModuleInfo

type ModuleInfo struct {
	Name string
	URL  string
}

type ModuleInitFunc added in v0.0.2

type ModuleInitFunc func(module *Module, c Call) (err error)

func ModuleInitWithDataDict added in v0.0.2

func ModuleInitWithDataDict(d Dict) ModuleInitFunc

func (ModuleInitFunc) Caller added in v0.0.2

func (f ModuleInitFunc) Caller(spec *ModuleSpec) func(module *Module) CallerObject

func (ModuleInitFunc) MustGetData added in v0.0.2

func (f ModuleInitFunc) MustGetData(module *Module) (data ModuleData)

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) AddBuiltinCompilableModule added in v0.0.2

func (m *ModuleMap) AddBuiltinCompilableModule(
	name string,
	compile BuiltinCompileModuleFunc,
) *ModuleMap

AddBuiltinCompilableModule adds a builtin compilable module.

func (*ModuleMap) AddBuiltinModule

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

AddBuiltinModule adds a builtin module.

func (*ModuleMap) AddBuiltinModuleInit added in v0.0.2

func (m *ModuleMap) AddBuiltinModuleInit(
	name string,
	init ModuleInitFunc,
) *ModuleMap

AddBuiltinModuleInit 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) Importers added in v0.0.2

func (m *ModuleMap) Importers() map[string]Importable

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 ModuleSetter added in v0.0.2

type ModuleSetter interface {
	SetModule(m *ModuleSpec)
}

type ModuleSpec added in v0.0.2

type ModuleSpec struct {
	ModuleInfo
	Index            int
	Path             []int
	Main             bool
	InitCompiledFunc *CompiledFunction
	InitGoFunc       func(module *Module) CallerObject
}

func NewModuleSpecFromName added in v0.0.2

func NewModuleSpecFromName(name string, opt ...func(s *ModuleSpec)) *ModuleSpec

func (*ModuleSpec) InitFunc added in v0.0.2

func (i *ModuleSpec) InitFunc(module *Module) CallerObject

func (*ModuleSpec) String added in v0.0.2

func (i *ModuleSpec) String() string

type ModuleStmt added in v0.0.2

type ModuleStmt struct {
	Module *ModuleSpec
	*parser.File
}

type Modules added in v0.0.2

type Modules []*Module

func (Modules) Get added in v0.0.2

func (m Modules) Get(name string) *Module

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
	Do     func(value Object) error
	*TypeAssertion
}

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

func (*NamedArgVar) IsFalsy added in v0.0.2

func (v *NamedArgVar) IsFalsy() bool

type NamedArgs

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

NamedArgs holds the keyword (name=value) arguments of a call.

Values are lazily materialised from sources into the m map on first access (see check). By default reading a value with GetValue/GetValueOrNil *consumes* it — the key is removed from m and recorded in ready — so a function only sees each named argument once and leftover names can be detected. When the NamedArgs is read-only (see WithReadOnly), reads do not consume, so the same NamedArgs can be reused across several calls; this is useful when reusing one instance in a loop and mutating a backing Dict between calls (Dict.ToNamedArgs keeps a live reference to that Dict in m).

func NewNamedArgs

func NewNamedArgs(pairs ...KeyValueArray) *NamedArgs

NewNamedArgs returns a NamedArgs from the given name=value pair lists. Later pairs take precedence over earlier ones for duplicate keys.

func (*NamedArgs) Add

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

func (*NamedArgs) AllDict

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

func (*NamedArgs) BinOpAdd added in v0.0.2

func (o *NamedArgs) BinOpAdd(_ *VM, right Object) (Object, error)

BinOpAdd merges a nil right operand (a no-op add); NamedArgs otherwise orders after nil and is not comparable to other operands.

func (*NamedArgs) BinOpGreater added in v0.0.2

func (o *NamedArgs) BinOpGreater(_ *VM, right Object) (Object, error)

func (*NamedArgs) BinOpGreaterEq added in v0.0.2

func (o *NamedArgs) BinOpGreaterEq(_ *VM, right Object) (Object, error)

func (*NamedArgs) BinOpLess added in v0.0.2

func (o *NamedArgs) BinOpLess(_ *VM, right Object) (Object, error)

func (*NamedArgs) BinOpLessEq added in v0.0.2

func (o *NamedArgs) BinOpLessEq(_ *VM, 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 reads each named arg in dst (by Name, type-checked via TypeAssertion) and is strict: it returns ErrUnexpectedNamedArg if any passed named arg is not covered by dst. Use it when dst is the complete set of accepted named args.

Errors:

  • ArgumentTypeError if a value fails its TypeAssertion.
  • ErrUnexpectedNamedArg if an unrecognised named arg was passed.

It does not run the Do handlers; see GetDo.

func (*NamedArgs) GetDo added in v0.0.2

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

GetDo is the strict form of GetDoCheck (check=true): it reads each named arg in dst, rejects any unrecognised named arg with ErrUnexpectedNamedArg, then runs each dst.Do handler (in dst order) for the args that were present.

Errors:

  • ArgumentTypeError if a value fails its TypeAssertion.
  • ErrUnexpectedNamedArg if an unrecognised named arg was passed.
  • any error returned by a dst.Do handler.

func (*NamedArgs) GetDoCheck added in v0.0.2

func (o *NamedArgs) GetDoCheck(check bool, dst ...*NamedArgVar) (err error)

GetDoCheck reads each named arg in dst (by Name, type-checked) and runs its Do handler when the arg was present. When check is true it additionally rejects any passed named arg not covered by dst with ErrUnexpectedNamedArg.

Pass check=false when dst is only a partial view of the accepted named args — i.e. the remaining ones are consumed by a later call on the same NamedArgs. This is the two-phase pattern used by the Class constructor, where the outer builtin handles `define` and Class.Define handles `fields`/`methods`/`new`/…; the outer call must not reject those it leaves for the inner call.

Errors:

  • ArgumentTypeError if a value fails its TypeAssertion.
  • ErrUnexpectedNamedArg only when check is true and an unrecognised named arg was passed.
  • any error returned by a dst.Do handler.

func (*NamedArgs) GetOne

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

GetOne reads each named arg in dst by Name (type-checked). Unlike Get it is lenient: it ignores any other passed named args, so it never returns ErrUnexpectedNamedArg. Use it when other args are consumed elsewhere.

Errors:

  • ArgumentTypeError if a value fails its TypeAssertion.

It does not run the Do handlers; see GetOneDo.

func (*NamedArgs) GetOneDo added in v0.0.2

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

GetOneDo is the Do-running form of GetOne: it reads each named arg in dst and runs its Do handler when present, without rejecting unrecognised named args. It is equivalent to GetDoCheck(false, dst...).

Errors:

  • ArgumentTypeError if a value fails its TypeAssertion.
  • any error returned by a dst.Do handler.

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 returns the value for key, or nil if absent. Unless the NamedArgs is read-only, the key is consumed (removed from m and recorded in ready) so it is reported only once.

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) IsReadOnly added in v0.0.2

func (o *NamedArgs) IsReadOnly() bool

IsReadOnly reports whether reads consume values.

func (*NamedArgs) Items

func (o *NamedArgs) Items(_ *VM, cb ItemsGetterCallback) (err error)

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) Print added in v0.0.2

func (o *NamedArgs) Print(state *PrinterState) (err error)

func (*NamedArgs) Ready

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

func (*NamedArgs) SetReadOnly added in v0.0.2

func (o *NamedArgs) SetReadOnly(v bool)

SetReadOnly sets the read-only flag (see WithReadOnly).

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.

func (*NamedArgs) WithReadOnly added in v0.0.2

func (o *NamedArgs) WithReadOnly(v bool) *NamedArgs

WithReadOnly sets the read-only flag and returns o. While read-only, reads do not consume values and Add returns ErrNotWriteable.

type NamedParam

type NamedParam struct {
	Name string
	// Value is a script of default value
	Value        string
	Usage        string
	Index        int
	TypesSymbols ParamType
	Types        ObjectTypes
	Symbol       *SymbolInfo
	Var          bool
}

func NewNamedParam

func NewNamedParam(name, value string) *NamedParam

func NewVarNamedParam added in v0.0.2

func NewVarNamedParam(name string) *NamedParam

func (*NamedParam) String

func (p *NamedParam) String() string

type NamedParamBuilder added in v0.0.2

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

func (*NamedParamBuilder) Type added in v0.0.2

func (*NamedParamBuilder) Usage added in v0.0.2

func (*NamedParamBuilder) Var added in v0.0.2

type NamedParams

type NamedParams struct {
	Items []*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) EachNonVar added in v0.0.2

func (n *NamedParams) EachNonVar(cb func(i int, p *NamedParam))

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 NamedParamsVar added in v0.0.2

type NamedParamsVar struct {
	Object
}

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) BinOpGreater added in v0.0.2

func (o *NilType) BinOpGreater(_ *VM, _ Object) (Object, error)

func (*NilType) BinOpGreaterEq added in v0.0.2

func (o *NilType) BinOpGreaterEq(_ *VM, right Object) (Object, error)

func (*NilType) BinOpLess added in v0.0.2

func (o *NilType) BinOpLess(_ *VM, right Object) (Object, error)

nil orders before every non-nil value and equals itself, so `nil < x` and `nil <= x` are true (false only against nil for `<`), while `nil > x` is false and `nil >= x` is true only against nil. These implement the comparison ObjectWith{Op}BinOperator interfaces.

func (*NilType) BinOpLessEq added in v0.0.2

func (o *NilType) BinOpLessEq(_ *VM, _ Object) (Object, error)

func (*NilType) BinOpSame added in v0.0.2

func (o *NilType) BinOpSame(_ *VM, right Object) (Object, error)

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) Print added in v0.0.2

func (o *NilType) Print(state *PrinterState) error

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 Object

type Object interface {
	Falser

	// Type should return the type object.
	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{}
)
var TimeLocalLoc Object = &Location{Value: time.Local}
var TimeUtcLoc Object = &Location{Value: time.UTC}
var TimeZeroTime Object = &Time{}

func AddMethod added in v0.0.2

func AddMethod(target Object, method ...TypedCallerObjectWithParamTypes) Object

func AddMethodOverride added in v0.0.2

func AddMethodOverride(override bool, target Object, method ...TypedCallerObjectWithParamTypes) Object

func AssignToType added in v0.0.2

func AssignToType(vm *VM, obj, to Object) (Object, error)

AssignToType implements the `obj :: to` assign-to-type operator: it returns obj when obj is assignable to the type value `to`, otherwise a type error. The target may be an ObjectType (plain type assignability) or a structural TypeAssigner such as a meti/interface (checked by value, like a parameter type). It is the runtime behind OpAssign and chains left-to-right for `obj::T1::T2`.

func BinaryOp added in v0.0.2

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

BinaryOp runs a binary operator on two objects through the per-operator ObjectWith{Op}BinOperator dispatch (binOpObject), matching gad.binOp. Internal callers (sort, value comparisons) and embedders use it.

func BuiltinAddMethodFunc added in v0.0.2

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

func BuiltinAppendFunc

func BuiltinAppendFunc(c Call) (Object, error)

func BuiltinBinaryOperatorFunc

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

func BuiltinCapFunc

func BuiltinCapFunc(arg Object) Object

func BuiltinCastFunc

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

func BuiltinCharsFunc

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

func BuiltinCloseFunc

func BuiltinCloseFunc(c Call) (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 BuiltinDeepCopyFunc

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

func BuiltinDeleteFunc

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

func BuiltinEachFunc

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

func BuiltinEnterFunc added in v0.0.2

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

BuiltinEnterFunc implements gad.enter(resource), the entry half of a `with` block: it runs the resource's Enter hook — the Go ObjectEnter interface or, for Gad objects, an `enter()` method. A resource with neither is a no-op. Returns the resource so it can be used directly.

func BuiltinEnumerateFunc

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

func BuiltinExitFunc added in v0.0.2

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

BuiltinExitFunc implements gad.exit(resource, err), the exit half of a `with` block: it runs the resource's Exit hook — the Go ObjectExit interface or, for Gad objects, an `exit(err)` method — passing any error raised in the block (nil on normal exit). A resource with neither is a no-op.

func BuiltinFilterFunc

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

func BuiltinFlushFunc

func BuiltinFlushFunc(c Call) (Object, error)

func BuiltinImplementsFunc added in v0.0.2

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

BuiltinImplementsFunc reports whether fn provides every header of the given method interfaces: implements(fn CALLABLE, mi MethodInterface, *otherMi) <bool>. Matching is by parameter arity and assignable parameter types.

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 BuiltinIterationDoneFunc

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

func BuiltinIteratorInputFunc

func BuiltinIteratorInputFunc(o Object) Object

func BuiltinKeysFunc

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

func BuiltinLenFunc

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

func BuiltinMakeArrayFunc

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

func BuiltinMakeArrayRestFunc added in v0.0.2

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

BuiltinMakeArrayRestFunc backs the private :makeArrayRest builtin used by array destructuring with a trailing `*rest` target. n is the number of fixed targets before the rest. It returns an Array of n+1 elements: indices 0..n-1 are arg's elements (padded with Nil when arg is shorter) and index n is the remaining elements (arg[n:]) as a fresh Array, empty when arg has n or fewer elements.

func BuiltinMapFunc

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

func BuiltinMethodFromArgsFunc added in v0.0.2

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

BuiltinMethodFromArgsFunc implements `gad.methodFromArgs(target, ...args)`: it resolves the method currently registered on target that a call with the given arguments would dispatch to, returning that caller (or nil if none matches).

Each argument after target may be a value — in which case its type is used — or an ObjectType, used directly; so a signature can be described by example values (`methodFromArgs(f, 1, "x")`) or by type names (`methodFromArgs(f, int, str)`). It underpins the `$old` override parameter, which captures the method being overridden before the override replaces it.

func BuiltinMultiValueDictFunc

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

func BuiltinNamedParamTypeCheckFunc

func BuiltinNamedParamTypeCheckFunc(c Call) (val 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) (bytesWritten Object, err error)

func BuiltinPrintfFunc

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

func BuiltinPrintlnFunc

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

func BuiltinPushWriterFunc

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

func BuiltinRawCallerFunc

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

func BuiltinReadFunc

func BuiltinReadFunc(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 BuiltinSelfAssignOperatorFunc

func BuiltinSelfAssignOperatorFunc(c Call) (ret 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 BuiltinToArrayFunc

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

func BuiltinTypeNameFunc

func BuiltinTypeNameFunc(arg Object) Object

func BuiltinTypeOfFunc

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

func BuiltinUnaryOperatorFunc added in v0.0.2

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

BuiltinUnaryOperatorFunc is the default handler of gad.unOp: it dispatches to the operand's per-operator ObjectWith{Op}UnaryOperator implementation (unOpObject). The logical NOT operator (`!`) is universal — any value that does not implement UnOpNot falls back to its truthiness.

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 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 MustVal

func MustVal(v Object, _ error) (ret Object)

func NewArrayFunc

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

func NewBufferFunc

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

func NewBytesFunc

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

func NewCalendarDateFunc added in v0.0.2

func NewCalendarDateFunc(c Call) (Object, error)

NewCalendarDateFunc is the calendarDate(...) constructor: a calendarDate pass-through, a calendarTime/time (its date part), an int/uint (YYYYMMDD) or a string (see strToDate).

func NewCalendarTimeFunc added in v0.0.2

func NewCalendarTimeFunc(c Call) (Object, error)

NewCalendarTimeFunc is the calendarTime(...) constructor: a calendarTime pass-through, a time/calendarDate (its wall-clock value), an int/uint (UnixNano) or a string (see strToCalendarTime).

func NewClassFunc added in v0.0.2

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

func NewComputedValue added in v0.0.2

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

func NewDictFunc

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

func NewDurationFunc added in v0.0.2

func NewDurationFunc(c Call) (Object, error)

NewDurationFunc is the duration(...) constructor: a duration pass-through, an int/uint (nanoseconds) or a string (see strToDuration, e.g. "1h30m").

func NewErrorFunc

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

func NewFuncFunc added in v0.0.2

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

func NewFunctionHeaderFunc added in v0.0.2

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

NewFunctionHeaderFunc builds a FuncHeaderObject from (name str, params array, namedParams array, return array).

func NewKeyValueArrayFunc

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

func NewKeyValueFunc

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

func NewLocationFunc added in v0.0.2

func NewLocationFunc(c Call) (Object, error)

NewLocationFunc is the Location(...) constructor: a Location pass-through, a string (offset/name, see strToLocation) or an int offset in seconds.

func NewMethodInterfaceFunc added in v0.0.2

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

NewMethodInterfaceFunc builds a MethodInterface from (name str, *headers FunctionHeader).

func NewMixedParamsFunc

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

func NewPrinterStateFunc

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

func NewPropFunc added in v0.0.2

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

NewPropFunc create prop instance.

func NewRangeFunc added in v0.0.2

func NewRangeFunc(c Call) (Object, error)

NewRangeFunc is the Range(from, to; step) constructor body shared by the typed methods.

func NewRawStrFunc

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

func NewRegexpFunc

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

func NewStrFunc

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

func NewSyncDictFunc

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

func NewTimeFunc added in v0.0.2

func NewTimeFunc(c Call) (Object, error)

NewTimeFunc is the time(...) constructor: a time pass-through, a string (see strToTime), a Date (midnight UTC) or an int (unix seconds).

func NewTypedIdentFunc added in v0.0.2

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

func ObjectOrNil added in v0.0.2

func ObjectOrNil(v Object) Object

func TimeAdd added in v0.0.2

func TimeAdd(t *Time, duration int64) Object

func TimeAddDate added in v0.0.2

func TimeAddDate(t *Time, years, months, days int) Object

func TimeAfter added in v0.0.2

func TimeAfter(t1, t2 *Time) Object

func TimeAppendFormat added in v0.0.2

func TimeAppendFormat(t *Time, b []byte, layout string) Object

func TimeBefore added in v0.0.2

func TimeBefore(t1, t2 *Time) Object

func TimeDateFunc added in v0.0.2

func TimeDateFunc(c Call) (Object, error)

func TimeDurationHoursFunc added in v0.0.2

func TimeDurationHoursFunc(d int64) Object

func TimeDurationMicrosecondsFunc added in v0.0.2

func TimeDurationMicrosecondsFunc(d int64) Object

func TimeDurationMillisecondsFunc added in v0.0.2

func TimeDurationMillisecondsFunc(d int64) Object

func TimeDurationMinutesFunc added in v0.0.2

func TimeDurationMinutesFunc(d int64) Object

func TimeDurationNanosecondsFunc added in v0.0.2

func TimeDurationNanosecondsFunc(d int64) Object

func TimeDurationRoundFunc added in v0.0.2

func TimeDurationRoundFunc(d, m int64) Object

func TimeDurationSecondsFunc added in v0.0.2

func TimeDurationSecondsFunc(d int64) Object

func TimeDurationStringFunc added in v0.0.2

func TimeDurationStringFunc(d int64) Object

func TimeDurationTruncateFunc added in v0.0.2

func TimeDurationTruncateFunc(d, m int64) Object

func TimeEqual added in v0.0.2

func TimeEqual(t1, t2 *Time) Object

func TimeFixedZoneFunc added in v0.0.2

func TimeFixedZoneFunc(name string, sec int) Object

func TimeFormat added in v0.0.2

func TimeFormat(t *Time, layout string) Object

func TimeIn added in v0.0.2

func TimeIn(t *Time, loc *Location) Object

func TimeIsLocationFunc added in v0.0.2

func TimeIsLocationFunc(o Object) Object

func TimeIsTimeFunc added in v0.0.2

func TimeIsTimeFunc(o Object) Object

func TimeLoadLocationFunc added in v0.0.2

func TimeLoadLocationFunc(name string) (Object, error)

func TimeLocalFunc added in v0.0.2

func TimeLocalFunc() Object

func TimeMonthStringFunc added in v0.0.2

func TimeMonthStringFunc(m int) Object

func TimeNewArgTypeErr added in v0.0.2

func TimeNewArgTypeErr(pos, want, got string) (Object, error)

func TimeNowFunc added in v0.0.2

func TimeNowFunc() Object

func TimeParseDurationFunc added in v0.0.2

func TimeParseDurationFunc(s string) (Object, error)

func TimeParseFunc added in v0.0.2

func TimeParseFunc(c Call) (Object, error)

func TimeRound added in v0.0.2

func TimeRound(t *Time, duration int64) Object

func TimeSinceFunc added in v0.0.2

func TimeSinceFunc(t *Time) Object

func TimeSleepFunc added in v0.0.2

func TimeSleepFunc(c Call) (Object, error)

func TimeSub added in v0.0.2

func TimeSub(t1, t2 *Time) Object

func TimeTruncate added in v0.0.2

func TimeTruncate(t *Time, duration int64) Object

func TimeUnixFunc added in v0.0.2

func TimeUnixFunc(c Call) (Object, error)

func TimeUntilFunc added in v0.0.2

func TimeUntilFunc(t *Time) Object

func TimeUtcFunc added in v0.0.2

func TimeUtcFunc() Object

func TimeWeekdayStringFunc added in v0.0.2

func TimeWeekdayStringFunc(w int) Object

func TimeZerotimeFunc added in v0.0.2

func TimeZerotimeFunc() 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) RegisterToGo added in v0.0.2

func (oc *ObjectConverters) RegisterToGo(objType ObjectType, togo func(vm *VM, v Object) any) *ObjectConverters

func (*ObjectConverters) RegisterToObject added in v0.0.2

func (oc *ObjectConverters) RegisterToObject(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 ObjectEnter added in v0.0.2

type ObjectEnter interface {
	Object
	Enter(vm *VM) error
}

ObjectEnter is implemented by values usable as a `with` resource. Enter runs when the `with` block is entered, via gad.enter(resource). The `with` statement/expression desugars to a deferb that pairs it with ObjectExit.

type ObjectExit added in v0.0.2

type ObjectExit interface {
	Object
	Exit(vm *VM, err error) (Object, error)
}

ObjectExit is implemented by values usable as a `with` resource. Exit runs when the `with` block is left, via gad.exit(resource, err), receiving any error raised in the block (nil on normal exit). A non-nil returned error propagates from the block.

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) BinOpAdd added in v0.0.2

func (o *ObjectPtr) BinOpAdd(vm *VM, right Object) (Object, error)

func (*ObjectPtr) BinOpAnd added in v0.0.2

func (o *ObjectPtr) BinOpAnd(vm *VM, right Object) (Object, error)

func (*ObjectPtr) BinOpAndNot added in v0.0.2

func (o *ObjectPtr) BinOpAndNot(vm *VM, right Object) (Object, error)

func (*ObjectPtr) BinOpGreater added in v0.0.2

func (o *ObjectPtr) BinOpGreater(vm *VM, right Object) (Object, error)

func (*ObjectPtr) BinOpGreaterEq added in v0.0.2

func (o *ObjectPtr) BinOpGreaterEq(vm *VM, right Object) (Object, error)

func (*ObjectPtr) BinOpLess added in v0.0.2

func (o *ObjectPtr) BinOpLess(vm *VM, right Object) (Object, error)

func (*ObjectPtr) BinOpLessEq added in v0.0.2

func (o *ObjectPtr) BinOpLessEq(vm *VM, right Object) (Object, error)

func (*ObjectPtr) BinOpMul added in v0.0.2

func (o *ObjectPtr) BinOpMul(vm *VM, right Object) (Object, error)

func (*ObjectPtr) BinOpOr added in v0.0.2

func (o *ObjectPtr) BinOpOr(vm *VM, right Object) (Object, error)

func (*ObjectPtr) BinOpPow added in v0.0.2

func (o *ObjectPtr) BinOpPow(vm *VM, right Object) (Object, error)

func (*ObjectPtr) BinOpQuo added in v0.0.2

func (o *ObjectPtr) BinOpQuo(vm *VM, right Object) (Object, error)

func (*ObjectPtr) BinOpRem added in v0.0.2

func (o *ObjectPtr) BinOpRem(vm *VM, right Object) (Object, error)

func (*ObjectPtr) BinOpShl added in v0.0.2

func (o *ObjectPtr) BinOpShl(vm *VM, right Object) (Object, error)

func (*ObjectPtr) BinOpShr added in v0.0.2

func (o *ObjectPtr) BinOpShr(vm *VM, right Object) (Object, error)

func (*ObjectPtr) BinOpSub added in v0.0.2

func (o *ObjectPtr) BinOpSub(vm *VM, right Object) (Object, error)

func (*ObjectPtr) BinOpXor added in v0.0.2

func (o *ObjectPtr) BinOpXor(vm *VM, right Object) (Object, error)

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 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 = 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
	fmt.Stringer
	TypeAssigner
	Name() string
	FullName() string
	GadObjectType()
}

type ObjectTypeArray

type ObjectTypeArray []ObjectType

func (ObjectTypeArray) Array

func (t ObjectTypeArray) Array() Array

func (ObjectTypeArray) Assign added in v0.0.2

func (t ObjectTypeArray) Assign(ot ObjectType) (ok bool)

func (ObjectTypeArray) Equal

func (t ObjectTypeArray) Equal(right Object) bool

func (ObjectTypeArray) Get added in v0.0.2

func (t ObjectTypeArray) Get(i int) ObjectType

func (ObjectTypeArray) HasVar added in v0.0.2

func (t ObjectTypeArray) HasVar() (ok bool)

func (ObjectTypeArray) IsFalsy

func (t ObjectTypeArray) IsFalsy() bool

func (ObjectTypeArray) IsZero added in v0.0.2

func (t ObjectTypeArray) IsZero() bool

func (ObjectTypeArray) Items added in v0.0.2

func (t ObjectTypeArray) Items() ObjectTypeArray

func (ObjectTypeArray) Keys added in v0.0.2

func (t ObjectTypeArray) Keys() (keys ObjectTypeKeys)

func (ObjectTypeArray) Last added in v0.0.2

func (t ObjectTypeArray) Last() ObjectType

func (ObjectTypeArray) Len added in v0.0.2

func (t ObjectTypeArray) Len() int

func (ObjectTypeArray) Print added in v0.0.2

func (t ObjectTypeArray) Print(state *PrinterState) error

func (ObjectTypeArray) String added in v0.0.2

func (t ObjectTypeArray) String() string

func (ObjectTypeArray) ToString

func (t ObjectTypeArray) ToString() string

func (ObjectTypeArray) Type

func (t ObjectTypeArray) Type() ObjectType

func (ObjectTypeArray) Var added in v0.0.2

func (t ObjectTypeArray) Var() (_ ObjectType)

func (ObjectTypeArray) VarSplit added in v0.0.2

func (t ObjectTypeArray) VarSplit() (nonVar ObjectTypeArray, varType ObjectType)

type ObjectTypeAssignersGetter added in v0.0.2

type ObjectTypeAssignersGetter interface {
	GetTypeAssigners(cb func(t ObjectType) any) any
}

type ObjectTypeKey added in v0.0.2

type ObjectTypeKey struct {
	T ObjectType
	// contains filtered or unexported fields
}

func KeyOfObjectType added in v0.0.2

func KeyOfObjectType(t ObjectType) *ObjectTypeKey

func (ObjectTypeKey) String added in v0.0.2

func (k ObjectTypeKey) String() string

type ObjectTypeKeys added in v0.0.2

type ObjectTypeKeys []*ObjectTypeKey

func (ObjectTypeKeys) Sort added in v0.0.2

func (o ObjectTypeKeys) Sort(reverse bool)

type ObjectTypeNode

type ObjectTypeNode struct {
	Var  bool
	Type ObjectType
	VarChildren,
	Children []*ObjectTypeNode
}

func (*ObjectTypeNode) Append

func (n *ObjectTypeNode) Append(o ParamsTypes) (err error)

func (*ObjectTypeNode) Walk

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

func (*ObjectTypeNode) WalkE

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

type ObjectTypes

type ObjectTypes []ObjectType

func (ObjectTypes) Get added in v0.0.2

func (t ObjectTypes) Get(i int) ObjectType

func (ObjectTypes) HasVar added in v0.0.2

func (t ObjectTypes) HasVar() (ok bool)

func (ObjectTypes) IsZero added in v0.0.2

func (t ObjectTypes) IsZero() bool

func (ObjectTypes) Items added in v0.0.2

func (t ObjectTypes) Items() ObjectTypes

func (ObjectTypes) Last added in v0.0.2

func (t ObjectTypes) Last() ObjectType

func (ObjectTypes) Len added in v0.0.2

func (t ObjectTypes) Len() int

func (ObjectTypes) Multi added in v0.0.2

func (t ObjectTypes) Multi() (m ParamsTypes)

func (ObjectTypes) String

func (t ObjectTypes) String() string

func (ObjectTypes) Var added in v0.0.2

func (t ObjectTypes) Var() (_ ObjectType)

func (ObjectTypes) VarSplit added in v0.0.2

func (t ObjectTypes) VarSplit() (nonVar ObjectTypes, varType ObjectType)

type ObjectWithAddBinOperator added in v0.0.2

type ObjectWithAddBinOperator interface {
	BinOpAdd(vm *VM, right Object) (Object, error)
}

ObjectWithAddBinOperator is implemented by an object that handles the `+` binary operator as the left operand.

type ObjectWithAddSelfAssignOperator added in v0.0.2

type ObjectWithAddSelfAssignOperator interface {
	SelfAssignOpAdd(vm *VM, value Object) (Object, error)
}

ObjectWithAddSelfAssignOperator is implemented by an object that handles the `+=` self-assign operator as the left operand.

type ObjectWithAddUnaryOperator added in v0.0.2

type ObjectWithAddUnaryOperator interface {
	UnOpAdd(vm *VM) (Object, error)
}

ObjectWithAddUnaryOperator is implemented by an object that handles the `+` unary operator.

type ObjectWithAinBinOperator added in v0.0.2

type ObjectWithAinBinOperator interface {
	BinOpAin(vm *VM, right Object) (Object, error)
}

ObjectWithAinBinOperator is implemented by an object that handles the `ain` binary operator as the left operand.

type ObjectWithAndBinOperator added in v0.0.2

type ObjectWithAndBinOperator interface {
	BinOpAnd(vm *VM, right Object) (Object, error)
}

ObjectWithAndBinOperator is implemented by an object that handles the `&` binary operator as the left operand.

type ObjectWithAndNotBinOperator added in v0.0.2

type ObjectWithAndNotBinOperator interface {
	BinOpAndNot(vm *VM, right Object) (Object, error)
}

ObjectWithAndNotBinOperator is implemented by an object that handles the `&^` binary operator as the left operand.

type ObjectWithAndNotSelfAssignOperator added in v0.0.2

type ObjectWithAndNotSelfAssignOperator interface {
	SelfAssignOpAndNot(vm *VM, value Object) (Object, error)
}

ObjectWithAndNotSelfAssignOperator is implemented by an object that handles the `&^=` self-assign operator as the left operand.

type ObjectWithAndSelfAssignOperator added in v0.0.2

type ObjectWithAndSelfAssignOperator interface {
	SelfAssignOpAnd(vm *VM, value Object) (Object, error)
}

ObjectWithAndSelfAssignOperator is implemented by an object that handles the `&=` self-assign operator as the left operand.

type ObjectWithDecBinOperator added in v0.0.2

type ObjectWithDecBinOperator interface {
	BinOpDec(vm *VM, right Object) (Object, error)
}

ObjectWithDecBinOperator is implemented by an object that handles the `--` binary operator as the left operand.

type ObjectWithDecSelfAssignOperator added in v0.0.2

type ObjectWithDecSelfAssignOperator interface {
	SelfAssignOpDec(vm *VM, value Object) (Object, error)
}

ObjectWithDecSelfAssignOperator is implemented by an object that handles the `--=` self-assign operator as the left operand.

type ObjectWithDecUnaryOperator added in v0.0.2

type ObjectWithDecUnaryOperator interface {
	UnOpDec(vm *VM) (Object, error)
}

ObjectWithDecUnaryOperator is implemented by an object that handles the `--` unary operator.

type ObjectWithDotDotBinOperator added in v0.0.2

type ObjectWithDotDotBinOperator interface {
	BinOpDotDot(vm *VM, right Object) (Object, error)
}

ObjectWithDotDotBinOperator is implemented by an object that handles the `..` binary operator as the left operand.

type ObjectWithDoubleModBinOperator added in v0.0.2

type ObjectWithDoubleModBinOperator interface {
	BinOpDoubleMod(vm *VM, right Object) (Object, error)
}

ObjectWithDoubleModBinOperator is implemented by an object that handles the `%%` binary operator as the left operand.

type ObjectWithDoubleModSelfAssignOperator added in v0.0.2

type ObjectWithDoubleModSelfAssignOperator interface {
	SelfAssignOpDoubleMod(vm *VM, value Object) (Object, error)
}

ObjectWithDoubleModSelfAssignOperator is implemented by an object that handles the `%%=` self-assign operator as the left operand.

type ObjectWithDoubleTildeBinOperator added in v0.0.2

type ObjectWithDoubleTildeBinOperator interface {
	BinOpDoubleTilde(vm *VM, right Object) (Object, error)
}

ObjectWithDoubleTildeBinOperator is implemented by an object that handles the `~~` binary operator as the left operand.

type ObjectWithEqualBinOperator added in v0.0.2

type ObjectWithEqualBinOperator interface {
	BinOpEqual(vm *VM, right Object) (Object, error)
}

ObjectWithEqualBinOperator is implemented by an object that handles the `==` binary operator as the left operand.

type ObjectWithGreaterBinOperator added in v0.0.2

type ObjectWithGreaterBinOperator interface {
	BinOpGreater(vm *VM, right Object) (Object, error)
}

ObjectWithGreaterBinOperator is implemented by an object that handles the `>` binary operator as the left operand.

type ObjectWithGreaterEqBinOperator added in v0.0.2

type ObjectWithGreaterEqBinOperator interface {
	BinOpGreaterEq(vm *VM, right Object) (Object, error)
}

ObjectWithGreaterEqBinOperator is implemented by an object that handles the `>=` binary operator as the left operand.

type ObjectWithInBinOperator added in v0.0.2

type ObjectWithInBinOperator interface {
	BinOpIn(vm *VM, right Object) (Object, error)
}

ObjectWithInBinOperator is implemented by an object that handles the `in` binary operator as the left operand.

type ObjectWithIncBinOperator added in v0.0.2

type ObjectWithIncBinOperator interface {
	BinOpInc(vm *VM, right Object) (Object, error)
}

ObjectWithIncBinOperator is implemented by an object that handles the `++` binary operator as the left operand.

type ObjectWithIncSelfAssignOperator added in v0.0.2

type ObjectWithIncSelfAssignOperator interface {
	SelfAssignOpInc(vm *VM, value Object) (Object, error)
}

ObjectWithIncSelfAssignOperator is implemented by an object that handles the `++=` self-assign operator as the left operand.

type ObjectWithIncUnaryOperator added in v0.0.2

type ObjectWithIncUnaryOperator interface {
	UnOpInc(vm *VM) (Object, error)
}

ObjectWithIncUnaryOperator is implemented by an object that handles the `++` unary operator.

type ObjectWithLAndBinOperator added in v0.0.2

type ObjectWithLAndBinOperator interface {
	BinOpLAnd(vm *VM, right Object) (Object, error)
}

ObjectWithLAndBinOperator is implemented by an object that handles the `&&` binary operator as the left operand.

type ObjectWithLOrSelfAssignOperator added in v0.0.2

type ObjectWithLOrSelfAssignOperator interface {
	SelfAssignOpLOr(vm *VM, value Object) (Object, error)
}

ObjectWithLOrSelfAssignOperator is implemented by an object that handles the `||=` self-assign operator as the left operand.

type ObjectWithLambdaBinOperator added in v0.0.2

type ObjectWithLambdaBinOperator interface {
	BinOpLambda(vm *VM, right Object) (Object, error)
}

ObjectWithLambdaBinOperator is implemented by an object that handles the `=>` binary operator as the left operand.

type ObjectWithLessBinOperator added in v0.0.2

type ObjectWithLessBinOperator interface {
	BinOpLess(vm *VM, right Object) (Object, error)
}

ObjectWithLessBinOperator is implemented by an object that handles the `<` binary operator as the left operand.

type ObjectWithLessEqBinOperator added in v0.0.2

type ObjectWithLessEqBinOperator interface {
	BinOpLessEq(vm *VM, right Object) (Object, error)
}

ObjectWithLessEqBinOperator is implemented by an object that handles the `<=` binary operator as the left operand.

type ObjectWithMulBinOperator added in v0.0.2

type ObjectWithMulBinOperator interface {
	BinOpMul(vm *VM, right Object) (Object, error)
}

ObjectWithMulBinOperator is implemented by an object that handles the `*` binary operator as the left operand.

type ObjectWithMulSelfAssignOperator added in v0.0.2

type ObjectWithMulSelfAssignOperator interface {
	SelfAssignOpMul(vm *VM, value Object) (Object, error)
}

ObjectWithMulSelfAssignOperator is implemented by an object that handles the `*=` self-assign operator as the left operand.

type ObjectWithNotEqualBinOperator added in v0.0.2

type ObjectWithNotEqualBinOperator interface {
	BinOpNotEqual(vm *VM, right Object) (Object, error)
}

ObjectWithNotEqualBinOperator is implemented by an object that handles the `!=` binary operator as the left operand.

type ObjectWithNotSameBinOperator added in v0.0.2

type ObjectWithNotSameBinOperator interface {
	BinOpNotSame(vm *VM, right Object) (Object, error)
}

ObjectWithNotSameBinOperator is implemented by an object that handles the `!==` binary operator as the left operand.

type ObjectWithNotUnaryOperator added in v0.0.2

type ObjectWithNotUnaryOperator interface {
	UnOpNot(vm *VM) (Object, error)
}

ObjectWithNotUnaryOperator is implemented by an object that handles the `!` unary operator.

type ObjectWithOrBinOperator added in v0.0.2

type ObjectWithOrBinOperator interface {
	BinOpOr(vm *VM, right Object) (Object, error)
}

ObjectWithOrBinOperator is implemented by an object that handles the `|` binary operator as the left operand.

type ObjectWithOrSelfAssignOperator added in v0.0.2

type ObjectWithOrSelfAssignOperator interface {
	SelfAssignOpOr(vm *VM, value Object) (Object, error)
}

ObjectWithOrSelfAssignOperator is implemented by an object that handles the `|=` self-assign operator as the left operand.

type ObjectWithPowBinOperator added in v0.0.2

type ObjectWithPowBinOperator interface {
	BinOpPow(vm *VM, right Object) (Object, error)
}

ObjectWithPowBinOperator is implemented by an object that handles the `**` binary operator as the left operand.

type ObjectWithPowSelfAssignOperator added in v0.0.2

type ObjectWithPowSelfAssignOperator interface {
	SelfAssignOpPow(vm *VM, value Object) (Object, error)
}

ObjectWithPowSelfAssignOperator is implemented by an object that handles the `**=` self-assign operator as the left operand.

type ObjectWithQuoBinOperator added in v0.0.2

type ObjectWithQuoBinOperator interface {
	BinOpQuo(vm *VM, right Object) (Object, error)
}

ObjectWithQuoBinOperator is implemented by an object that handles the `/` binary operator as the left operand.

type ObjectWithQuoSelfAssignOperator added in v0.0.2

type ObjectWithQuoSelfAssignOperator interface {
	SelfAssignOpQuo(vm *VM, value Object) (Object, error)
}

ObjectWithQuoSelfAssignOperator is implemented by an object that handles the `/=` self-assign operator as the left operand.

type ObjectWithRemBinOperator added in v0.0.2

type ObjectWithRemBinOperator interface {
	BinOpRem(vm *VM, right Object) (Object, error)
}

ObjectWithRemBinOperator is implemented by an object that handles the `%` binary operator as the left operand.

type ObjectWithRemSelfAssignOperator added in v0.0.2

type ObjectWithRemSelfAssignOperator interface {
	SelfAssignOpRem(vm *VM, value Object) (Object, error)
}

ObjectWithRemSelfAssignOperator is implemented by an object that handles the `%=` self-assign operator as the left operand.

type ObjectWithSameBinOperator added in v0.0.2

type ObjectWithSameBinOperator interface {
	BinOpSame(vm *VM, right Object) (Object, error)
}

ObjectWithSameBinOperator is implemented by an object that handles the `===` binary operator as the left operand.

type ObjectWithShlBinOperator added in v0.0.2

type ObjectWithShlBinOperator interface {
	BinOpShl(vm *VM, right Object) (Object, error)
}

ObjectWithShlBinOperator is implemented by an object that handles the `<<` binary operator as the left operand.

type ObjectWithShlSelfAssignOperator added in v0.0.2

type ObjectWithShlSelfAssignOperator interface {
	SelfAssignOpShl(vm *VM, value Object) (Object, error)
}

ObjectWithShlSelfAssignOperator is implemented by an object that handles the `<<=` self-assign operator as the left operand.

type ObjectWithShrBinOperator added in v0.0.2

type ObjectWithShrBinOperator interface {
	BinOpShr(vm *VM, right Object) (Object, error)
}

ObjectWithShrBinOperator is implemented by an object that handles the `>>` binary operator as the left operand.

type ObjectWithShrSelfAssignOperator added in v0.0.2

type ObjectWithShrSelfAssignOperator interface {
	SelfAssignOpShr(vm *VM, value Object) (Object, error)
}

ObjectWithShrSelfAssignOperator is implemented by an object that handles the `>>=` self-assign operator as the left operand.

type ObjectWithSubBinOperator added in v0.0.2

type ObjectWithSubBinOperator interface {
	BinOpSub(vm *VM, right Object) (Object, error)
}

ObjectWithSubBinOperator is implemented by an object that handles the `-` binary operator as the left operand.

type ObjectWithSubSelfAssignOperator added in v0.0.2

type ObjectWithSubSelfAssignOperator interface {
	SelfAssignOpSub(vm *VM, value Object) (Object, error)
}

ObjectWithSubSelfAssignOperator is implemented by an object that handles the `-=` self-assign operator as the left operand.

type ObjectWithSubUnaryOperator added in v0.0.2

type ObjectWithSubUnaryOperator interface {
	UnOpSub(vm *VM) (Object, error)
}

ObjectWithSubUnaryOperator is implemented by an object that handles the `-` unary operator.

type ObjectWithTildeBinOperator added in v0.0.2

type ObjectWithTildeBinOperator interface {
	BinOpTilde(vm *VM, right Object) (Object, error)
}

ObjectWithTildeBinOperator is implemented by an object that handles the `~` binary operator as the left operand.

type ObjectWithTripleGreaterBinOperator added in v0.0.2

type ObjectWithTripleGreaterBinOperator interface {
	BinOpTripleGreater(vm *VM, right Object) (Object, error)
}

ObjectWithTripleGreaterBinOperator is implemented by an object that handles the `>>>` binary operator as the left operand.

type ObjectWithTripleGreaterSelfAssignOperator added in v0.0.2

type ObjectWithTripleGreaterSelfAssignOperator interface {
	SelfAssignOpTripleGreater(vm *VM, value Object) (Object, error)
}

ObjectWithTripleGreaterSelfAssignOperator is implemented by an object that handles the `>>>=` self-assign operator as the left operand.

type ObjectWithTripleLessBinOperator added in v0.0.2

type ObjectWithTripleLessBinOperator interface {
	BinOpTripleLess(vm *VM, right Object) (Object, error)
}

ObjectWithTripleLessBinOperator is implemented by an object that handles the `<<<` binary operator as the left operand.

type ObjectWithTripleLessSelfAssignOperator added in v0.0.2

type ObjectWithTripleLessSelfAssignOperator interface {
	SelfAssignOpTripleLess(vm *VM, value Object) (Object, error)
}

ObjectWithTripleLessSelfAssignOperator is implemented by an object that handles the `<<<=` self-assign operator as the left operand.

type ObjectWithTripleTildeBinOperator added in v0.0.2

type ObjectWithTripleTildeBinOperator interface {
	BinOpTripleTilde(vm *VM, right Object) (Object, error)
}

ObjectWithTripleTildeBinOperator is implemented by an object that handles the `~~~` binary operator as the left operand.

type ObjectWithXorBinOperator added in v0.0.2

type ObjectWithXorBinOperator interface {
	BinOpXor(vm *VM, right Object) (Object, error)
}

ObjectWithXorBinOperator is implemented by an object that handles the `^` binary operator as the left operand.

type ObjectWithXorSelfAssignOperator added in v0.0.2

type ObjectWithXorSelfAssignOperator interface {
	SelfAssignOpXor(vm *VM, value Object) (Object, error)
}

ObjectWithXorSelfAssignOperator is implemented by an object that handles the `^=` self-assign operator as the left operand.

type ObjectWithXorUnaryOperator added in v0.0.2

type ObjectWithXorUnaryOperator interface {
	UnOpXor(vm *VM) (Object, error)
}

ObjectWithXorUnaryOperator is implemented by an object that handles the `^` unary operator.

type Objector

type Objector interface {
	Object
	Fields() Dict
}

type OpCallFlag

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

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
	OpBinary
	OpUnary
	OpSelfAssign
	OpEqual
	OpNotEqual
	OpJump
	OpJumpFalsy
	OpAndJump
	OpOrJump
	OpDict
	OpArray
	OpSliceIndex
	OpGetIndex
	OpSetIndex
	OpNil
	OpStdIn
	OpStdOut
	OpStdErr
	OpDotName
	OpDotFile
	OpIsMain
	OpNotIsMain
	OpModule
	OpGlobals
	OpPop
	OpGetFree
	OpSetFree
	OpGetLocalPtr
	OpGetFreePtr
	OpClosure
	OpIterInit
	OpIterNext
	OpIterNextElse
	OpIterKey
	OpIterValue
	OpLoadModule
	OpInitModule
	OpSetupTry
	OpSetupCatch
	OpSetupFinally
	OpThrow
	OpFinalizer
	OpReturn
	OpSetReturn
	OpSetReturnModule
	OpDefineLocal
	OpTrue
	OpFalse
	OpYes
	OpNo
	OpCallName
	OpJumpNil
	OpJumpNotNil
	OpKeyValueArray
	OpKeyValue
	OpCallee
	OpArgs
	OpNamedArgs
	OpTextWriter
	OpIsNil
	OpNotIsNil
	OpNamedParamsVar
	OpNamedParamValue
	OpComputedValue
	OpAddMethod
	OpExtendModule
	OpToRawStr
	OpAddMethodOverride
	OpAssign
)

List of opcodes

func (Opcode) String

func (o Opcode) String() string

type OptimizerError

type OptimizerError struct {
	FilePos source.FilePos
	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 Param

type Param struct {
	Name         string
	TypesSymbols ParamType
	Types        ObjectTypes
	Var          bool
	Symbol       *SymbolInfo
	Usage        string
	Index        int
}

func (*Param) String

func (p *Param) String() string

type ParamBuilder added in v0.0.2

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

func (*ParamBuilder) Type added in v0.0.2

func (b *ParamBuilder) Type(typ ...ObjectType) *ParamBuilder

func (*ParamBuilder) Usage added in v0.0.2

func (b *ParamBuilder) Usage(v string) *ParamBuilder

func (*ParamBuilder) Var added in v0.0.2

func (b *ParamBuilder) Var() *ParamBuilder

type ParamOption

type ParamOption func(p *Param)

func ParamWithType

func ParamWithType(t ...*SymbolInfo) ParamOption

func ParamWithTypeO

func ParamWithTypeO(t ...ObjectType) ParamOption

type ParamType

type ParamType []*SymbolInfo

func (ParamType) Accept

func (t ParamType) Accept(vm *VM, obj Object) (ok bool, err error)

Accept reports whether obj satisfies the parameter type list. An ObjectType entry is matched by the (resolved) type of obj (assignability); a structural entry (a meti/interface, i.e. a TypeAssigner that is not an ObjectType) is matched by its CanAssign check. An empty list accepts anything.

func (ParamType) String

func (t ParamType) String() string

type ParamTypes added in v0.0.2

type ParamTypes interface {
	fmt.Stringer
	zeroer.Zeroer
	Items() ObjectTypes
	Len() int
	Get(int) ObjectType
}

type Params

type Params struct {
	Items []*Param
	// contains filtered or unexported fields
}

func NewParams added in v0.0.2

func NewParams(params ...*Param) (np *Params)

func (*Params) BuildTypes added in v0.0.2

func (p *Params) BuildTypes() (t ParamsTypes)

func (*Params) ByName added in v0.0.2

func (p *Params) ByName() map[string]int

func (*Params) Empty

func (p *Params) Empty() bool

func (*Params) Len added in v0.0.2

func (p *Params) Len() int

func (*Params) Names added in v0.0.2

func (p *Params) Names() (names []string)

func (*Params) PosLen added in v0.0.2

func (p *Params) PosLen() int

func (Params) RequiredCount

func (p Params) RequiredCount() (n int)

func (*Params) String

func (p *Params) String() string

func (*Params) ToMap added in v0.0.2

func (p *Params) ToMap() (np map[string]*Param)

func (*Params) Typed

func (p *Params) Typed() bool

func (*Params) Var

func (p *Params) Var() bool

func (*Params) Variadic added in v0.0.2

func (p *Params) Variadic() bool

type ParamsTypes added in v0.0.2

type ParamsTypes []ParamTypes

func ParamTypesOfRawCaller added in v0.0.2

func ParamTypesOfRawCaller(vm *VM, caller Object) (types ParamsTypes, err error)

func (ParamsTypes) String added in v0.0.2

func (t ParamsTypes) String() string

func (ParamsTypes) Tree added in v0.0.2

func (t ParamsTypes) Tree() (r *ObjectTypeNode, err error)

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 (i *PipedInvokeIterator) Call(state *IteratorState) (err error)

func (*PipedInvokeIterator) Handler

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

func (*PipedInvokeIterator) Input

func (i *PipedInvokeIterator) Input() Object

func (*PipedInvokeIterator) Next

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

func (*PipedInvokeIterator) PostCall

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

func (*PipedInvokeIterator) PreCall

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

func (*PipedInvokeIterator) Print added in v0.0.2

func (i *PipedInvokeIterator) Print(state *PrinterState) error

func (*PipedInvokeIterator) SetHandler

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

func (*PipedInvokeIterator) SetPostCall

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

func (*PipedInvokeIterator) SetPreCall

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

func (*PipedInvokeIterator) SetType

func (*PipedInvokeIterator) Start

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

func (*PipedInvokeIterator) Type

func (i *PipedInvokeIterator) Type() ObjectType

type PrintBuilder added in v0.0.2

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

func NewPrintBuilder added in v0.0.2

func NewPrintBuilder(vm *VM, o ...PrinterStateOption) *PrintBuilder

func (*PrintBuilder) MustString added in v0.0.2

func (b *PrintBuilder) MustString(o ...Object) string

func (*PrintBuilder) Options added in v0.0.2

func (b *PrintBuilder) Options(f func(opts PrinterStateOptions)) *PrintBuilder

func (*PrintBuilder) Print added in v0.0.2

func (b *PrintBuilder) Print(w io.Writer, o ...Object) (err error)

func (*PrintBuilder) State added in v0.0.2

func (b *PrintBuilder) State(f func(s *PrinterState)) *PrintBuilder

func (*PrintBuilder) String added in v0.0.2

func (b *PrintBuilder) String(o ...Object) (_ string, err error)

type PrintStateDictEntries added in v0.0.2

type PrintStateDictEntries []*PrintStateDictEntry

func (PrintStateDictEntries) Sort added in v0.0.2

type PrintStateDictEntry added in v0.0.2

type PrintStateDictEntry struct {
	Name  string
	Value Object
}

type PrintStateOptionSortType

type PrintStateOptionSortType uint8
const (
	PrintStateOptionSortTypeAuto PrintStateOptionSortType = iota
	PrintStateOptionSortTypeAscending
	PrintStateOptionSortTypeDescending
)

type Printabler added in v0.0.2

type Printabler interface {
	Print(state *PrinterState) error
}

type PrinterState

type PrinterState struct {
	VM     *VM
	IsRepr bool
	// contains filtered or unexported fields
}

PrinterState represents the printer state passed to custom formatters. It provides access to the io.Writer interface plus information about the flags and options for the operand's format specifier.

func NewPrinterState

func NewPrinterState(VM *VM, writer io.Writer, option ...PrinterStateOption) *PrinterState

func PrinterStateFromCall

func PrinterStateFromCall(c *Call) (state *PrinterState)

func (*PrinterState) BytesWritten

func (s *PrinterState) BytesWritten() int64

func (*PrinterState) Context

func (s *PrinterState) Context() context.Context

func (PrinterState) Copy

func (s PrinterState) Copy() *PrinterState

func (*PrinterState) Do added in v0.0.2

func (s *PrinterState) Do(f func(s *PrinterState)) *PrinterState

func (*PrinterState) DoEnter

func (s *PrinterState) DoEnter(f func() error) error

func (*PrinterState) DoVisit

func (s *PrinterState) DoVisit(obj Object, f func() error) (err error)

func (*PrinterState) Enter

func (s *PrinterState) Enter() (leave func())

func (*PrinterState) Equal

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

func (*PrinterState) GoWriter added in v0.0.2

func (s *PrinterState) GoWriter() io.Writer

func (*PrinterState) Indent

func (s *PrinterState) Indent() []byte

func (*PrinterState) Indented

func (s *PrinterState) Indented() bool

func (*PrinterState) IndexGet

func (s *PrinterState) IndexGet(_ *VM, index Object) (value Object, err error)

func (*PrinterState) IsFalsy

func (s *PrinterState) IsFalsy() bool

func (*PrinterState) OnVisite added in v0.0.2

func (s *PrinterState) OnVisite(f func(old func(o Object) (done func())) func(o Object) (done func()))

func (*PrinterState) Option

func (s *PrinterState) Option(key string) Object

func (*PrinterState) OptionDefault

func (s *PrinterState) OptionDefault(key string, defaul Object) (value Object)

func (*PrinterState) OptionOk

func (s *PrinterState) OptionOk(key string) (value Object, ok bool)

func (*PrinterState) Options

func (s *PrinterState) Options() PrinterStateOptions

func (*PrinterState) ParseOptions added in v0.0.2

func (s *PrinterState) ParseOptions(na *NamedArgs) *PrinterState

func (*PrinterState) Print

func (s *PrinterState) Print(o Object) (err error)

func (*PrinterState) PrintArray added in v0.0.2

func (s *PrinterState) PrintArray(l int, get func(i int) (Object, error)) (err error)

func (*PrinterState) PrintDict added in v0.0.2

func (s *PrinterState) PrintDict(l int, key, value func(i int) (Object, error)) (err error)

func (*PrinterState) PrintDictEntries added in v0.0.2

func (s *PrinterState) PrintDictEntries(entries PrintStateDictEntries) (err error)

func (*PrinterState) PrintFromArgs

func (s *PrinterState) PrintFromArgs(sep []byte, args Args) (err error)

func (*PrinterState) PrintIndent

func (s *PrinterState) PrintIndent()

func (*PrinterState) PrintKey added in v0.0.2

func (s *PrinterState) PrintKey(o Object) (err error)

func (*PrinterState) PrintKeySafe added in v0.0.2

func (s *PrinterState) PrintKeySafe(safe bool, o Object) (err error)

func (*PrinterState) PrintLine

func (s *PrinterState) PrintLine()

func (*PrinterState) PrintLineIndent

func (s *PrinterState) PrintLineIndent()

func (*PrinterState) PrintMany

func (s *PrinterState) PrintMany(sep []byte, o ...Object) (err error)

func (*PrinterState) PrintPairs added in v0.0.2

func (s *PrinterState) PrintPairs(l int, safeKey bool, open, close, keySep, itemSep []byte, getKey, getValue func(i int) (Object, error)) (err error)

func (*PrinterState) PrintValues added in v0.0.2

func (s *PrinterState) PrintValues(l int, open, close, itemSep []byte, get func(i int) (Object, error)) (err error)

func (*PrinterState) QuoteNextStr added in v0.0.2

func (s *PrinterState) QuoteNextStr(level int64)

func (*PrinterState) Repr added in v0.0.2

func (s *PrinterState) Repr(o Object) error

func (*PrinterState) SkipDepth

func (s *PrinterState) SkipDepth() bool

func (*PrinterState) SkipNexDepth added in v0.0.2

func (s *PrinterState) SkipNexDepth() bool

func (*PrinterState) Stack

func (s *PrinterState) Stack() *PrinterStateStack

func (*PrinterState) ToString

func (s *PrinterState) ToString() string

func (*PrinterState) Type

func (s *PrinterState) Type() ObjectType

func (*PrinterState) Update added in v0.0.2

func (s *PrinterState) Update() *PrinterState

func (*PrinterState) Value

func (s *PrinterState) Value(key any) (value any)

Value get context value by key or nil

func (*PrinterState) Visited

func (s *PrinterState) Visited(obj Object) bool

func (*PrinterState) WithContext

func (s *PrinterState) WithContext(ctx context.Context) *PrinterState

WithContext override context

func (*PrinterState) WithRepr added in v0.0.2

func (s *PrinterState) WithRepr(cb func(s *PrinterState) error) error

func (*PrinterState) WithValue

func (s *PrinterState) WithValue(key, value any) *PrinterState

WithValue add context value by key

func (*PrinterState) WithValueBackup

func (s *PrinterState) WithValueBackup(key, value any) (restore func())

WithValueBackup add context value by key and return restore func

func (*PrinterState) WithoutRepr added in v0.0.2

func (s *PrinterState) WithoutRepr(cb func(s *PrinterState) error) error

func (*PrinterState) WrapIndentedReprString added in v0.0.2

func (s *PrinterState) WrapIndentedReprString(str string) func()

func (*PrinterState) WrapRepr added in v0.0.2

func (s *PrinterState) WrapRepr(o Object) func()

func (*PrinterState) WrapReprString added in v0.0.2

func (s *PrinterState) WrapReprString(str string) func()

func (*PrinterState) Write

func (s *PrinterState) Write(b []byte) (n int, err error)

Write is the function to call to emit formatted output to be printed.

func (*PrinterState) WriteByte added in v0.0.2

func (s *PrinterState) WriteByte(c byte) (err error)

func (*PrinterState) WriteString added in v0.0.2

func (s *PrinterState) WriteString(b string) (err error)

type PrinterStateOption

type PrinterStateOption func(s *PrinterState)

func PrinterStateWithContext

func PrinterStateWithContext(ctx context.Context) PrinterStateOption

func PrinterStateWithOptions

func PrinterStateWithOptions(options PrinterStateOptions) PrinterStateOption

func PrinterStateWithOptionsFromNamedArgs added in v0.0.2

func PrinterStateWithOptionsFromNamedArgs(na *NamedArgs) PrinterStateOption

type PrinterStateOptions added in v0.0.2

type PrinterStateOptions map[string]Object

func (PrinterStateOptions) Anonymous added in v0.0.2

func (o PrinterStateOptions) Anonymous() (v bool, ok bool)

func (PrinterStateOptions) Backup added in v0.0.2

func (o PrinterStateOptions) Backup(key string) (restore func())

func (PrinterStateOptions) BytesToHex added in v0.0.2

func (o PrinterStateOptions) BytesToHex() (v bool, ok bool)

func (PrinterStateOptions) DefaultIndent added in v0.0.2

func (o PrinterStateOptions) DefaultIndent()

func (PrinterStateOptions) Dict added in v0.0.2

func (o PrinterStateOptions) Dict() Dict

func (PrinterStateOptions) Indent added in v0.0.2

func (o PrinterStateOptions) Indent() (v string, ok bool)

func (PrinterStateOptions) Indexes added in v0.0.2

func (o PrinterStateOptions) Indexes() (v bool, ok bool)

func (PrinterStateOptions) IsAnonymous added in v0.0.2

func (o PrinterStateOptions) IsAnonymous() (v bool)

func (PrinterStateOptions) IsBytesToHex added in v0.0.2

func (o PrinterStateOptions) IsBytesToHex() (is bool)

func (PrinterStateOptions) IsIndexes added in v0.0.2

func (o PrinterStateOptions) IsIndexes() (v bool)

func (PrinterStateOptions) IsQuoteStr added in v0.0.2

func (o PrinterStateOptions) IsQuoteStr() (is bool)

func (PrinterStateOptions) IsSortKeys added in v0.0.2

func (o PrinterStateOptions) IsSortKeys() (v PrintStateOptionSortType)

func (PrinterStateOptions) IsTypesAsFullNames added in v0.0.2

func (o PrinterStateOptions) IsTypesAsFullNames() (v bool)

func (PrinterStateOptions) IsZeros added in v0.0.2

func (o PrinterStateOptions) IsZeros() (v bool)

func (PrinterStateOptions) MaxDepth added in v0.0.2

func (o PrinterStateOptions) MaxDepth() (v int64, ok bool)

func (PrinterStateOptions) QuoteStr added in v0.0.2

func (o PrinterStateOptions) QuoteStr() (v bool, ok bool)

func (PrinterStateOptions) Raw added in v0.0.2

func (o PrinterStateOptions) Raw() (v bool, ok bool)

func (PrinterStateOptions) Repr added in v0.0.2

func (o PrinterStateOptions) Repr() (v bool, ok bool)

func (PrinterStateOptions) SetAnonymous added in v0.0.2

func (o PrinterStateOptions) SetAnonymous(v bool)

func (PrinterStateOptions) SetBytesToHex added in v0.0.2

func (o PrinterStateOptions) SetBytesToHex(v bool)

func (PrinterStateOptions) SetIndent added in v0.0.2

func (o PrinterStateOptions) SetIndent(v Object)

func (PrinterStateOptions) SetIndexes added in v0.0.2

func (o PrinterStateOptions) SetIndexes(v bool)

func (PrinterStateOptions) SetMaxDepth added in v0.0.2

func (o PrinterStateOptions) SetMaxDepth(v int64)

func (PrinterStateOptions) SetQuoteStr added in v0.0.2

func (o PrinterStateOptions) SetQuoteStr(v bool)

func (PrinterStateOptions) SetRaw added in v0.0.2

func (o PrinterStateOptions) SetRaw(v bool)

func (PrinterStateOptions) SetRepr added in v0.0.2

func (o PrinterStateOptions) SetRepr(v bool)

func (PrinterStateOptions) SetSortKeys added in v0.0.2

func (PrinterStateOptions) SetTrimEmbedPath added in v0.0.2

func (o PrinterStateOptions) SetTrimEmbedPath(v Array)

func (PrinterStateOptions) SetTypesAsFullNames added in v0.0.2

func (o PrinterStateOptions) SetTypesAsFullNames(v bool)

func (PrinterStateOptions) SetZeros added in v0.0.2

func (o PrinterStateOptions) SetZeros(v bool)

func (PrinterStateOptions) SortKeys added in v0.0.2

func (o PrinterStateOptions) SortKeys() (v PrintStateOptionSortType, ok bool)

func (PrinterStateOptions) TrimEmbedPath added in v0.0.2

func (o PrinterStateOptions) TrimEmbedPath() (v Array, ok bool)

func (PrinterStateOptions) TypesAsFullNames added in v0.0.2

func (o PrinterStateOptions) TypesAsFullNames() (v bool, ok bool)

func (PrinterStateOptions) WithAnonymous added in v0.0.2

func (o PrinterStateOptions) WithAnonymous() PrinterStateOptions

func (PrinterStateOptions) WithBackup added in v0.0.2

func (o PrinterStateOptions) WithBackup(key string, value Object) (restore func())

func (PrinterStateOptions) WithBytesToHex added in v0.0.2

func (o PrinterStateOptions) WithBytesToHex()

func (PrinterStateOptions) WithIndent added in v0.0.2

func (PrinterStateOptions) WithIndexes added in v0.0.2

func (o PrinterStateOptions) WithIndexes() PrinterStateOptions

func (PrinterStateOptions) WithMaxDepth added in v0.0.2

func (o PrinterStateOptions) WithMaxDepth(v int64) PrinterStateOptions

func (PrinterStateOptions) WithQuoteStr added in v0.0.2

func (o PrinterStateOptions) WithQuoteStr()

func (PrinterStateOptions) WithRaw added in v0.0.2

func (o PrinterStateOptions) WithRaw()

func (PrinterStateOptions) WithRepr added in v0.0.2

func (PrinterStateOptions) WithTrimEmbedPath added in v0.0.2

func (o PrinterStateOptions) WithTrimEmbedPath(v Array) PrinterStateOptions

func (PrinterStateOptions) WithTypesAsFullNames added in v0.0.2

func (o PrinterStateOptions) WithTypesAsFullNames() PrinterStateOptions

func (PrinterStateOptions) WithZeros added in v0.0.2

func (PrinterStateOptions) Zeros added in v0.0.2

func (o PrinterStateOptions) Zeros() (v bool, ok bool)

type PrinterStateStack

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

func (*PrinterStateStack) Prev

func (*PrinterStateStack) PrevValue

func (e *PrinterStateStack) PrevValue() Object

func (*PrinterStateStack) Value

func (e *PrinterStateStack) Value() Object

type Prop added in v0.0.2

type Prop struct {
	Module   *ModuleSpec
	PropName string
	// contains filtered or unexported fields
}

Prop is a named, callable Object whose invocations are dispatched to getter and setter methods held in its FuncSpec. Calling it with no arguments runs the getter; calling it with one argument runs the setter whose parameter type matches the argument. It implements CallerObject, so a Prop value can be called directly like a function.

func NewProp added in v0.0.2

func NewProp(module *ModuleSpec, name string) *Prop

NewProp returns a method-less Prop named name bound to module. Use AddGetter, AddSetter or AddMethodByTypes to attach behaviour.

func (*Prop) Add added in v0.0.2

func (p *Prop) Add(handler CallerObject, argTypes ParamsTypes) (err error)

func (*Prop) AddGetter added in v0.0.2

func (p *Prop) AddGetter(v Object, onAdd func(method *TypedCallerMethod) error) (err error)

func (*Prop) AddMethodByTypes added in v0.0.2

func (p *Prop) AddMethodByTypes(_ *VM, argTypes ParamsTypes, handler CallerObject, override bool, onAdd func(method *TypedCallerMethod) error) error

AddMethodByTypes register prop methods. - **getter** no have params and return value: `handler() <ret>` - **setter** have one param and not return value: `handler(v)`

func (*Prop) AddSetter added in v0.0.2

func (p *Prop) AddSetter(v Object, valueType ParamTypes, override bool, onAdd func(method *TypedCallerMethod) error) (err error)

func (*Prop) Call added in v0.0.2

func (p *Prop) Call(c Call) (Object, error)

Call dispatches a prop invocation through its FuncSpec methods (like *Func): no args invokes the getter, one arg the matching setter.

func (Prop) Clone added in v0.0.2

func (p Prop) Clone() *Prop

func (*Prop) Equal added in v0.0.2

func (p *Prop) Equal(right Object) bool

func (*Prop) FullName added in v0.0.2

func (p *Prop) FullName() string

func (*Prop) FuncSpecName added in v0.0.2

func (p *Prop) FuncSpecName() string

func (*Prop) GetModule added in v0.0.2

func (p *Prop) GetModule() *ModuleSpec

func (*Prop) IsFalsy added in v0.0.2

func (p *Prop) IsFalsy() bool

func (*Prop) Name added in v0.0.2

func (p *Prop) Name() string

func (*Prop) Print added in v0.0.2

func (p *Prop) Print(state *PrinterState) (err error)

func (*Prop) SetModule added in v0.0.2

func (p *Prop) SetModule(m *ModuleSpec)

func (*Prop) String added in v0.0.2

func (p *Prop) String() string

func (*Prop) ToString added in v0.0.2

func (p *Prop) ToString() string

func (*Prop) Type added in v0.0.2

func (p *Prop) Type() ObjectType

func (*Prop) VMAdd added in v0.0.2

func (p *Prop) VMAdd(vm *VM, v Object) error

type Range added in v0.0.2

type Range struct {
	From Object
	To   Object
	Step Object // nil = default
}

Range is an iterable produced by the `..` operator or the Range(from, to; step) constructor. It yields values from From toward To (inclusive), advancing by Step in the direction of To. From and To share an element kind; Step is a number for numeric/char ranges and a duration for temporal ranges (nil selects the default: 1 for numbers, one day for dates/times).

func (*Range) BinOpQuo added in v0.0.2

func (o *Range) BinOpQuo(_ *VM, right Object) (Object, error)

BinOpQuo handles `range / step` (ObjectWithQuoBinOperator), returning a new range with that step.

func (*Range) Equal added in v0.0.2

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

Equal reports whether right is a range with equal bounds and effective step.

func (*Range) IndexGet added in v0.0.2

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

IndexGet exposes the `from` and `to` fields and the `step` method. `r.step()` returns the current step; `r.step(n)` returns a new range with step n.

func (*Range) IsFalsy added in v0.0.2

func (o *Range) IsFalsy() bool

IsFalsy always reports false: a range yields at least its From element.

func (*Range) Iterate added in v0.0.2

func (o *Range) Iterate(_ *VM, _ *NamedArgs) Iterator

Iterate yields the range values; the entry key is the 0-based position and the value is the element.

func (*Range) ToString added in v0.0.2

func (o *Range) ToString() string

ToString renders the range as `from .. to` (with ` / step` when a step is set).

func (*Range) Type added in v0.0.2

func (o *Range) Type() ObjectType

Type returns the Range builtin type.

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) Print added in v0.0.2

func (it *RangeIteration) Print(state *PrinterState) 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 RawCallerWithMethods added in v0.0.2

type RawCallerWithMethods interface {
	MethodCaller
	// Caller return the raw caller
	Caller() CallerObject
}

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) BinOpAdd added in v0.0.2

func (o RawStr) BinOpAdd(_ *VM, right Object) (Object, error)

BinOpAdd concatenates; a non-string/Bytes operand is stringified (ObjectWithAddBinOperator).

func (RawStr) BinOpGreater added in v0.0.2

func (o RawStr) BinOpGreater(_ *VM, right Object) (Object, error)

func (RawStr) BinOpGreaterEq added in v0.0.2

func (o RawStr) BinOpGreaterEq(_ *VM, right Object) (Object, error)

func (RawStr) BinOpIn added in v0.0.2

func (o RawStr) BinOpIn(_ *VM, v Object) (Object, error)

BinOpIn implements the `in` operator (ObjectWithInBinOperator): reports whether v occurs as a substring of o, like Str.BinOpIn.

func (RawStr) BinOpLess added in v0.0.2

func (o RawStr) BinOpLess(_ *VM, right Object) (Object, error)

func (RawStr) BinOpLessEq added in v0.0.2

func (o RawStr) BinOpLessEq(_ *VM, right Object) (Object, error)

func (RawStr) BinOpSame added in v0.0.2

func (o RawStr) BinOpSame(_ *VM, right Object) (Object, error)

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

func ReaderFrom

func ReaderFrom(o Object) (r 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) 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) Print

func (o *ReflectArray) Print(state *PrinterState) (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) Name added in v0.0.2

func (r *ReflectFunc) Name() string

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

func (o *ReflectMap) Print(state *PrinterState) (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) AppendObjects

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

func (*ReflectSlice) Copy

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

func (*ReflectSlice) Insert

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

func (*ReflectSlice) Print added in v0.0.2

func (o *ReflectSlice) Print(state *PrinterState) (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) Call

func (s *ReflectStruct) Call(c Call) (Object, error)

func (*ReflectStruct) CallName

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

func (*ReflectStruct) CanCall

func (s *ReflectStruct) CanCall() bool

func (*ReflectStruct) CanClose

func (s *ReflectStruct) CanClose() bool

func (*ReflectStruct) CanIterationDone

func (s *ReflectStruct) CanIterationDone() (ok bool)

func (*ReflectStruct) Close

func (s *ReflectStruct) Close() 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) Init

func (s *ReflectStruct) Init()

func (*ReflectStruct) Iterate

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

func (*ReflectStruct) IterationDone

func (s *ReflectStruct) IterationDone(vm *VM) error

func (*ReflectStruct) Name added in v0.0.2

func (s *ReflectStruct) Name() string

func (*ReflectStruct) Print

func (s *ReflectStruct) Print(state *PrinterState) (err error)

Print prints object writing output to out writer. Options: - anonymous flag: include anonymous fields. - zeros flag: include zero fields. - sortKeys int = 0: fields sorting. 1: ASC, 2: DESC.

func (*ReflectStruct) Reader

func (s *ReflectStruct) Reader() Reader

func (*ReflectStruct) ReprTypeName added in v0.0.2

func (s *ReflectStruct) ReprTypeName() string

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

func (*ReflectStruct) Writer

func (s *ReflectStruct) Writer() Writer

type ReflectType

type ReflectType struct {
	RType       reflect.Type
	RMethods    map[string]*ReflectMethod
	FieldsNames []string
	RFields     map[string]*ReflectField

	CallObject        func(obj *ReflectStruct, c Call) (Object, error)
	InstancePrintFunc func(state *PrinterState, obj *ReflectValue) error
	StaticMethods     map[string]CallerObject
	*FuncSpec
	// contains filtered or unexported fields
}

func NewReflectType

func NewReflectType(t any) (rt *ReflectType)

func ReflectTypeFor added in v0.0.2

func ReflectTypeFor[T any]() *ReflectType

func ReflectTypeOf

func ReflectTypeOf(v any) (rt *ReflectType)

func (*ReflectType) AssignTo added in v0.0.2

func (t *ReflectType) AssignTo(_ *VM, obj Object, to TypeAssigner) (Object, error)

func (*ReflectType) Call

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

func (*ReflectType) CanAssign added in v0.0.2

func (t *ReflectType) CanAssign(obj Object) (bool, error)

func (*ReflectType) Equal

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

func (*ReflectType) Fields

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

func (*ReflectType) Fqn

func (t *ReflectType) Fqn() string

func (*ReflectType) FullName added in v0.0.2

func (t *ReflectType) FullName() string

func (*ReflectType) FuncSpecName added in v0.0.2

func (t *ReflectType) FuncSpecName() string

func (ReflectType) GadObjectType added in v0.0.2

func (ReflectType) GadObjectType()

func (*ReflectType) GetRMethods

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

func (*ReflectType) Name

func (t *ReflectType) Name() string

func (*ReflectType) New

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

func (*ReflectType) NewDefault added in v0.0.2

func (t *ReflectType) NewDefault(c Call) (Object, error)

func (*ReflectType) Print

func (t *ReflectType) Print(state *PrinterState) (err error)

func (*ReflectType) StaticMethod added in v0.0.2

func (t *ReflectType) StaticMethod(name string, co CallerObject)

func (*ReflectType) String

func (t *ReflectType) String() string

func (*ReflectType) ToString

func (t *ReflectType) ToString() string

func (*ReflectType) Type

func (t *ReflectType) Type() ObjectType

type ReflectValue

type ReflectValue struct {
	RType  *ReflectType
	RValue reflect.Value

	Options *ReflectValueOptions

	*FuncSpec
	// 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) Init

func (r *ReflectValue) Init()

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

func (r *ReflectValue) Method(name string) *ReflectFunc

func (*ReflectValue) Methods

func (r *ReflectValue) Methods() *IndexGetProxy

func (*ReflectValue) Print

func (r *ReflectValue) Print(state *PrinterState) (err error)

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

type ReflectValuePrinter interface {
	GadPrint(state *PrinterState) (err 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)
Example (StructuralContract)

ExampleNewReflectValue_structuralContract embeds a Go value in a script and checks it against a Gad interface built from its Go fields and methods.

// rfPerson is a Go struct with a Name/Age field and a Greet() method.
rv, _ := NewReflectValue(rfPerson{Name: "Ann", Age: 30})

builtins := NewBuiltins()
st := NewSymbolTable(builtins.NameSet)
_, _ = st.DefineGlobals([]string{"p"})

src := `
		interface Greeter { Name str; Greet() <str> }
		p :: Greeter          // rejected unless p has the Name field and Greet()
		println(p.Greet())
	`
_, bc, err := Compile(st, []byte(src), CompileOptions{})
if err != nil {
	panic(err)
}
vm := NewVM(builtins.Build(), bc)
if _, err = vm.RunOpts(&RunOpts{StdOut: os.Stdout, Globals: Dict{"p": rv}}); err != nil {
	panic(err)
}
Output:
hi Ann

type Regexp

type Regexp regexp.Regexp

func (*Regexp) BinOpDoubleTilde added in v0.0.2

func (o *Regexp) BinOpDoubleTilde(_ *VM, right Object) (Object, error)

func (*Regexp) BinOpOr added in v0.0.2

func (o *Regexp) BinOpOr(_ *VM, right Object) (Object, error)

func (*Regexp) BinOpTilde added in v0.0.2

func (o *Regexp) BinOpTilde(_ *VM, right Object) (Object, error)

BinOpTilde (`re ~ s`) matches, BinOpDoubleTilde (`re ~~ s`) finds the first match, BinOpTripleTilde (`re ~~~ s`) finds all, and BinOpOr (`re | repl`) yields a unary replacer. These implement the per-operator interfaces.

func (*Regexp) BinOpTripleTilde added in v0.0.2

func (o *Regexp) BinOpTripleTilde(_ *VM, right Object) (Object, error)

func (*Regexp) CallName

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

func (*Regexp) Equal

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

func (*Regexp) Find

func (o *Regexp) Find(arg Object) (ret Object)

func (*Regexp) FindAll

func (o *Regexp) FindAll(arg Object, n int) (ret Object)

func (*Regexp) Go

func (o *Regexp) Go() *regexp.Regexp

func (*Regexp) IsFalsy

func (o *Regexp) IsFalsy() bool

func (*Regexp) Match

func (o *Regexp) Match(arg Object) (ret Bool)

func (*Regexp) Print added in v0.0.2

func (o *Regexp) Print(state *PrinterState) error

func (*Regexp) Replace added in v0.0.2

func (o *Regexp) Replace(vm *VM, subject, repl Object) (Object, error)

Replace replaces all matches of o in subject with repl. repl may be a Str/RawStr/Bytes template (Go's $1 / ${name} group expansion applies) or a callable returning each replacement. The callable is invoked once per match with the matched substring as the positional argument and two named arguments: `m`, the full submatch (whole match + capture groups, so groups are `m[1]`, `m[2]`, …), and `re`, the regexp itself.

func (*Regexp) ToInterface

func (o *Regexp) ToInterface() any

func (*Regexp) ToString

func (o *Regexp) ToString() string

func (*Regexp) Type

func (o *Regexp) Type() ObjectType

type RegexpBytesResult

type RegexpBytesResult [][]byte

func (RegexpBytesResult) Equal

func (o RegexpBytesResult) Equal(right Object) bool

func (RegexpBytesResult) IndexGet added in v0.0.2

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

IndexGet returns submatch i as bytes (i == 0 is the full match).

func (RegexpBytesResult) IsFalsy

func (o RegexpBytesResult) IsFalsy() bool

func (RegexpBytesResult) Iterate added in v0.0.2

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

func (RegexpBytesResult) Length added in v0.0.2

func (o RegexpBytesResult) Length() int

Length returns the number of submatches (the full match plus capture groups).

func (RegexpBytesResult) Print added in v0.0.2

func (o RegexpBytesResult) Print(state *PrinterState) error

func (RegexpBytesResult) ToArray

func (o RegexpBytesResult) ToArray() Array

func (RegexpBytesResult) ToString

func (o RegexpBytesResult) ToString() string

func (RegexpBytesResult) Type

func (o RegexpBytesResult) Type() ObjectType

type RegexpBytesSliceResult

type RegexpBytesSliceResult [][][]byte

func (RegexpBytesSliceResult) Equal

func (o RegexpBytesSliceResult) Equal(right Object) bool

func (RegexpBytesSliceResult) IndexGet added in v0.0.2

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

IndexGet returns match i, itself a submatch list (full match + groups).

func (RegexpBytesSliceResult) IsFalsy

func (o RegexpBytesSliceResult) IsFalsy() bool

func (RegexpBytesSliceResult) Iterate added in v0.0.2

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

func (RegexpBytesSliceResult) Length added in v0.0.2

func (o RegexpBytesSliceResult) Length() int

Length returns the number of matches.

func (RegexpBytesSliceResult) Print added in v0.0.2

func (o RegexpBytesSliceResult) Print(state *PrinterState) error

func (RegexpBytesSliceResult) ToArray

func (o RegexpBytesSliceResult) ToArray() Array

func (RegexpBytesSliceResult) ToString

func (o RegexpBytesSliceResult) ToString() string

func (RegexpBytesSliceResult) Type

type RegexpStrsResult

type RegexpStrsResult []string

func (RegexpStrsResult) Equal

func (o RegexpStrsResult) Equal(right Object) bool

func (RegexpStrsResult) IndexGet added in v0.0.2

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

IndexGet returns submatch i (i == 0 is the full match, i >= 1 are the capture groups), so groups are accessed like an array.

func (RegexpStrsResult) IsFalsy

func (o RegexpStrsResult) IsFalsy() bool

func (RegexpStrsResult) Iterate added in v0.0.2

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

func (RegexpStrsResult) Length added in v0.0.2

func (o RegexpStrsResult) Length() int

Length returns the number of submatches (the full match plus capture groups).

func (RegexpStrsResult) Print added in v0.0.2

func (o RegexpStrsResult) Print(state *PrinterState) error

func (RegexpStrsResult) ToArray

func (o RegexpStrsResult) ToArray() Array

func (RegexpStrsResult) ToString

func (o RegexpStrsResult) ToString() string

func (RegexpStrsResult) Type

func (o RegexpStrsResult) Type() ObjectType

type RegexpStrsSliceResult

type RegexpStrsSliceResult [][]string

func (RegexpStrsSliceResult) Equal

func (o RegexpStrsSliceResult) Equal(right Object) bool

func (RegexpStrsSliceResult) IndexGet added in v0.0.2

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

IndexGet returns match i, itself a submatch list (full match + groups).

func (RegexpStrsSliceResult) IsFalsy

func (o RegexpStrsSliceResult) IsFalsy() bool

func (RegexpStrsSliceResult) Iterate added in v0.0.2

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

func (RegexpStrsSliceResult) Length added in v0.0.2

func (o RegexpStrsSliceResult) Length() int

Length returns the number of matches.

func (RegexpStrsSliceResult) Print added in v0.0.2

func (o RegexpStrsSliceResult) Print(state *PrinterState) error

func (RegexpStrsSliceResult) ToArray

func (o RegexpStrsSliceResult) ToArray() Array

func (RegexpStrsSliceResult) ToString

func (o RegexpStrsSliceResult) ToString() string

func (RegexpStrsSliceResult) Type

type ReprTypeNamer added in v0.0.2

type ReprTypeNamer interface {
	ReprTypeName() string
}

type ReturnVar added in v0.0.2

type ReturnVar struct {
	Name         string
	TypesSymbols ParamType
	Types        ObjectTypes
}

func (*ReturnVar) String added in v0.0.2

func (v *ReturnVar) String() string

String renders a return type as "type" (anonymous) or "name type" (named), where multiple types are joined by "|".

type ReturnVars added in v0.0.2

type ReturnVars []*ReturnVar

func (ReturnVars) String added in v0.0.2

func (v ReturnVars) String() string

String renders a function return-type list as " <T1, T2, ...>". It returns an empty string when there are no return types.

func (ReturnVars) Types added in v0.0.2

func (v ReturnVars) Types() (t []ObjectTypes)

func (ReturnVars) VMTypes added in v0.0.2

func (v ReturnVars) VMTypes(vm *VM) (t []ObjectTypes, err 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) FileSet

func (o *RuntimeError) FileSet() *source.FileSet

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() source.FilePosStackTrace

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 SelfAssignOperatorType

type SelfAssignOperatorType token.Token

func (SelfAssignOperatorType) AssignTo added in v0.0.2

func (b SelfAssignOperatorType) AssignTo(_ *VM, obj Object, to TypeAssigner) (Object, error)

func (SelfAssignOperatorType) Call

func (SelfAssignOperatorType) CanAssign added in v0.0.2

func (b SelfAssignOperatorType) CanAssign(obj Object) (bool, error)

func (SelfAssignOperatorType) Equal

func (b SelfAssignOperatorType) Equal(right Object) bool

func (SelfAssignOperatorType) Fields

func (SelfAssignOperatorType) Fields() Dict

func (SelfAssignOperatorType) FullName added in v0.0.2

func (b SelfAssignOperatorType) FullName() string

func (SelfAssignOperatorType) GadObjectType added in v0.0.2

func (b SelfAssignOperatorType) GadObjectType()

func (SelfAssignOperatorType) Getters

func (SelfAssignOperatorType) Getters() Dict

func (SelfAssignOperatorType) IsFalsy

func (b SelfAssignOperatorType) IsFalsy() bool

func (SelfAssignOperatorType) Methods

func (SelfAssignOperatorType) Methods() Dict

func (SelfAssignOperatorType) MethodsDisabled

func (SelfAssignOperatorType) MethodsDisabled() bool

func (SelfAssignOperatorType) Name

func (b SelfAssignOperatorType) Name() string

func (SelfAssignOperatorType) Setters

func (SelfAssignOperatorType) Setters() Dict

func (SelfAssignOperatorType) String

func (b SelfAssignOperatorType) String() string

func (SelfAssignOperatorType) ToString

func (b SelfAssignOperatorType) ToString() string

func (SelfAssignOperatorType) Token

func (SelfAssignOperatorType) Type

type SetupOpts

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

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,
	module *ModuleSpec,
	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, module *ModuleSpec) (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 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)
	// contains filtered or unexported fields
}

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) 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 StaticBuiltins added in v0.0.2

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

func (*StaticBuiltins) ArgsInvoker added in v0.0.2

func (b *StaticBuiltins) ArgsInvoker(t BuiltinType, c Call) func(arg ...Object) (Object, error)

func (*StaticBuiltins) Builtins added in v0.0.2

func (b *StaticBuiltins) Builtins() *Builtins

func (*StaticBuiltins) Call added in v0.0.2

func (b *StaticBuiltins) Call(t BuiltinType, c Call) (Object, error)

func (*StaticBuiltins) Caller added in v0.0.2

func (*StaticBuiltins) Get added in v0.0.2

func (b *StaticBuiltins) Get(t BuiltinType) Object

func (*StaticBuiltins) Invoker added in v0.0.2

func (b *StaticBuiltins) Invoker(t BuiltinType, c Call) func() (Object, error)

func (*StaticBuiltins) OpMethoded added in v0.0.2

func (b *StaticBuiltins) OpMethoded(bt BuiltinType) callerMethoded

OpMethoded returns operator builtin bt as a callerMethoded (or nil) via the precomputed slice, falling back to a map lookup if the cache is absent.

func (*StaticBuiltins) Set added in v0.0.2

func (b *StaticBuiltins) Set(name string, obj Object) BuiltinType

func (*StaticBuiltins) Update added in v0.0.2

func (b *StaticBuiltins) Update(key BuiltinType, value Object)

type StaticTypeKey added in v0.0.2

type StaticTypeKey uint16

func NewStaticType added in v0.0.2

func NewStaticType(objectType ObjectType) StaticTypeKey

type StaticTypes added in v0.0.2

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

func NewStaticTypes added in v0.0.2

func NewStaticTypes() *StaticTypes

func (*StaticTypes) Add added in v0.0.2

func (st *StaticTypes) Add(objectType ObjectType) StaticTypeKey

func (StaticTypes) Clone added in v0.0.2

func (st StaticTypes) Clone() *StaticTypes

func (*StaticTypes) Get added in v0.0.2

func (st *StaticTypes) Get(key StaticTypeKey) ObjectType

type Str

type Str string

Str represents string values and implements Object interface.

func MustToStr added in v0.0.2

func MustToStr(vm *VM, o Object) (_ Str)

func ToRepr

func ToRepr(vm *VM, o Object, opts ...PrinterStateOptions) (_ 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) BinOpAdd added in v0.0.2

func (o Str) BinOpAdd(_ *VM, right Object) (Object, error)

BinOpAdd concatenates; a non-Str/Bytes operand is stringified (ObjectWithAddBinOperator).

func (Str) BinOpGreater added in v0.0.2

func (o Str) BinOpGreater(_ *VM, right Object) (Object, error)

func (Str) BinOpGreaterEq added in v0.0.2

func (o Str) BinOpGreaterEq(_ *VM, right Object) (Object, error)

func (Str) BinOpIn added in v0.0.2

func (o Str) BinOpIn(_ *VM, v Object) (Object, error)

BinOpIn implements the `in` operator (ObjectWithInBinOperator): reports whether v occurs as a substring of o. A char needle matches its rune (so `'e' in "hello"`) and a str needle matches a substring (`"ell" in "hello"`); any other needle is compared by its string form, mirroring the `contains` builtin.

func (Str) BinOpLess added in v0.0.2

func (o Str) BinOpLess(_ *VM, right Object) (Object, error)

func (Str) BinOpLessEq added in v0.0.2

func (o Str) BinOpLessEq(_ *VM, right Object) (Object, error)

func (Str) BinOpSame added in v0.0.2

func (o Str) BinOpSame(_ *VM, right Object) (Object, error)

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) Print added in v0.0.2

func (o Str) Print(state *PrinterState) error

func (Str) Quoted

func (o Str) Quoted() string

func (Str) ToString

func (o Str) ToString() string

func (Str) Type

func (o Str) Type() ObjectType

type StringIndexSetter added in v0.0.2

type StringIndexSetter interface {
	Object
	Set(key string, value Object)
}

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
	ScopeModule
	// ScopeConstant references a bytecode constant by Index. Used for a
	// structural type reference (a `meti`/`interface` literal compiled to a
	// constant and used as a parameter/field type).
	ScopeConstant
)

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 BuiltinsNameSet) *SymbolTable

NewSymbolTable creates new symbol table object.

func (*SymbolTable) Builtins

func (st *SymbolTable) Builtins() BuiltinsNameSet

func (*SymbolTable) DefineGlobal

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

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

func (*SymbolTable) DefineGlobals

func (st *SymbolTable) DefineGlobals(names []string) (s []*Symbol, err error)

DefineGlobals adds a new symbols 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) DefineParams added in v0.0.2

func (st *SymbolTable) DefineParams(positional *Params, named *NamedParams) (err error)

DefineParams sets parameters defined in the scope with then variables. This can be called only once.

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) LocalNames added in v0.0.2

func (st *SymbolTable) LocalNames() map[int]string

LocalNames returns the recorded slot index -> name map for this function scope (debug symbols). The returned map must not be mutated.

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

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

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

func (*SyncDict) BinOpAdd added in v0.0.2

func (o *SyncDict) BinOpAdd(vm *VM, right Object) (Object, error)

The binary operators delegate to the guarded dict under a read lock, mirroring Dict's per-operator ObjectWith{Op}BinOperator implementations.

func (*SyncDict) BinOpGreater added in v0.0.2

func (o *SyncDict) BinOpGreater(vm *VM, right Object) (Object, error)

func (*SyncDict) BinOpGreaterEq added in v0.0.2

func (o *SyncDict) BinOpGreaterEq(vm *VM, right Object) (Object, error)

func (*SyncDict) BinOpIn added in v0.0.2

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

Contains reports whether v is a key of the dict (`v in syncDict`). BinOpIn implements the `in` operator (ObjectWithInBinOperator): reports whether v is a key of the guarded dict.

func (*SyncDict) BinOpLess added in v0.0.2

func (o *SyncDict) BinOpLess(vm *VM, right Object) (Object, error)

func (*SyncDict) BinOpLessEq added in v0.0.2

func (o *SyncDict) BinOpLessEq(vm *VM, right Object) (Object, error)

func (*SyncDict) BinOpSub added in v0.0.2

func (o *SyncDict) BinOpSub(vm *VM, right Object) (Object, error)

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, cb ItemsGetterCallback) (err 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 TestBytecodesEqualOptions added in v0.0.2

type TestBytecodesEqualOptions struct {
	NoInsertMainModule bool
}

type Time added in v0.0.2

type Time struct {
	Value time.Time
}

Time represents time values and implements Object interface.

func ToTime added in v0.0.2

func ToTime(o Object) (ret *Time, ok bool)

ToTime will try to convert given Object to *Time value.

func (*Time) BinOpAdd added in v0.0.2

func (o *Time) BinOpAdd(_ *VM, right Object) (Object, error)

BinOpAdd shifts the time forward by an Int (nanoseconds) or Duration.

func (*Time) BinOpGreater added in v0.0.2

func (o *Time) BinOpGreater(_ *VM, right Object) (Object, error)

func (*Time) BinOpGreaterEq added in v0.0.2

func (o *Time) BinOpGreaterEq(_ *VM, right Object) (Object, error)

func (*Time) BinOpLess added in v0.0.2

func (o *Time) BinOpLess(_ *VM, right Object) (Object, error)

func (*Time) BinOpLessEq added in v0.0.2

func (o *Time) BinOpLessEq(_ *VM, right Object) (Object, error)

func (*Time) BinOpSub added in v0.0.2

func (o *Time) BinOpSub(_ *VM, right Object) (Object, error)

BinOpSub shifts back by an Int/Duration, or returns the gap between two times.

func (*Time) CallName added in v0.0.2

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

func (*Time) Equal added in v0.0.2

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

Equal implements Object interface.

func (*Time) IndexGet added in v0.0.2

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

IndexGet implements Object interface.

func (*Time) IsFalsy added in v0.0.2

func (o *Time) IsFalsy() bool

IsFalsy implements Object interface.

func (*Time) MarshalBinary added in v0.0.2

func (o *Time) MarshalBinary() ([]byte, error)

MarshalBinary implements encoding.BinaryMarshaler interface.

func (*Time) MarshalJSON added in v0.0.2

func (o *Time) MarshalJSON() ([]byte, error)

MarshalJSON implements json.JSONMarshaler interface.

func (*Time) Print added in v0.0.2

func (o *Time) Print(s *PrinterState) error

Print writes the time as a leaf value. *Time is a primitive (see IsPrimitive), so it must print as its ToString rather than letting the generic printer recurse into the wrapped time.Time internals.

func (*Time) ToString added in v0.0.2

func (o *Time) ToString() string

ToString implements Object interface.

func (*Time) Type added in v0.0.2

func (*Time) Type() ObjectType

func (*Time) UnOpDec added in v0.0.2

func (o *Time) UnOpDec(*VM) (Object, error)

func (*Time) UnOpInc added in v0.0.2

func (o *Time) UnOpInc(*VM) (Object, error)

func (*Time) UnmarshalBinary added in v0.0.2

func (o *Time) UnmarshalBinary(data []byte) error

UnmarshalBinary implements encoding.BinaryUnmarshaler interface.

func (*Time) UnmarshalJSON added in v0.0.2

func (o *Time) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.JSONUnmarshaler interface.

type ToArrayAppenderObject

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

type ToArrayConveter

type ToArrayConveter interface {
	ToArray() Array
}

type ToDictConverter added in v0.0.2

type ToDictConverter interface {
	ToDict() Dict
}

type ToIterfaceConverter

type ToIterfaceConverter interface {
	ToInterface() any
}

type ToIterfaceVMConverter

type ToIterfaceVMConverter interface {
	ToInterface(*VM) any
}

type ToReaderConverter

type ToReaderConverter interface {
	Reader() Reader
}

type ToWriter

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

type ToWriterConverter

type ToWriterConverter interface {
	Writer() Writer
}

type Type

type Type struct {
	Parent ObjectType
	Static Dict
	Module *ModuleSpec

	*FuncSpec
	// contains filtered or unexported fields
}

func NewType added in v0.0.2

func NewType(typeName string, parent ...ObjectType) (t *Type)

func (*Type) AssignTo added in v0.0.2

func (t *Type) AssignTo(_ *VM, obj Object, to TypeAssigner) (Object, error)

func (*Type) Caller

func (t *Type) Caller() CallerObject

func (*Type) CanAssign added in v0.0.2

func (t *Type) CanAssign(obj Object) (bool, error)

func (*Type) Constructor

func (t *Type) Constructor() CallerObject

func (Type) Copy added in v0.0.2

func (t Type) Copy() Object

func (*Type) Equal

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

func (Type) Fields

func (Type) Fields() Dict

func (Type) FullName added in v0.0.2

func (t Type) FullName() string

func (*Type) FuncSpecName added in v0.0.2

func (t *Type) FuncSpecName() string

func (Type) GadObjectType added in v0.0.2

func (Type) GadObjectType()

func (*Type) GetModule added in v0.0.2

func (t *Type) GetModule() *ModuleSpec

func (Type) Getters

func (Type) Getters() Dict

func (*Type) IndexDelete

func (t *Type) IndexDelete(vm *VM, index Object) (err error)

func (*Type) IndexGet

func (t *Type) IndexGet(vm *VM, index Object) (value Object, err error)

func (*Type) IndexSet

func (t *Type) IndexSet(vm *VM, index, value Object) (err error)

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) Print added in v0.0.2

func (t *Type) Print(state *PrinterState) (err error)

func (Type) Setters

func (Type) Setters() Dict

func (*Type) String

func (t *Type) String() string

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) WithStatic added in v0.0.2

func (t *Type) WithStatic(d Dict) *Type

type TypeAssertion

type TypeAssertion struct {
	Types    []ObjectType
	Handlers TypeAssertionHandlers
}

func NewTypeAssertion

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

func TypeAssertionFlag

func TypeAssertionFlag() *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)

func (*TypeAssertion) Options added in v0.0.2

func (a *TypeAssertion) Options(opt ...TypeAsssertionOption) *TypeAssertion

type TypeAssertionHandler

type TypeAssertionHandler func(v Object) bool

type TypeAssertionHandlers

type TypeAssertionHandlers map[string]TypeAssertionHandler

func TypeAssertions added in v0.0.2

func TypeAssertions(opt ...TypeAsssertionOption) TypeAssertionHandlers

type TypeAssigner added in v0.0.2

type TypeAssigner interface {
	Object
	// AssignTo returns obj when obj (of the receiver's kind) is assignable to
	// `to`, otherwise an error (ErrIncompatibleCast). It returns obj unchanged on
	// success (the value already satisfies the target).
	AssignTo(vm *VM, obj Object, to TypeAssigner) (Object, error)

	// CanAssign returns if obj can assign to this
	CanAssign(obj Object) (bool, error)
}

TypeAssigner is a value that can decide whether another value is assignable to it — the abstraction behind parameter/field type checking. An ObjectType assigns by type (assignability), a *MethodInterface by a structural `implements` check, and a *Interface by structural satisfaction.

type TypeAssignerArray added in v0.0.2

type TypeAssignerArray []TypeAssigner

TypeAssignerArray is a list of type assigners (e.g. the allowed types of a parameter): ObjectTypes and/or structural types (meti/interface). Named to avoid a clash with the existing TypeAssigners walker function.

type TypeAsssertionOption added in v0.0.2

type TypeAsssertionOption func(a TypeAssertionHandlers)

func WithArray added in v0.0.2

func WithArray() TypeAsssertionOption

func WithCallable added in v0.0.2

func WithCallable() TypeAsssertionOption

func WithFlag added in v0.0.2

func WithFlag() TypeAsssertionOption

func WithIsAssignable added in v0.0.2

func WithIsAssignable(types ...ObjectType) TypeAsssertionOption

func WithMethodAdder added in v0.0.2

func WithMethodAdder() TypeAsssertionOption

func WithMethodCaller added in v0.0.2

func WithMethodCaller() TypeAsssertionOption

func WithRawCallable added in v0.0.2

func WithRawCallable() TypeAsssertionOption

type TypedCallerMethod added in v0.0.2

type TypedCallerMethod struct {
	*CallerMethod
	// contains filtered or unexported fields
}

func (*TypedCallerMethod) IndexGet added in v0.0.2

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

func (*TypedCallerMethod) IsVar added in v0.0.2

func (o *TypedCallerMethod) IsVar() bool

func (*TypedCallerMethod) Print added in v0.0.2

func (o *TypedCallerMethod) Print(state *PrinterState) error

func (*TypedCallerMethod) String added in v0.0.2

func (o *TypedCallerMethod) String() string

func (*TypedCallerMethod) StringTarget added in v0.0.2

func (o *TypedCallerMethod) StringTarget(target bool) string

func (*TypedCallerMethod) ToString added in v0.0.2

func (o *TypedCallerMethod) ToString() string

func (*TypedCallerMethod) Types added in v0.0.2

type TypedCallerMethods added in v0.0.2

type TypedCallerMethods []*TypedCallerMethod

type TypedCallerObjectWithParamTypes added in v0.0.2

type TypedCallerObjectWithParamTypes interface {
	CallerObject
	ParamTypes() ParamsTypes
	ReturnVars() ReturnVars
}

TypedCallerObjectWithParamTypes is an interface for objects that can be called with Call method with parameters with types and typed return vars.

type TypedIdent added in v0.0.2

type TypedIdent struct {
	Name  string
	Types Array
	// TypesSymbols holds the parameter's type references as compile-time symbols
	// when a func-header value is compiled to a constant (see
	// compileFuncHeaderExpr). When set, the resolved Types are produced per-VM on
	// demand (resolveTypes) so the shared constant stays immutable and
	// thread-safe. Empty for TypedIdent values built at run time (the
	// `typedIdent`/`FunctionHeader` builtins), which carry resolved Types.
	TypesSymbols ParamType
}

func (*TypedIdent) Equal added in v0.0.2

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

func (*TypedIdent) IndexGet added in v0.0.2

func (t *TypedIdent) IndexGet(vm *VM, index Object) (value Object, err error)

func (*TypedIdent) IndexSet added in v0.0.2

func (t *TypedIdent) IndexSet(_ *VM, index, value Object) (err error)

func (*TypedIdent) IsFalsy added in v0.0.2

func (t *TypedIdent) IsFalsy() bool

func (*TypedIdent) Print added in v0.0.2

func (t *TypedIdent) Print(state *PrinterState) error

func (*TypedIdent) ToString added in v0.0.2

func (t *TypedIdent) ToString() string

func (*TypedIdent) Type added in v0.0.2

func (t *TypedIdent) Type() ObjectType

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) BinOpAdd added in v0.0.2

func (o Uint) BinOpAdd(vm *VM, right Object) (Object, error)

func (Uint) BinOpAnd added in v0.0.2

func (o Uint) BinOpAnd(vm *VM, right Object) (Object, error)

func (Uint) BinOpAndNot added in v0.0.2

func (o Uint) BinOpAndNot(vm *VM, right Object) (Object, error)

func (Uint) BinOpGreater added in v0.0.2

func (o Uint) BinOpGreater(vm *VM, right Object) (Object, error)

func (Uint) BinOpGreaterEq added in v0.0.2

func (o Uint) BinOpGreaterEq(vm *VM, right Object) (Object, error)

func (Uint) BinOpLess added in v0.0.2

func (o Uint) BinOpLess(vm *VM, right Object) (Object, error)

func (Uint) BinOpLessEq added in v0.0.2

func (o Uint) BinOpLessEq(vm *VM, right Object) (Object, error)

func (Uint) BinOpMul added in v0.0.2

func (o Uint) BinOpMul(vm *VM, right Object) (Object, error)

func (Uint) BinOpOr added in v0.0.2

func (o Uint) BinOpOr(vm *VM, right Object) (Object, error)

func (Uint) BinOpPow added in v0.0.2

func (o Uint) BinOpPow(vm *VM, right Object) (Object, error)

Uint has no native power; `uint ** float|decimal` promotes to that type.

func (Uint) BinOpQuo added in v0.0.2

func (o Uint) BinOpQuo(vm *VM, right Object) (Object, error)

func (Uint) BinOpRem added in v0.0.2

func (o Uint) BinOpRem(vm *VM, right Object) (Object, error)

func (Uint) BinOpSame added in v0.0.2

func (o Uint) BinOpSame(_ *VM, right Object) (Object, error)

func (Uint) BinOpShl added in v0.0.2

func (o Uint) BinOpShl(vm *VM, right Object) (Object, error)

func (Uint) BinOpShr added in v0.0.2

func (o Uint) BinOpShr(vm *VM, right Object) (Object, error)

func (Uint) BinOpSub added in v0.0.2

func (o Uint) BinOpSub(vm *VM, right Object) (Object, error)

func (Uint) BinOpXor added in v0.0.2

func (o Uint) BinOpXor(vm *VM, right Object) (Object, error)

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

func (Uint) UnOpAdd added in v0.0.2

func (o Uint) UnOpAdd(*VM) (Object, error)

func (Uint) UnOpDec added in v0.0.2

func (o Uint) UnOpDec(*VM) (Object, error)

func (Uint) UnOpInc added in v0.0.2

func (o Uint) UnOpInc(*VM) (Object, error)

func (Uint) UnOpSub added in v0.0.2

func (o Uint) UnOpSub(*VM) (Object, error)

func (Uint) UnOpXor added in v0.0.2

func (o Uint) UnOpXor(*VM) (Object, error)

type UnaryOperatorType added in v0.0.2

type UnaryOperatorType token.Token

func (UnaryOperatorType) AssignTo added in v0.0.2

func (b UnaryOperatorType) AssignTo(_ *VM, obj Object, to TypeAssigner) (Object, error)

func (UnaryOperatorType) Call added in v0.0.2

func (UnaryOperatorType) CanAssign added in v0.0.2

func (b UnaryOperatorType) CanAssign(obj Object) (bool, error)

func (UnaryOperatorType) Equal added in v0.0.2

func (b UnaryOperatorType) Equal(right Object) bool

func (UnaryOperatorType) Fields added in v0.0.2

func (UnaryOperatorType) Fields() Dict

func (UnaryOperatorType) FullName added in v0.0.2

func (b UnaryOperatorType) FullName() string

func (UnaryOperatorType) GadObjectType added in v0.0.2

func (b UnaryOperatorType) GadObjectType()

func (UnaryOperatorType) Getters added in v0.0.2

func (UnaryOperatorType) Getters() Dict

func (UnaryOperatorType) IsFalsy added in v0.0.2

func (b UnaryOperatorType) IsFalsy() bool

func (UnaryOperatorType) Methods added in v0.0.2

func (UnaryOperatorType) Methods() Dict

func (UnaryOperatorType) MethodsDisabled added in v0.0.2

func (UnaryOperatorType) MethodsDisabled() bool

func (UnaryOperatorType) Name added in v0.0.2

func (b UnaryOperatorType) Name() string

func (UnaryOperatorType) Setters added in v0.0.2

func (UnaryOperatorType) Setters() Dict

func (UnaryOperatorType) String added in v0.0.2

func (b UnaryOperatorType) String() string

func (UnaryOperatorType) ToString added in v0.0.2

func (b UnaryOperatorType) ToString() string

func (UnaryOperatorType) Token added in v0.0.2

func (b UnaryOperatorType) Token() token.Token

func (UnaryOperatorType) Type added in v0.0.2

func (b UnaryOperatorType) Type() ObjectType

type UpDownLines

type UpDownLines struct {
	Up, Down int
}

type UserDataStorage

type UserDataStorage interface {
	Object
	UserData() Indexer
}

type VM

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

	*SetupOpts
	// contains filtered or unexported fields
}

VM executes the instructions in Bytecode.

func NewVM

func NewVM(builtins *StaticBuiltins, 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 ParamsTypes, caller CallerObject, onAdd func(method *TypedCallerMethod) error) (err error)

func (*VM) AddCallerMethodOverride

func (vm *VM) AddCallerMethodOverride(co CallerObject, types ParamsTypes, override bool, caller CallerObject, onAdd func(method *TypedCallerMethod) error) (err error)

func (*VM) CallBuiltin

func (vm *VM) CallBuiltin(t BuiltinType, namedArgs *NamedArgs, args ...Object) (Object, error)

func (*VM) Clear

func (vm *VM) Clear() *VM

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

func (*VM) CurrentModule added in v0.0.2

func (vm *VM) CurrentModule() *Module

func (*VM) CurrentModuleSpec added in v0.0.2

func (vm *VM) CurrentModuleSpec() *ModuleSpec

func (*VM) DebugAbort added in v0.0.2

func (vm *VM) DebugAbort()

DebugAbort requests the running VM to stop (equivalent to Abort).

func (*VM) DebugFrames added in v0.0.2

func (vm *VM) DebugFrames() []DebugFrame

DebugFrames returns the active call frames from outermost to innermost (the current frame is last).

func (*VM) DebugIP added in v0.0.2

func (vm *VM) DebugIP() int

DebugIP returns the index of the instruction about to execute.

func (*VM) DebugLocalNames added in v0.0.2

func (vm *VM) DebugLocalNames() []string

DebugLocalNames returns the debug names of the current frame's local slots (index -> name); entries may be empty when a name is unavailable.

func (*VM) DebugLocals added in v0.0.2

func (vm *VM) DebugLocals() []Object

DebugLocals returns the local variable values of the current frame (dereferencing captured pointers).

func (*VM) DebugOpcode added in v0.0.2

func (vm *VM) DebugOpcode() Opcode

DebugOpcode returns the opcode about to execute.

func (*VM) DebugSourcePos added in v0.0.2

func (vm *VM) DebugSourcePos() source.FilePos

DebugSourcePos returns the source position (file/line/column) of the instruction about to execute, or a zero FilePos when unavailable.

func (*VM) Debugger added in v0.0.2

func (vm *VM) Debugger() DebugStepper

Debugger returns the attached DebugStepper, or nil.

func (*VM) Fork added in v0.0.2

func (vm *VM) Fork(cf *CompiledFunction, usePool bool) (child *VM)

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) ModuleByIndex added in v0.0.2

func (vm *VM) ModuleByIndex(ix int) *Module

func (*VM) ModuleFromIndex added in v0.0.2

func (vm *VM) ModuleFromIndex(index int) *Module

func (*VM) Read

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

func (*VM) ResolveType added in v0.0.2

func (vm *VM) ResolveType(ot ObjectType) ObjectType

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) SetDebugger added in v0.0.2

func (vm *VM) SetDebugger(d DebugStepper)

SetDebugger attaches d, switching the VM to its debug execution loop on the next run. Pass nil to detach. Must be set before Run/RunOpts.

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

func (vm *VM) SourcePos() source.FilePos

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 VarObjectType added in v0.0.2

type VarObjectType struct {
	ObjectType
}

func (*VarObjectType) FullName added in v0.0.2

func (v *VarObjectType) FullName() string

func (*VarObjectType) Name added in v0.0.2

func (v *VarObjectType) Name() string

func (*VarObjectType) String added in v0.0.2

func (v *VarObjectType) String() string

type VarParamTypes added in v0.0.2

type VarParamTypes []ObjectType

func (VarParamTypes) Get added in v0.0.2

func (t VarParamTypes) Get(i int) ObjectType

func (VarParamTypes) IsZero added in v0.0.2

func (t VarParamTypes) IsZero() bool

func (VarParamTypes) Items added in v0.0.2

func (t VarParamTypes) Items() ObjectTypes

func (VarParamTypes) Len added in v0.0.2

func (t VarParamTypes) Len() int

func (VarParamTypes) String added in v0.0.2

func (t VarParamTypes) String() string

type Writer

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

func NewWriter

func NewWriter(w io.Writer) Writer

func WriterFrom

func WriterFrom(o Object) (r Writer)

Source Files

Directories

Path Synopsis
cmd
build-website command
Command build-website renders the Gad documentation (./doc) into a static, GitHub-Pages-ready website with client-side search, a light/dark theme and a WebAssembly playground.
Command build-website renders the Gad documentation (./doc) into a static, GitHub-Pages-ready website with client-side search, a light/dark theme and a WebAssembly playground.
gad command
gaddoc command
internal/pluginsync
Package pluginsync extracts the authoritative Gad language vocabulary (keywords, atoms, constants, builtin functions) from the gad/token packages and keeps the editor plugins (codemirror-gad, prism-gad) in sync with it.
Package pluginsync extracts the authoritative Gad language vocabulary (keywords, atoms, constants, builtin functions) from the gad/token packages and keeps the editor plugins (codemirror-gad, prism-gad) in sync with it.
mkcallable command
mkoptypes command
update-codemirror-plugin command
Command update-codemirror-plugin keeps web/codemirror-gad in sync with the Gad language: it adds any keywords/atoms/constants/builtins the plugin is missing and reports the language commits since the plugin was last updated.
Command update-codemirror-plugin keeps web/codemirror-gad in sync with the Gad language: it adds any keywords/atoms/constants/builtins the plugin is missing and reports the language commits since the plugin was last updated.
update-delve command
Command update-delve keeps the VM's debug execution loop (vm_loop_debug.go) in sync with the production loop (vm_loop.go).
Command update-delve keeps the VM's debug execution loop (vm_loop_debug.go) in sync with the production loop (vm_loop.go).
update-prism-plugin command
Command update-prism-plugin keeps web/prism-gad in sync with the Gad language: it adds any keywords/atoms/builtins the grammar is missing and reports the language commits since the plugin was last updated.
Command update-prism-plugin keeps web/prism-gad in sync with the Gad language: it adds any keywords/atoms/builtins the grammar is missing and reports the language commits since the plugin was last updated.
update-vscode-plugin command
Command update-vscode-plugin regenerates the VS Code extension's TextMate grammar (editors/vscode-gad/syntaxes/gad.tmLanguage.json) from the current Gad language vocabulary, so highlighting stays in sync with the compiler.
Command update-vscode-plugin regenerates the VS Code extension's TextMate grammar (editors/vscode-gad/syntaxes/gad.tmLanguage.json) from the current Gad language vocabulary, so highlighting stays in sync with the compiler.
Package debug provides a breakpoint/stepping debugger engine for the Gad VM.
Package debug provides a breakpoint/stepping debugger engine for the Gad VM.
ast
fmt
Package fmt provides the importable `fmt` module.
Package fmt provides the importable `fmt` module.
os
strings
Package strings provides the importable `strings` module.
Package strings provides the importable `strings` module.
test
Package test provides the `test` builtin module and the `T` context passed to test/benchmark functions run by `gad test`.
Package test provides the `test` builtin module and the `T` context passed to test/benchmark functions run by `gad test`.
time
Package time provides the importable `time` module.
Package time provides the importable `time` module.
web
app
Package webapp provides access to the built web UI.
Package webapp provides access to the built web UI.
gadbridge
Package gadbridge exposes Gad's format, diagnose and run capabilities behind a small, JSON-friendly API.
Package gadbridge exposes Gad's format, diagnose and run capabilities behind a small, JSON-friendly API.
ide
Package ide implements the backend for `gad ide`: a small HTTP server that turns a workspace directory into a multi-file editing environment.
Package ide implements the backend for `gad ide`: a small HTTP server that turns a workspace directory into a multi-file editing environment.
server command
Command server is the backend example for the Gad CodeMirror integration.
Command server is the backend example for the Gad CodeMirror integration.
wasm command
Command wasm compiles the Gad bridge to WebAssembly.
Command wasm compiles the Gad bridge to WebAssembly.

Jump to

Keyboard shortcuts

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