charlang

package module
v0.0.0-...-6d56b49 Latest Latest
Warning

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

Go to latest
Published: Jan 31, 2025 License: MIT Imports: 52 Imported by: 6

README

The Char Language (Charlang)

Charlang is a fast, dynamic scripting language to embed in Go applications. Charlang is compiled and executed as bytecode on stack-based VM that's written in native Go. Charlang has a more-common runtime error handling(try-catch-finally) than Golang.

Charlang is inspired by and based on awesome script language uGo. Special thanks to uGo's creater(ozanh) and contributors.

1. Features

  • Written in native Go (no cgo).
  • if else statements.
  • for and for in statements.
  • try catch finally statements.
  • param, global, var and const declarations.
  • Rich builtins.
  • Module support.
  • Go like syntax with additions.

2. New Features

  • New types such as Byte, Image, Any...
  • New functions: NewCommonError, NewError and more...
  • New builtin functions: getRandomInt, writeResp, setRespHeader, writeRespHeader and much more...
  • New global variables and resources.
  • A new thread-model.
  • Runtime/dynamically script compiling and running capability.
  • Server mode: quickly start a WEB and/or application server.
  • Run as system service.

Fibonacci Example

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

Charlang Home

Go Reference

Builtin Functions

4. Download

Or download the package from Charlang Official Site

5. Installation

Download the latest Charlang executable file or compressed package above or from the official website, and then put it in a directory, preferably within the system path(such as C:\Windows in Windows or /usr/bin). If you download a compressed package, decompress it first. Then it is ready to use, run it in any terminal or console application(Window CMD, PowerShell, Terminal or bash);

6. Quick Start

Install Charlang first according to the installation guide, or build from source code by:

go get -u github.com/topxeq/charlang

go get -u github.com/topxeq/charlang/cmd/char

Charlang has a REPL application to learn and test Charlang language, run Charlang's main executable file with no command-line arguments to start it.

char.exe or ./char

package main

import (
    "fmt"

    "github.com/topxeq/charlang"
)

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

mapEach := func(seq, fn) {

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

    var out = []

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

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

global multiplier

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

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

7. Documentation

7.1 Get the Binary

Download the binary release files according to your OS from the website: Charlang Homepage.

7.2 Compile from Source Code
go get -u github.com/topxeq/charlang

or

cd $GOPATH/src/github.com/topxeq

git clone https://github.com/topxeq/tkc

git clone https://github.com/topxeq/charlang

cd $GOPATH/src/github.com/topxeq/charlang/cmd

go install
7.3 Start Running the Shell or Scripts

After download, extract the executable from the zip file, put it into a directory, better in the system path.

Then type 'char' in the terminal/console to start the interactive command-line shell interface. Also you can run some scripts using command like 'char test.char', or 'char -example basic.char'. Here 'test.char' is the source code file(in UTF-8 encoding, plain text format).

Using command-line switch '-view' will show the source code of the script instead of run it.

7.4 Various Ways to Run Charlang Scripts

Examples:

  • Run from a source file: char d:\scripts\test.char
  • Run the text in clipboard as script source: char -clip
  • Run from the remote server: char -remote http://replacewithyourdomain.com/script/abc.char
  • Run the example code: char -example basic.char
  • Run from Golang source directory: char -gopath basic.char
  • Run from local scripts directory: place a config file local.cfg in the subdirectory 'char' under the user's home directory, with text content such as c:\scripts, then char -local basic.char will run 'c:\script\basic.char'
  • Run from cloud/network: place a config file cloud.cfg in the subdirectory 'char' under the user's home directory, with text content such as http://script.my.com/, then char -cloud basic.char will be the same as char -remote http://script.my.com/basic.char
  • Select the script(or input the script file path in console mode) to run: char -selectScript
  • Load the script: char -edit d:\scripts\test.char, then run it in the editor(click the 'Quick Run' button) on Windows(WebView2)
  • Run it in the CharEd IDE(Lazarus), which can be downloaded from the official website, in the Windows package
  • Use it as an embeded script language engine, in any Golang compatible languages
  • Run it through other languages, with the compiled DLL of Charlang
7.5 Get the Examples

All the source code examples marked by file names in the document can be retrieved or run by the command line like:

C:\Users\Administrator>char -example -view basic.char
// do simple add operation
x := 1.2
y := x + 1

println(x + y)

pass()

C:\Users\Administrator>char -example basic.char
3.4000000000000004

C:\Users\Administrator>

You can browse to https://topget.org/dc/c/charlang/example/basic.char to view the source code in an online text editor.

Using command-line switch '-viewPage' with '-example' will show the online code page in system-default browser as well.

7.6 Quick Tour
Hello World!

file: example001.char

// function 'pln' is the same as 'println' in other languages
pln("Hello world!")

The function 'pln' is the same as 'println' in other languages. pln formats using the default formats for its arguments and writes to standard output.

And in Charlang, comments are supported. You can use // or /* ... */ to guide the comments.

The resulting output of the script:

C:\Users\Administrator>char -example example001.char
Hello world!

C:\Users\Administrator>

Comments

file: example002.char

As mentioned above, like Golang, Charlang supports line comments (//...) and block comments (/* ... */). Comments in the code will be ignored by the compiler and virtual machine. You can use Ctrl+/key combination in many text or source code editors to switch whether the line is commented or not.

/*
  multi-line block comments - 1
  multi-line block comments - 2
  multi-line block comments - 3
*/

a := 8    // line comments

// line comments at the start of a new line
pln("a:", a)

The output:

C:\Users\Administrator>char -example example002.char
a: 8

Define Variables

file: example003.char

// define a variable before using it
var a

a = 1

pln(a)

// assign a value of another type to a
a = "abc"

pln(a)

// define and assign in one step
b := true

pln(b)

// can not use := again for the same variable
// the next line will cause error
// b := 1.1

The result:

C:\Users\Administrator>char -example example003.char
1
abc
true

Note that unlike Golang, a variable can be assigned a value of different types.

Declare more than 1 variable in one line within a pair of parentheses.

var (a, b, c)

...
Data Type Name

file: example004.char


a := 3 // assign an integer(int) value to variable 'a'

// function 'pl' is equivalent to the printf function in other languages, 
// followed by an additional newline character "\n"
// and the conversion characters are the same as Golang, 
// '%T' is used to output the value's type, '%v' is the general output format for any value
pl("[%T] %v", a, a)

// Instead of using '%T', which will output the native type in Golang(in which Charlang is written)
// function 'typeOf' is often used to get the type name of a variable in Charlang
pl("[%v] %v", typeOf(a), a)

The output:

C:\Users\Administrator>char -example example004.char
[charlang.Int] 3
[int] 3

Boolean Data Type

file: example005.char


// Boolean values

b := true

// function 'prf' is the same as 'printf' in C/C++/Golang
prf("[%v] %v\n", typeOf(b), b)

c := false

prf("[%T] %v\n", c, c)

prf("!b = %v\n", !b) // the operators are the same as Golang and many other languages

prf("b == c: %v\n", b == c)

prf("1 > 14: %v\n", 1 > 14)

prf("b == true: %v\n", b == true)

prf("b && c: %v\n", b && c)

prf("b || c: %v\n", b || c)

The output:

C:\Users\Administrator>char -example example005.char
[bool] true
[charlang.Bool] false
!b = false
b == c: false
1 > 14: false
b == true: true
b && c: false
b || c: true

Integer Data Type

file: example006.char


// Integer

c1 := 19

c2 := 18

pln(c1 + c2/3)

pl("%v, %v", typeOf(c1), c1)

pl("%T, %v", c1+c2, c1+c2)
pl("%v, %v", typeOf(c2/3), c2/3)
pl("%v, %v", typeOf(c1+c2/3), c1+c2/3)
pl("%T, %v", (c1+c2/3)*6, (c1+c2/3)*6)

The output:

C:\Users\Administrator>char -example example006.char
25
int, 19
charlang.Int, 37
int, 6
int, 25
charlang.Int, 150

Float Data Type

file: example007.char


// Float

f1 := 1.32

pl("%v, %v", typeOf(f1), f1)

previus_f1 := f1

f1 = f1 * 0.8

// function 'pr' is the same as 'print' in other languages
pr(previus_f1, "*", 0.8, "=", f1)

pln()

f2 := 0.93
f2 /= 0.3

pr(0.93, "/", 0.3, "=", f2, "\n")

The output:

C:\Users\Administrator>char -example example007.char
float, 1.32
1.32*0.8=1.056
0.93/0.3=3.1

String/Bytes/Chars Data Type

file: example008.char


// String, Bytes and Chars

s1 := "abc"

// concatenate strings
s2 := s1 + "3"

// function 'plt' will output the value with its Charlang type
plt(s2)

pln(s1, "+", "3", "=", s2)

s5 := "上善若水"

// function 'plt' will output the value with its internal(Golang) type
plo(s5)

s6 := bytes(s5)

// s6 will be a bytes array
pln("s6:", s6)

// t will be a utf-8 character(rune in Golang)
t := char(5)

plo(t)

// s7 will be array of chars
// in this example, will be 4 unicode characters, each has 3 bytes
s7 := chars(s5)

plt(s7)

// slice of s5(string) will be a string with only one ASCII(0-255) character
pl("s5[1:2] = %v(%#v)", s5[1:2], s5[1:2])

// slice of s6(bytes, i.e. array of byte) will be a byte array contains only one item
pl("s6[1:2] = %v(%#v)", s6[1:2], s6[1:2])

// slice of s7(chars, i.e. array of char) will be a char array contains only one item
pl("s7[1:2] = %v(%#v)", s7[1:2], s7[1:2])

// covert utf-8 chars to string
pl("string(s7[1:3]) = %v(%#v)", string(s7[1:3]), string(s7[1:3]))

// covert utf-8 chars to bytes, then to string, has the same effect as above
pl("string(bytes(string(s7[1:3]))) = %v(%#v)", string(bytes(string(s7[1:3]))), string(bytes(string(s7[1:3]))))

// output the first item of string, bytes and chars, as a single character
pl("%c", s5[1])
pl("%c", s6[1])
pl("%c", s7[1])

// output the first item of string, bytes and chars, with its value and type
pl("%T, %#v", s5[1], s5[1])
pl("%v, %#v", typeOf(s6[1]), s6[1])
pl("%T, %#v", s7[1], s7[1])

// iterate the string using 'for' loop
for i := 0; i < len(s5); i++ {
	pl("%v: %v, %v", i, typeOf(s5[i]), s5[i])
}

// iterate the string using 'for-in' loop
for i, v in s5 {
	pl("%v: %v, %v", i, typeOf(v), v)
}

// iterate the chars
for i, v in s7 {
	// function 'typeName' is equivalent to 'typeOf'
	pl("%v: %v, %v", i, typeName(v), v)
}

The output:

C:\Users\Administrator>char -example example008.char
(string)abc3
abc + 3 = abc3
(charlang.String)"上善若水"
s6: [228 184 138 229 150 132 232 139 165 230 176 180]
(charlang.Char)5
(chars)[19978 21892 33509 27700]
s5[1:2] = �("\xb8")
s6[1:2] = [184]([]byte{0xb8})
s7[1:2] = [21892]([]int32{21892})
string(s7[1:3]) = 善若("善若")
string(bytes(string(s7[1:3]))) = 善若("善若")
¸
¸
善
charlang.Int, 184
int, 184
charlang.Char, 21892
0: int, 228
1: int, 184
2: int, 138
3: int, 229
4: int, 150
5: int, 132
6: int, 232
7: int, 139
8: int, 165
9: int, 230
10: int, 176
11: int, 180
0: byte, 228
1: byte, 184
2: byte, 138
3: byte, 229
4: byte, 150
5: byte, 132
6: byte, 232
7: byte, 139
8: byte, 165
9: byte, 230
10: byte, 176
11: byte, 180
0: char, 19978
1: char, 21892
2: char, 33509
3: char, 27700

Array
// declare an array
a := [1, 2, 3, "abc", 12.3]

println("a:", a)

println("a[2]:", a[2])

println("length of a:", len(a))

// reassign the array variable
a = [1, 2]

// append values
a = append(a, "abc")

// array item can be any type, even another array
b := ["xyz", 16, a]

pln("b:", b)

output:

a: [1, 2, 3, "abc", 12.3]
a[2]: 3
length of a: 5
b: ["xyz", 16, [1, 2, "abc"]]

Refer to the array example in More Examples section for more information about array type.

Map

In Charlang, map is a set of key-value pairs where key is string and the value is of any value types. Value of a map can be accessed using indexer [] or selector '.' operators.

// declare an empty map
a := {}

// all keys will be converted to string type, values keep their original types
a["Num"] = 3
a[5] = "abc"
a[-1] = true
a["ary"] = [1, "xyz", false]
a[false] = "not true"
a.Item1 = "item 1"

pln(a)

// length is the number of key-value pairs in the map
pl("length of a: %v", len(a))

// index by dot
pl("a.Num: %v", a.Num)

// index by square brackets
a["Num"]++
pln(a["Num"])

// slice
pln(a[5][2:3])

a[5] = a[5] + a[5]

// slice to end
a[5] = a[5][1:]
pl("a[5]: %v", a[5])

// slice from begining
pln(a[5][:2])

// iterate
for k, v in a {
	println("[", k, "]:", v)
}
  
pln("---")

// declare map with initial values
b := {"intItem": 12, "floatItem": 5.6, "boolItem": true, "stringItem": "str1", "arrayItem": ["array", "in", "map"], "mapItem": {"map": 1, "in": "map"}}

plt(b)

pln("---")

c := {}

// all keys will be converted to string type
c[3] = "3"
c[18] = "abc"
c[-198] = "true"

pl("c: %v", c)

v1 := c[18]

if v1 == undefined {
	println("v1:", v1)
}

// index with non-existent key
v2 := c[19]

if v2 == undefined {
	println("v2:", v2)
}

// remove key-value pair
delete(c, 18)

println("c:", c)

output:

{"Num": 3, "5": "abc", "-1": true, "ary": [1, "xyz", false], "false": "not true", "Item1": "item 1"}
length of a: 6
a.Num: 3
4
c
a[5]: bcabc
bc
[ Num ]: 4
[ 5 ]: bcabc
[ -1 ]: true
[ ary ]: [1, "xyz", false]
[ false ]: not true
[ Item1 ]: item 1
---
(map){"intItem": 12, "floatItem": 5.6, "boolItem": true, "stringItem": "str1", "arrayItem": ["array", "in", "map"], "mapItem": {"map": 1, "in": "map"}}
---
c: {"3": "3", "18": "abc", "-198": "true"}
v2: undefined
c: {"3": "3", "-198": "true"}

Refer to the map example in More Examples section for more information about map type.

Function Type(Declare Function)

Function is a data type in Charlang.

// declare a function with arguments
f1 := func(a, b, c, d) {
	return a*b + c/d
}

result1 := f1(3, 6, 8, 9)

pln("result1=", result1)

// variadic function(function accepts a variable number of arguments)
f2 := func(v0, v1, ...args) {
	sum := v0 + v1

	argsLen := len(args)

	for i := 0; i < argsLen; i++ {
		sum += args[i]
	}

	return sum
}

result2 := f2(3, 6, 8, 9, 7)

pln("result2=", result2)

For Loop
c1 := 0

// classic for loop
for i := 0; i < 5; i++ {
	c1 += i
}

pln(c1 * 3)

// for loop with condition only
i := 0

for i < 5 {
	pl("i: %v", i)

	i = i + 1
}

// infinite loop(if no break)

c := 5
for {
	c = c + 5

	if c < 10 {
		continue
	}

	if c > 30 {
		break
	}
}

pln("c:", c)

Output:

30
i: 0
i: 1
i: 2
i: 3
i: 4
c: 35
If Statement
var a

if !a {
	pln("!a")
}

pln("!a", !a)

if a {
	pln("a =", a)
} else {
	pln("a is not initialized")
}

b := 1

if b {
	pln("b =", b)
} else {
	pln("b is not initialized")
}

pln("!b", !b)

var c = "abc"

pln("!c", !c)

Output:

!a
!a true
a is not initialized
b = 1
!b false
!c false
Predefined Global Variables

There are some prefined global variables in Charlang, which can be refered by 'global' keyword. The following code will show the command-line arguments in order,

global argsG

for i, v in argsG {
    pl("[%v] %v", i, v)
}

The global predefined variable 'argsG' holds the command-line parameters while running the Charlang's main program. The data type of argsG is array, so we could use it instantly without other declaration.

If using Charlang as a library in Golang, we can pass other global variables other than the predefined ones.

The common global predefined variables include:

  • versionG: the current version of Charlang;
  • basePathG: the base path of Charlang, will be the current user's home directory such as c:\Users\Administrator or the service root directory(c:\char in Windows and /char in Linux);
  • argsG: the array typed variable holds the command-line parameters;
  • scriptPathG: the path of the script file running currently;
  • runModeG: running mode of Charlang(script, repl, service, charms, chp, chardc, ...)

And while runnin as a WEB/Application/Micro-service server, there are additional predefined global variables:

  • requestG: the HTTP request object, holds the request information;
  • responseG: the HTTP respone object that could write response to, or set response settings;
  • reqUriG: the route of the request, such as 'static/images/img001.png'
  • paraMapG: holds the GET/POST form values, in a map object, such as {"auth": "xxxxx", "input1": "value1"}

In Windows platform, there are some additional predefined global variables:

  • guiG: holds the object to interact with WebView2 component which could used to establish GUI applications.
Error handling: Try-Catch-Finally
a := 0

var r

try {
	r = 3 / a

} catch e {
	pln("exception:", e)

} finally {
	
	pln("r:", r)
}

pln("done")

Output:

D:\tmp>char -example tryCatch.char
exception: ZeroDivisionError: 
r: undefined
done
Run Charlang Script/Code
  • Run a piece of Charlang code(in format as string),
sourceT := `
param (v1, v2)

return v1 + v2
`

codeT := charCode(sourceT)

codeT.compile()

resultT := codeT.run(12, 8.5)

pl("result: %v", resultT)


charCode is the object type to hold Charlang code to run, compile the source code before run it. Various parameters could be passed to the code object.

The output:

D:\tmp>char -exam runCode.char
result: 20.5
  • Passing various length paramters,
sourceT := `
param ...vargs

pln(toJson(vargs, "-sort"))

return vargs[2]

`

codeT := charCode(sourceT)

codeT.compile()

rs := codeT.run("abc", 123.5, true, {"name": "Tom", "age": 16})

pl("rs: %v", rs)

  • Run code like a function call, and the fix part of parameters with various length paramters,
sourceT := `
param (v1, v2, ...vargs)

pln("input:", v1, v2, ...vargs)

sum := v1 + v2

for i, v in vargs {
	sum += v
}

return sum
`

addAll := charCode(sourceT).compile()

resultT := addAll(12, 8.5, 2, 3, 16)

pl("result: %v", resultT)

Multi-Threading
  • First way:
func1 := func(v0) {
	for i := 0; i < 5; i++ {
		v0++

		pl("(thread) v0=%v", v0)

		sleep(1.0)
	}
}

a := 5

func1.threadRun(a)

sleep(0.15)

for i := 0; i < 5; i++ {
	a += 10

	pl("(main) a=%v", a)

	sleep(1.3)
}

  • Second way, import the 'ex' module and use the ex.threadRunFunc function:

Note: here also demonstrate the usage of mutex and pass/set value by reference.

ex := import("ex")

roundsT := 1000

mutex1 := mutex()

func1 := func(v0) {

	for i := 0; i < roundsT; i++ {
		lock(mutex1)

		setValueByRef(v0, unref(v0)+1)

		unlock(mutex1)

		pl("(thread) *v0=%v", unref(v0))

		sleep(0.05)
	}
}

a := new("int", 5)

ex.threadRunFunc(func1, a)

sleep(0.15)

for i := 0; i < roundsT; i++ {
	lock(mutex1)

	setValueByRef(a, unref(a)+10)

	unlock(mutex1)

	pl("(main) *a=%v", unref(a))

	sleep(0.065)
}


  • The third way, run in another VM:

Note: this example also demonstrate how to pass parameters to the thread runs in another VM.

// using Array or Map to pass parameters which may change in the thread

sourceT := `
param (v0)

for i := 0; i < 5; i++ {
	v0[0] ++

	pl("(thread) v0=%v", v0[0])

	sleep(1.0)
}

return

`

c1 := charCode(sourceT).compile()

if isErr(c1) {
	fatalf("failed to compile code: %v", c1)
}

a := [5]

c1.threadRun(a)

sleep(0.15)

for i := 0; i < 5; i++ {
	a[0] += 10

	pl("(main) a=%v", a[0])

	sleep(1.3)
}

Gel

Gel in Charlang is an object to encapsulate values or functions.

sourceT := `
param (v0, ...vargs)

pln(v0, vargs)

add := func(a1, a2) {
	return a1 + a2
}

mul := func(a1, a2) {
	return a1 * a2
}

if v0 == "add" {
	return add
} else if v0 == "mul" {
	return mul
} else if v0 == "Pi" {
	return 3.1415926
}

return errStrf("member/method not found: %v", v0)
`

c1 := charCode(sourceT)

if isErr(c1.compile()) {
	pl("failed to compile: %v", c1.lastError)
	exit()
}

g1 := gel(c1)

rs := g1.add(1, 2)

plo(rs)

pl("g1.Pi: %v", g1.Pi)

pl("unknown member: %v", g1.var1)

pln(isErr(g1.var1))

pln(getErrStr(g1.var1))

try {
	pl("unknown func: %v", g1.func1())
} catch e {
	pl("unknown func(%v): %v", g1.func1, e)
}

rs2 := g1.mul(3.6, 8)

plo(rs2)

The output:

D:\tmp>char -example gel1.char
add []
(charlang.Int)3
Pi []
g1.Pi: 3.1415926
var1 []
unknown member: TXERROR:member/method not found: var1
true
member/method not found: var1
func1 []
unknown func(TXERROR:member/method not found: func1): NotCallableError: string
mul []
(charlang.Float)28.8

We can use 'ex' module to load gels as well, loaded gels are compiled already.

ex := import("ex")

sourceT := `
param (v0, ...vargs)

pln(v0, vargs)

add := func(a1, a2) {
	return a1 + a2
}

mul := func(a1, a2) {
	return a1 * a2
}

if v0 == "add" {
	return add
} else if v0 == "mul" {
	return mul
} else if v0 == "Pi" {
	return 3.1415926
}

return errStrf("member/method not found: %v", v0)
`

g1 := ex.loadGel(sourceT)

rs := g1.add(1, 2)

plo(rs)

pl("g1.Pi: %v", g1.Pi)

pl("unknown member: %v", g1.var1)

pln(isErrX(g1.var1))

pln(getErrStrX(g1.var1))

try {
	pl("unknown func: %v", g1.func1())
} catch e {
	pl("unknown func(%v): %v", g1.func1, e)
}

rs2 := g1.mul(3.6, 8)

plo(rs2)

Eval Machine(Virtual Machine to Run More Than One Piece of Script)

Demonstrate how to create a new virtual machine to run scripts and/or eval the result value.

ev1 := evalMachine("value1", "value2", 2, true)

// parameters could be passed in global variable inputG
// and argsG which all values will be converted to string
rs1 := ev1.eval(`
global inputG
global argsG

pln(inputG)
pln(argsG)

`)

plt(rs1)

rs := ev1.eval("3.6 * 12.5")

plt(rs)

rs = ev1.eval("a := 4")

plt(rs)

rs = ev1.eval("mathSqrt(16 * a)")

plt(rs)

// modify one of the paramter
ev1.eval("inputG[2] = 3.1415926")

rs = ev1.eval(`
return inputG
`)

plt(rs)

Running result:

D:\tmpx>char -exam eval1.char
["value1", "value2", 2, true]
["value1", "value2", "2", "true"]
(undefined)undefined
(float)45
(undefined)undefined
(float)8
(array)["value1", "value2", 3.1415926, true]
  • to modify and/or add value to parameters
// pass parameters through evaluations of an evalMachine
aryT := [[1, 2, 3]]

ev1 := evalMachine(1, 2, aryT)

rs1 := ev1.eval(`
global inputG

ary1 := inputG[2][0]

ary1[0] + ary1[1] + ary1[2]

`)

plt(rs1)

// change the value
aryT[0][2] = 5

rs := ev1.eval("return ary1[0] + ary1[1] + ary1[2]")

plt(rs)

// append a value
aryT[0] = append(aryT[0], 18)

rs = ev1.eval(`

ary1 = inputG[2][0]

plt(ary1)

return ary1[0] + ary1[1] + ary1[2] + ary1[3]
`)

plt(rs)

Output:

(int)6
(int)8
(array)[1, 2, 5, 18]
(int)26
Implement a Common Web Server

Demonstrate how to implement a more flexible Web server, with support of static files, dynamic pages(as PHP, JSP, ASPX...) and micro-services.

Start a Simple Web Server(with SSL Support) to Serve Static Files
// quickly start a static web server to serve files under certain directory
// port and certificate directory could be set
handlerT := httpHandler("static", joinPath(getHomeDir(), "pages"))

if isErr(handlerT) {
	fatalf("failed to create httpHandler: %v", getErrStr(handlerT))
}

muxT := mux()

muxT.setHandler("/", handlerT)

pln("starting http server on port 80(default)...")
checkErr(muxT.threadStartHttpServer())

// the certificate files should be server.crt and server.key
pln("starting https(SSL) server on port 443...")
plErr(muxT.threadStartHttpsServer("-port=443", "-certDir=."))

for {
	pln(time().format("2006-01-02 15:04:05"), "heartbeat")
	sleep(5.0)
}

Start a Common Web Server
// a very simple web server
// to test the server, open your browser, and browse to the URL address: http://127.0.0.1

muxT := mux()

handlerT := func(requestA, responseA) {
	// pl("req: %#v, res: %#v", requestA, responseA)

	writeResp(responseA, "This is a test!")

	return "TX_END_RESPONSE_XT"
}

muxT.setHandler("/", handlerT)

rs := muxT.startHttpServer()

pl("result: %v", rs)

Modify the code part in handlerT to fulfill customized requirement of the Web server. You can mix a static files handler with the same Mux object in different route, such as:

muxT.setHandler("/", staticFileHandlerT)
muxT.setHandler("/common", commonHandlerT)
Web Server with Multi-thread

One more example to Demonstrate the usage of mutex to avoid conflicts for multi http requests:

n1 := new("int", 0)

mutex1 := mutex()

muxT := mux()

handlerT := func(requestA, responseA) {
	pl("req: %#v, res: %#v", requestA, responseA)

	params1 := parseReqFormEx(requestA)

	plo(params1)

	setRespHeader(responseA, "Access-Control-Allow-Origin", "*")
	setRespHeader(responseA, "Access-Control-Allow-Headers", "*")
	setRespHeader(responseA, "Content-Type", "application/json;charset=utf-8")

	authT := trim(params1["auth"])

	if authT != "abc123" {
		writeResp(responseA, genJsonResp(requestA, "fail", "auth failed"))
		return "TX_END_RESPONSE_XT"
	}

	inputT := params1["input"]

	if inputT == undefined {
		writeResp(responseA, genJsonResp(requestA, "fail", "input could not be empty"))
		return "TX_END_RESPONSE_XT"
	}

	c1 := int(inputT)

	mutex1.lock()
	setValueByRef(n1, unref(n1)+c1)
	mutex1.unlock()

	writeResp(responseA, genJsonResp(requestA, "success", toStr(unref(n1))))

	return "TX_END_RESPONSE_XT"
}

muxT.setHandler("/test", handlerT)

rs := muxT.startHttpServer()

pl("result: %v", rs)

Request Handler Running in a New Virtual Machine

Another example to Demonstrate how to set handler runnin in a new VM, and the way to pass parameters to it:

// handler runs in a seperate VM, more safe but with a little more system resource(and time) cost/overhead
n1 := new("int", 0)

mutex1 := mutex()

muxT := mux()

handlerT := httpHandler().set("code", `
param(n1, mutex1)

global requestG
global responseG

pl("req: %#v, res: %#v", requestG, responseG)

pl("n1: %#v, mutex1: %#v", n1, mutex1)

params1 := parseReqForm(requestG)

plo(params1)

setRespHeader(responseG, "Access-Control-Allow-Origin", "*")
setRespHeader(responseG, "Access-Control-Allow-Headers", "*")
setRespHeader(responseG, "Content-Type", "application/json;charset=utf-8")

authT := trim(params1["auth"])

if authT != "abc123" {
	writeResp(responseG, genJsonResp(requestG, "fail", "auth failed"))
	return "TX_END_RESPONSE_XT"
}

inputT := params1["input"]

if inputT == undefined {
	writeResp(responseG, genJsonResp(requestG, "fail", "input could not be empty"))
	return "TX_END_RESPONSE_XT"
}

c1 := int(inputT)

pln("c1:", c1)

mutex1.lock()

setValueByRef(n1, unref(n1)+c1)
mutex1.unlock()

writeResp(responseG, genJsonResp(requestG, "success", toStr(unref(n1))))

return "TX_END_RESPONSE_XT"

`, n1, mutex1)

if isErr(handlerT) {
	fatalf("failed to create http handler: %v", getErrStr(handlerT))
}

muxT.setHandler("/test", handlerT)

pln("starting web server on port 8080...")
rs := muxT.startHttpServer("-port=8080")

pl("result: %v", rs)

Serve Static and Dynamic HTML Pages at the Same Time

Read HTML template from the file according to the route(in the URL parameter).

// demonstrate how to serve static and dynamic HTML pages, not this is not the only way

staticHandlerT := httpHandler("static", joinPath(getHomeDir(), "pages"))

if isErr(staticHandlerT) {
	fatalf("failed to create static handler: %v", getErrStr(staticHandlerT))
}

dynamicHandlerT := func(requestA, responseA) {
	// set the proper response header
	setRespHeader(responseA, "Access-Control-Allow-Origin", "*")
	setRespHeader(responseA, "Access-Control-Allow-Headers", "*")
	setRespHeader(responseA, "Content-Type", "text/html;charset=utf-8")

	// get the parameters from the HTTP request
	paramsT := parseReqForm(requestG)

	// get the 'req' parameter from query string or post form values
	// it will be used as route
	reqT := trim(params1["req"])

	// get HTML template from specified folder
	templateDirT := `c:\test\tmpl`

	templateFileT := joinPath(templateDirT, reqT+".html")

	templateHtmlT := loadText(templateFileT)

	// do some modifications on the template
	strReplace(templateHtmlT, "{{field1}}", getNowStr())

	// write the processed text to HTTP response
	writeResp(responseA, templateHtmlT)

	// write "TX_END_RESPONSE_XT" to end the response stream/output
	return "TX_END_RESPONSE_XT"
}

// serve dynamic pages
muxT.setHandler("/pages", dynamicHandlerT)

// serve other route as static pages
muxT.setHandler("/", staticHandlerT)

rs := muxT.startHttpServer()

pl("result: %v", rs)

Charlang's Embedded Fully Functional Web/Microservices/Application Server

 

Charlang's main program comes with a server mode that supports a lightweight WEB/Application/API all-in-one server. You can start it using the following command line:

D:\tmp>char -server -dir=scripts
[2024/08/23 08:08:22] Charlang Server V1.3.3 -port=:80 -sslPort=:443 -dir=scripts -webDir=scripts -certDir=scripts
[2024/08/23 08:08:22] try starting ssl server on :443...
[2024/08/23 08:08:22] try starting server on :80 ...
[2024/08/23 08:08:22] failed to start https: open scripts\server.crt: The system cannot find the file specified.

As can be seen, the server mode of Charlang can be started with the '-server' parameter, and the '-port' parameter can be used to specify the HTTP service port (please add a colon), '-sslPort' can be used to specify the SSL port, '-certDir' can be used to specify the certificate file directory of the SSL service (which should be two files: server.crt and server.key), '-dir' can be used to specify the root directory of the service, and '-webDir' can be used to specify the web service for static pages and resources. These parameters have default values and can be seen without entering any parameters.

The error in the output information is because the SSL certificate was not provided, and the SSL service will not be able to start. Adding the certificate files will suffice.

Then open a browser to access the address http://127.0.0.1:80 to access the all-in-one web service written in Charlang.

Assuming that the specified directory contains three files: charmsIndex.char, charmsTmpl.html, and charmsApi.char, various modes supported by the application server established by Charlang can be displayed.

First, access it with a browser http://127.0.0.1/charmsTmpl.html This will be accessing general web services, as the web directory defaults to the same as the server root directory. Therefore, the static file charmsTmpl.html under the root directory will be displayed, which is an example web page.

Screenshot

You can see that the "{{text1}}" tag after the text 'Please click the button ' in the webpage. This is the tag that we need to replace when displaying the dynamic webpage later. The content of the charmsTmpl.html file is as follows:

<html>
<body>
    <script>
        function test() {
            let xhr = new XMLHttpRequest();

            xhr.open('POST', 'http://127.0.0.1:80/charms/charmsApi', true);

            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")

            xhr.onload = function(){
                alert(xhr.responseText);
            }

            xhr.send("param1=abc&param2=123");
        }
    </script>

    <div>
        <span>Please click the button {{text1}}:</span><button onclick="javascript:test();">Button1</button>
    </div>

</body>
</html>

Then we try to perform dynamic web page output, which is similar to dynamically rendering of webpages in the background supported by PHP, ASP, JSP, or other similar frameworks. Then browse to 'http://127.0.0.1/charms/charmsIndex' . Add the charms path to the URL, which is a virtual path indicating that the server will search for the charmsIndex.char file in the root directory while starting the server. This code will output the webpage content. Let's take a look inside the charmsIndex.char file.

// responseG is the predefined global variable which holds the HTTP response object to write to
global responseG

// basePathG is the predefined global variable which holds the specified base path while starting the server
global basePathG

// Set the default global return value variable outG to the string TX_END_RESPONSE_XT
// If the default Charlang server receives a function to process a request, the return result is TX_END_RESPONSE_XT
// The server processing(output of the HTTP response) of the page will be terminated, otherwise the return value will be output as a string to the webpage
outG := "TX_END_RESPONSE_XT"

// Obtain the corresponding web page template(HTML)
// The joinPath function will merge multiple file paths into one complete file path
// The first parameter represents the variable to be placed in the result, where $push represents stack pushing
// basePathG is a built-in global variable that represents the root directory of the service
templatePathT := joinPath(basePathG, `charmsTmpl.html`)

// Load the file as a text string(HTML)
templateTextT := loadText(templatePathT)

// Replace the {{text1}} tag to letter A
templateTextT = strReplace(templateTextT, "{{text1}}", "A")

// Set the corresponding response header
setRespHeader(responseG, "Content-Type", "text/html; charset=utf-8")

// Write the HTML to the web page output
// responseG is also a predefined global variable that represents the HTTP/webpage output object to be written to
writeResp(responseG, templateTextT)

// Return 'TX_END_RESPONSE_XT' to end the output
return outG

In Charlang server model, each HTTP request will be processed by a separate virtual machine, which can be seen as a microservice concept. The microservice in this example only replaces the specified tags in the loaded webpage template and outputs them to the webpage. Although it is simple, it has already demonstrated the basic principle of dynamic webpage, that is, it can perform necessary and controllable rendering before outputting the webpage.

Let's browse to 'http://127.0.0.1/charms/charmsIndex'. It will result in the following results:

Screenshot

We can found that the original tag has indeed been replaced with the uppercase letter A, verifying the effect of dynamic web pages.

Looking at the webpage template file charmsTmpl.html above, once the button is clicked, the JavaScript function test will be executed, where an AJAX request is made and the result of the request will be output using the alert function. This is a typical example of a client accessing a backend API service. Let's take a look at how to implement this backend API service. The following is the content of the charmsApi.char file also located in the server root directory:

// declare the global variables to use in the context
global requestG
global reqNameG
global reqUriG
global responseG
global paraMapG

// Get the current time and put it into variable t
t := getNowStr()

// Output reference information(to server's local console, not the HTTP response)
// Where reqNameG is a predefined global variable that represents the service name, which is the last part of the access URL
// reqUriG is a predefined global variable that represents the service route/path
// paraMapG is also a global variable that represents the query string or form parameters contained in HTTP requests (which can be in GET or POST requests)
pl(`[%v] reqNameG: %v, reqUriG: %v, paraMapG: %v`, t, reqNameG, reqUriG, paraMapG)

// Set output response header information (to JSON format)
setRespHeader(responseG, "Content-Type", "text/json; charset=utf-8")

// Set the response status to 200 (HTTP_oK), indicating a successful request response
writeRespHeader(responseG, 200)

// Assembling response strings using spr instructions
str1 := spr("The request is: %v, uri: %v, parameters: %v", reqNameG, reqUriG, paraMapG)

// Generate encapsulated JSON responses using genJsonResp, or output strings in other formats on your own
respStr := genJsonResp(requestG, "success", str1)

// Write and output the response string (to a webpage)
writeResp(responseG, respStr)

// End processing and return 'TX_END_RESPONSE_XT' to terminate the continued output of the response stream
return "TX_END_RESPONSE_XT"

Then, if we click button button1 on the webpage, we will get the following alert pop-up:

Screenshot

This is because the webpage charmsTmpl.html called AJAX request to the service located at http://127.0.0.1:80/charms/charmsApi. And our Charlang server will find charmsApi.char (automatically added with the .char file name suffix) and execute it, so it will output the content we want.

Now, an example of a small but fully functional WEB/application/API all-in-one server has been fully demonstrated. It is already sufficient for a general and small application service, and has almost no external dependencies. Deployment is also very convenient, only requiring the main program of Charlang and corresponding HTML and script files in the specified directory.

 

Charlang as System Service

Charlang can be started as a system service and supports operating systems such as Windows and Linux. As long as you add the command line parameter '-reinstallService' to run the Charlang main program, you can install a system service called charService in the system (which can be seen using the service management module in computer management under Windows). Note that installing services in the operating system generally requires administrator privileges. Under Windows, you need to open the CMD window as an administrator to execute this command, while under Linux, you need to execute it as root or with the sudo command.

After the service is started, a log will be recorded in the file charService.log in the service root directory (c:\char in Windows and /char in Linux). When the service starts for the first time, it will search for all files with names similar to taskXXX.char in the service root directory (such as task001.char, taskAbc.char, etc.) and run them one by one, and output their execution results (returned value) to the log. This type of code file is called a one-time-run task file, and is generally used in situations where it needs to be started and run once. It can also be manually run the command 'char -restartService' to restart the service and achieve the goal of task re-execution.

There are another kind of one-time-run task files which will be run in a seperated thread called 'thread tasks', their file name similar to threadTaskXXX.char in the service root directory (such as threadTask001.char, threadTaskAbc.char, etc.). These tasks is for those tasks need running continously, such as WEB servers, FRP server or client, ... If some error occur while running thread-tasks, the information will be logged in file 'runThreadTask.log' in service root directory.

In addition, during operation, the charService service checks the service root directory every 5 seconds. If there are files with names similar to autoRemoveTaskXXX.char (such as autoRemoveTask001.char, autoRemoveTaskAbc.char, etc.), the code in these files will be immediately executed and then deleted. This mechanism is similar to a task queue, allowing us to add tasks to the queue (placed in the service root directory) at any time, and Charlang service will execute these tasks at any time. And since the task will be deleted immediately after execution, it will not be executed repeatedly.

The command line parameters related to service installation, removal, start, stop, and restart of the Charlang main program also include '-installService', '-removeService', '-startService', '-stopService', '-restartService', and so on.

The task code can refer to examples such as task001.char, threadTask001.char, autoRemoveTask001.char, etc.

  • One-time-task Example

file: task001.char

global basePathG

logPathT := joinPath(basePathG, "charService.log")

rs := appendText("\ntask001.char\n", logPathT)

return "task001 returns some result 000"

  • Thread-task Example

file: threadTask001.char

for {
	saveText(getNowStr(), `c:\char\task1.txt`)

	sleep(60.0)
}

It will be a continous loop which will write the current time string in the file every 60 seconds.

The following is the thread-task to run Frpc client when system started,

file: threadTaskFrpc.char

appendText(spr("\n[%v] %v %v\n", getNowStr(), "threadTaskFrpc", "starting..."), `c:\logs\frpcTask.log`)

rs := systemCmd(`c:\tools\frp\frpc.exe`, `-c`, `c:\tools\frp\frpc.ini`)

appendText(spr("\n[%v] %v %v\n", getNowStr(), "threadTaskFrpc", rs), `c:\logs\frpcTask.log`)


  • Auto-remove-task Example

file: autoRemoveTask001.char

global basePathG

logPathT := joinPath(basePathG, "charService.log")

rs := appendText("\nautoRemoveTask001.char\n", logPathT)

7.7 More Examples
Builtin Function: checkErr

checkErr: check if the object is error or error string, if true, exit the program with output, usage: checkErr(result, "-format=Failed to process: %v\n"), the default format is "Error: %v\n"

file: checkErr.char

Anonymous Function

file: anonymousFunc.char

More About Array

file: array.char

More About Map

file: map.char

Mutable String

file: mutableString.char

Big Int

file: bigInt.char

Big Float

file: bigFloat.char

Bitwise Processing

file: bitwise.char

Calculate BMI

file: bmi.char

Calculate Cosine Similarity of Two Vectors

file: calCosineSimilarity.char

Calculate Cosine Similarity of Two Vectors by Big Floats
  • more precision

file: calCosineSimilarityBig.char

One More Example for Gels

file: gel3.char

Redirect Stdout to a File

Note: Better run the example code with charw.exe(i.e. the GUI version of Charlang in Windows).

file: guiRedirectStdout.char

Get Named Value in Charlang

Note: These values should be defined in the Charlang source code first before using them. In charadd.go:

...

var namedValueMapG = map[string]interface{}{
	"tk.TimeFormat":            tk.TimeFormat,            // "2006-01-02 15:04:05"
	"tk.TimeFormatMS":          tk.TimeFormatMS,          // "2006-01-02 15:04:05.000"
	"tk.TimeFormatMSCompact":   tk.TimeFormatMSCompact,   // "20060102150405.000"
	"tk.TimeFormatCompact":     tk.TimeFormatCompact,     // "20060102150405"
	"tk.TimeFormatCompact2":    tk.TimeFormatCompact2,    // "2006/01/02 15:04:05"
	"tk.TimeFormatDateCompact": tk.TimeFormatDateCompact, // "20060102"

	"time.Layout":   time.Layout,
	"time.RFC1123":  time.RFC1123,
	"time.RFC3339":  time.RFC3339,
	"time.DateTime": time.DateTime,
	"time.DateOnly": time.DateOnly,
	"time.TimeOnly": time.TimeOnly,

	"maxInt":   math.MaxInt,
	"minInt":   math.MinInt,
	"maxFloat": math.MaxFloat64,
	"minFloat": math.SmallestNonzeroFloat64,

...

Get these values by calling getNamedValue(getConst) function.

file: namedValue.char

Call Named Function in Golang

Note: These functions should be defined in the Charlang source code first before calling them. In charadd.go:

...

var namedFuncMapG = map[string]interface{}{
	"fmt.Fprintf": fmt.Fprintf,
	"tk.NewTK":    tk.NewTK,
}

...

Call these functions by calling callNamedValue function and passing the proper parameters.

file: callNamedFunc.char

With this method, in theory, we can add any functions in Golang's standard library or 3rd party repositories.

Compare Binary Files

file: binCompare.char

A Simple Text Editor

file: editFile.char

A simple text editor with file load/save, JSON validate, code running features, in GUI.

Base64 Encoding of Images

file: base64EncodeImage.char

Encode an image file to Base64 code to use in img tag in HTML, for example,

D:\tmp>char -exam base64EncodeImage.char -file=d:\downtemp\curtain-2757815_960_720.png
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA8AAAAHECAYAAAD22EOkAAABeGlDQ1BJQ0MgUHJvZmlsZQAAeJx1kL9LAmEcxh+1sB+GQRINDTdIQyiEDTWWDUKIiBlktdyddxqcetydRDQ2tDq4VLRk0X9QW/QPBEFQTUHU3FAQQcj1nCcood/jve+H5/0+7733AN60JpfMgTmgVLaMTCIubOQ2Bf8rhjGOSYSwIMqmvpxOJ9G3vh/hcfpD1Dmr/1zPGs0rpgx4hsiLsm5Y5CVyatfSHa6RQ3JRzJPPyRGDFyTfO7rk8rvDBZd/HDaymRXAGyALhS6WulguGiVyhBwuaVW5fR/nTwJKeX2Nfbq1TGSQQBwCJFSxAw0WouxlZt...
Plot Data Graph in Console

file: asciiPlot.char

Snapshot

Plot Data Graph in Console with Realtime Data Update

file: asciiPlotRealTime.char

Demonstrate multi-thread, update one area of console...

Plot Simple Data Graph to Image

file: basicPlot.char

Demonstrate plotting a simple line chart with data in an array...

Plot Simple Data Graph to Web View

file: basicPlotToWebView.char

Demonstrate plotting a simple line chart with data in an array, then render it into an IMG element in WebView2...

Plot Line Charts

file: imagePlot.char

More examples of plotting line charts to images...

Calculator in WebView2

file: calculatorInWebView.char

A tiny GUI calculator running in WebView2, use the HTML/CSS/JavaScript example code from github.com/WebDevSimplified/Vanilla-JavaScript-Calculator. Demonstrate how to embed WEB applications in Charlang.

Byte Queue

file: byteQueue.char

Demonstrate usage of a non-builtin data type "byteQueue", using 'newObj' function.

7.8 Advance Topics
Language Considerations

Charlang source code is compiled to bytecode and run in a Virtual Machine (VM). Compiled bytecode can be serialized/deserialized for wire to remove compilation step before execution for remote processes, and deserialization will solve version differences to a certain degree.

Main script and Charlang source modules in Charlang are all functions which have compiledFunction type name. Parameters can be defined for main function with param statement and main function returns a value with return statement as well. If return statement is missing, undefined value is returned by default. All functions return single value but thanks to destructuring feature Charlang allows to return multiple values as an array and set returning array elements to multiple variables.

Charlang relies on Go's garbage collector and there is no allocation limit for objects. Builtin objects can be disabled before compilation.

Charlang can handle runtime errors and Go panic with try-catch-finally statements which is similar to Ecmascript implementation with a few minor differences. Although Go developers are not fan of try-catch-finally, they are well known statements to work with.

Charlang is developed to be an embedded script language for Go applications also, and importing source modules from files will not be added in near future but one can implement a custom module to return file content to the compiler.

Charlang currently has a simple optimizer for constant folding and evaluating expressions which do not have side effects. Optimizer greedily evaluates expressions having only literals (int, uint, char, float, bool, string). Optimizer can be disabled with compiler options.

Run Script from Command Line
  • One line
D:\tmp>char -cmd=pln(1+3)
4
  • Multiple lines and/or with spaces

Original code:

a := 3
pln(a * 12)

Command-line after url-encode the parameter:

D:\tmp>char -cmd=a%20:=3%0Apln(a%20*%2012) -urlDecode
36
  • Multiple lines and/or with spaces(alternative way)

Encrypt the script first:

D:\tmp>char
Charlang 1.2.2 by TopXeQ
> encryptText("a := 12\npln(a * 5)", "char") 
694B9F86EB4B1024390E25200A6264602C571C20282F29
>

Then prefix the string //TXDEF# before the parameter,

D:\tmp>char -cmd=//TXDEF#694B9F86EB4B1024390E25200A6264602C571C20282F29
60
Show Environment Information of Charlang
D:\tmp>char -env
Charlang by TopXeQ V1.2.3
basePath: C:\Users\Administrator\char
localPath: d:\scripts
cloudPath: https://script.example.com/scripts/
Compile a Script to One Executable
D:\tmp>char -compile -output=basic.exe -example basic.char

D:\tmpx>basic.exe
3.4000000000000004

D:\tmpx>basic
3.4000000000000004

Compile a script with charw.exe in Windows, to avoid the console window(CMD) to show while running. For example:


charw -compile -output=cal.exe -example guiCalculator.char

D:\tmpx>cal.exe

Snapshot

Charlang as An Embedded Language in Golang

To run a Charlang script in Golang, it must be compiled to create a Bytecode object then it is provided to Virtual Machine (VM). Charlang has a simple optimizer enabled by default in the compiler. Optimizer evaluates simple expressions not having side effects to replace expressions with constant values. Note that, optimizer can be disabled to speed up compilation process.

package main

import (
  "fmt"

  "github.com/topxeq/charlang"
)

func main() {
  script := `
  param num

  var fib
  fib = func(n, a, b) {
    if n == 0 {
      return a
    } else if n == 1 {
      return b
    }
    return fib(n-1, b, a+b)
    }
  return fib(num, 0, 1)
  `
  bytecode, err := charlang.Compile([]byte(script), charlang.DefaultCompilerOptions)

  if err != nil {
    panic(err)
  }

  retValue, err := charlang.NewVM(bytecode).Run(nil,  charlang.Int(35))

  if err != nil {
    panic(err)
  }

  fmt.Println(retValue) // 9227465
}

Script above is pretty self explanatory, which calculates the fibonacci number of given number.

Compiler options hold all customizable options for the compiler. TraceCompilerOptions is used to trace parse-optimize-compile steps for debugging and testing purposes like below;

bytecode, err := charlang.Compile([]byte(script), charlang.TraceCompilerOptions)
// or change output and disable tracing parser
// opts := charlang.TraceCompilerOptions
// opts.Trace = os.Stderr
// opts.TraceParser = false
// bytecode, err := charlang.Compile([]byte(script), opts)

VM execution can be aborted by using Abort method which cause Run method to return an error wrapping ErrVMAborted error. Abort must be called from a different goroutine and it is safe to call multiple times.

Errors returned from Run method can be checked for specific error values with Go's errors.Is function in errors package.

VM instances are reusable. Clear method of VM clears all references held and ensures stack and module cache is cleaned.

vm := charlang.NewVM(bytecode)
retValue, err := vm.Run(nil,  Charlang.Int(35))
/* ... */
// vm.Clear()
retValue, err := vm.Run(nil,  Charlang.Int(34))
/* ... */

Global variables can be provided to VM which are declared with global keyword. Globals are accessible to source modules as well. Map like objects should be used to get/set global variables as below.

script := `
param num
global upperBound
return num > upperBound ? "big" : "small"
`
bytecode, err := charlang.Compile([]byte(script), charlang.DefaultCompilerOptions)

if err != nil {
  panic(err)
}

g := charlang.Map{"upperBound": charlang.Int(1984)}
retValue, err := charlang.NewVM(bytecode).Run(g, charlang.Int(2018))
// retValue == charlang.String("big")

There is a special type SyncMap in charlang to make goroutine safe map object where scripts/Go might need to interact with each other concurrently, e.g. one can collect statistics or data within maps. Underlying map of SyncMap is guarded with a sync.RWMutex.

module := `
global stats

return func() {
  stats.fn2++
  /* ... */
}
`
script := `
global stats

fn1 := func() {
  stats.fn1++
  /* ... */
}

fn1()

fn2 := import("module")
fn2()
`
mm := charlang.NewModuleMap()
mm.AddSourceModule("module", []byte(module))

opts := charlang.DefaultCompilerOptions
opts.ModuleMap = mm

bytecode, err := charlang.Compile([]byte(script), opts)

if err != nil {
  panic(err)
}

g := &charlang.SyncMap{
    Map: charlang.Map{"stats": charlang.Map{"fn1": charlang.Int(0), "fn2": charlang.Int(0)}},
}
_, err = charlang.NewVM(bytecode).Run(g)
/* ... */

As can be seen from examples above, VM's Run method takes arguments and its signature is as below. A map like globals argument or nil value can be provided for globals parameter. args variadic parameter enables providing arbitrary number of arguments to VM which are accessed via param statement.

func (vm *VM) Run(globals Object, args ...Object) (Object, error)
Variables Declaration and Scopes
param

param keyword is used to declare a parameter for main function (main script). Parenthesis is required for multiple declarations. Last argument can also be variadic. Unlike var keyword, initializing value is illegal. Variadic argument initialized as an empty array [], and others are initialized as undefined if not provided. param keyword can be used only once in main function.

param (arg0, arg1, ...vargs)
param foo
param bar    // illegal, multiple param keyword is not allowed
if condition  {
  param arg    // illegal, not allowed in this scope
}

func(){
    param (a, b)    // illegal, not allowed in this scope
}
global

global keyword is to declare global variables. Note that var statements or short variable declaration := always creates local variables not global. Parenthesis is required for multiple declarations. Unlike var, initializing value is illegal. global statements can appear multiple times in the scripts.

global gives access to indexable globals argument with a variable name provided to Virtual Machine (VM).

If nil is passed to VM as globals, a temporary map assigned to globals.

Any assignment to a global variable creates or updates the globals element.

Note that global variables can be accessed by imported source modules which enables to export objects to scripts like extern in C.

global foo
global (bar, baz)
// "globals" builtin function returns "globals" provided to VM.
g := globals()
v := g["foo"]    // same as `global foo; v := foo`
if condition {
  global x     // illegal, not allowed in this scope
}

func() {
  global y     // illegal, not allowed in this scope
}
var

var keyword is used to declare a local variable. Parenthesis is required for multiple declaration. Note: Tuple assignment is not supported with var statements.

var foo               // foo == undefined
var (bar, baz = 1)    // bar == undefined, baz == 1
var (bar,
     baz = 1)         // valid
var (
    foo = 1
    bar
    baz = "baz"
)                     // valid

A value can be assigned to a variable using short variable declaration := and assignment = operators.

  • := operator defines a new variable in the scope and assigns a value.
  • = operator assigns a new value to an existing variable in the scope.
                 // function scope A
a := "foo"       // define 'a' in local scope

func() {         // function scope B
  b := 52        // define 'b' in function scope B
  
  func() {       // function scope C
    c := 19.84   // define 'c' in function scope C

    a = "bee"    // ok: assign new value to 'a' from function scope A
    b = 20       // ok: assign new value to 'b' from function scope B

    b := true    // ok: define new 'b' in function scope C
                 //     (shadowing 'b' from function scope B)
  }
  
  a = "bar"      // ok: assign new value to 'a' from function scope A
  b = 10         // ok: assign new value to 'b'
  a := -100      // ok: define new 'a' in function scope B
                 //     (shadowing 'a' from function scope A)
  
  c = -9.1       // illegal: 'c' is not defined
  var b = [1, 2] // illegal: 'b' is already defined in the same scope
}

b = 25           // illegal: 'b' is not defined
var a = {d: 2}   // illegal: 'a' is already defined in the same scope

Following is illegal because variable is not defined when function is created.

In assignment statements right hand side is compiled before left hand side.

f := func() {
  f()    // illegal: unresolved symbol "f"
}
var f
f = func() {
  f()    // ok: "f" is declared before assignment.
}

Unlike Go, a variable can be assigned a value of different types.

a := 123        // assigned    'int'
a = "123"       // reassigned 'string'
a = [1, 2, 3]   // reassigned 'array'

Capturing loop variables returns the last value of the variable set after last post statement of the for loop, like Go.

var f

for i := 0; i < 3; i++ {
  f = func(){
    return i
  }  
}

println(f())  // 3

Like Go, to capture the variable define a new variable using same name or different.

var f

for i := 0; i < 3; i++ {
  i := i
  f = func(){
    return i
  }  
}

println(f())  // 2
const

const keyword is used to declare a local constant variable. Parenthesis is required for multiple declaration. Note: Tuple assignment is not supported.

The value of a constant can't be changed through reassignment.

Reassignment is checked during compilation and an error is thrown.

An initializer for a constant is required while declaring. The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable.

const (
  a = 1
  b = {foo: "bar"}
)

const c       // illegal, no initializer

a = 2         // illegal, reassignment
b.foo = "baz" // legal

iota is supported as well.

const (
  x = iota
  y
  z
)
println(x, y, z) // 0 1 2
const (
  x = 1<<iota
  y
  z
)
println(x, y, z) // 1 2 4
const (
  _ = 1<<iota
  x
  y
  z
)
println(x, y, z) // 2 4 8
const (
  x = 1+iota
  _
  z
)
println(x, z) // 1 3
const (
  x = func() { return iota }() // illegal, compile error
)
const (
  iota = 1 // illegal, compile error
)

RHS of the assignment can be any expression so iota can be used with them as well.

const (
  x = [iota]
  y
)
println(x) // [0]
println(y) // [1]
const (
  _ = iota
  x = "string" + iota
  y
)
println(x) // string1
println(y) // string2

Warning: if a variable named iota is created before const assignments, iota is not used for enumeration and it is treated as normal variable.

iota := "foo"

const (
  x = iota
  y
)
println(x) // foo
println(y) // foo
Values and Value Types

In Charlang, everything is a value, and, all values are associated with a type(object).

19 + 84                 // int values
1u + 5u                 // uint values
"foo" + `bar`           // string values
-9.22 + 1e10            // float values
true || false           // bool values
'ç' > '9'               // char values
[1, false, "foo"]       // array value
{a: 12.34, "b": "bar"}  // map value
func() { /*...*/ }      // function value

Here's a list of fundamental value types in Charlang.

Charlang Type Description Equivalent Type in Go
int signed 64-bit integer value int64
uint unsigned 64-bit integer value uint64
float 64-bit floating point value float64
bool boolean value bool
char unicode character rune
string unicode string string
bytes byte array []byte
error error value -
array value array []Object
map value map with string keys map[string]Object
undefined undefined value -
compiledFunction function value -
Error Values

In Charlang, an error can be represented using "error" typed values. An error value is created using error builtin function, and, it has an underlying message. The underlying message of an error can be accessed using .Message selector. Error has also a name which is accessed using .Name. Errors created with error builtin have default name error but builtin errors have different names like NotIterableError, ZeroDivisionError.

First argument passed to error builtin function is converted to string as message.

err1 := error("oops")
err2 := error(1+2+3)         // equivalent to err2 := error("6")
if isError(err1) {           // 'isError' is a builtin function
  name := err1.Name          // get underlying name
  message := err1.Message    // get underlying message
}  
Charlang Runtime Types
Basic types:
  • bool: boolean (bool in Go)
  • byte: unsigned 8bit integer (uint8 in Go)
  • char: character (rune in Go)
  • int: signed 64bit integer (int64 in Go)
  • uint: unsigned 64bit integer (uint64 in Go)
  • float: 64bit floating point (float64 in Go)
  • string: string (string in Go)
  • bytes: byte array ([]byte in Go)
  • chars: character ([]rune in Go)
  • array: objects array ([]Object in Go)
  • map: objects map with string keys (map[string]Object in Go)
  • error: an error with a string Name and Message
  • undefined: undefined
More types:
  • bigInt: holds an big integer value
  • bigFloat: holds an big float value
  • mutableString: mutable string
  • orderedMap: map with fix-ordered items
  • objectRef: object reference to pass to functions
  • stack: a common stack
  • queue: a common queue
  • function: callable function
  • compiledFunction: compiled function
  • charCode: holds the source code and runnable Charlang code
  • gel: holds the source code and runnable Charlang code mainly for remote call
  • statusResult: status object, usually return by server side, in form of: {"Status": "success", "Value": "more info"} or {"Status": "fail", "Value": "error message"}
  • stringBuilder: holds a strings.Builder object in Golang
  • bytesBuffer: holds a bytes.Buffer object in Golang
  • database: holds a database object in Golang
  • time: holds a time.Time object in Golang
  • location: holds a time.Location object in Golang
  • seq: an object to generate unique, sequential numbers
  • mutex: mutex for multi-threading
  • mux: mux(router) for http request
  • httpReq: holds a http.Request object in Golang
  • httpResp: holds a http.Response object in Golang
  • httpHandler: holds a http.HandleFunc object in Golang
  • reader: holds a io.Reader object in Golang
  • writer: holds a io.Writer object in Golang
  • file: holds a os.File object in Golang
  • image: holds a image.Image object in Golang
  • delegate: holds a delegate(callback) function for calling
  • etable: holds an object with multi-sheet table data like Excel or CSV
  • excel: holds an object with Excel data
  • any: an object to hold any value types
Go Type Definitions
  • int
type Int int64
  • uint
type Uint uint64

Note: uint values can be represented by adding u suffix to integer values.

  • float
type Float float64
  • bool
type Bool bool
  • char
type Char rune
  • string
type String string
  • bytes
type Bytes []byte
  • error
type Error struct {
  Name    string
  Message string
  Cause   error
}
  • array
type Array []Object
  • map
type Map map[string]Object
  • syncMap
type SyncMap struct {
  mu sync.RWMutex
  Map
}
Type Conversion/Coercion Table
int uint float bool char string bytes array map error undefined
int - uint64(v) float64(v) !IsFalsy() rune(v) strconv X X X String() X
uint int64(v) - float64(v) !IsFalsy() rune(v) strconv X X X String() X
float int64(v) uint64(v) - !IsFalsy() rune(v) strconv X X X String() X
bool 1 / 0 1 / 0 1.0 / 0.0 - 1 / 0 "true" / "false" X X X String() X
char int64(v) uint64(v) float64(v) !IsFalsy() - string(v) X X X String() X
string strconv strconv strconv !IsFalsy() utf8. DecodeRuneInString(v) - []byte(v) X X String() X
bytes X X X !IsFalsy() X string(v) - X X String() X
array X X X !IsFalsy() X String() X - X String() X
map X X X !IsFalsy() X String() X X - String() X
error X X X X X String() X X X - X
undefined X X X !IsFalsy() X String() X X X X -
  • X: No conversion. Conversion function will throw runtime error, TypeError.
  • strconv: converted using Go's conversion functions from strconv package.
  • IsFalsy(): use Object.IsFalsy() function.
  • String(): use Object.String() function.
Object.IsFalsy()

Object.IsFalsy() interface method is used to determine if a given value should evaluate to false (e.g. for condition expression of if statement).

  • int: v == 0
  • uint: v == 0
  • float: math.IsNaN(v)
  • bool: !v
  • char: v == 0
  • string: len(v) == 0
  • bytes: len(v) == 0
  • array: len(v) == 0
  • map: len(v) == 0
  • error: true (error is always falsy)
  • undefined: true (undefined is always falsy)
Builtin Errors

Builtin errors do not have message but have name. With .New(message) function call on an error value creates a new error by wrapping the error.

  • WrongNumArgumentsError
  • InvalidOperatorError
  • IndexOutOfBoundsError
  • NotIterableError
  • NotIndexableError
  • NotIndexAssignableError
  • NotCallableError
  • NotImplementedError
  • ZeroDivisionError
  • TypeError
Undefined Values

In Charlang, an undefined value can be used to represent an unexpected or non-existing value:

  • A function that does not return a value explicitly considered to return undefined value.
  • Indexer or selector on composite value types may return undefined if the key or index does not exist.
  • Builtin functions may return undefined.
a := func() { b := 4 }()    // a == undefined
c := {a: "foo"}["b"]        // c == undefined
d := sort(undefined)        // d == undefined
e := delete({}, "foo")      // "delete" always returns undefined

Builtin function isUndefined, isUndef or == operator can be used to check value is undefined.

Array Values

In Charlang, array is an ordered list of values of any types. Elements of an array can be accessed using indexer [].

[1, 2, 3][0]       // == 1
[1, 2, 3][2]       // == 3
[1, 2, 3][3]       // RuntimeError: IndexOutOfBoundsError

["foo", 'x', [1, 2, 3], {bar: 2u}, true, undefined, bytes()]   // ok
Map Values

In Charlang, map is a set of key-value pairs where key is string and the value is of any value types. Value of a map can be accessed using indexer [] or selector '.' operators.

m := { a: 1, "b": false, c: "foo" }
m["b"]                                // == false
m.c                                   // == "foo"
m.x                                   // == undefined

{a: [1, 2, 3], b: {c: "foo", d: "bar"}} // ok
Function Values

In Charlang, function is a callable value with a number of function arguments and a return value. Just like any other values, functions can be passed into or returned from another function.

sum := func(arg1, arg2) {
  return arg1 + arg2
}

var mul = func(arg1, arg2) {
  return arg1 * arg2
}

adder := func(base) {
  return func(x) { return base + x }  // capturing 'base'
}

add5 := adder(5)
nine := add5(4)    // == 9

Unlike Go, Charlang does not have function declarations. All functions are anonymous functions. So the following code is illegal:

func foo(arg1, arg2) {  // illegal
  return arg1 + arg2
}

Charlang also supports variadic functions:

variadic := func (a, b, ...c) {
  return [a, b, c]
}
variadic(1, 2, 3, 4) // [1, 2, [3, 4]]

variadicClosure := func(a) {
  return func(b, ...c) {
    return [a, b, c]
  }
}
variadicClosure(1)(2, 3, 4) // [1, 2, [3, 4]]

Only the last parameter can be variadic. The following code is illegal:

// illegal, because "a" is variadic and is not the last parameter
illegal := func(...a, b) {}

When calling a function, the number of passing arguments must match that of function definition.

f := func(a, b) {}
f(1, 2, 3)    // RuntimeError: WrongNumArgumentsError

Like Go, you can use ellipsis ... to pass value of array type as its last parameter:

f1 := func(a, b, c) { return a + b + c }
f1(...[1, 2, 3])    // => 6
f1(1, ...[2, 3])    // => 6
f1(1, 2, ...[3])    // => 6
f1(...[1, 2])       // RuntimeError: WrongNumArgumentsError

f2 := func(a, ...b) {}
f2(1)               // valid; a == 1, b == []
f2(1, 2)            // valid; a == 1, b == [2]
f2(1, 2, 3)         // valid; a == 1, b == [2, 3]
f2(...[1, 2, 3])    // valid; a == 1, b == [2, 3]
Type Conversions

Although the type is not directly specified in Charlang, one can use type conversion builtin functions to convert between value types.

s1 := string(1984)    // "1984"
i2 := int("-999")     // -999
f3 := float(-51)      // -51.0
b4 := bool(1)         // true
c5 := char("X")       // 'X'
Order of evaluation

Expressions are evaluated from left to right but in assignments, right hand sideof the assignment is evaluated before left hand side.

a := 1
f := func() {
  a*=10
  return a
}
g := func() {
  a++
  return a
}
h := func() {
  a+=2
  return a
}
d := {}
d[f()] = [g(), h()]
return d    // d == {"40": [2, 4]}
Operators
Unary Operators
Operator Operation Types(Results)
+ 0 + x int(int), uint(uint), char(char), float(float), bool(int)
- 0 - x int(int), uint(uint), char(int), float(float), bool(int)
^ bitwise complement ^x int(int), uint(uint), char(char), bool(int)
! logical NOT all types*

* In Charlang, all values can be either truthy or falsy.

Binary Operators
Operator Usage
== equal
!= not equal
&& logical AND
|| logical OR
+ add/concat
- subtract
* multiply
/ divide
& bitwise AND
| bitwise OR
^ bitwise XOR
&^ bitclear (AND NOT)
<< shift left
>> shift right
< less than
<= less than or equal to
> greater than
>= greater than or equal to
Ternary Operators

Charlang has a ternary conditional operator (condition expression) ? (true expression) : (false expression).

a := true ? 1 : -1    // a == 1

min := func(a, b) {
  return a < b ? a : b
}
b := min(5, 10)      // b == 5
Assignment and Increment Operators
Operator Usage
+= (lhs) = (lhs) + (rhs)
-= (lhs) = (lhs) - (rhs)
*= (lhs) = (lhs) * (rhs)
/= (lhs) = (lhs) / (rhs)
%= (lhs) = (lhs) % (rhs)
&= (lhs) = (lhs) & (rhs)
|= (lhs) = (lhs) | (rhs)
&^= (lhs) = (lhs) &^ (rhs)
^= (lhs) = (lhs) ^ (rhs)
<<= (lhs) = (lhs) << (rhs)
>>= (lhs) = (lhs) >> (rhs)
++ (lhs) = (lhs) + 1
-- (lhs) = (lhs) - 1
Operator Precedences

Unary operators have the highest precedence, and, ternary operator has the lowest precedence. There are five precedence levels for binary operators. Multiplication operators bind strongest, followed by addition operators, comparison operators, && (logical AND), and finally || (logical OR):

Precedence Operator
5 * / % << >> & &^
4 + - | ^
3 == != < <= > >=
2 &&
1 ||

Like Go, ++ and -- operators form statements, not expressions, they fall outside the operator hierarchy.

Selector and Indexer

One can use selector (.) and indexer ([]) operators to read or write elements of composite types (array, map, string, bytes).

["one", "two", "three"][1]  // == "two"

bytes(0, 1, 2, 3)[1]    // == 1

// Like Go, indexing string returns byte value of index as int value.
"foobarbaz"[4]    // == 97

m := {
  a: 1,
  b: [2, 3, 4],
  c: func() { return 10 }
}
m.a              // == 1
m["b"][1]        // == 3
m.c()            // == 10
m.x.y.z          // == undefined
m.x.y.z = 1      // RuntimeError: NotIndexAssignableError
m.x = 5          // add 'x' to map 'm'

Like Go, one can use slice operator [:] for sequence value types such as array, string, bytes. Negative indexes are illegal.

a := [1, 2, 3, 4, 5][1:3]    // == [2, 3]
b := [1, 2, 3, 4, 5][3:]     // == [4, 5]
c := [1, 2, 3, 4, 5][:3]     // == [1, 2, 3]
d := "hello world"[2:10]     // == "llo worl"
e := [1, 2, 3, 4, 5][:]      // == [1, 2, 3, 4, 5]
f := [1, 2, 3, 4, 5][-1:]    // RuntimeError: InvalidIndexError
g := [1, 2, 3, 4, 5][10:]    // RuntimeError: IndexOutOfBoundsError

Note: Keywords cannot be used as selectors.

a := {}
a.func = ""     // Parse Error: expected selector, found 'func'

Use double quotes and indexer to use keywords with maps.

a := {}
a["func"] = ""
Statements
If Statement

"If" statement is very similar to Go.

if a < 0 {
  // execute if 'a' is negative
} else if a == 0 {
  // execute if 'a' is zero
} else {
  // execute if 'a' is positive
}

Like Go, the condition expression may be preceded by a simple statement, which executes before the expression is evaluated.

if a := foo(); a < 0 {
  // execute if 'a' is negative
}
For Statement

"For" statement is very similar to Go.

// for (init); (condition); (post) {}
for a:=0; a<10; a++ {
  // ...
}

// for (condition) {}
for a < 10 {
  // ...
}

// for {}
for {
  // ...
}
For-In Statement

It's similar to Go's for range statement. "For-In" statement can iterate any iterable value types (array, map, bytes, string).

for v in [1, 2, 3] {          // array: element
  // 'v' is array element value
}
for i, v in [1, 2, 3] {       // array: index and element
  // 'i' is index
  // 'v' is array element value
}
for k, v in {k1: 1, k2: 2} {  // map: key and value
  // 'k' is key
  // 'v' is map element value
}
for i, v in "foo" {           // array: index and element
  // 'i' is index
  // 'v' is char
}
Modules

Module is the basic compilation unit in Charlang. A module can import another module using import expression. There 3 types of modules. Source modules, builtin modules and custom modules. Source module is in the form Charlang code. Builtin module type is map[string]Object. Lastly, any value implementing Go Importable interface can be a module. Import method must return a valid Charlang Object or []byte. Source module is called like a compiled function and returned value is stored for future use. Other module values are copied while importing in VM if Copier interface is implemented.

type Importable interface {
  Import(moduleName string) (interface{}, error)
}
type Copier interface {
  Copy() Object
}

Main module:

sum := import("sum")    // load a module
println(sum(10))        // module function

Source module as sum:

base := 5

return func(x) {
  return x + base
}

In Charlang, modules are very similar to functions.

  • import expression loads the module code and execute it like a function.
  • Module should return a value using return statement.
    • Module can return a value of any types: int, map, function, etc.
    • return in a module stops execution and return a value to the importing code.
    • If the module does not have any return statement, import expression simply returns undefined. (Just like the function that has no return.)
  • importing same module multiple times at different places or in different modules returns the same object so it preserves the state of imported object.
  • Arguments cannot be provided to source modules while importing although it is allowed to use param statement in module.
  • Modules can use global statements to access globally shared object.
Differences from Go

Unlike Go, Charlang does not have the following:

  • Imaginary values
  • Structs
  • Pointers
  • Channels
  • Goroutines
  • Tuple assignment (Charlang supports destructuring array)
  • Switch statement
  • Goto statement
  • Defer statement
  • Panic and recover
  • Type assertion
Interfaces

Charlang types implement Object interface. Any Go type implementing Object interface can be provided to Charlang VM.

Object interface

// Object represents an object in the VM.
type Object interface {
  // TypeName should return the name of the type.
  TypeName() string

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

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

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

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

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

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

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

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

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

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

If an object's CanIterate method returns true, its Iterate method must return a value implementing Iterator interface to use in for-in loops.

// Iterator wraps the methods required to iterate Objects in VM.
type Iterator interface {
  // Next returns true if there are more elements to iterate.
  Next() bool

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

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

Assignments to Charlang values copy the values except array, map or bytes like Go. copy builtin function returns the copy of a value if Copier interface is implemented by object. If not implemented, same object is returned which copies the value under the hood by Go.

// Copier wraps the Copy method to create a deep copy of an object.
type Copier interface {
  Copy() Object
}
IndexDeleter interface

delete builtin checks if the given object implements IndexDeleter interface to delete an element from the object. map and syncMap implement this interface.

// IndexDeleter wraps the IndexDelete method to delete an index of an object.
type IndexDeleter interface {
    IndexDelete(Object) error
}
LengthGetter interface

len builtin checks if the given object implements IndexDeleter interface to get the length of an object. array, bytes, string, map and syncMap implement this interface.

// LengthGetter wraps the Len method to get the number of elements of an object.
type LengthGetter interface {
    Len() int
}
Object Interface Extensions

Note that ExCallerObject will replace the existing Object interface in the uture.

// ExCallerObject is an interface for objects that can be called with CallEx
// method. It is an extended version of the Call method that can be used to
// call an object with a Call struct. Objects implementing this interface is
// called with CallEx method instead of Call method.
// Note that CanCall() should return true for objects implementing this
// interface.
type ExCallerObject interface {
    Object
    CallEx(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 NameCallerObject interface {
    Object
    CallName(name string, c Call) (Object, error)
}

Documentation

Index

Constants

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

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

Variables

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

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

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

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

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

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

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

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

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

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

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

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

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

	// ErrType represents a type error.
	ErrType = &Error{Name: "TypeError"}
)
View Source
var BigFloatZero = big.NewFloat(0)
View Source
var BigIntZero = big.NewInt(0)
View Source
var BuiltinCharCodeFunc = builtinCharCodeFunc
View Source
var BuiltinObjects = [...]Object{}/* 481 elements not displayed */

BuiltinObjects is list of builtins, exported for REPL.

View Source
var BuiltinsMap = map[string]BuiltinType{}/* 535 elements not displayed */

BuiltinsMap is list of builtin types, exported for REPL.

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

OpcodeNames are string representation of opcodes.

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

OpcodeOperands is the number of operands.

View Source
var (
	// PrintWriter is the default writer for printf and println builtins.
	PrintWriter io.Writer = os.Stdout
)
View Source
var RandomGeneratorG *tk.RandomX = nil
View Source
var RegiCountG int = 30
View Source
var ServerModeG = false
View Source
var StatusResultFail = StatusResult{Status: "fail", Value: ""}
View Source
var StatusResultInvalid = StatusResult{Status: "", Value: ""}
View Source
var StatusResultSuccess = StatusResult{Status: "success", Value: ""}
View Source
var VerboseG = false
View Source
var VersionG = "1.7.9"

global vars

Functions

func AnysToOriginal

func AnysToOriginal(aryA []Object) []interface{}

func ConvertFromObject

func ConvertFromObject(vA Object) interface{}

func DownloadStringFromSSH

func DownloadStringFromSSH(sshA string, filePathA string) string

func FormatInstructions

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

FormatInstructions returns string representation of bytecode instructions.

func FromStringObject

func FromStringObject(argA String) string

func GetCfgString

func GetCfgString(fileNameA string) string

func GetMagic

func GetMagic(numberA int) string

func GetSwitchFromObjects

func GetSwitchFromObjects(argsA []Object, switchA string, defaultA string) string

func IfSwitchExistsInObjects

func IfSwitchExistsInObjects(argsA []Object, switchA string) bool

func IsUndefInternal

func IsUndefInternal(o Object) bool

func IterateInstructions

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

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

func MakeInstruction

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

MakeInstruction returns a bytecode for an Opcode and the operands.

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

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

Warning: Unknown Opcode causes panic!

func NewChar

func NewChar(codeA string) (interface{}, error)

func ObjectsToBytes

func ObjectsToBytes(aryA []Object) []byte

func ObjectsToI

func ObjectsToI(aryA []Object) []interface{}

func ObjectsToN

func ObjectsToN(aryA []Object) []int

func ObjectsToO

func ObjectsToO(aryA []Object) []interface{}

func ObjectsToS

func ObjectsToS(aryA []Object) []string

func QuickCompile

func QuickCompile(codeA string, compilerOptionsA ...*CompilerOptions) interface{}

func QuickRun

func QuickRun(codeA interface{}, globalsA map[string]interface{}, additionsA ...Object) interface{}

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 RunAsFunc

func RunAsFunc(codeA interface{}, argsA ...interface{}) interface{}

func RunCharCode

func RunCharCode(codeA string, envA map[string]interface{}, paraMapA map[string]string, argsA ...Object) (interface{}, error)

func RunScriptOnHttp

func RunScriptOnHttp(codeA string, compilerOptionsA *CompilerOptions, res http.ResponseWriter, req *http.Request, inputA string, argsA []string, parametersA map[string]string, globalsA map[string]interface{}, optionsA ...string) (string, error)

func SetCfgString

func SetCfgString(fileNameA string, strA string) string

func ToFloatQuick

func ToFloatQuick(o Object) float64

func ToGoBool

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

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

func ToGoByteSlice

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

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

func ToGoFloat64

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

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

func ToGoInt

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

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

func ToGoInt64

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

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

func ToGoIntWithDefault

func ToGoIntWithDefault(o Object, defaultA int) int

func ToGoRune

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

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

func ToGoString

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

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

func ToGoUint64

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

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

func ToIntQuick

func ToIntQuick(o Object) int

func ToInterface

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

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

Types

type Any

type Any struct {
	ObjectImpl
	Value        interface{}
	OriginalType string
	OriginalCode int

	Members map[string]Object `json:"-"`
}

Any represents container object and implements the Object interfaces. Any is used to hold some data which is not an Object in Charlang, such as structured data from Golang function call

func NewAny

func NewAny(vA interface{}, argsA ...string) *Any

func (*Any) BinaryOp

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

BinaryOp implements Object interface.

func (*Any) Call

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

Call implements Object interface.

func (*Any) CallMethod

func (o *Any) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*Any) CallName

func (o *Any) CallName(nameA string, c Call) (Object, error)

func (*Any) CanCall

func (*Any) CanCall() bool

CanCall implements Object interface.

func (*Any) CanIterate

func (*Any) CanIterate() bool

CanIterate implements Object interface.

func (*Any) Copy

func (o *Any) Copy() Object

Copy implements Copier interface.

func (*Any) Equal

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

Equal implements Object interface.

func (*Any) GetMember

func (o *Any) GetMember(idxA string) Object

func (*Any) GetValue

func (o *Any) GetValue() Object

func (*Any) HasMemeber

func (o *Any) HasMemeber() bool

func (*Any) IndexGet

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

IndexGet implements Object interface.

func (*Any) IndexSet

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

IndexSet implements Object interface.

func (*Any) IsFalsy

func (o *Any) IsFalsy() bool

IsFalsy implements Object interface.

func (*Any) Iterate

func (*Any) Iterate() Iterator

Iterate implements Object interface.

func (*Any) SetMember

func (o *Any) SetMember(idxA string, valueA Object) error

func (*Any) SetValue

func (o *Any) SetValue(valueA Object) error

func (*Any) String

func (o *Any) String() string

String implements Object interface.

func (*Any) TypeCode

func (o *Any) TypeCode() int

func (*Any) TypeName

func (*Any) TypeName() string

TypeName implements Object interface.

type Array

type Array []Object

Array represents array of objects and implements Object interface.

func ToArray

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

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

func (Array) BinaryOp

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

BinaryOp implements Object interface.

func (Array) Call

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

Call implements Object interface.

func (Array) CallMethod

func (o Array) CallMethod(nameA string, argsA ...Object) (Object, error)

func (Array) CanCall

func (Array) CanCall() bool

CanCall implements Object interface.

func (Array) CanIterate

func (Array) CanIterate() bool

CanIterate implements Object interface.

func (Array) Copy

func (o Array) Copy() Object

Copy implements Copier interface.

func (Array) Equal

func (o Array) Equal(right Object) bool

Equal implements Object interface.

func (Array) GetMember

func (o Array) GetMember(idxA string) Object

func (Array) GetValue

func (o Array) GetValue() Object

func (Array) HasMemeber

func (o Array) HasMemeber() bool

func (Array) IndexGet

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

IndexGet implements Object interface.

func (Array) IndexSet

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

IndexSet implements Object interface.

func (Array) IsFalsy

func (o Array) IsFalsy() bool

IsFalsy implements Object interface.

func (Array) Iterate

func (o Array) Iterate() Iterator

Iterate implements Iterable interface.

func (Array) Len

func (o Array) Len() int

Len implements LengthGetter interface.

func (Array) SetMember

func (o Array) SetMember(idxA string, valueA Object) error

func (Array) String

func (o Array) String() string

String implements Object interface.

func (Array) TypeCode

func (Array) TypeCode() int

func (Array) TypeName

func (Array) TypeName() string

TypeName implements Object interface.

type ArrayIterator

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

ArrayIterator represents an iterator for the array.

func (*ArrayIterator) Key

func (it *ArrayIterator) Key() Object

Key implements Iterator interface.

func (*ArrayIterator) Next

func (it *ArrayIterator) Next() bool

Next implements Iterator interface.

func (*ArrayIterator) Value

func (it *ArrayIterator) Value() Object

Value implements Iterator interface.

type BigFloat

type BigFloat struct {
	Value *big.Float

	Members map[string]Object `json:"-"`
}

BigFloat represents large signed float values and implements Object interface.

func (*BigFloat) BinaryOp

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

func (*BigFloat) Call

func (o *BigFloat) Call(_ ...Object) (Object, error)

func (*BigFloat) CallMethod

func (o *BigFloat) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*BigFloat) CanCall

func (o *BigFloat) CanCall() bool

func (*BigFloat) CanIterate

func (*BigFloat) CanIterate() bool

func (*BigFloat) Equal

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

func (*BigFloat) GetMember

func (o *BigFloat) GetMember(idxA string) Object

func (*BigFloat) GetValue

func (o *BigFloat) GetValue() Object

func (*BigFloat) HasMemeber

func (o *BigFloat) HasMemeber() bool

func (*BigFloat) IndexGet

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

func (*BigFloat) IndexSet

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

func (*BigFloat) IsFalsy

func (o *BigFloat) IsFalsy() bool

func (*BigFloat) Iterate

func (*BigFloat) Iterate() Iterator

func (*BigFloat) SetMember

func (o *BigFloat) SetMember(idxA string, valueA Object) error

func (*BigFloat) SetValue

func (o *BigFloat) SetValue(valueA Object) error

func (*BigFloat) String

func (o *BigFloat) String() string

func (*BigFloat) TypeCode

func (*BigFloat) TypeCode() int

func (*BigFloat) TypeName

func (*BigFloat) TypeName() string

type BigInt

type BigInt struct {
	Value *big.Int

	Members map[string]Object `json:"-"`
}

BigInt represents large signed integer values and implements Object interface.

func (*BigInt) BinaryOp

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

func (*BigInt) Call

func (o *BigInt) Call(_ ...Object) (Object, error)

func (*BigInt) CallMethod

func (o *BigInt) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*BigInt) CanCall

func (o *BigInt) CanCall() bool

func (*BigInt) CanIterate

func (*BigInt) CanIterate() bool

func (*BigInt) Equal

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

func (*BigInt) GetMember

func (o *BigInt) GetMember(idxA string) Object

func (*BigInt) GetValue

func (o *BigInt) GetValue() Object

func (*BigInt) HasMemeber

func (o *BigInt) HasMemeber() bool

func (*BigInt) IndexGet

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

func (*BigInt) IndexSet

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

func (*BigInt) IsFalsy

func (o *BigInt) IsFalsy() bool

func (*BigInt) Iterate

func (*BigInt) Iterate() Iterator

func (*BigInt) SetMember

func (o *BigInt) SetMember(idxA string, valueA Object) error

func (*BigInt) SetValue

func (o *BigInt) SetValue(valueA Object) error

func (*BigInt) String

func (o *BigInt) String() string

func (*BigInt) TypeCode

func (*BigInt) TypeCode() int

func (*BigInt) TypeName

func (*BigInt) TypeName() string

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 Charlang bool value.

func (Bool) BinaryOp

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

BinaryOp implements Object interface.

func (Bool) Call

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

Call implements Object interface.

func (Bool) CallMethod

func (o Bool) CallMethod(nameA string, argsA ...Object) (Object, error)

func (Bool) CanCall

func (Bool) CanCall() bool

CanCall implements Object interface.

func (Bool) CanIterate

func (Bool) CanIterate() bool

CanIterate implements Object interface.

func (Bool) Equal

func (o Bool) Equal(right Object) bool

Equal implements Object interface.

func (Bool) Format

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

Format implements fmt.Formatter interface.

func (Bool) GetMember

func (o Bool) GetMember(idxA string) Object

func (Bool) GetValue

func (o Bool) GetValue() Object

func (Bool) HasMemeber

func (o Bool) HasMemeber() bool

func (Bool) IndexGet

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

IndexGet implements Object interface.

func (Bool) IndexSet

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

IndexSet implements Object interface.

func (Bool) IsFalsy

func (o Bool) IsFalsy() bool

IsFalsy implements Object interface.

func (Bool) Iterate

func (Bool) Iterate() Iterator

Iterate implements Object interface.

func (Bool) SetMember

func (o Bool) SetMember(idxA string, valueA Object) error

func (Bool) String

func (o Bool) String() string

String implements Object interface.

func (Bool) TypeCode

func (Bool) TypeCode() int

func (Bool) TypeName

func (Bool) TypeName() string

TypeName implements Object interface.

type BuiltinFunction

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

	Members map[string]Object `json:"-"`
	Methods map[string]*Function

	Remark string
}

BuiltinFunction represents a builtin function object and implements Object interface.

func (*BuiltinFunction) Call

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

Call implements Object interface.

func (*BuiltinFunction) CallEx

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

func (*BuiltinFunction) CallMethod

func (o *BuiltinFunction) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*BuiltinFunction) CanCall

func (*BuiltinFunction) CanCall() bool

CanCall implements Object interface.

func (*BuiltinFunction) Copy

func (o *BuiltinFunction) Copy() Object

Copy implements Copier interface.

func (*BuiltinFunction) Equal

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

Equal implements Object interface.

func (*BuiltinFunction) GetMember

func (o *BuiltinFunction) GetMember(idxA string) Object

func (*BuiltinFunction) GetValue

func (o *BuiltinFunction) GetValue() Object

func (*BuiltinFunction) HasMemeber

func (o *BuiltinFunction) HasMemeber() bool

func (*BuiltinFunction) IndexGet

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

func (*BuiltinFunction) IsFalsy

func (o *BuiltinFunction) IsFalsy() bool

IsFalsy implements Object interface.

func (*BuiltinFunction) SetMember

func (o *BuiltinFunction) SetMember(idxA string, valueA Object) error

func (*BuiltinFunction) String

func (o *BuiltinFunction) String() string

String implements Object interface.

func (*BuiltinFunction) TypeCode

func (*BuiltinFunction) TypeCode() int

func (*BuiltinFunction) TypeName

func (*BuiltinFunction) TypeName() string

TypeName implements Object interface.

type BuiltinModule

type BuiltinModule struct {
	Attrs map[string]Object
}

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

func (*BuiltinModule) Import

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

Import returns an immutable map for the module.

type BuiltinType

type BuiltinType int

BuiltinType represents a builtin type

const (
	BuiltinAppend BuiltinType = iota

	BuiltinReset
	BuiltinStatusToStr
	BuiltinStatusToMap
	BuiltinDocxToStrs
	BuiltinGuiServerCommand
	BuiltinGetMapItem
	BuiltinSetMapItem
	BuiltinSendMail
	BuiltinGetTextSimilarity
	BuiltinLeSshInfo
	BuiltinStack
	BuiltinQueue
	BuiltinMapArray
	BuiltinPlotClearConsole
	BuiltinPlotDataToStr
	BuiltinPlotDataToImage
	BuiltinPlotLoadFont
	BuiltinResizeImage
	BuiltinImageToAscii
	BuiltinLoadImageFromFile
	BuiltinSaveImageToFile
	BuiltinGetImageInfo
	BuiltinStrToRgba
	BuiltinEncodeImage
	BuiltinEncodeBytesInImage
	BuiltinDecodeBytesFromImage
	BuiltinDrawImageOnImage
	BuiltinDrawTextWrappedOnImage
	BuiltinGenQr
	BuiltinSaveImageToBytes
	BuiltinClose
	BuiltinRegSplit
	BuiltinReadCsv
	BuiltinExcelNew
	BuiltinExcelOpen
	BuiltinExcelOpenFile
	BuiltinExcelSaveAs
	BuiltinExcelWriteTo
	BuiltinExcelClose
	BuiltinExcelNewSheet
	BuiltinExcelReadAll
	BuiltinExcelGetSheetCount
	BuiltinExcelGetSheetList
	BuiltinExcelGetSheetName
	BuiltinExcelReadSheet
	BuiltinExcelReadCell
	BuiltinExcelWriteSheet
	BuiltinExcelWriteCell
	BuiltinWriteCsv
	BuiltinRemovePath
	BuiltinRemoveDir
	BuiltinGetInput
	BuiltinGetInputf
	BuiltinGetChar
	BuiltinSetStdin
	BuiltinSetStdout
	BuiltinSetStderr
	BuiltinGetPipe
	BuiltinRegCount
	BuiltinStrRepeat
	BuiltinRegMatch
	BuiltinRegContains
	BuiltinRegContainsIn
	BuiltinLePrint
	BuiltinLeFindLines
	BuiltinLeFind
	BuiltinLeFindAll
	BuiltinLeReplace
	BuiltinLeLoadFromSsh
	BuiltinLeSaveToSsh
	BuiltinLeRemoveLine
	BuiltinLeRemoveLines
	BuiltinLeInsertLine
	BuiltinLeAppendLine
	BuiltinLeGetLine
	BuiltinLeSetLine
	BuiltinLeSetLines
	BuiltinLeConvertToUtf8
	BuiltinLeSort
	BuiltinLeViewAll
	BuiltinLeViewLine
	BuiltinLeViewLines
	BuiltinLeLoadFromUrl
	BuiltinLeLoadFromClip
	BuiltinLeSaveToClip
	BuiltinLeAppendFromFile
	BuiltinLeAppendToFile
	BuiltinLeLoadFromFile
	BuiltinLeSaveToFile
	BuiltinLeLoadFromStr
	BuiltinLeSaveToStr
	BuiltinLeGetList
	BuiltinLeAppendFromStr
	BuiltinLeClear
	BuiltinS3GetObjectBytes
	BuiltinS3GetObjectText
	BuiltinS3PutObject
	BuiltinS3GetObjectToFile
	BuiltinS3GetObjectReader
	BuiltinS3GetObjectUrl
	BuiltinS3GetObjectTags
	BuiltinS3GetObjectStat
	BuiltinS3StatObject
	BuiltinS3CopyObject
	BuiltinS3MoveObject
	BuiltinS3RemoveObject
	BuiltinS3ListObjects
	BuiltinAwsSign
	BuiltinNow
	BuiltinTimeToTick
	BuiltinFormatTime
	BuiltinTimeAddSecs
	BuiltinTimeAddDate
	BuiltinTimeBefore
	BuiltinGetNowTimeStamp
	BuiltinBase64Encode
	BuiltinBase64Decode
	BuiltinXmlGetNodeStr
	BuiltinStrXmlEncode
	BuiltinFromXml
	BuiltinFormatXml
	BuiltinMd5
	BuiltinPostRequest
	BuiltinHttpRedirect
	BuiltinReader
	BuiltinWriter
	BuiltinFile
	BuiltinBytesBuffer
	BuiltinImage
	BuiltinLoadImageFromBytes
	BuiltinThumbImage
	BuiltinBytesStartsWith
	BuiltinBytesEndsWith
	BuiltinBytesContains
	BuiltinBytesIndex
	BuiltinIsEncrypted
	BuiltinEncryptData
	BuiltinDecryptData
	BuiltinEncryptStream
	BuiltinDecryptStream
	BuiltinSimpleEncode
	BuiltinSimpleDecode
	BuiltinToPinYin
	BuiltinKanjiToKana
	BuiltinKanaToRomaji
	BuiltinKanjiToRomaji
	BuiltinIsHttps
	BuiltinCopyFile
	BuiltinRenameFile
	BuiltinStrJoin
	BuiltinStrCount
	BuiltinStrPad
	BuiltinStrRuneLen
	BuiltinStrIn
	BuiltinStrGetLastComponent
	BuiltinEnsureMakeDirs
	BuiltinExtractFileDir
	BuiltinExtractFileName
	BuiltinCheckToken
	BuiltinGetOtpCode
	BuiltinCheckOtpCode
	BuiltinEncryptText
	BuiltinDecryptText
	BuiltinEncryptTextByTXTE
	BuiltinDecryptTextByTXTE
	BuiltinAesEncrypt
	BuiltinAesDecrypt
	BuiltinHtmlEncode
	BuiltinHtmlDecode
	BuiltinServeFile
	BuiltinGetFileInfo
	BuiltinGetFileAbs
	BuiltinGetFileRel
	BuiltinGetFileExt
	BuiltinGetMimeType
	BuiltinStartSocksServer
	BuiltinStartSocksClient
	BuiltinStartTransparentProxy
	BuiltinStartTransparentProxyEx
	BuiltinRenderMarkdown
	BuiltinReplaceHtmlByMap
	BuiltinProcessHtmlTemplate
	BuiltinIsDir
	BuiltinStrStartsWith
	BuiltinStrEndsWith
	BuiltinStrSplit
	BuiltinStrSplitN
	BuiltinGenToken
	BuiltinStrContains
	BuiltinStrContainsAny
	BuiltinStrContainsIn
	BuiltinStrIndex
	BuiltinGetNowStr
	BuiltinGetNowStrCompact
	BuiltinLock
	BuiltinUnlock
	BuiltinTryLock
	BuiltinRLock
	BuiltinRUnlock
	BuiltinTryRLock
	BuiltinToKMG
	BuiltinFloatToStr
	BuiltinGetFileList
	BuiltinMathAbs
	BuiltinMathSqrt
	BuiltinMathPow
	BuiltinMathExp
	BuiltinMathLog
	BuiltinMathLog10
	BuiltinMathMin
	BuiltinMathMax
	BuiltinMathCeil
	BuiltinMathFloor
	BuiltinMathRound
	BuiltinFlexEval
	BuiltinAdjustFloat
	BuiltinBigInt
	BuiltinBigFloat
	BuiltinToOrderedMap
	BuiltinUnhex
	BuiltinHexToStr
	BuiltinBitNot
	BuiltinToUpper
	BuiltinToLower
	BuiltinSscanf
	BuiltinStrQuote
	BuiltinStrUnquote
	BuiltinStrToInt
	BuiltinStrToTime
	BuiltinDealStr
	BuiltinToInt
	BuiltinToBool
	BuiltinToBoolWithDefault
	BuiltinToFloat
	BuiltinToHex
	BuiltinCompareBytes
	BuiltinLoadBytes
	BuiltinLoadBytesFromFile
	BuiltinSaveBytes
	BuiltinOpenFile
	BuiltinCloseFile
	BuiltinCompressData
	BuiltinCompressStr
	BuiltinUncompressData
	BuiltinUncompressStr
	BuiltinUrlEncode
	BuiltinUrlEncode1
	BuiltinUrlDecode
	BuiltinOrderedMap
	BuiltinExcel
	BuiltinArrayContains
	BuiltinSortArray
	// BuiltinSortByFunc
	BuiltinLimitStr
	BuiltinStrFindDiffPos
	BuiltinStrFindAllSub
	BuiltinRemoveItems
	BuiltinAppendList
	BuiltinGetRandomInt
	BuiltinGetRandomFloat
	BuiltinGetRandomStr
	BuiltinFormatSQLValue
	BuiltinDbClose
	BuiltinDbQuery
	BuiltinDbQueryOrdered
	BuiltinDbQueryRecs
	BuiltinDbQueryMap
	BuiltinDbQueryMapArray
	BuiltinDbQueryCount
	BuiltinDbQueryFloat
	BuiltinDbQueryString
	BuiltinDbExec
	BuiltinRemoveFile
	BuiltinFileExists
	BuiltinGenJSONResp
	BuiltinUrlExists
	BuiltinParseUrl
	BuiltinParseQuery
	BuiltinErrStrf
	BuiltinErrf
	BuiltinCharCode
	BuiltinEvalMachine
	BuiltinGel
	BuiltinDelegate
	BuiltinGetReqBody
	BuiltinGetReqHeader
	BuiltinWriteRespHeader
	BuiltinSetRespHeader
	BuiltinParseReqForm
	BuiltinParseReqFormEx
	BuiltinWriteResp
	BuiltinMux
	BuiltinMutex
	BuiltinHttpHandler
	BuiltinHttpReq
	BuiltinFatalf
	BuiltinSeq
	BuiltinIsNil
	BuiltinIsNilOrEmpty
	BuiltinIsNilOrErr
	BuiltinGetValue
	BuiltinSetValue
	BuiltinGetMember
	BuiltinSetMember
	BuiltinCallMethod
	BuiltinDumpVar
	BuiltinDebugInfo
	BuiltinMake
	BuiltinDatabase
	BuiltinStatusResult
	BuiltinUnref
	BuiltinSetValueByRef
	BuiltinGetWeb
	BuiltinGetWebBytes
	BuiltinGetWebBytesWithHeaders
	BuiltinGetWebRespBody
	BuiltinRegFindFirstGroups
	BuiltinReadAllStr
	BuiltinReadAllBytes
	BuiltinReadBytes
	BuiltinWriteStr
	BuiltinWriteBytes
	BuiltinWriteBytesAt
	BuiltinIoCopy
	BuiltinStrSplitLines
	BuiltinNew
	BuiltinStringBuilder
	BuiltinStrReplace
	BuiltinGetErrStrX
	BuiltinFtpList
	BuiltinFtpCreateDir
	BuiltinFtpSize
	BuiltinFtpUpload
	BuiltinFtpUploadFromReader
	BuiltinSshUpload
	BuiltinSshUploadBytes
	BuiltinSshDownload
	BuiltinSshRun
	BuiltinArchiveFilesToZip
	BuiltinGetOSName
	BuiltinGetOSArch
	BuiltinGetOSArgs
	BuiltinGetAppDir
	BuiltinGetCurDir
	BuiltinGetHomeDir
	BuiltinGetTempDir
	BuiltinChangeDir
	BuiltinLookPath
	BuiltinGetClipText
	BuiltinSetClipText
	BuiltinRegQuote
	BuiltinRegReplace
	BuiltinAny
	BuiltinTrim
	BuiltinStrTrim
	BuiltinStrTrimStart
	BuiltinStrTrimEnd
	BuiltinStrTrimLeft
	BuiltinStrTrimRight
	BuiltinRegFindFirst
	BuiltinRegFindAll
	BuiltinRegFindAllIndex
	BuiltinRegFindAllGroups
	BuiltinCheckErrX
	BuiltinCheckEmpty
	BuiltinLoadText
	BuiltinSaveText
	BuiltinAppendText
	BuiltinJoinPath
	BuiltinGetEnv
	BuiltinSetEnv
	BuiltinTypeOfAny
	BuiltinToStr
	BuiltinCallNamedFunc
	BuiltinCallInternalFunc
	BuiltinGetProcessVar
	BuiltinSetProcessVar
	BuiltinDeleteProcessVar
	BuiltinGetNamedValue
	BuiltinNewEx
	BuiltinCallMethodEx
	BuiltinToTime
	// BuiltinNewAny
	BuiltinTime
	BuiltinSleep
	BuiltinExit
	BuiltinSystemCmd
	BuiltinSystemCmdDetached
	BuiltinSystemStart
	BuiltinIsErrX
	BuiltinIsErrStr
	BuiltinToJSON
	BuiltinFromJSON
	BuiltinFormatJson
	BuiltinCompactJson
	BuiltinGetJsonNodeStr
	BuiltinGetJsonNodeStrs
	BuiltinStrsToJson
	BuiltinPlo
	BuiltinPlt
	BuiltinPlErr
	BuiltinGetParam
	BuiltinGetParams
	BuiltinGetSwitch
	BuiltinGetSwitches
	BuiltinGetIntSwitch
	BuiltinIfSwitchExists
	BuiltinTypeCode
	BuiltinTypeName
	BuiltinPl
	BuiltinPr
	BuiltinPrf
	BuiltinFprf
	BuiltinPlNow
	BuiltinPln
	BuiltinPlv
	BuiltinSpr
	BuiltinSpln
	BuiltinTestByText
	BuiltinTestByStartsWith
	BuiltinTestByEndsWith
	BuiltinTestByContains
	BuiltinTestByRegContains
	BuiltinTestByReg
	BuiltinGetSeq
	BuiltinMagic
	BuiltinGetUuid
	BuiltinPass

	BuiltinDelete
	BuiltinGetArrayItem
	BuiltinCopy
	BuiltinCopyBytes
	BuiltinRepeat
	BuiltinContains
	BuiltinLen
	BuiltinSort
	BuiltinSortReverse
	BuiltinError
	BuiltinBool
	BuiltinInt
	BuiltinUint
	BuiltinFloat
	BuiltinChar
	BuiltinByte
	BuiltinString
	BuiltinMutableString
	BuiltinBytes
	BuiltinBytesWithSize
	BuiltinBytesWithCap
	BuiltinChars
	BuiltinPrintf
	BuiltinPrintln
	BuiltinSprintf
	BuiltinGlobals

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

	BuiltinWrongNumArgumentsError
	BuiltinInvalidOperatorError
	BuiltinIndexOutOfBoundsError
	BuiltinNotIterableError
	BuiltinNotIndexableError
	BuiltinNotIndexAssignableError
	BuiltinNotCallableError
	BuiltinNotImplementedError
	BuiltinZeroDivisionError
	BuiltinTypeError

	BuiltinMakeArray
	BuiltinCap
)

Builtins

type Byte

type Byte byte

func (Byte) BinaryOp

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

BinaryOp implements Object interface.

func (Byte) Call

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

Call implements Object interface.

func (Byte) CallMethod

func (o Byte) CallMethod(nameA string, argsA ...Object) (Object, error)

func (Byte) CanCall

func (o Byte) CanCall() bool

CanCall implements Object interface.

func (Byte) CanIterate

func (Byte) CanIterate() bool

CanIterate implements Object interface.

func (Byte) Equal

func (o Byte) Equal(right Object) bool

Equal implements Object interface.

func (Byte) Format

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

Format implements fmt.Formatter interface.

func (Byte) GetMember

func (o Byte) GetMember(idxA string) Object

func (Byte) GetValue

func (o Byte) GetValue() Object

func (Byte) HasMemeber

func (o Byte) HasMemeber() bool

func (Byte) IndexGet

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

IndexGet implements Object interface.

func (Byte) IndexSet

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

IndexSet implements Object interface.

func (Byte) IsFalsy

func (o Byte) IsFalsy() bool

IsFalsy implements Object interface.

func (Byte) Iterate

func (Byte) Iterate() Iterator

Iterate implements Object interface.

func (Byte) SetMember

func (o Byte) SetMember(idxA string, valueA Object) error

func (Byte) String

func (o Byte) String() string

String implements Object interface.

func (Byte) TypeCode

func (Byte) TypeCode() int

func (Byte) TypeName

func (Byte) TypeName() string

TypeName implements Object interface.

type Bytecode

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

Bytecode holds the compiled functions and constants.

func Compile

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

Compile compiles given script to Bytecode.

func (*Bytecode) Fprint

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

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

func (*Bytecode) String

func (bc *Bytecode) String() string

type Bytes

type Bytes []byte

Bytes represents byte slice and implements Object interface.

func ToBytes

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

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

func (Bytes) BinaryOp

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

BinaryOp implements Object interface.

func (Bytes) Call

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

Call implements Object interface.

func (Bytes) CallMethod

func (o Bytes) CallMethod(nameA string, argsA ...Object) (Object, error)

func (Bytes) CanCall

func (o Bytes) CanCall() bool

CanCall implements Object interface.

func (Bytes) CanIterate

func (Bytes) CanIterate() bool

CanIterate implements Object interface.

func (Bytes) Copy

func (o Bytes) Copy() Object

Copy implements Copier interface.

func (Bytes) Equal

func (o Bytes) Equal(right Object) bool

Equal implements Object interface.

func (Bytes) Format

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

Format implements fmt.Formatter interface.

func (Bytes) GetMember

func (o Bytes) GetMember(idxA string) Object

func (Bytes) GetValue

func (o Bytes) GetValue() Object

func (Bytes) HasMemeber

func (o Bytes) HasMemeber() bool

func (Bytes) IndexGet

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

IndexGet represents string values and implements Object interface.

func (Bytes) IndexSet

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

IndexSet implements Object interface.

func (Bytes) IsFalsy

func (o Bytes) IsFalsy() bool

IsFalsy implements Object interface.

func (Bytes) Iterate

func (o Bytes) Iterate() Iterator

Iterate implements Object interface.

func (Bytes) Len

func (o Bytes) Len() int

Len implements LengthGetter interface.

func (Bytes) SetMember

func (o Bytes) SetMember(idxA string, valueA Object) error

func (Bytes) String

func (o Bytes) String() string

func (Bytes) TypeCode

func (Bytes) TypeCode() int

func (Bytes) TypeName

func (Bytes) TypeName() string

TypeName implements Object interface.

type BytesBuffer

type BytesBuffer struct {
	ObjectImpl
	Value *bytes.Buffer

	Members map[string]Object `json:"-"`
}

func (*BytesBuffer) BinaryOp

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

func (*BytesBuffer) Call

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

func (*BytesBuffer) CallMethod

func (o *BytesBuffer) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*BytesBuffer) CanCall

func (*BytesBuffer) CanCall() bool

func (*BytesBuffer) CanIterate

func (*BytesBuffer) CanIterate() bool

func (*BytesBuffer) Copy

func (o *BytesBuffer) Copy() Object

func (*BytesBuffer) Equal

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

func (*BytesBuffer) GetMember

func (o *BytesBuffer) GetMember(idxA string) Object

func (*BytesBuffer) GetValue

func (o *BytesBuffer) GetValue() Object

func (*BytesBuffer) HasMemeber

func (o *BytesBuffer) HasMemeber() bool

func (*BytesBuffer) IndexGet

func (o *BytesBuffer) IndexGet(index Object) (value Object, err error)

func (*BytesBuffer) IndexSet

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

func (*BytesBuffer) IsFalsy

func (o *BytesBuffer) IsFalsy() bool

func (*BytesBuffer) Iterate

func (*BytesBuffer) Iterate() Iterator

func (*BytesBuffer) SetMember

func (o *BytesBuffer) SetMember(idxA string, valueA Object) error

func (*BytesBuffer) String

func (o *BytesBuffer) String() string

func (*BytesBuffer) TypeCode

func (o *BytesBuffer) TypeCode() int

func (*BytesBuffer) TypeName

func (o *BytesBuffer) TypeName() string

type BytesIterator

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

BytesIterator represents an iterator for the bytes.

func (*BytesIterator) Key

func (it *BytesIterator) Key() Object

Key implements Iterator interface.

func (*BytesIterator) Next

func (it *BytesIterator) Next() bool

Next implements Iterator interface.

func (*BytesIterator) Value

func (it *BytesIterator) Value() Object

Value implements Iterator interface.

type Call

type Call struct {
	Vm    *VM
	This  Object
	Args  []Object
	Vargs []Object
}

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

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

func NewCall

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

NewCall creates a new Call struct with the given arguments.

func (*Call) CheckLen

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

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

func (*Call) Get

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

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

func (*Call) GetArgs

func (c *Call) GetArgs() []Object

func (*Call) Len

func (c *Call) Len() int

Len returns the number of arguments including variadic arguments.

func (*Call) VM

func (c *Call) VM() *VM

VM returns the VM of the call.

type CallableExFunc

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

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

func FnAARAex

func FnAARAex(fn func(interface{}) interface{}) CallableExFunc

func FnAARSex

func FnAARSex(fn func(interface{}) string) CallableExFunc

func FnAARex

func FnAARex(fn func(interface{})) CallableExFunc

func FnAAVaRAex

func FnAAVaRAex(fn func(interface{}, ...interface{}) interface{}) CallableExFunc

func FnAAVaRSex

func FnAAVaRSex(fn func(interface{}, ...interface{}) string) CallableExFunc

func FnADSSVaRAex

func FnADSSVaRAex(fn func(*sql.DB, string, string, ...interface{}) interface{}) CallableExFunc

func FnADSVaRAex

func FnADSVaRAex(fn func(*sql.DB, string, ...interface{}) interface{}) CallableExFunc

func FnAFRFex

func FnAFRFex(fn func(float64) float64) CallableExFunc

func FnAFRSex

func FnAFRSex(fn func(float64) string) CallableExFunc

func FnALbyLbyViRLLiex

func FnALbyLbyViRLLiex(fn func([]byte, []byte, ...int) [][]int) CallableExFunc

func FnALbySREex

func FnALbySREex(fn func([]byte, string) error) CallableExFunc

func FnALsRLsex

func FnALsRLsex(fn func([]string) []string) CallableExFunc

func FnALsSViRIex

func FnALsSViRIex(fn func([]string, string, ...int) int) CallableExFunc

func FnALyARBex

func FnALyARBex(fn func([]byte, interface{}) bool) CallableExFunc

func FnALyARIex

func FnALyARIex(fn func([]byte, interface{}) int) CallableExFunc

func FnALyRBex

func FnALyRBex(fn func([]byte) bool) CallableExFunc

func FnALyVsRAex

func FnALyVsRAex(fn func([]byte, ...string) interface{}) CallableExFunc

func FnALyVsRLyex

func FnALyVsRLyex(fn func([]byte, ...string) []byte) CallableExFunc

func FnARAex

func FnARAex(fn func() interface{}) CallableExFunc

func FnARIex

func FnARIex(fn func() int) CallableExFunc

func FnARLsex

func FnARLsex(fn func() []string) CallableExFunc

func FnARSWREex

func FnARSWREex(fn func(io.Reader, string, io.Writer) error) CallableExFunc

func FnARSex

func FnARSex(fn func() string) CallableExFunc

func FnARTex

func FnARTex(fn func() time.Time) CallableExFunc

func FnARex

func FnARex(fn func()) CallableExFunc

func FnASARex

func FnASARex(fn func(string, interface{})) CallableExFunc

func FnASIRSex

func FnASIRSex(fn func(string, int) string) CallableExFunc

func FnASIVsRSex

func FnASIVsRSex(fn func(string, int, ...string) string) CallableExFunc

func FnASRAex

func FnASRAex(fn func(string) interface{}) CallableExFunc

func FnASRBex

func FnASRBex(fn func(string) bool) CallableExFunc

func FnASREex

func FnASREex(fn func(string) error) CallableExFunc

func FnASRIex

func FnASRIex(fn func(string) int) CallableExFunc

func FnASRLbyex

func FnASRLbyex(fn func(string) []byte) CallableExFunc

func FnASRLsex

func FnASRLsex(fn func(string) []string) CallableExFunc

func FnASRSEex

func FnASRSEex(fn func(string) (string, error)) CallableExFunc

func FnASRSex

func FnASRSex(fn func(string) string) CallableExFunc

func FnASRex

func FnASRex(fn func(string)) CallableExFunc

func FnASSAVaRAex

func FnASSAVaRAex(fn func(string, string, interface{}, ...string) interface{}) CallableExFunc

func FnASSIRLsex

func FnASSIRLsex(fn func(string, string, int) []string) CallableExFunc

func FnASSIRSex

func FnASSIRSex(fn func(string, string, int) string) CallableExFunc

func FnASSRA2Iex

func FnASSRA2Iex(fn func(string, string) [][]int) CallableExFunc

func FnASSRA2Nex

func FnASSRA2Nex(fn func(string, string) [][]int) CallableExFunc

func FnASSRAex

func FnASSRAex(fn func(string, string) interface{}) CallableExFunc

func FnASSRBex

func FnASSRBex(fn func(string, string) bool) CallableExFunc

func FnASSREex

func FnASSREex(fn func(string, string) error) CallableExFunc

func FnASSRFex

func FnASSRFex(fn func(string, string) float64) CallableExFunc

func FnASSRIex

func FnASSRIex(fn func(string, string) int) CallableExFunc

func FnASSRLlsex

func FnASSRLlsex(fn func(string, string) [][]string) CallableExFunc

func FnASSRLsex

func FnASSRLsex(fn func(string, string) []string) CallableExFunc

func FnASSRSEex

func FnASSRSEex(fn func(string, string) (string, error)) CallableExFunc

func FnASSRSex

func FnASSRSex(fn func(string, string) string) CallableExFunc

func FnASSSRSex

func FnASSSRSex(fn func(string, string, string) string) CallableExFunc

func FnASSSVsRSex

func FnASSSVsRSex(fn func(string, string, string, ...string) string) CallableExFunc

func FnASSVIRFex

func FnASSVIRFex(fn func(string, string, ...int) float64) CallableExFunc

func FnASSViRLsex

func FnASSViRLsex(fn func(string, string, ...int) []string) CallableExFunc

func FnASSVsRBex

func FnASSVsRBex(fn func(string, string, ...string) bool) CallableExFunc

func FnASSVsREex

func FnASSVsREex(fn func(string, string, ...string) error) CallableExFunc

func FnASVaRAex

func FnASVaRAex(fn func(string, ...interface{}) interface{}) CallableExFunc

func FnASVaREex

func FnASVaREex(fn func(string, ...interface{}) error) CallableExFunc

func FnASVaRIEex

func FnASVaRIEex(fn func(string, ...interface{}) (int, error)) CallableExFunc

like fmt.printf

func FnASVaRSex

func FnASVaRSex(fn func(string, ...interface{}) string) CallableExFunc

func FnASVaRex

func FnASVaRex(fn func(string, ...interface{})) CallableExFunc

func FnASViRAex

func FnASViRAex(fn func(string, ...int) interface{}) CallableExFunc

func FnASViRIex

func FnASViRIex(fn func(string, ...int) int) CallableExFunc

func FnASVsRAex

func FnASVsRAex(fn func(string, ...string) interface{}) CallableExFunc

func FnASVsRBex

func FnASVsRBex(fn func(string, ...string) bool) CallableExFunc

func FnASVsRLmssex

func FnASVsRLmssex(fn func(string, ...string) []map[string]string) CallableExFunc

func FnASVsRSex

func FnASVsRSex(fn func(string, ...string) string) CallableExFunc

func FnATFRTex

func FnATFRTex(fn func(time.Time, float64) time.Time) CallableExFunc

func FnATIIIRTex

func FnATIIIRTex(fn func(time.Time, int, int, int) time.Time) CallableExFunc

func FnATRSex

func FnATRSex(fn func(time.Time) string) CallableExFunc

func FnATVsRSex

func FnATVsRSex(fn func(time.Time, ...string) string) CallableExFunc

func FnAVaRAex

func FnAVaRAex(fn func(...interface{}) interface{}) CallableExFunc

func FnAVaRIEex

func FnAVaRIEex(fn func(...interface{}) (int, error)) CallableExFunc

func FnAVaRSex

func FnAVaRSex(fn func(...interface{}) string) CallableExFunc

func FnAVaRex

func FnAVaRex(fn func(...interface{})) CallableExFunc

func FnAVsREex

func FnAVsREex(fn func(...string) error) CallableExFunc

func FnAVsRSex

func FnAVsRSex(fn func(...string) string) CallableExFunc

func FnAWSVaRIEex

func FnAWSVaRIEex(fn func(io.Writer, string, ...interface{}) (int, error)) CallableExFunc

func FnAWtRdRI64Eex

func FnAWtRdRI64Eex(fn func(io.Writer, io.Reader) (int64, error)) CallableExFunc

type CallableFunc

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

CallableFunc is a function signature for a callable function.

func CallExAdapter

func CallExAdapter(fn CallableExFunc) CallableFunc

func FnAAR

func FnAAR(fn func(interface{})) CallableFunc

like tk.PlErrX

func FnAARA

func FnAARA(fn func(interface{}) interface{}) CallableFunc

like tk.Ceil

func FnAARS

func FnAARS(fn func(interface{}) string) CallableFunc

like tk.GetErrStrX

func FnAAVaRA

func FnAAVaRA(fn func(interface{}, ...interface{}) interface{}) CallableFunc

like tk.Compress

func FnAAVaRS

func FnAAVaRS(fn func(interface{}, ...interface{}) string) CallableFunc

like tk.ErrStrf

func FnADSSVaRA

func FnADSSVaRA(fn func(*sql.DB, string, string, ...interface{}) interface{}) CallableFunc

like sqltk.QueryDBMapX

func FnADSVaRA

func FnADSVaRA(fn func(*sql.DB, string, ...interface{}) interface{}) CallableFunc

like sqltk.ExecDBX

func FnAFRF

func FnAFRF(fn func(float64) float64) CallableFunc

like math.Sqrt

func FnAFRS

func FnAFRS(fn func(float64) string) CallableFunc

like tk.Float64ToStr

func FnALbyLbyViRLLi

func FnALbyLbyViRLLi(fn func([]byte, []byte, ...int) [][]int) CallableFunc

like tk.CompareBytes(func([]byte, []byte, ...int) [][]int)

func FnALbySRE

func FnALbySRE(fn func([]byte, string) error) CallableFunc

like tk.SaveBytesToFileE(func(bytesA []byte, fileA string) error)

func FnALsRLs

func FnALsRLs(fn func([]string) []string) CallableFunc

like tk.GetAllParameters

func FnALsSViRI

func FnALsSViRI(fn func([]string, string, ...int) int) CallableFunc

like tk.GetSwitchWithDefaultIntValue

func FnALyARB

func FnALyARB(fn func([]byte, interface{}) bool) CallableFunc

like tk.BytesStartsWith

func FnALyARI

func FnALyARI(fn func([]byte, interface{}) int) CallableFunc

like tk.BytesIndex

func FnALyRB

func FnALyRB(fn func([]byte) bool) CallableFunc

like tk.IsDataEncryptedByTXDEF

func FnALyVsRA

func FnALyVsRA(fn func([]byte, ...string) interface{}) CallableFunc

like tk.LoadImageFromBytes

func FnALyVsRLy

func FnALyVsRLy(fn func([]byte, ...string) []byte) CallableFunc

like tk.EncryptDataByTXDEF

func FnAR

func FnAR(fn func()) CallableFunc

like tk.Pass

func FnARA

func FnARA(fn func() interface{}) CallableFunc

like tk.GetChar

func FnARI

func FnARI(fn func() int) CallableFunc

like tk.GetSeq

func FnARLs

func FnARLs(fn func() []string) CallableFunc

like tk.GetOSArgs

func FnARS

func FnARS(fn func() string) CallableFunc

like tk.GetOSName

func FnARSWRE

func FnARSWRE(fn func(io.Reader, string, io.Writer) error) CallableFunc

like tk.EncryptStreamByTXDEF

func FnART

func FnART(fn func() time.Time) CallableFunc

like time.Now

func FnASAR

func FnASAR(fn func(string, interface{})) CallableFunc

like tk.SetVar

func FnASIRS

func FnASIRS(fn func(string, int) string) CallableFunc

like strings.Repeat

func FnASIVsRS

func FnASIVsRS(fn func(string, int, ...string) string) CallableFunc

like tk.LimitString

func FnASR

func FnASR(fn func(string)) CallableFunc

like tk.DeleteVar

func FnASRA

func FnASRA(fn func(string) interface{}) CallableFunc

like tk.FromBase64

func FnASRB

func FnASRB(fn func(string) bool) CallableFunc

like tk.IfFileExists

func FnASRE

func FnASRE(fn func(string) error) CallableFunc

like tk.SetClipText

func FnASRI

func FnASRI(fn func(string) int) CallableFunc

like tk.RuneLen

func FnASRLby

func FnASRLby(fn func(string) []byte) CallableFunc

like tk.HexToBytes

func FnASRLs

func FnASRLs(fn func(string) []string) CallableFunc

like tk.SplitLines

func FnASRS

func FnASRS(fn func(string) string) CallableFunc

like os.GetEnv

func FnASRSE

func FnASRSE(fn func(string) (string, error)) CallableFunc

like kanjikana.ConvertKanjiToRomaji

func FnASSAVaRA

func FnASSAVaRA(fn func(string, string, interface{}, ...string) interface{}) CallableFunc

like tk.ProcessHtmlTemplate

func FnASSIRLs

func FnASSIRLs(fn func(string, string, int) []string) CallableFunc

like tk.RegFindAllX

func FnASSIRS

func FnASSIRS(fn func(string, string, int) string) CallableFunc

like tk.RegFindFirstX

func FnASSRA

func FnASSRA(fn func(string, string) interface{}) CallableFunc

like tk.GetJSONNodeStrings

func FnASSRA2I

func FnASSRA2I(fn func(string, string) [][]int) CallableFunc

like tk.FindSubStringAll

func FnASSRA2N

func FnASSRA2N(fn func(string, string) [][]int) CallableFunc

like tk.RegFindAllIndexX

func FnASSRB

func FnASSRB(fn func(string, string) bool) CallableFunc

like strings.Contains

func FnASSRE

func FnASSRE(fn func(string, string) error) CallableFunc

like os.SetEnv

func FnASSRF

func FnASSRF(fn func(string, string) float64) CallableFunc

like tk.CalTextSimilarity

func FnASSRI

func FnASSRI(fn func(string, string) int) CallableFunc

like tk.FindFirstDiffPosInStrs

func FnASSRLls

func FnASSRLls(fn func(string, string) [][]string) CallableFunc

like tk.RegFindAllGroupsX

func FnASSRLs

func FnASSRLs(fn func(string, string) []string) CallableFunc

like tk.RegFindFirstGroupsX

func FnASSRS

func FnASSRS(fn func(string, string) string) CallableFunc

like tk.SaveStringToFile

func FnASSRSE

func FnASSRSE(fn func(string, string) (string, error)) CallableFunc

like filepath.Rel

func FnASSSRS

func FnASSSRS(fn func(string, string, string) string) CallableFunc

like tk.RegReplaceX

func FnASSSVsRS

func FnASSSVsRS(fn func(string, string, string, ...string) string) CallableFunc

like tk.GenerateToken

func FnASSVIRF

func FnASSVIRF(fn func(string, string, ...int) float64) CallableFunc

like tk.GetTextSimilarity

func FnASSViRLs

func FnASSViRLs(fn func(string, string, ...int) []string) CallableFunc

like tk.RegSplitX

func FnASSVsRB

func FnASSVsRB(fn func(string, string, ...string) bool) CallableFunc

like tk.ValidateOtpCode

func FnASSVsRE

func FnASSVsRE(fn func(string, string, ...string) error) CallableFunc

like tk.RenameFile

func FnASVaR

func FnASVaR(fn func(string, ...interface{})) CallableFunc

like tk.Pln

func FnASVaRA

func FnASVaRA(fn func(string, ...interface{}) interface{}) CallableFunc

like tk.GetWeb

func FnASVaRE

func FnASVaRE(fn func(string, ...interface{}) error) CallableFunc

like tk.Errf

func FnASVaRS

func FnASVaRS(fn func(string, ...interface{}) string) CallableFunc

like tk.ErrStrf

func FnASViRA

func FnASViRA(fn func(string, ...int) interface{}) CallableFunc

like tk.LoadBytesFromFile

func FnASViRI

func FnASViRI(fn func(string, ...int) int) CallableFunc

like tk.StrToIntWithDefaultValue

func FnASVsRA

func FnASVsRA(fn func(string, ...string) interface{}) CallableFunc

like tk.ToPinyin

func FnASVsRB

func FnASVsRB(fn func(string, ...string) bool) CallableFunc

like tk.InStrings

func FnASVsRLmss

func FnASVsRLmss(fn func(string, ...string) []map[string]string) CallableFunc

like tk.GetFileList

func FnASVsRS

func FnASVsRS(fn func(string, ...string) string) CallableFunc

like tk.SystemCmd

func FnATFRT

func FnATFRT(fn func(time.Time, float64) time.Time) CallableFunc

like tk.TimeAddSecs

func FnATIIIRT

func FnATIIIRT(fn func(time.Time, int, int, int) time.Time) CallableFunc

like tk.TimeAddDate

func FnATRS

func FnATRS(fn func(time.Time) string) CallableFunc

like tk.GetTimeStampMid

func FnATVsRS

func FnATVsRS(fn func(time.Time, ...string) string) CallableFunc

like tk.FormatTime

func FnAVaR

func FnAVaR(fn func(...interface{})) CallableFunc

like tk.Pln

func FnAVaRA

func FnAVaRA(fn func(...interface{}) interface{}) CallableFunc

like tk.Min

func FnAVaRIE

func FnAVaRIE(fn func(...interface{}) (int, error)) CallableFunc

like fmt.Print

func FnAVaRS

func FnAVaRS(fn func(...interface{}) string) CallableFunc

like fmt.Sprintln

func FnAVsRE

func FnAVsRE(fn func(...string) error) CallableFunc

like tk.StartSocksServer

func FnAVsRS

func FnAVsRS(fn func(...string) string) CallableFunc

like filepath.Join

func FnAWSVaRIE

func FnAWSVaRIE(fn func(io.Writer, string, ...interface{}) (int, error)) CallableFunc

like fmt.Printf

func FnAWtRdRI64E

func FnAWtRdRI64E(fn func(io.Writer, io.Reader) (int64, error)) CallableFunc

like io.Copy

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 Charlang char value.

func (Char) BinaryOp

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

BinaryOp implements Object interface.

func (Char) Call

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

Call implements Object interface.

func (Char) CallMethod

func (o Char) CallMethod(nameA string, argsA ...Object) (Object, error)

func (Char) CanCall

func (o Char) CanCall() bool

CanCall implements Object interface.

func (Char) CanIterate

func (Char) CanIterate() bool

CanIterate implements Object interface.

func (Char) Equal

func (o Char) Equal(right Object) bool

Equal implements Object interface.

func (Char) Format

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

Format implements fmt.Formatter interface.

func (Char) GetMember

func (o Char) GetMember(idxA string) Object

func (Char) GetValue

func (o Char) GetValue() Object

func (Char) HasMemeber

func (o Char) HasMemeber() bool

func (Char) IndexGet

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

IndexGet implements Object interface.

func (Char) IndexSet

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

IndexSet implements Object interface.

func (Char) IsFalsy

func (o Char) IsFalsy() bool

IsFalsy implements Object interface.

func (Char) Iterate

func (Char) Iterate() Iterator

Iterate implements Object interface.

func (Char) SetMember

func (o Char) SetMember(idxA string, valueA Object) error

func (Char) String

func (o Char) String() string

String implements Object interface.

func (Char) TypeCode

func (Char) TypeCode() int

func (Char) TypeName

func (Char) TypeName() string

TypeName implements Object interface.

type CharCode

type CharCode struct {
	ObjectImpl
	Source string
	Value  *Bytecode

	CompilerOptions *CompilerOptions

	LastError string

	Members map[string]Object `json:"-"`
}

CharCode object is used for represent thent io.Reader type value

func NewCharCode

func NewCharCode(srcA string, optsA ...*CompilerOptions) *CharCode

func (*CharCode) BinaryOp

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

func (*CharCode) Call

func (o *CharCode) Call(argsA ...Object) (Object, error)

func (*CharCode) CallMethod

func (o *CharCode) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*CharCode) CanCall

func (o *CharCode) CanCall() bool

func (*CharCode) CanIterate

func (*CharCode) CanIterate() bool

func (*CharCode) Equal

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

func (*CharCode) GetMember

func (o *CharCode) GetMember(idxA string) Object

func (*CharCode) GetValue

func (o *CharCode) GetValue() Object

func (*CharCode) HasMemeber

func (o *CharCode) HasMemeber() bool

func (*CharCode) IndexGet

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

func (*CharCode) IndexSet

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

func (*CharCode) IsFalsy

func (o *CharCode) IsFalsy() bool

func (*CharCode) Iterate

func (o *CharCode) Iterate() Iterator

func (*CharCode) SetMember

func (o *CharCode) SetMember(idxA string, valueA Object) error

func (*CharCode) String

func (o *CharCode) String() string

func (*CharCode) TypeCode

func (*CharCode) TypeCode() int

func (*CharCode) TypeName

func (*CharCode) TypeName() string

TypeName implements Object interface.

type Chars

type Chars []rune

Chars represents byte slice and implements Object interface.

func (Chars) BinaryOp

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

BinaryOp implements Object interface.

func (Chars) Call

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

Call implements Object interface.

func (Chars) CallMethod

func (o Chars) CallMethod(nameA string, argsA ...Object) (Object, error)

func (Chars) CanCall

func (o Chars) CanCall() bool

CanCall implements Object interface.

func (Chars) CanIterate

func (Chars) CanIterate() bool

CanIterate implements Object interface.

func (Chars) Copy

func (o Chars) Copy() Object

Copy implements Copier interface.

func (Chars) Equal

func (o Chars) Equal(right Object) bool

Equal implements Object interface.

func (Chars) Format

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

Format implements fmt.Formatter interface.

func (Chars) GetMember

func (o Chars) GetMember(idxA string) Object

func (Chars) GetValue

func (o Chars) GetValue() Object

func (Chars) HasMemeber

func (o Chars) HasMemeber() bool

func (Chars) IndexGet

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

IndexGet represents string values and implements Object interface.

func (Chars) IndexSet

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

IndexSet implements Object interface.

func (Chars) IsFalsy

func (o Chars) IsFalsy() bool

IsFalsy implements Object interface.

func (Chars) Iterate

func (o Chars) Iterate() Iterator

Iterate implements Object interface.

func (Chars) Len

func (o Chars) Len() int

Len implements LengthGetter interface.

func (Chars) SetMember

func (o Chars) SetMember(idxA string, valueA Object) error

func (Chars) String

func (o Chars) String() string

func (Chars) TypeCode

func (Chars) TypeCode() int

func (Chars) TypeName

func (Chars) TypeName() string

TypeName implements Object interface.

type CharsIterator

type CharsIterator struct {
	V Chars
	// contains filtered or unexported fields
}

CharsIterator represents an iterator for the chars.

func (*CharsIterator) Key

func (it *CharsIterator) Key() Object

Key implements Iterator interface.

func (*CharsIterator) Next

func (it *CharsIterator) Next() bool

Next implements Iterator interface.

func (*CharsIterator) Value

func (it *CharsIterator) Value() Object

Value implements Iterator interface.

type CompiledFunction

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

	Members map[string]Object `json:"-"`
}

CompiledFunction holds the constants and instructions to pass VM.

func (*CompiledFunction) BinaryOp

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

BinaryOp implements Object interface.

func (*CompiledFunction) Call

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

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

func (*CompiledFunction) CallMethod

func (o *CompiledFunction) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*CompiledFunction) CanCall

func (*CompiledFunction) CanCall() bool

CanCall implements Object interface.

func (*CompiledFunction) CanIterate

func (*CompiledFunction) CanIterate() bool

CanIterate implements Object interface.

func (*CompiledFunction) Copy

func (o *CompiledFunction) Copy() Object

Copy implements the Copier interface.

func (*CompiledFunction) Equal

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

Equal implements Object interface.

func (*CompiledFunction) Fprint

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

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

func (*CompiledFunction) GetMember

func (o *CompiledFunction) GetMember(idxA string) Object

func (*CompiledFunction) GetValue

func (o *CompiledFunction) GetValue() Object

func (*CompiledFunction) HasMemeber

func (o *CompiledFunction) HasMemeber() bool

func (*CompiledFunction) IndexGet

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

IndexGet represents string values and implements Object interface.

func (*CompiledFunction) IndexSet

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

IndexSet implements Object interface.

func (*CompiledFunction) IsFalsy

func (o *CompiledFunction) IsFalsy() bool

IsFalsy implements Object interface.

func (*CompiledFunction) Iterate

func (*CompiledFunction) Iterate() Iterator

Iterate implements Object interface.

func (*CompiledFunction) SetMember

func (o *CompiledFunction) SetMember(idxA string, valueA Object) error

func (*CompiledFunction) SourcePos

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

SourcePos returns the source position of the instruction at ip.

func (*CompiledFunction) String

func (o *CompiledFunction) String() string

func (*CompiledFunction) TypeCode

func (*CompiledFunction) TypeCode() int

func (*CompiledFunction) TypeName

func (*CompiledFunction) TypeName() string

TypeName implements Object interface

type Compiler

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

Compiler compiles the AST into a bytecode.

func NewCompiler

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

NewCompiler creates a new Compiler object.

func (*Compiler) Bytecode

func (c *Compiler) Bytecode() *Bytecode

Bytecode returns compiled Bytecode ready to run in VM.

func (*Compiler) Compile

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

Compile compiles parser.Node and builds Bytecode.

func (*Compiler) SetGlobalSymbolsIndex

func (c *Compiler) SetGlobalSymbolsIndex()

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

type CompilerError

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

CompilerError represents a compiler error.

func (*CompilerError) Error

func (e *CompilerError) Error() string

func (*CompilerError) Unwrap

func (e *CompilerError) Unwrap() error

type CompilerOptions

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

CompilerOptions represents customizable options for Compile().

var MainCompilerOptions *CompilerOptions = nil

type Copier

type Copier interface {
	Copy() Object
}

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

type Database

type Database struct {
	ObjectImpl
	Value           *sql.DB
	DBType          string
	DBConnectString string

	Members map[string]Object    `json:"-"`
	Methods map[string]*Function `json:"-"`
}

func (*Database) BinaryOp

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

func (*Database) Call

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

func (*Database) CallMethod

func (o *Database) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*Database) CanCall

func (*Database) CanCall() bool

func (*Database) CanIterate

func (*Database) CanIterate() bool

func (Database) Equal

func (o Database) Equal(right Object) bool

func (*Database) GetMember

func (o *Database) GetMember(idxA string) Object

func (*Database) GetValue

func (o *Database) GetValue() Object

func (*Database) HasMemeber

func (o *Database) HasMemeber() bool

func (*Database) IndexGet

func (o *Database) IndexGet(index Object) (value Object, err error)

func (*Database) IndexSet

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

func (*Database) IsFalsy

func (o *Database) IsFalsy() bool

func (*Database) Iterate

func (*Database) Iterate() Iterator

func (*Database) SetMember

func (o *Database) SetMember(idxA string, valueA Object) error

func (*Database) String

func (o *Database) String() string

func (*Database) TypeCode

func (o *Database) TypeCode() int

func (*Database) TypeName

func (o *Database) TypeName() string

type Delegate

type Delegate struct {
	// ObjectImpl
	Code  *CharCode
	Value tk.QuickVarDelegate

	Members map[string]Object `json:"-"`
}

Delegate represents an function caller and implements Object interface.

func (*Delegate) BinaryOp

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

func (*Delegate) Call

func (o *Delegate) Call(argsA ...Object) (Object, error)

func (*Delegate) CallMethod

func (o *Delegate) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*Delegate) CanCall

func (o *Delegate) CanCall() bool

func (*Delegate) CanIterate

func (*Delegate) CanIterate() bool

func (*Delegate) Equal

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

func (*Delegate) GetMember

func (o *Delegate) GetMember(idxA string) Object

func (*Delegate) GetValue

func (o *Delegate) GetValue() Object

func (*Delegate) HasMemeber

func (o *Delegate) HasMemeber() bool

func (*Delegate) IndexGet

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

func (*Delegate) IndexSet

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

func (*Delegate) IsFalsy

func (o *Delegate) IsFalsy() bool

func (*Delegate) Iterate

func (*Delegate) Iterate() Iterator

func (*Delegate) SetMember

func (o *Delegate) SetMember(idxA string, valueA Object) error

func (*Delegate) SetValue

func (o *Delegate) SetValue(valueA Object) error

func (*Delegate) String

func (o *Delegate) String() string

func (*Delegate) TypeCode

func (*Delegate) TypeCode() int

func (*Delegate) TypeName

func (*Delegate) TypeName() string

type Error

type Error struct {
	Name    string
	Message string
	Cause   error

	Members map[string]Object `json:"-"`
}

Error represents Error Object and implements error and Object interfaces.

func NewArgumentTypeError

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

NewArgumentTypeError creates a new Error from ErrType.

func NewCommonError

func NewCommonError(formatA string, argsA ...interface{}) *Error

func NewCommonErrorWithPos

func NewCommonErrorWithPos(c Call, formatA string, argsA ...interface{}) *Error

func NewError

func NewError(nameA string, formatA string, argsA ...interface{}) *Error

func NewFromError

func NewFromError(errA error) *Error

func NewIndexTypeError

func NewIndexTypeError(expectType, foundType string) *Error

NewIndexTypeError creates a new Error from ErrType.

func NewIndexValueTypeError

func NewIndexValueTypeError(expectType, foundType string) *Error

NewIndexValueTypeError creates a new Error from ErrType.

func NewOperandTypeError

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

NewOperandTypeError creates a new Error from ErrType.

func WrapError

func WrapError(errA error) *Error

func (*Error) BinaryOp

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

BinaryOp implements Object interface.

func (*Error) Call

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

Call implements Object interface.

func (*Error) CallMethod

func (o *Error) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*Error) CanCall

func (*Error) CanCall() bool

CanCall implements Object interface.

func (*Error) CanIterate

func (*Error) CanIterate() bool

CanIterate implements Object interface.

func (*Error) Copy

func (o *Error) Copy() Object

Copy implements Copier interface.

func (*Error) Equal

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

Equal implements Object interface.

func (*Error) Error

func (o *Error) Error() string

Error implements error interface.

func (*Error) GetMember

func (o *Error) GetMember(idxA string) Object

func (*Error) GetValue

func (o *Error) GetValue() Object

func (*Error) HasMemeber

func (o *Error) HasMemeber() bool

func (*Error) IndexGet

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

IndexGet implements Object interface.

func (*Error) IndexSet

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

IndexSet implements Object interface.

func (*Error) IsFalsy

func (o *Error) IsFalsy() bool

IsFalsy implements Object interface.

func (*Error) Iterate

func (*Error) Iterate() Iterator

Iterate implements Object interface.

func (*Error) NewError

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

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

func (*Error) SetMember

func (o *Error) SetMember(idxA string, valueA Object) error

func (*Error) String

func (o *Error) String() string

String implements Object interface.

func (*Error) TypeCode

func (*Error) TypeCode() int

func (*Error) TypeName

func (*Error) TypeName() string

TypeName implements Object interface.

func (*Error) Unwrap

func (o *Error) Unwrap() error

type Eval

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

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

func NewEval

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

NewEval returns new Eval object.

func NewEvalQuick

func NewEvalQuick(globalsA map[string]interface{}, optsA *CompilerOptions, localsA ...Object) *Eval

func (*Eval) Run

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

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

type EvalMachine

type EvalMachine struct {
	Value *Eval

	Members map[string]Object `json:"-"`
}

EvalMachine represents an Charlang Virtual Machine could run script once or more

func (*EvalMachine) BinaryOp

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

func (*EvalMachine) Call

func (o *EvalMachine) Call(_ ...Object) (Object, error)

func (*EvalMachine) CallMethod

func (o *EvalMachine) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*EvalMachine) CallName

func (o *EvalMachine) CallName(nameA string, c Call) (Object, error)

func (*EvalMachine) CanCall

func (o *EvalMachine) CanCall() bool

func (*EvalMachine) CanIterate

func (*EvalMachine) CanIterate() bool

func (*EvalMachine) Equal

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

func (*EvalMachine) GetMember

func (o *EvalMachine) GetMember(idxA string) Object

func (*EvalMachine) GetValue

func (o *EvalMachine) GetValue() Object

func (*EvalMachine) HasMemeber

func (o *EvalMachine) HasMemeber() bool

func (*EvalMachine) IndexGet

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

func (*EvalMachine) IndexSet

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

func (*EvalMachine) IsFalsy

func (o *EvalMachine) IsFalsy() bool

func (*EvalMachine) Iterate

func (*EvalMachine) Iterate() Iterator

func (*EvalMachine) SetMember

func (o *EvalMachine) SetMember(idxA string, valueA Object) error

func (*EvalMachine) SetValue

func (o *EvalMachine) SetValue(valueA Object) error

func (*EvalMachine) String

func (o *EvalMachine) String() string

func (*EvalMachine) TypeCode

func (*EvalMachine) TypeCode() int

func (*EvalMachine) TypeName

func (*EvalMachine) TypeName() string

type ExCallerObject

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

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

type Excel

type Excel struct {
	// ObjectImpl
	Value *excelize.File

	Members map[string]Object `json:"-"`
}

Excel represents an Excel(or compatible) file and implements Object interface.

func (*Excel) BinaryOp

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

func (*Excel) Call

func (o *Excel) Call(argsA ...Object) (Object, error)

func (*Excel) CallMethod

func (o *Excel) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*Excel) CanCall

func (o *Excel) CanCall() bool

func (*Excel) CanIterate

func (*Excel) CanIterate() bool

func (*Excel) Equal

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

func (*Excel) GetMember

func (o *Excel) GetMember(idxA string) Object

func (*Excel) GetValue

func (o *Excel) GetValue() Object

func (*Excel) HasMemeber

func (o *Excel) HasMemeber() bool

func (*Excel) IndexGet

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

func (*Excel) IndexSet

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

func (*Excel) IsFalsy

func (o *Excel) IsFalsy() bool

func (*Excel) Iterate

func (*Excel) Iterate() Iterator

func (*Excel) SetMember

func (o *Excel) SetMember(idxA string, valueA Object) error

func (*Excel) SetValue

func (o *Excel) SetValue(valueA Object) error

func (*Excel) String

func (o *Excel) String() string

func (*Excel) TypeCode

func (*Excel) TypeCode() int

func (*Excel) TypeName

func (*Excel) TypeName() string

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
	// 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 imported dynamically like a file.

type File

type File struct {
	ObjectImpl
	Value *os.File

	Members map[string]Object `json:"-"`
}

File object is used for represent os.File type value

func (*File) BinaryOp

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

func (*File) Call

func (o *File) Call(_ ...Object) (Object, error)

func (*File) CallMethod

func (o *File) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*File) CallName

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

func (*File) CanCall

func (o *File) CanCall() bool

func (*File) CanIterate

func (*File) CanIterate() bool

func (*File) Close

func (o *File) Close() error

comply to io.Closer

func (*File) Equal

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

func (*File) GetMember

func (o *File) GetMember(idxA string) Object

func (*File) GetValue

func (o *File) GetValue() Object

func (*File) HasMemeber

func (o *File) HasMemeber() bool

func (*File) IndexGet

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

func (*File) IndexSet

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

func (*File) IsFalsy

func (o *File) IsFalsy() bool

func (*File) Iterate

func (o *File) Iterate() Iterator

func (*File) Read

func (o *File) Read(p []byte) (n int, err error)

comply to io.Reader

func (*File) SetMember

func (o *File) SetMember(idxA string, valueA Object) error

func (*File) String

func (o *File) String() string

func (*File) TypeCode

func (*File) TypeCode() int

func (*File) TypeName

func (*File) TypeName() string

TypeName implements Object interface.

func (*File) Writer

func (o *File) Writer(p []byte) (n int, err error)

comply to io.Writer

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 Charlang float value.

func (Float) BinaryOp

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

BinaryOp implements Object interface.

func (Float) Call

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

Call implements Object interface.

func (Float) CallMethod

func (o Float) CallMethod(nameA string, argsA ...Object) (Object, error)

func (Float) CanCall

func (o Float) CanCall() bool

CanCall implements Object interface.

func (Float) CanIterate

func (Float) CanIterate() bool

CanIterate implements Object interface.

func (Float) Equal

func (o Float) Equal(right Object) bool

Equal implements Object interface.

func (Float) Format

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

Format implements fmt.Formatter interface.

func (Float) GetMember

func (o Float) GetMember(idxA string) Object

func (Float) GetValue

func (o Float) GetValue() Object

func (Float) HasMemeber

func (o Float) HasMemeber() bool

func (Float) IndexGet

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

IndexGet implements Object interface.

func (Float) IndexSet

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

IndexSet implements Object interface.

func (Float) IsFalsy

func (o Float) IsFalsy() bool

IsFalsy implements Object interface.

func (Float) Iterate

func (Float) Iterate() Iterator

Iterate implements Object interface.

func (Float) SetMember

func (o Float) SetMember(idxA string, valueA Object) error

func (Float) String

func (o Float) String() string

String implements Object interface.

func (Float) TypeCode

func (Float) TypeCode() int

func (Float) TypeName

func (Float) TypeName() string

TypeName implements Object interface.

type Function

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

	Members map[string]Object `json:"-"`
}

Function represents a function object and implements Object interface.

func (*Function) Call

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

Call implements Object interface.

func (*Function) CallEx

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

func (*Function) CallMethod

func (o *Function) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*Function) CanCall

func (*Function) CanCall() bool

CanCall implements Object interface.

func (*Function) Copy

func (o *Function) Copy() Object

Copy implements Copier interface.

func (*Function) Equal

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

Equal implements Object interface.

func (*Function) GetMember

func (o *Function) GetMember(idxA string) Object

func (*Function) GetValue

func (o *Function) GetValue() Object

func (*Function) HasMemeber

func (o *Function) HasMemeber() bool

func (*Function) IsFalsy

func (o *Function) IsFalsy() bool

IsFalsy implements Object interface.

func (*Function) SetMember

func (o *Function) SetMember(idxA string, valueA Object) error

func (*Function) String

func (o *Function) String() string

String implements Object interface.

func (*Function) TypeCode

func (*Function) TypeCode() int

func (*Function) TypeName

func (*Function) TypeName() string

TypeName implements Object interface.

type Gel

type Gel struct {
	ObjectImpl
	// Source string
	Value *CharCode

	Members map[string]Object `json:"-"`
}

Gel object is like modules based on CharCode object

func (*Gel) BinaryOp

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

func (*Gel) Call

func (o *Gel) Call(_ ...Object) (Object, error)

func (*Gel) CallMethod

func (o *Gel) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*Gel) CanCall

func (o *Gel) CanCall() bool

func (*Gel) CanIterate

func (*Gel) CanIterate() bool

func (*Gel) Equal

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

func (*Gel) GetMember

func (o *Gel) GetMember(idxA string) Object

func (*Gel) GetValue

func (o *Gel) GetValue() Object

func (*Gel) HasMemeber

func (o *Gel) HasMemeber() bool

func (*Gel) IndexGet

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

func (*Gel) IndexSet

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

func (*Gel) IsFalsy

func (o *Gel) IsFalsy() bool

func (*Gel) Iterate

func (o *Gel) Iterate() Iterator

func (*Gel) SetMember

func (o *Gel) SetMember(idxA string, valueA Object) error

func (*Gel) String

func (o *Gel) String() string

func (*Gel) TypeCode

func (*Gel) TypeCode() int

func (*Gel) TypeName

func (*Gel) TypeName() string

TypeName implements Object interface.

type GlobalContext

type GlobalContext struct {
	SyncMap   tk.SyncMap
	SyncQueue tk.SyncQueue
	SyncStack tk.SyncStack

	SyncSeq tk.Seq

	Vars map[string]interface{}

	Regs []interface{}

	VerboseLevel int
}
var GlobalsG *GlobalContext

type HttpHandler

type HttpHandler struct {
	// ObjectImpl
	Value func(http.ResponseWriter, *http.Request)

	Members map[string]Object `json:"-"`
}

HttpHandler object is used to represent the http response

func (*HttpHandler) BinaryOp

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

func (*HttpHandler) Call

func (o *HttpHandler) Call(_ ...Object) (Object, error)

func (*HttpHandler) CallMethod

func (o *HttpHandler) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*HttpHandler) CanCall

func (o *HttpHandler) CanCall() bool

func (*HttpHandler) CanIterate

func (*HttpHandler) CanIterate() bool

func (*HttpHandler) Equal

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

func (*HttpHandler) GetMember

func (o *HttpHandler) GetMember(idxA string) Object

func (*HttpHandler) GetValue

func (o *HttpHandler) GetValue() Object

func (*HttpHandler) HasMemeber

func (o *HttpHandler) HasMemeber() bool

func (*HttpHandler) IndexGet

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

func (*HttpHandler) IndexSet

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

func (*HttpHandler) IsFalsy

func (o *HttpHandler) IsFalsy() bool

func (*HttpHandler) Iterate

func (o *HttpHandler) Iterate() Iterator

func (*HttpHandler) SetMember

func (o *HttpHandler) SetMember(idxA string, valueA Object) error

func (*HttpHandler) String

func (o *HttpHandler) String() string

func (*HttpHandler) TypeCode

func (*HttpHandler) TypeCode() int

func (*HttpHandler) TypeName

func (*HttpHandler) TypeName() string

TypeName implements Object interface.

type HttpReq

type HttpReq struct {
	ObjectImpl
	Value *http.Request

	Members map[string]Object `json:"-"`
}

HttpReq object is used to represent the http request

func (*HttpReq) BinaryOp

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

func (*HttpReq) Call

func (o *HttpReq) Call(_ ...Object) (Object, error)

func (*HttpReq) CallMethod

func (o *HttpReq) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*HttpReq) CanCall

func (o *HttpReq) CanCall() bool

func (*HttpReq) CanIterate

func (*HttpReq) CanIterate() bool

func (*HttpReq) Equal

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

func (*HttpReq) GetMember

func (o *HttpReq) GetMember(idxA string) Object

func (*HttpReq) GetValue

func (o *HttpReq) GetValue() Object

func (*HttpReq) HasMemeber

func (o *HttpReq) HasMemeber() bool

func (*HttpReq) IndexGet

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

func (*HttpReq) IndexSet

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

func (*HttpReq) IsFalsy

func (o *HttpReq) IsFalsy() bool

func (*HttpReq) Iterate

func (o *HttpReq) Iterate() Iterator

func (*HttpReq) SetMember

func (o *HttpReq) SetMember(idxA string, valueA Object) error

func (*HttpReq) String

func (o *HttpReq) String() string

func (*HttpReq) TypeCode

func (*HttpReq) TypeCode() int

func (*HttpReq) TypeName

func (*HttpReq) TypeName() string

TypeName implements Object interface.

type HttpResp

type HttpResp struct {
	ObjectImpl
	Value http.ResponseWriter

	Members map[string]Object `json:"-"`
}

HttpResp object is used to represent the http response

func (*HttpResp) BinaryOp

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

func (*HttpResp) Call

func (o *HttpResp) Call(_ ...Object) (Object, error)

func (*HttpResp) CallMethod

func (o *HttpResp) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*HttpResp) CanCall

func (o *HttpResp) CanCall() bool

func (*HttpResp) CanIterate

func (*HttpResp) CanIterate() bool

func (*HttpResp) Equal

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

func (*HttpResp) GetMember

func (o *HttpResp) GetMember(idxA string) Object

func (*HttpResp) GetValue

func (o *HttpResp) GetValue() Object

func (*HttpResp) HasMemeber

func (o *HttpResp) HasMemeber() bool

func (*HttpResp) IndexGet

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

func (*HttpResp) IndexSet

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

func (*HttpResp) IsFalsy

func (o *HttpResp) IsFalsy() bool

func (*HttpResp) Iterate

func (o *HttpResp) Iterate() Iterator

func (*HttpResp) SetMember

func (o *HttpResp) SetMember(idxA string, valueA Object) error

func (*HttpResp) String

func (o *HttpResp) String() string

func (*HttpResp) TypeCode

func (*HttpResp) TypeCode() int

func (*HttpResp) TypeName

func (*HttpResp) TypeName() string

TypeName implements Object interface.

func (*HttpResp) Write

func (o *HttpResp) Write(p []byte) (n int, err error)

comply to io.Writer

type Image

type Image struct {
	Value image.Image

	Members map[string]Object `json:"-"`
}

Image represents an image and implements Object interface.

func (*Image) BinaryOp

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

func (*Image) Call

func (o *Image) Call(_ ...Object) (Object, error)

func (*Image) CallMethod

func (o *Image) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*Image) CanCall

func (o *Image) CanCall() bool

func (*Image) CanIterate

func (*Image) CanIterate() bool

func (*Image) Equal

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

func (*Image) GetMember

func (o *Image) GetMember(idxA string) Object

func (*Image) GetValue

func (o *Image) GetValue() Object

func (*Image) HasMemeber

func (o *Image) HasMemeber() bool

func (*Image) IndexGet

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

func (*Image) IndexSet

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

func (*Image) IsFalsy

func (o *Image) IsFalsy() bool

func (*Image) Iterate

func (*Image) Iterate() Iterator

func (*Image) SetMember

func (o *Image) SetMember(idxA string, valueA Object) error

func (*Image) SetValue

func (o *Image) SetValue(valueA Object) error

func (*Image) String

func (o *Image) String() string

func (*Image) TypeCode

func (*Image) TypeCode() int

func (*Image) TypeName

func (*Image) TypeName() string

type Importable

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

Importable interface represents importable module instance.

type IndexDeleter

type IndexDeleter interface {
	IndexDelete(Object) error
}

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

type Int

type Int int64

Int represents signed integer values and implements Object interface.

func ToInt

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

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

func ToIntObject

func ToIntObject(argA interface{}, defaultA ...int) Int

func (Int) BinaryOp

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

BinaryOp implements Object interface.

func (Int) Call

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

Call implements Object interface.

func (Int) CallMethod

func (o Int) CallMethod(nameA string, argsA ...Object) (Object, error)

func (Int) CanCall

func (o Int) CanCall() bool

CanCall implements Object interface.

func (Int) CanIterate

func (Int) CanIterate() bool

CanIterate implements Object interface.

func (Int) Equal

func (o Int) Equal(right Object) bool

Equal implements Object interface.

func (Int) Format

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

Format implements fmt.Formatter interface.

func (Int) GetMember

func (o Int) GetMember(idxA string) Object

func (Int) GetValue

func (o Int) GetValue() Object

func (Int) HasMemeber

func (o Int) HasMemeber() bool

func (Int) IndexGet

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

IndexGet implements Object interface.

func (Int) IndexSet

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

IndexSet implements Object interface.

func (Int) IsFalsy

func (o Int) IsFalsy() bool

IsFalsy implements Object interface.

func (Int) Iterate

func (o Int) Iterate() Iterator

Iterate implements Object interface.

func (Int) SetMember

func (o Int) SetMember(idxA string, valueA Object) error

func (Int) String

func (o Int) String() string

String implements Object interface.

func (Int) TypeCode

func (Int) TypeCode() int

func (Int) TypeName

func (Int) TypeName() string

TypeName implements Object interface.

type IntIterator

type IntIterator struct {
	V Int
	// contains filtered or unexported fields
}

IntIterator represents an iterator for the Int.

func (*IntIterator) Key

func (it *IntIterator) Key() Object

Key implements Iterator interface.

func (*IntIterator) Next

func (it *IntIterator) Next() bool

Next implements Iterator interface.

func (*IntIterator) Value

func (it *IntIterator) Value() Object

Value implements Iterator interface.

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 Invoke calls. This is useful when you want to execute multiple functions in a single VM. For example, you can use Acquire and Release to execute multiple functions in a single VM instance. Note that you should call Release after Acquire, if you want to reuse the VM. If you don't want to use the pool, you can just call Invoke method. It is unsafe to hold a reference to the VM after Release is called. Using VM pool is about three times faster than creating a new VM for each Invoke call.

func NewInvoker

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

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

Invoke invokes the callee object with the given arguments.

func (*Invoker) Release

func (inv *Invoker) Release()

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

type Iterator

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

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

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

Iterator wraps the methods required to iterate Objects in VM.

type LengthGetter

type LengthGetter interface {
	Len() int
}

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

type Location

type Location struct {
	ObjectImpl
	Value *time.Location

	Members map[string]Object `json:"-"`
}

Location represents location values and implements Object interface.

func ToLocation

func ToLocation(o Object) (ret *Location, ok bool)

ToLocation will try to convert given Object to *Location value.

func (*Location) CallMethod

func (o *Location) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*Location) Equal

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

Equal implements Object interface.

func (*Location) GetMember

func (o *Location) GetMember(idxA string) Object

func (*Location) GetValue

func (o *Location) GetValue() Object

func (*Location) HasMemeber

func (o *Location) HasMemeber() bool

func (*Location) IsFalsy

func (o *Location) IsFalsy() bool

IsFalsy implements Object interface.

func (*Location) SetMember

func (o *Location) SetMember(idxA string, valueA Object) error

func (*Location) String

func (o *Location) String() string

String implements Object interface.

func (*Location) TypeCode

func (*Location) TypeCode() int

func (*Location) TypeName

func (*Location) TypeName() string

TypeName implements Object interface.

type Map

type Map map[string]Object

Map represents map of objects and implements Object interface.

func NewBaseEnv

func NewBaseEnv(varsA map[string]interface{}, additionsA ...Object) *Map

func ToMap

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

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

func (Map) BinaryOp

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

BinaryOp implements Object interface.

func (Map) Call

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

Call implements Object interface.

func (Map) CallMethod

func (o Map) CallMethod(nameA string, argsA ...Object) (Object, error)

func (Map) CallName

func (o Map) CallName(nameA string, c Call) (Object, error)

func (Map) CanCall

func (Map) CanCall() bool

CanCall implements Object interface.

func (Map) CanIterate

func (Map) CanIterate() bool

CanIterate implements Object interface.

func (Map) Copy

func (o Map) Copy() Object

Copy implements Copier interface.

func (Map) Equal

func (o Map) Equal(right Object) bool

Equal implements Object interface.

func (Map) GetMember

func (o Map) GetMember(idxA string) Object

func (Map) GetValue

func (o Map) GetValue() Object

func (Map) HasMemeber

func (o Map) HasMemeber() bool

func (Map) IndexDelete

func (o Map) IndexDelete(key Object) error

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

func (Map) IndexGet

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

IndexGet implements Object interface.

func (Map) IndexSet

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

IndexSet implements Object interface.

func (Map) IsFalsy

func (o Map) IsFalsy() bool

IsFalsy implements Object interface.

func (Map) Iterate

func (o Map) Iterate() Iterator

Iterate implements Iterable interface.

func (Map) Len

func (o Map) Len() int

Len implements LengthGetter interface.

func (Map) SetMember

func (o Map) SetMember(idxA string, valueA Object) error

func (Map) String

func (o Map) String() string

String implements Object interface.

func (Map) TypeCode

func (Map) TypeCode() int

func (Map) TypeName

func (Map) TypeName() string

TypeName implements Object interface.

type MapArray

type MapArray struct {
	Value *tk.SimpleFlexObject
}

MapArray represents an SimpleFlexObject which is an array with some items have keys

func (*MapArray) BinaryOp

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

func (*MapArray) Call

func (o *MapArray) Call(_ ...Object) (Object, error)

func (*MapArray) CallMethod

func (o *MapArray) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*MapArray) CallName

func (o *MapArray) CallName(nameA string, c Call) (Object, error)

func (*MapArray) CanCall

func (o *MapArray) CanCall() bool

func (*MapArray) CanIterate

func (*MapArray) CanIterate() bool

func (*MapArray) Equal

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

func (*MapArray) GetMember

func (o *MapArray) GetMember(idxA string) Object

func (*MapArray) GetValue

func (o *MapArray) GetValue() Object

func (*MapArray) HasMemeber

func (o *MapArray) HasMemeber() bool

func (*MapArray) IndexGet

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

func (*MapArray) IndexSet

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

func (*MapArray) IsFalsy

func (o *MapArray) IsFalsy() bool

func (*MapArray) Iterate

func (o *MapArray) Iterate() Iterator

func (*MapArray) Len

func (o *MapArray) Len() int

Len implements LengthGetter interface.

func (*MapArray) SetMember

func (o *MapArray) SetMember(idxA string, valueA Object) error

func (*MapArray) SetValue

func (o *MapArray) SetValue(valueA Object) error

func (*MapArray) String

func (o *MapArray) String() string

func (*MapArray) TypeCode

func (*MapArray) TypeCode() int

func (*MapArray) TypeName

func (*MapArray) TypeName() string

type MapArrayIterator

type MapArrayIterator struct {
	V *MapArray
	// contains filtered or unexported fields
}

MapArrayIterator represents an iterator for the array.

func (*MapArrayIterator) Key

func (it *MapArrayIterator) Key() Object

Key implements Iterator interface.

func (*MapArrayIterator) Next

func (it *MapArrayIterator) Next() bool

Next implements Iterator interface.

func (*MapArrayIterator) Value

func (it *MapArrayIterator) Value() Object

Value implements Iterator interface.

type MapIterator

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

MapIterator represents an iterator for the map.

func (*MapIterator) Key

func (it *MapIterator) Key() Object

Key implements Iterator interface.

func (*MapIterator) Next

func (it *MapIterator) Next() bool

Next implements Iterator interface.

func (*MapIterator) Value

func (it *MapIterator) Value() Object

Value implements Iterator interface.

type ModuleMap

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

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

func NewModuleMap

func NewModuleMap() *ModuleMap

NewModuleMap creates a new module map.

func (*ModuleMap) Add

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

Add adds an importable module.

func (*ModuleMap) AddBuiltinModule

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

AddBuiltinModule adds a builtin module.

func (*ModuleMap) AddSourceModule

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

AddSourceModule adds a source module.

func (*ModuleMap) Copy

func (m *ModuleMap) Copy() *ModuleMap

Copy creates a copy of the module map.

func (*ModuleMap) Fork

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

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

func (*ModuleMap) Get

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

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

func (*ModuleMap) Remove

func (m *ModuleMap) Remove(name string)

Remove removes a named module.

func (*ModuleMap) SetExtImporter

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

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

type MutableString

type MutableString struct {
	ObjectImpl
	Value string

	Members map[string]Object `json:"-"`
}

MutableString represents string values and implements Object interface, compare to String, it supports setValue method.

func ToMutableStringObject

func ToMutableStringObject(argA interface{}) *MutableString

func (*MutableString) BinaryOp

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

BinaryOp implements Object interface.

func (*MutableString) Call

func (o *MutableString) Call(_ ...Object) (Object, error)

Call implements Object interface.

func (*MutableString) CallMethod

func (o *MutableString) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*MutableString) CanCall

func (o *MutableString) CanCall() bool

CanCall implements Object interface.

func (*MutableString) CanIterate

func (*MutableString) CanIterate() bool

CanIterate implements Object interface.

func (*MutableString) Equal

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

Equal implements Object interface.

func (*MutableString) Format

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

Format implements fmt.Formatter interface.

func (*MutableString) GetMember

func (o *MutableString) GetMember(idxA string) Object

func (*MutableString) GetValue

func (o *MutableString) GetValue() Object

func (*MutableString) HasMemeber

func (o *MutableString) HasMemeber() bool

func (*MutableString) IndexGet

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

IndexGet represents string values and implements Object interface.

func (*MutableString) IndexSet

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

IndexSet implements Object interface.

func (*MutableString) IsFalsy

func (o *MutableString) IsFalsy() bool

IsFalsy implements Object interface.

func (*MutableString) Iterate

func (o *MutableString) Iterate() Iterator

Iterate implements Object interface.

func (*MutableString) Len

func (o *MutableString) Len() int

Len implements LengthGetter interface.

func (*MutableString) MarshalJSON

func (o *MutableString) MarshalJSON() ([]byte, error)

func (*MutableString) SetMember

func (o *MutableString) SetMember(idxA string, valueA Object) error

func (*MutableString) SetValue

func (o *MutableString) SetValue(valueA Object) error

func (*MutableString) String

func (o *MutableString) String() string

func (*MutableString) TypeCode

func (*MutableString) TypeCode() int

func (*MutableString) TypeName

func (*MutableString) TypeName() string

TypeName implements Object interface.

type MutableStringIterator

type MutableStringIterator struct {
	V *MutableString
	// contains filtered or unexported fields
}

MutableStringIterator represents an iterator for the string.

func (*MutableStringIterator) Key

func (it *MutableStringIterator) Key() Object

Key implements Iterator interface.

func (*MutableStringIterator) Next

func (it *MutableStringIterator) Next() bool

Next implements Iterator interface.

func (*MutableStringIterator) Value

func (it *MutableStringIterator) Value() Object

Value implements Iterator interface.

type Mutex

type Mutex struct {
	ObjectImpl
	Value *(sync.RWMutex)

	Members map[string]Object `json:"-"`
}

Mutex object is used for thread-safe actions note that the members set/get operations are not thread-safe

func NewMutex

func NewMutex(argsA ...Object) *Mutex

func (*Mutex) BinaryOp

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

func (*Mutex) Call

func (o *Mutex) Call(_ ...Object) (Object, error)

func (*Mutex) CallMethod

func (o *Mutex) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*Mutex) CanCall

func (o *Mutex) CanCall() bool

func (*Mutex) CanIterate

func (*Mutex) CanIterate() bool

func (*Mutex) Equal

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

func (*Mutex) GetMember

func (o *Mutex) GetMember(idxA string) Object

func (*Mutex) GetValue

func (o *Mutex) GetValue() Object

func (*Mutex) HasMemeber

func (o *Mutex) HasMemeber() bool

func (*Mutex) IndexGet

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

func (*Mutex) IndexSet

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

func (*Mutex) IsFalsy

func (o *Mutex) IsFalsy() bool

func (*Mutex) Iterate

func (o *Mutex) Iterate() Iterator

func (*Mutex) SetMember

func (o *Mutex) SetMember(idxA string, valueA Object) error

func (*Mutex) String

func (o *Mutex) String() string

func (*Mutex) TypeCode

func (*Mutex) TypeCode() int

func (*Mutex) TypeName

func (*Mutex) TypeName() string

TypeName implements Object interface.

type Mux

type Mux struct {
	ObjectImpl
	Value *http.ServeMux

	Members map[string]Object `json:"-"`
}

Mux object is used for http handlers

func NewMux

func NewMux(argsA ...Object) *Mux

func (*Mux) BinaryOp

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

func (*Mux) Call

func (o *Mux) Call(_ ...Object) (Object, error)

func (*Mux) CallMethod

func (o *Mux) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*Mux) CanCall

func (o *Mux) CanCall() bool

func (*Mux) CanIterate

func (*Mux) CanIterate() bool

func (*Mux) Equal

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

func (*Mux) GetMember

func (o *Mux) GetMember(idxA string) Object

func (*Mux) GetValue

func (o *Mux) GetValue() Object

func (*Mux) HasMemeber

func (o *Mux) HasMemeber() bool

func (*Mux) IndexGet

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

func (*Mux) IndexSet

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

func (*Mux) IsFalsy

func (o *Mux) IsFalsy() bool

func (*Mux) Iterate

func (o *Mux) Iterate() Iterator

func (*Mux) SetMember

func (o *Mux) SetMember(idxA string, valueA Object) error

func (*Mux) String

func (o *Mux) String() string

func (*Mux) TypeCode

func (*Mux) TypeCode() int

func (*Mux) TypeName

func (*Mux) TypeName() string

TypeName implements Object interface.

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 Object

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

	// TypeCode should return the code of the type.
	TypeCode() int

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

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

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

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

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

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

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

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

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

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

	GetValue() Object
	HasMemeber() bool
	GetMember(string) Object
	SetMember(string, Object) error
	CallMethod(string, ...Object) (Object, error)
}

Object represents an object in the VM.

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

func BuiltinDbCloseFunc

func BuiltinDbCloseFunc(c Call) (Object, error)

func BuiltinDealStrFunc

func BuiltinDealStrFunc(c Call) (Object, error)

func BuiltinDelegateFunc

func BuiltinDelegateFunc(c Call) (Object, error)

func CallObjectMethodFunc

func CallObjectMethodFunc(o Object, idxA string, argsA ...Object) (Object, error)

func ConvertToObject

func ConvertToObject(vA interface{}) Object

func GenStatusResult

func GenStatusResult(args ...Object) (Object, error)

func GetObjectMethodFunc

func GetObjectMethodFunc(o Object, idxA string) (Object, error)

func NewBigFloat

func NewBigFloat(c Call) (Object, error)

func NewBigInt

func NewBigInt(c Call) (Object, error)

func NewBytesBuffer

func NewBytesBuffer(c Call) (Object, error)

func NewDelegate

func NewDelegate(c Call) (Object, error)

func NewEvalMachine

func NewEvalMachine(c Call) (Object, error)

func NewExcel

func NewExcel(c Call) (Object, error)

func NewExternalDelegate

func NewExternalDelegate(funcA func(...interface{}) interface{}) Object

func NewFile

func NewFile(c Call) (Object, error)

func NewGel

func NewGel(argsA ...Object) (Object, error)

func NewHttpHandler

func NewHttpHandler(c Call) (Object, error)

func NewHttpReq

func NewHttpReq(c Call) (Object, error)

func NewImage

func NewImage(c Call) (Object, error)

func NewMapArray

func NewMapArray(c Call) (Object, error)

func NewOrderedMap

func NewOrderedMap(argsA ...Object) (Object, error)

func NewQueue

func NewQueue(c Call) (Object, error)

func NewReader

func NewReader(c Call) (Object, error)

func NewStack

func NewStack(c Call) (Object, error)

func NewWriter

func NewWriter(c Call) (Object, error)

func ToObject

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

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

func ToObjectAlt

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

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

type ObjectImpl

type ObjectImpl struct {
}

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

func (ObjectImpl) BinaryOp

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

BinaryOp implements Object interface.

func (ObjectImpl) Call

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

Call implements Object interface.

func (ObjectImpl) CallMethod

func (o ObjectImpl) CallMethod(nameA string, argsA ...Object) (Object, error)

func (ObjectImpl) CanCall

func (ObjectImpl) CanCall() bool

CanCall implements Object interface.

func (ObjectImpl) CanIterate

func (ObjectImpl) CanIterate() bool

CanIterate implements Object interface.

func (ObjectImpl) Equal

func (ObjectImpl) Equal(Object) bool

Equal implements Object interface.

func (ObjectImpl) GetMember

func (o ObjectImpl) GetMember(idxA string) Object

func (ObjectImpl) GetValue

func (o ObjectImpl) GetValue() Object

func (ObjectImpl) HasMemeber

func (o ObjectImpl) HasMemeber() bool

func (ObjectImpl) IndexGet

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

IndexGet implements Object interface.

func (ObjectImpl) IndexSet

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

IndexSet implements Object interface.

func (ObjectImpl) IsFalsy

func (ObjectImpl) IsFalsy() bool

IsFalsy implements Object interface.

func (ObjectImpl) Iterate

func (ObjectImpl) Iterate() Iterator

Iterate implements Object interface.

func (ObjectImpl) SetMember

func (o ObjectImpl) SetMember(idxA string, valueA Object) error

func (ObjectImpl) String

func (o ObjectImpl) String() string

String implements Object interface.

func (ObjectImpl) TypeCode

func (ObjectImpl) TypeCode() int

func (ObjectImpl) TypeName

func (ObjectImpl) TypeName() string

TypeName implements Object interface.

type ObjectPtr

type ObjectPtr struct {
	ObjectImpl
	Value *Object

	Members map[string]Object `json:"-"`
}

ObjectPtr represents a pointer variable. this class is for internal use only, for common purpose, use ObjectRef instead

func (*ObjectPtr) BinaryOp

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

BinaryOp implements Object interface.

func (*ObjectPtr) Call

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

Call implements Object interface.

func (*ObjectPtr) CallMethod

func (o *ObjectPtr) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*ObjectPtr) CanCall

func (o *ObjectPtr) CanCall() bool

CanCall implements Object interface.

func (*ObjectPtr) Copy

func (o *ObjectPtr) Copy() Object

Copy implements Copier interface.

func (*ObjectPtr) Equal

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

Equal implements Object interface.

func (*ObjectPtr) GetMember

func (o *ObjectPtr) GetMember(idxA string) Object

func (*ObjectPtr) GetValue

func (o *ObjectPtr) GetValue() Object

func (*ObjectPtr) HasMemeber

func (o *ObjectPtr) HasMemeber() bool

func (*ObjectPtr) IsFalsy

func (o *ObjectPtr) IsFalsy() bool

IsFalsy implements Object interface.

func (*ObjectPtr) SetMember

func (o *ObjectPtr) SetMember(idxA string, valueA Object) error

func (*ObjectPtr) String

func (o *ObjectPtr) String() string

String implements Object interface.

func (*ObjectPtr) TypeCode

func (o *ObjectPtr) TypeCode() int

func (*ObjectPtr) TypeName

func (o *ObjectPtr) TypeName() string

TypeName implements Object interface.

type ObjectRef

type ObjectRef struct {
	ObjectImpl
	Value *Object

	Members map[string]Object `json:"-"`
}

ObjectRef represents a reference variable. always refer to an Object(i.e. *Object)

func (*ObjectRef) BinaryOp

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

BinaryOp implements Object interface.

func (*ObjectRef) Call

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

Call implements Object interface.

func (*ObjectRef) CallMethod

func (o *ObjectRef) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*ObjectRef) CanCall

func (o *ObjectRef) CanCall() bool

CanCall implements Object interface.

func (*ObjectRef) Copy

func (o *ObjectRef) Copy() Object

Copy implements Copier interface.

func (*ObjectRef) Equal

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

Equal implements Object interface.

func (*ObjectRef) GetMember

func (o *ObjectRef) GetMember(idxA string) Object

func (*ObjectRef) GetValue

func (o *ObjectRef) GetValue() Object

func (*ObjectRef) HasMemeber

func (o *ObjectRef) HasMemeber() bool

func (*ObjectRef) IsFalsy

func (o *ObjectRef) IsFalsy() bool

IsFalsy implements Object interface.

func (*ObjectRef) SetMember

func (o *ObjectRef) SetMember(idxA string, valueA Object) error

func (*ObjectRef) String

func (o *ObjectRef) String() string

String implements Object interface.

func (*ObjectRef) TypeCode

func (o *ObjectRef) TypeCode() int

func (*ObjectRef) TypeName

func (o *ObjectRef) TypeName() string

TypeName implements Object interface.

type Opcode

type Opcode = byte

Opcode represents a single byte operation code.

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

List of opcodes

type OptimizerError

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

OptimizerError represents an optimizer error.

func (*OptimizerError) Error

func (e *OptimizerError) Error() string

func (*OptimizerError) Unwrap

func (e *OptimizerError) Unwrap() error

type OrderedMap

type OrderedMap struct {
	ObjectImpl
	Value *tk.OrderedMap
}

OrderedMap represents map of objects but has order(in the order of push-in) and implements Object interface.

func (*OrderedMap) BinaryOp

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

BinaryOp implements Object interface.

func (*OrderedMap) Call

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

Call implements Object interface.

func (*OrderedMap) CallMethod

func (o *OrderedMap) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*OrderedMap) CanCall

func (*OrderedMap) CanCall() bool

CanCall implements Object interface.

func (*OrderedMap) CanIterate

func (*OrderedMap) CanIterate() bool

CanIterate implements Object interface.

func (*OrderedMap) Copy

func (o *OrderedMap) Copy() Object

Copy implements Copier interface.

func (*OrderedMap) Equal

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

Equal implements Object interface.

func (*OrderedMap) GetMember

func (o *OrderedMap) GetMember(idxA string) Object

func (*OrderedMap) GetValue

func (o *OrderedMap) GetValue() Object

func (*OrderedMap) HasMemeber

func (o *OrderedMap) HasMemeber() bool

func (*OrderedMap) IndexDelete

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

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

func (*OrderedMap) IndexGet

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

IndexGet implements Object interface.

func (*OrderedMap) IndexSet

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

IndexSet implements Object interface.

func (*OrderedMap) IsFalsy

func (o *OrderedMap) IsFalsy() bool

IsFalsy implements Object interface.

func (*OrderedMap) Iterate

func (o *OrderedMap) Iterate() Iterator

Iterate implements Iterable interface.

func (*OrderedMap) Len

func (o *OrderedMap) Len() int

Len implements LengthGetter interface.

func (*OrderedMap) SetMember

func (o *OrderedMap) SetMember(idxA string, valueA Object) error

func (*OrderedMap) String

func (o *OrderedMap) String() string

String implements Object interface.

func (*OrderedMap) TypeCode

func (*OrderedMap) TypeCode() int

func (*OrderedMap) TypeName

func (*OrderedMap) TypeName() string

TypeName implements Object interface.

type OrderedMapIterator

type OrderedMapIterator struct {
	V *OrderedMap
	// contains filtered or unexported fields
}

OrderedMapIterator represents an iterator for the map.

func (*OrderedMapIterator) Key

func (it *OrderedMapIterator) Key() Object

Key implements Iterator interface.

func (*OrderedMapIterator) Next

func (it *OrderedMapIterator) Next() bool

Next implements Iterator interface.

func (*OrderedMapIterator) Value

func (it *OrderedMapIterator) Value() Object

Value implements Iterator interface.

type Queue

type Queue struct {
	ObjectImpl
	Value *tk.AnyQueue

	Members map[string]Object `json:"-"`
}

Queue represents a generic FIFO queue object and implements Object interface.

func (*Queue) BinaryOp

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

BinaryOp implements Object interface.

func (*Queue) Call

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

Call implements Object interface.

func (*Queue) CallMethod

func (o *Queue) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*Queue) CanCall

func (*Queue) CanCall() bool

CanCall implements Object interface.

func (*Queue) CanIterate

func (*Queue) CanIterate() bool

CanIterate implements Object interface.

func (*Queue) GetMember

func (o *Queue) GetMember(idxA string) Object

func (*Queue) GetValue

func (o *Queue) GetValue() Object

func (*Queue) HasMemeber

func (o *Queue) HasMemeber() bool

func (*Queue) IndexGet

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

IndexGet implements Object interface.

func (*Queue) IndexSet

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

IndexSet implements Object interface.

func (*Queue) IsFalsy

func (o *Queue) IsFalsy() bool

IsFalsy implements Object interface.

func (*Queue) Iterate

func (o *Queue) Iterate() Iterator

Iterate implements Iterable interface.

func (*Queue) Len

func (o *Queue) Len() int

Len implements LengthGetter interface.

func (*Queue) SetMember

func (o *Queue) SetMember(idxA string, valueA Object) error

func (*Queue) String

func (o *Queue) String() string

String implements Object interface.

func (*Queue) TypeCode

func (*Queue) TypeCode() int

func (*Queue) TypeName

func (*Queue) TypeName() string

TypeName implements Object interface.

type QueueIterator

type QueueIterator struct {
	V *Queue
	// contains filtered or unexported fields
}

QueueIterator represents an iterator for the Queue.

func (*QueueIterator) Key

func (it *QueueIterator) Key() Object

Key implements Iterator interface.

func (*QueueIterator) Next

func (it *QueueIterator) Next() bool

Next implements Iterator interface.

func (*QueueIterator) Value

func (it *QueueIterator) Value() Object

Value implements Iterator interface.

type Reader

type Reader struct {
	ObjectImpl
	Value io.Reader

	Members map[string]Object `json:"-"`
}

Reader object is used for represent io.Reader type value

func (*Reader) BinaryOp

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

func (*Reader) Call

func (o *Reader) Call(_ ...Object) (Object, error)

func (*Reader) CallMethod

func (o *Reader) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*Reader) CanCall

func (o *Reader) CanCall() bool

func (*Reader) CanIterate

func (*Reader) CanIterate() bool

func (*Reader) Close

func (o *Reader) Close() error

comply to io.Closer

func (*Reader) Equal

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

func (*Reader) GetMember

func (o *Reader) GetMember(idxA string) Object

func (*Reader) GetValue

func (o *Reader) GetValue() Object

func (*Reader) HasMemeber

func (o *Reader) HasMemeber() bool

func (*Reader) IndexGet

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

func (*Reader) IndexSet

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

func (*Reader) IsFalsy

func (o *Reader) IsFalsy() bool

func (*Reader) Iterate

func (o *Reader) Iterate() Iterator

func (*Reader) Read

func (o *Reader) Read(p []byte) (n int, err error)

comply to io.Reader

func (*Reader) SetMember

func (o *Reader) SetMember(idxA string, valueA Object) error

func (*Reader) String

func (o *Reader) String() string

func (*Reader) TypeCode

func (*Reader) TypeCode() int

func (*Reader) TypeName

func (*Reader) TypeName() string

TypeName implements Object interface.

type RuntimeError

type RuntimeError struct {
	Err *Error

	Trace []parser.Pos

	Members map[string]Object `json:"-"`
	// contains filtered or unexported fields
}

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

func (*RuntimeError) BinaryOp

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

BinaryOp implements Object interface.

func (*RuntimeError) Call

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

Call implements Object interface.

func (*RuntimeError) CallMethod

func (o *RuntimeError) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*RuntimeError) CanCall

func (*RuntimeError) CanCall() bool

CanCall implements Object interface.

func (*RuntimeError) CanIterate

func (*RuntimeError) CanIterate() bool

CanIterate implements Object interface.

func (*RuntimeError) Copy

func (o *RuntimeError) Copy() Object

Copy implements Copier interface.

func (*RuntimeError) Equal

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

Equal implements Object interface.

func (*RuntimeError) Error

func (o *RuntimeError) Error() string

Error implements error interface.

func (*RuntimeError) Format

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

Format implements fmt.Formater interface.

func (*RuntimeError) GetMember

func (o *RuntimeError) GetMember(idxA string) Object

func (*RuntimeError) GetValue

func (o *RuntimeError) GetValue() Object

func (*RuntimeError) HasMemeber

func (o *RuntimeError) HasMemeber() bool

func (*RuntimeError) IndexGet

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

IndexGet implements Object interface.

func (*RuntimeError) IndexSet

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

IndexSet implements Object interface.

func (*RuntimeError) IsFalsy

func (o *RuntimeError) IsFalsy() bool

IsFalsy implements Object interface.

func (*RuntimeError) Iterate

func (*RuntimeError) Iterate() Iterator

Iterate implements Object interface.

func (*RuntimeError) NewError

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

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

func (*RuntimeError) SetMember

func (o *RuntimeError) SetMember(idxA string, valueA Object) error

func (*RuntimeError) StackTrace

func (o *RuntimeError) StackTrace() StackTrace

StackTrace returns stack trace if set otherwise returns nil.

func (*RuntimeError) String

func (o *RuntimeError) String() string

String implements Object interface.

func (*RuntimeError) TypeCode

func (*RuntimeError) TypeCode() int

func (*RuntimeError) TypeName

func (*RuntimeError) TypeName() string

TypeName implements Object interface.

func (*RuntimeError) Unwrap

func (o *RuntimeError) Unwrap() error

type Seq

type Seq struct {
	ObjectImpl
	Value *(tk.Seq)

	Members map[string]Object `json:"-"`
}

Seq object is used for generate unique sequence number(integer)

func NewSeq

func NewSeq(argsA ...Object) *Seq

func (*Seq) BinaryOp

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

func (*Seq) Call

func (o *Seq) Call(_ ...Object) (Object, error)

func (*Seq) CallMethod

func (o *Seq) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*Seq) CanCall

func (o *Seq) CanCall() bool

func (*Seq) CanIterate

func (*Seq) CanIterate() bool

func (*Seq) Equal

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

func (*Seq) GetMember

func (o *Seq) GetMember(idxA string) Object

func (*Seq) GetValue

func (o *Seq) GetValue() Object

func (*Seq) HasMemeber

func (o *Seq) HasMemeber() bool

func (*Seq) IndexGet

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

func (*Seq) IndexSet

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

func (*Seq) IsFalsy

func (o *Seq) IsFalsy() bool

func (*Seq) Iterate

func (o *Seq) Iterate() Iterator

func (*Seq) SetMember

func (o *Seq) SetMember(idxA string, valueA Object) error

func (*Seq) SetValue

func (o *Seq) SetValue(valueA Object) error

func (*Seq) String

func (o *Seq) String() string

func (*Seq) TypeCode

func (*Seq) TypeCode() int

func (*Seq) TypeName

func (*Seq) TypeName() string

TypeName implements Object interface.

type SimpleOptimizer

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

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

func NewOptimizer

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

NewOptimizer creates an Optimizer object.

func (*SimpleOptimizer) Optimize

func (so *SimpleOptimizer) Optimize() error

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

func (*SimpleOptimizer) Total

func (so *SimpleOptimizer) Total() int

Total returns total number of evaluated constants and expressions.

type SourceModule

type SourceModule struct {
	Src []byte
}

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

func (*SourceModule) Import

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

Import returns a module source code.

type Stack

type Stack struct {
	ObjectImpl
	Value *tk.SimpleStack

	Members map[string]Object `json:"-"`
}

Stack represents a generic stack object and implements Object interface.

func (*Stack) BinaryOp

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

BinaryOp implements Object interface.

func (*Stack) Call

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

Call implements Object interface.

func (*Stack) CallMethod

func (o *Stack) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*Stack) CanCall

func (*Stack) CanCall() bool

CanCall implements Object interface.

func (*Stack) CanIterate

func (*Stack) CanIterate() bool

CanIterate implements Object interface.

func (*Stack) Equal

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

Equal implements Object interface.

func (*Stack) GetMember

func (o *Stack) GetMember(idxA string) Object

func (*Stack) GetValue

func (o *Stack) GetValue() Object

func (*Stack) HasMemeber

func (o *Stack) HasMemeber() bool

func (*Stack) IndexGet

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

IndexGet implements Object interface.

func (*Stack) IndexSet

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

IndexSet implements Object interface.

func (*Stack) IsFalsy

func (o *Stack) IsFalsy() bool

IsFalsy implements Object interface.

func (*Stack) Iterate

func (o *Stack) Iterate() Iterator

Iterate implements Iterable interface.

func (*Stack) Len

func (o *Stack) Len() int

Len implements LengthGetter interface.

func (*Stack) Queue

func (o *Stack) Queue(right Object) bool

Equal implements Object interface.

func (*Stack) SetMember

func (o *Stack) SetMember(idxA string, valueA Object) error

func (*Stack) String

func (o *Stack) String() string

String implements Object interface.

func (*Stack) TypeCode

func (*Stack) TypeCode() int

func (*Stack) TypeName

func (*Stack) TypeName() string

TypeName implements Object interface.

type StackIterator

type StackIterator struct {
	V *Stack
	// contains filtered or unexported fields
}

StackIterator represents an iterator for the Stack.

func (*StackIterator) Key

func (it *StackIterator) Key() Object

Key implements Iterator interface.

func (*StackIterator) Next

func (it *StackIterator) Next() bool

Next implements Iterator interface.

func (*StackIterator) Value

func (it *StackIterator) Value() Object

Value implements Iterator interface.

type StackTrace

type StackTrace []parser.SourceFilePos

StackTrace is the stack of source file positions.

func (StackTrace) Format

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

Format formats the StackTrace to the fmt.Formatter interface.

type StatusResult

type StatusResult struct {
	ObjectImpl
	Status  string
	Value   string
	Objects interface{}

	Members map[string]Object    `json:"-"`
	Methods map[string]*Function `json:"-"`
}

func (*StatusResult) BinaryOp

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

func (*StatusResult) Call

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

func (*StatusResult) CallMethod

func (o *StatusResult) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*StatusResult) Equal

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

func (*StatusResult) GetMember

func (o *StatusResult) GetMember(idxA string) Object

func (*StatusResult) GetValue

func (o *StatusResult) GetValue() Object

func (*StatusResult) HasMemeber

func (o *StatusResult) HasMemeber() bool

func (*StatusResult) IndexGet

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

func (*StatusResult) IndexSet

func (o *StatusResult) IndexSet(key, value Object) error

func (*StatusResult) SetMember

func (o *StatusResult) SetMember(idxA string, valueA Object) error

func (*StatusResult) String

func (o *StatusResult) String() string

func (*StatusResult) TypeCode

func (o *StatusResult) TypeCode() int

func (*StatusResult) TypeName

func (o *StatusResult) TypeName() string

type String

type String struct {
	ObjectImpl
	Value string

	Members map[string]Object `json:"-"`
}

String represents string values and implements Object interface.

func ToString

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

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

func ToStringObject

func ToStringObject(argA interface{}) String

func (String) BinaryOp

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

BinaryOp implements Object interface.

func (String) Call

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

Call implements Object interface.

func (String) CallMethod

func (o String) CallMethod(nameA string, argsA ...Object) (Object, error)

func (String) CanCall

func (o String) CanCall() bool

CanCall implements Object interface.

func (String) CanIterate

func (String) CanIterate() bool

CanIterate implements Object interface.

func (String) Copy

func (o String) Copy() Object

func (String) Equal

func (o String) Equal(right Object) bool

Equal implements Object interface.

func (String) Format

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

Format implements fmt.Formatter interface.

func (String) GetMember

func (o String) GetMember(idxA string) Object

func (String) GetValue

func (o String) GetValue() Object

func (String) HasMemeber

func (o String) HasMemeber() bool

func (String) IndexGet

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

IndexGet represents string values and implements Object interface.

func (String) IndexSet

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

IndexSet implements Object interface.

func (String) IsFalsy

func (o String) IsFalsy() bool

IsFalsy implements Object interface.

func (String) Iterate

func (o String) Iterate() Iterator

Iterate implements Object interface.

func (String) Len

func (o String) Len() int

Len implements LengthGetter interface.

func (String) MarshalJSON

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

func (String) SetMember

func (o String) SetMember(idxA string, valueA Object) error

func (String) String

func (o String) String() string

func (String) TypeCode

func (String) TypeCode() int

func (String) TypeName

func (String) TypeName() string

TypeName implements Object interface.

type StringBuilder

type StringBuilder struct {
	ObjectImpl
	Value *strings.Builder

	Members map[string]Object `json:"-"`
}

func (*StringBuilder) BinaryOp

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

func (*StringBuilder) Call

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

func (*StringBuilder) CallMethod

func (o *StringBuilder) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*StringBuilder) CallName

func (o *StringBuilder) CallName(nameA string, c Call) (Object, error)

func (*StringBuilder) CanCall

func (*StringBuilder) CanCall() bool

func (*StringBuilder) CanIterate

func (*StringBuilder) CanIterate() bool

func (*StringBuilder) Copy

func (o *StringBuilder) Copy() Object

func (*StringBuilder) Equal

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

func (*StringBuilder) GetMember

func (o *StringBuilder) GetMember(idxA string) Object

func (*StringBuilder) GetValue

func (o *StringBuilder) GetValue() Object

func (*StringBuilder) HasMemeber

func (o *StringBuilder) HasMemeber() bool

func (*StringBuilder) IndexGet

func (o *StringBuilder) IndexGet(index Object) (value Object, err error)

func (*StringBuilder) IndexSet

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

func (*StringBuilder) IsFalsy

func (o *StringBuilder) IsFalsy() bool

func (*StringBuilder) Iterate

func (*StringBuilder) Iterate() Iterator

func (*StringBuilder) SetMember

func (o *StringBuilder) SetMember(idxA string, valueA Object) error

func (*StringBuilder) String

func (o *StringBuilder) String() string

func (*StringBuilder) TypeCode

func (o *StringBuilder) TypeCode() int

func (*StringBuilder) TypeName

func (o *StringBuilder) TypeName() string

type StringIterator

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

StringIterator represents an iterator for the string.

func (*StringIterator) Key

func (it *StringIterator) Key() Object

Key implements Iterator interface.

func (*StringIterator) Next

func (it *StringIterator) Next() bool

Next implements Iterator interface.

func (*StringIterator) Value

func (it *StringIterator) Value() Object

Value implements Iterator interface.

type Symbol

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

Symbol represents a symbol in the symbol table.

func (*Symbol) String

func (s *Symbol) String() string

type SymbolScope

type SymbolScope string

SymbolScope represents a symbol scope.

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

List of symbol scopes

type SymbolTable

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

SymbolTable represents a symbol table.

func NewSymbolTable

func NewSymbolTable() *SymbolTable

NewSymbolTable creates new symbol table object.

func (*SymbolTable) DefineGlobal

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

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

func (*SymbolTable) DefineLocal

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

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

func (*SymbolTable) DisableBuiltin

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

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

func (*SymbolTable) DisabledBuiltins

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

DisabledBuiltins returns disabled builtin names.

func (*SymbolTable) EnableParams

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

EnableParams enables or disables definition of parameters.

func (*SymbolTable) Fork

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

Fork creates a new symbol table for a new scope.

func (*SymbolTable) FreeSymbols

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

FreeSymbols returns registered free symbols for the scope.

func (*SymbolTable) InBlock

func (st *SymbolTable) InBlock() bool

InBlock returns true if symbol table belongs to a block.

func (*SymbolTable) MaxSymbols

func (st *SymbolTable) MaxSymbols() int

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

func (*SymbolTable) NextIndex

func (st *SymbolTable) NextIndex() int

NextIndex returns the next symbol index.

func (*SymbolTable) NumParams

func (st *SymbolTable) NumParams() int

NumParams returns number of parameters for the scope.

func (*SymbolTable) Parent

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

Parent returns the outer scope of the current symbol table.

func (*SymbolTable) Resolve

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

Resolve resolves a symbol with a given name.

func (*SymbolTable) SetParams

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

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

func (*SymbolTable) ShadowedBuiltins

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

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

func (*SymbolTable) Symbols

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

Symbols returns registered symbols for the scope.

type SyncIterator

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

SyncIterator represents an iterator for the SyncMap.

func (*SyncIterator) Key

func (it *SyncIterator) Key() Object

Key implements Iterator interface.

func (*SyncIterator) Next

func (it *SyncIterator) Next() bool

Next implements Iterator interface.

func (*SyncIterator) Value

func (it *SyncIterator) Value() Object

Value implements Iterator interface.

type SyncMap

type SyncMap struct {
	Value Map

	Members map[string]Object `json:"-"`
	// contains filtered or unexported fields
}

SyncMap represents map of objects and implements Object interface.

func ToSyncMap

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

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

func (*SyncMap) BinaryOp

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

BinaryOp implements Object interface.

func (*SyncMap) Call

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

Call implements Object interface.

func (*SyncMap) CallMethod

func (o *SyncMap) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*SyncMap) CanCall

func (*SyncMap) CanCall() bool

CanCall implements Object interface.

func (*SyncMap) CanIterate

func (o *SyncMap) CanIterate() bool

CanIterate implements Object interface.

func (*SyncMap) Copy

func (o *SyncMap) Copy() Object

Copy implements Copier interface.

func (*SyncMap) Equal

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

Equal implements Object interface.

func (*SyncMap) Get

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

Get returns Object in map if exists.

func (*SyncMap) GetMember

func (o *SyncMap) GetMember(idxA string) Object

func (*SyncMap) GetValue

func (o *SyncMap) GetValue() Object

func (*SyncMap) HasMemeber

func (o *SyncMap) HasMemeber() bool

func (*SyncMap) IndexDelete

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

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

func (*SyncMap) IndexGet

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

IndexGet implements Object interface.

func (*SyncMap) IndexSet

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

IndexSet implements Object interface.

func (*SyncMap) IsFalsy

func (o *SyncMap) IsFalsy() bool

IsFalsy implements Object interface.

func (*SyncMap) Iterate

func (o *SyncMap) Iterate() Iterator

Iterate implements Iterable interface.

func (*SyncMap) Len

func (o *SyncMap) Len() int

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

func (*SyncMap) Lock

func (o *SyncMap) Lock()

Lock locks the underlying mutex for writing.

func (*SyncMap) RLock

func (o *SyncMap) RLock()

RLock locks the underlying mutex for reading.

func (*SyncMap) RUnlock

func (o *SyncMap) RUnlock()

RUnlock unlocks the underlying mutex for reading.

func (*SyncMap) SetMember

func (o *SyncMap) SetMember(idxA string, valueA Object) error

func (*SyncMap) String

func (o *SyncMap) String() string

String implements Object interface.

func (*SyncMap) TypeCode

func (*SyncMap) TypeCode() int

func (*SyncMap) TypeName

func (*SyncMap) TypeName() string

TypeName implements Object interface.

func (*SyncMap) Unlock

func (o *SyncMap) Unlock()

Unlock unlocks the underlying mutex for writing.

type Time

type Time struct {
	Value time.Time

	Members map[string]Object `json:"-"`
}

Time represents time values and implements Object interface.

func ToTime

func ToTime(o Object) (ret *Time, ok bool)

ToTime will try to convert given given Object to *Time value.

func (*Time) BinaryOp

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

BinaryOp implements Object interface.

func (*Time) Call

func (*Time) Call(args ...Object) (Object, error)

Call implements Object interface.

func (*Time) CallMethod

func (o *Time) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*Time) CallName

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

func (*Time) CanCall

func (*Time) CanCall() bool

CanCall implements Object interface.

func (*Time) CanIterate

func (*Time) CanIterate() bool

CanIterate implements Object interface.

func (*Time) Equal

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

Equal implements Object interface.

func (*Time) GetMember

func (o *Time) GetMember(idxA string) Object

func (*Time) GetValue

func (o *Time) GetValue() Object

func (*Time) HasMemeber

func (o *Time) HasMemeber() bool

func (*Time) IndexGet

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

IndexGet implements Object interface.

func (*Time) IndexSet

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

IndexSet implements Object interface.

func (*Time) IsFalsy

func (o *Time) IsFalsy() bool

IsFalsy implements Object interface.

func (*Time) Iterate

func (*Time) Iterate() Iterator

Iterate implements Object interface.

func (*Time) MarshalBinary

func (o *Time) MarshalBinary() ([]byte, error)

MarshalBinary implements encoding.BinaryMarshaler interface.

func (*Time) MarshalJSON

func (o *Time) MarshalJSON() ([]byte, error)

MarshalJSON implements json.JSONMarshaler interface.

func (*Time) SetMember

func (o *Time) SetMember(idxA string, valueA Object) error

func (*Time) String

func (o *Time) String() string

String implements Object interface.

func (*Time) TypeCode

func (*Time) TypeCode() int

func (*Time) TypeName

func (*Time) TypeName() string

TypeName implements Object interface.

func (*Time) UnmarshalBinary

func (o *Time) UnmarshalBinary(data []byte) error

UnmarshalBinary implements encoding.BinaryUnmarshaler interface.

func (*Time) UnmarshalJSON

func (o *Time) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.JSONUnmarshaler interface.

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 Charlang uint value.

func (Uint) BinaryOp

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

BinaryOp implements Object interface.

func (Uint) Call

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

Call implements Object interface.

func (Uint) CallMethod

func (o Uint) CallMethod(nameA string, argsA ...Object) (Object, error)

func (Uint) CanCall

func (o Uint) CanCall() bool

CanCall implements Object interface.

func (Uint) CanIterate

func (Uint) CanIterate() bool

CanIterate implements Object interface.

func (Uint) Equal

func (o Uint) Equal(right Object) bool

Equal implements Object interface.

func (Uint) Format

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

Format implements fmt.Formatter interface.

func (Uint) GetMember

func (o Uint) GetMember(idxA string) Object

func (Uint) GetValue

func (o Uint) GetValue() Object

func (Uint) HasMemeber

func (o Uint) HasMemeber() bool

func (Uint) IndexGet

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

IndexGet implements Object interface.

func (Uint) IndexSet

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

IndexSet implements Object interface.

func (Uint) IsFalsy

func (o Uint) IsFalsy() bool

IsFalsy implements Object interface.

func (Uint) Iterate

func (Uint) Iterate() Iterator

Iterate implements Object interface.

func (Uint) SetMember

func (o Uint) SetMember(idxA string, valueA Object) error

func (Uint) String

func (o Uint) String() string

String implements Object interface.

func (Uint) TypeCode

func (Uint) TypeCode() int

func (Uint) TypeName

func (Uint) TypeName() string

TypeName implements Object interface.

type UndefinedType

type UndefinedType struct {
	ObjectImpl
}

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

func (*UndefinedType) BinaryOp

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

BinaryOp implements Object interface.

func (*UndefinedType) Call

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

Call implements Object interface.

func (*UndefinedType) CallMethod

func (o *UndefinedType) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*UndefinedType) Equal

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

Equal implements Object interface.

func (*UndefinedType) GetMember

func (o *UndefinedType) GetMember(idxA string) Object

func (*UndefinedType) GetValue

func (o *UndefinedType) GetValue() Object

func (*UndefinedType) HasMemeber

func (o *UndefinedType) HasMemeber() bool

func (*UndefinedType) IndexGet

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

IndexGet implements Object interface.

func (*UndefinedType) IndexSet

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

IndexSet implements Object interface.

func (*UndefinedType) SetMember

func (o *UndefinedType) SetMember(idxA string, valueA Object) error

func (*UndefinedType) String

func (o *UndefinedType) String() string

String implements Object interface.

func (*UndefinedType) TypeCode

func (o *UndefinedType) TypeCode() int

func (*UndefinedType) TypeName

func (o *UndefinedType) TypeName() string

TypeName implements Object interface.

type VM

type VM struct {
	LeBuf     []string
	LeSshInfo map[string]string
	// contains filtered or unexported fields
}

VM executes the instructions in Bytecode.

func NewVM

func NewVM(bc *Bytecode) *VM

NewVM creates a VM object.

func (*VM) Abort

func (vm *VM) Abort()

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

func (*VM) Aborted

func (vm *VM) Aborted() bool

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

func (*VM) Clear

func (vm *VM) Clear() *VM

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

func (*VM) GetBytecode

func (vm *VM) GetBytecode() *Bytecode

func (*VM) GetBytecodeInfo

func (vm *VM) GetBytecodeInfo() string

func (*VM) GetCompilerOptions

func (vm *VM) GetCompilerOptions() *CompilerOptions

func (*VM) GetCurFunc

func (vm *VM) GetCurFunc() Object

func (*VM) GetCurInstr

func (vm *VM) GetCurInstr() Object

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

func (vm *VM) GetLocalsQuick() []Object

func (*VM) GetSrcPos

func (vm *VM) GetSrcPos() parser.Pos

func (*VM) Run

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

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

func (*VM) RunCompiledFunction

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

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

func (*VM) SetBytecode

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

SetBytecode enables to set a new Bytecode.

func (*VM) SetRecover

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

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

type ValueSetter

type ValueSetter interface {
	SetValue(Object) error
}

type Writer

type Writer struct {
	ObjectImpl
	Value io.Writer

	Members map[string]Object `json:"-"`
}

Writer object is used for represent io.Writer type value

func (*Writer) BinaryOp

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

func (*Writer) Call

func (o *Writer) Call(_ ...Object) (Object, error)

func (*Writer) CallMethod

func (o *Writer) CallMethod(nameA string, argsA ...Object) (Object, error)

func (*Writer) CanCall

func (o *Writer) CanCall() bool

func (*Writer) CanIterate

func (*Writer) CanIterate() bool

func (*Writer) Close

func (o *Writer) Close() error

comply to io.Closer

func (*Writer) Equal

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

func (*Writer) GetMember

func (o *Writer) GetMember(idxA string) Object

func (*Writer) GetValue

func (o *Writer) GetValue() Object

func (*Writer) HasMemeber

func (o *Writer) HasMemeber() bool

func (*Writer) IndexGet

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

func (*Writer) IndexSet

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

func (*Writer) IsFalsy

func (o *Writer) IsFalsy() bool

func (*Writer) Iterate

func (o *Writer) Iterate() Iterator

func (*Writer) SetMember

func (o *Writer) SetMember(idxA string, valueA Object) error

func (*Writer) String

func (o *Writer) String() string

func (*Writer) TypeCode

func (*Writer) TypeCode() int

func (*Writer) TypeName

func (*Writer) TypeName() string

TypeName implements Object interface.

func (*Writer) Write

func (o *Writer) Write(p []byte) (n int, err error)

comply to io.Writer

Directories

Path Synopsis
cmd
char Module
dll module
internal
ex
Package ex provides ex module implementing some extra functions.
Package ex provides ex module implementing some extra functions.
fmt
strings
Package strings provides strings module implementing simple functions to manipulate UTF-8 encoded strings for Charlang script language.
Package strings provides strings module implementing simple functions to manipulate UTF-8 encoded strings for Charlang script language.
time
Package time provides time module for measuring and displaying time for Charlang script language.
Package time provides time module for measuring and displaying time for Charlang script language.
test1 module

Jump to

Keyboard shortcuts

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