This commit is contained in:
Star 2024-02-06 17:39:51 +08:00
commit d7054c4994
23 changed files with 4134 additions and 0 deletions

24
LICENSE Normal file
View File

@ -0,0 +1,24 @@
MIT License
Copyright (c) 2022 Brian Wang <wangbuke@gmail.com>
Copyright (c) 2020 Kenta Iwasaki <kenta@lithdew.net>
Copyright (c) 2017-2020 Fabrice Bellard
Copyright (c) 2017-2020 Charlie Gordon
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

276
README.md Normal file
View File

@ -0,0 +1,276 @@
# quickjs-go
English | [简体中文](README_zh-cn.md)
Fork from https://github.com/buke/quickjs-go, fixed performance bug for function callback
[![Test](https://github.com/buke/quickjs-go/workflows/Test/badge.svg)](https://github.com/buke/quickjs-go/actions?query=workflow%3ATest)
[![codecov](https://codecov.io/gh/buke/quickjs-go/branch/main/graph/badge.svg?token=DW5RGD01AG)](https://codecov.io/gh/buke/quickjs-go)
[![Go Report Card](https://goreportcard.com/badge/github.com/buke/quickjs-go)](https://goreportcard.com/report/github.com/buke/quickjs-go)
[![GoDoc](https://pkg.go.dev/badge/github.com/buke/quickjs-go?status.svg)](https://pkg.go.dev/github.com/buke/quickjs-go?tab=doc)
[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fbuke%2Fquickjs-go.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2Fbuke%2Fquickjs-go?ref=badge_shield)
Go bindings to QuickJS: a fast, small, and embeddable ES2020 JavaScript interpreter.
## Features
* Evaluate script
* Compile script into bytecode and Eval from bytecode
* Operate JavaScript values and objects in Go
* Bind Go function to JavaScript async/sync function
* Simple exception throwing and catching
## Guidelines
1. Free `quickjs.Runtime` and `quickjs.Context` once you are done using them.
2. Free `quickjs.Value`'s returned by `Eval()` and `EvalFile()`. All other values do not need to be freed, as they get garbage-collected.
3. Use `ExecuteAllPendingJobs` wait for promise/job result after you using promise/job
4. You may access the stacktrace of an error returned by `Eval()` or `EvalFile()` by casting it to a `*quickjs.Error`.
5. Make new copies of arguments should you want to return them in functions you created.
## Usage
```go
import "apigo.cloud/git/apigo/qjs"
```
### Run a script
```go
package main
import (
"fmt"
"apigo.cloud/git/apigo/qjs"
)
func main() {
// Create a new runtime
rt := quickjs.NewRuntime()
defer rt.Close()
// Create a new context
ctx := rt.NewContext()
defer ctx.Close()
ret, err := ctx.Eval("'Hello ' + 'QuickJS!'")
if err != nil {
println(err.Error())
}
fmt.Println(ret.String())
}
```
### Get/Set Javascript Object
```go
package main
import (
"fmt"
"apigo.cloud/git/apigo/qjs"
)
func main() {
// Create a new runtime
rt := quickjs.NewRuntime()
defer rt.Close()
// Create a new context
ctx := rt.NewContext()
defer ctx.Close()
test := ctx.Object()
test.Set("A", ctx.String("String A"))
test.Set("B", ctx.String("String B"))
test.Set("C", ctx.String("String C"))
ctx.Globals().Set("test", test)
ret, _ := ctx.Eval(`Object.keys(test).map(key => test[key]).join(" ")`)
defer ret.Free()
fmt.Println(ret.String())
}
```
### Bind Go Funtion to Javascript async/sync function
```go
package main
import "apigo.cloud/git/apigo/qjs"
func main() {
// Create a new runtime
rt := quickjs.NewRuntime()
defer rt.Close()
// Create a new context
ctx := rt.NewContext()
defer ctx.Close()
// Create a new object
test := ctx.Object()
defer test.Free()
// bind properties to the object
test.Set("A", test.Context().String("String A"))
test.Set("B", ctx.Int32(0))
test.Set("C", ctx.Bool(false))
// bind go function to js object
test.Set("hello", ctx.Function(func(ctx *quickjs.Context, this quickjs.Value, args []quickjs.Value) quickjs.Value {
return ctx.String("Hello " + args[0].String())
}))
// bind "test" object to global object
ctx.Globals().Set("test", test)
// call js function by js
js_ret, _ := ctx.Eval(`test.hello("Javascript!")`)
fmt.Println(js_ret.String())
// call js function by go
go_ret := ctx.Globals().Get("test").Call("hello", ctx.String("Golang!"))
fmt.Println(go_ret.String())
//bind go function to Javascript async function
ctx.Globals().Set("testAsync", ctx.AsyncFunction(func(ctx *quickjs.Context, this quickjs.Value, promise quickjs.Value, args []quickjs.Value) {
promise.Call("resolve", ctx.String("Hello Async Function!"))
}))
ret, _ := ctx.Eval(`
var ret;
testAsync().then(v => ret = v)
`)
defer ret.Free()
// wait for promise resolve
rt.ExecuteAllPendingJobs()
//get promise result
asyncRet, _ := ctx.Eval("ret")
defer asyncRet.Free()
fmt.Println(asyncRet.String())
// Output:
// Hello Javascript!
// Hello Golang!
// Hello Async Function!
}
```
### Error Handling
```go
package main
import (
"fmt"
"apigo.cloud/git/apigo/qjs"
)
func main() {
// Create a new runtime
rt := quickjs.NewRuntime()
defer rt.Close()
// Create a new context
ctx := rt.NewContext()
defer ctx.Close()
ctx.Globals().SetFunction("A", func(ctx *Context, this Value, args []Value) Value {
// raise error
return ctx.ThrowError(expected)
})
_, actual := ctx.Eval("A()")
fmt.Println(actual.Error())
}
```
### Bytecode Compiler
```go
package main
import (
"fmt"
"apigo.cloud/git/apigo/qjs"
)
func main() {
// Create a new runtime
rt := quickjs.NewRuntime()
defer rt.Close()
// Create a new context
ctx := rt.NewContext()
defer ctx.Close()
jsStr := `
function fib(n)
{
if (n <= 0)
return 0;
else if (n == 1)
return 1;
else
return fib(n - 1) + fib(n - 2);
}
fib(10)
`
// Compile the script to bytecode
buf, _ := ctx.Compile(jsStr)
// Create a new runtime
rt2 := quickjs.NewRuntime()
defer rt2.Close()
// Create a new context
ctx2 := rt2.NewContext()
defer ctx2.Close()
//Eval bytecode
result, _ := ctx2.EvalBytecode(buf)
fmt.Println(result.Int32())
}
```
### Runtime Options: memory, stack, GC, ...
```go
package main
import (
"fmt"
"apigo.cloud/git/apigo/qjs"
)
func main() {
// Create a new runtime
rt := quickjs.NewRuntime()
defer rt.Close()
// set runtime options
rt.SetMemoryLimit(256 * 1024) //256KB
rt.SetMaxStackSize(65534)
// Create a new context
ctx := rt.NewContext()
defer ctx.Close()
result, err := ctx.Eval(`var array = []; while (true) { array.push(null) }`)
defer result.Free()
}
```
## Documentation
Go Reference & more examples: https://pkg.go.dev/github.com/buke/quickjs-go
## License
[MIT](./LICENSE)
[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fbuke%2Fquickjs-go.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2Fbuke%2Fquickjs-go?ref=badge_large)
## Related Projects
* https://github.com/buke/quickjs-go-polyfill

276
README_zh-cn.md Normal file
View File

@ -0,0 +1,276 @@
# quickjs-go
[English](README.md) | 简体中文
源自 https://github.com/buke/quickjs-go, 修复了函数回调时的性能问题
[![Test](https://github.com/buke/quickjs-go/workflows/Test/badge.svg)](https://github.com/buke/quickjs-go/actions?query=workflow%3ATest)
[![codecov](https://codecov.io/gh/buke/quickjs-go/branch/main/graph/badge.svg?token=DW5RGD01AG)](https://codecov.io/gh/buke/quickjs-go)
[![Go Report Card](https://goreportcard.com/badge/github.com/buke/quickjs-go)](https://goreportcard.com/report/github.com/buke/quickjs-go)
[![GoDoc](https://pkg.go.dev/badge/github.com/buke/quickjs-go?status.svg)](https://pkg.go.dev/github.com/buke/quickjs-go?tab=doc)
[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fbuke%2Fquickjs-go.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2Fbuke%2Fquickjs-go?ref=badge_shield)
Go 语言的QuickJS绑定库快速、小型、可嵌入的ES2020 JavaScript解释器。
## 功能
* 执行javascript脚本
* 编译javascript脚本到字节码并执行字节码
* 在 Go 中操作 JavaScript 值和对象
* 绑定 Go 函数到 JavaScript 同步函数和异步函数
* 简单的异常抛出和捕获
## 指南
1. 在使用完毕后,请记得关闭 `quickjs.Runtime``quickjs.Context`
2. 请记得关闭由 `Eval()``EvalFile()` 返回的 `quickjs.Value`。其他值不需要关闭,因为它们会被垃圾回收。
3. 如果你使用了promise 或 async function请使用 `ExecuteAllPendingJobs` 等待所有的promise/job结果。
4. You may access the stacktrace of an error returned by `Eval()` or `EvalFile()` by casting it to a `*quickjs.Error`.
4. 如果`Eval()` 或 `EvalFile()`返回了错误,可强制转换为`*quickjs.Error`以读取错误的堆栈信息。
5. 如果你想在函数中返回参数,请在函数中复制参数。
## 用法
```go
import "apigo.cloud/git/apigo/qjs"
```
### 执行javascript脚本
```go
package main
import (
"fmt"
"apigo.cloud/git/apigo/qjs"
)
func main() {
// Create a new runtime
rt := quickjs.NewRuntime()
defer rt.Close()
// Create a new context
ctx := rt.NewContext()
defer ctx.Close()
ret, err := ctx.Eval("'Hello ' + 'QuickJS!'")
if err != nil {
println(err.Error())
}
fmt.Println(ret.String())
}
```
### 读取/设置 JavaScript 对象
```go
package main
import (
"fmt"
"apigo.cloud/git/apigo/qjs"
)
func main() {
// Create a new runtime
rt := quickjs.NewRuntime()
defer rt.Close()
// Create a new context
ctx := rt.NewContext()
defer ctx.Close()
test := ctx.Object()
test.Set("A", ctx.String("String A"))
test.Set("B", ctx.String("String B"))
test.Set("C", ctx.String("String C"))
ctx.Globals().Set("test", test)
ret, _ := ctx.Eval(`Object.keys(test).map(key => test[key]).join(" ")`)
defer ret.Free()
fmt.Println(ret.String())
}
```
### 函数绑定
```go
package main
import "apigo.cloud/git/apigo/qjs"
func main() {
// Create a new runtime
rt := quickjs.NewRuntime()
defer rt.Close()
// Create a new context
ctx := rt.NewContext()
defer ctx.Close()
// Create a new object
test := ctx.Object()
defer test.Free()
// bind properties to the object
test.Set("A", test.Context().String("String A"))
test.Set("B", ctx.Int32(0))
test.Set("C", ctx.Bool(false))
// bind go function to js object
test.Set("hello", ctx.Function(func(ctx *quickjs.Context, this quickjs.Value, args []quickjs.Value) quickjs.Value {
return ctx.String("Hello " + args[0].String())
}))
// bind "test" object to global object
ctx.Globals().Set("test", test)
// call js function by js
js_ret, _ := ctx.Eval(`test.hello("Javascript!")`)
fmt.Println(js_ret.String())
// call js function by go
go_ret := ctx.Globals().Get("test").Call("hello", ctx.String("Golang!"))
fmt.Println(go_ret.String())
//bind go function to Javascript async function
ctx.Globals().Set("testAsync", ctx.AsyncFunction(func(ctx *quickjs.Context, this quickjs.Value, promise quickjs.Value, args []quickjs.Value) {
promise.Call("resolve", ctx.String("Hello Async Function!"))
}))
ret, _ := ctx.Eval(`
var ret;
testAsync().then(v => ret = v)
`)
defer ret.Free()
// wait for promise resolve
rt.ExecuteAllPendingJobs()
//get promise result
asyncRet, _ := ctx.Eval("ret")
defer asyncRet.Free()
fmt.Println(asyncRet.String())
// Output:
// Hello Javascript!
// Hello Golang!
// Hello Async Function!
}
```
### 异常抛出和捕获
```go
package main
import (
"fmt"
"apigo.cloud/git/apigo/qjs"
)
func main() {
// Create a new runtime
rt := quickjs.NewRuntime()
defer rt.Close()
// Create a new context
ctx := rt.NewContext()
defer ctx.Close()
ctx.Globals().SetFunction("A", func(ctx *Context, this Value, args []Value) Value {
// raise error
return ctx.ThrowError(expected)
})
_, actual := ctx.Eval("A()")
fmt.Println(actual.Error())
}
```
### Bytecode编译和执行
```go
package main
import (
"fmt"
"apigo.cloud/git/apigo/qjs"
)
func main() {
// Create a new runtime
rt := quickjs.NewRuntime()
defer rt.Close()
// Create a new context
ctx := rt.NewContext()
defer ctx.Close()
jsStr := `
function fib(n)
{
if (n <= 0)
return 0;
else if (n == 1)
return 1;
else
return fib(n - 1) + fib(n - 2);
}
fib(10)
`
// Compile the script to bytecode
buf, _ := ctx.Compile(jsStr)
// Create a new runtime
rt2 := quickjs.NewRuntime()
defer rt2.Close()
// Create a new context
ctx2 := rt2.NewContext()
defer ctx2.Close()
//Eval bytecode
result, _ := ctx2.EvalBytecode(buf)
fmt.Println(result.Int32())
}
```
### 设置内存、栈、GC等等
```go
package main
import (
"fmt"
"apigo.cloud/git/apigo/qjs"
)
func main() {
// Create a new runtime
rt := quickjs.NewRuntime()
defer rt.Close()
// set runtime options
rt.SetMemoryLimit(256 * 1024) //256KB
rt.SetMaxStackSize(65534)
// Create a new context
ctx := rt.NewContext()
defer ctx.Close()
result, err := ctx.Eval(`var array = []; while (true) { array.push(null) }`)
defer result.Free()
}
```
## 文档
Go 语言文档和示例: https://pkg.go.dev/github.com/buke/quickjs-go
## 协议
[MIT](./LICENSE)
[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fbuke%2Fquickjs-go.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2Fbuke%2Fquickjs-go?ref=badge_large)
## 相关项目
* https://github.com/buke/quickjs-go-polyfill

29
bridge.c Normal file
View File

@ -0,0 +1,29 @@
#include "_cgo_export.h"
#include "quickjs.h"
JSValue JS_NewNull() { return JS_NULL; }
JSValue JS_NewUndefined() { return JS_UNDEFINED; }
JSValue JS_NewUninitialized() { return JS_UNINITIALIZED; }
JSValue ThrowSyntaxError(JSContext *ctx, const char *fmt) { return JS_ThrowSyntaxError(ctx, "%s", fmt); }
JSValue ThrowTypeError(JSContext *ctx, const char *fmt) { return JS_ThrowTypeError(ctx, "%s", fmt); }
JSValue ThrowReferenceError(JSContext *ctx, const char *fmt) { return JS_ThrowReferenceError(ctx, "%s", fmt); }
JSValue ThrowRangeError(JSContext *ctx, const char *fmt) { return JS_ThrowRangeError(ctx, "%s", fmt); }
JSValue ThrowInternalError(JSContext *ctx, const char *fmt) { return JS_ThrowInternalError(ctx, "%s", fmt); }
JSValue InvokeProxy(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) {
return goProxy(ctx, this_val, argc, argv);
}
JSValue InvokeAsyncProxy(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) {
return goAsyncProxy(ctx, this_val, argc, argv);
}
int interruptHandler(JSRuntime *rt, void *handlerArgs) {
return goInterruptHandler(rt, handlerArgs);
}
void SetInterruptHandler(JSRuntime *rt, void *handlerArgs){
JS_SetInterruptHandler(rt, &interruptHandler, handlerArgs);
}

114
bridge.go Normal file
View File

@ -0,0 +1,114 @@
package quickjs
import (
"runtime/cgo"
"sync"
"sync/atomic"
"unsafe"
)
/*
#include <stdint.h>
#include "bridge.h"
*/
import "C"
type funcEntry struct {
ctx *Context
fn func(ctx *Context, this Value, args []Value) Value
asyncFn func(ctx *Context, this Value, promise Value, args []Value) Value
}
var funcPtrLen int64
var funcPtrLock sync.Mutex
var funcPtrStore = make(map[int64]funcEntry)
var funcPtrClassID C.JSClassID
func init() {
C.JS_NewClassID(&funcPtrClassID)
}
func storeFuncPtr(v funcEntry) int64 {
id := atomic.AddInt64(&funcPtrLen, 1) - 1
if id >= 9223372036854775807 {
id = 0
}
funcPtrLock.Lock()
defer funcPtrLock.Unlock()
funcPtrStore[id] = v
return id
}
func restoreFuncPtr(ptr int64) funcEntry {
funcPtrLock.Lock()
defer funcPtrLock.Unlock()
return funcPtrStore[ptr]
}
func freeFuncPtr(ptr int64) {
funcPtrLock.Lock()
defer funcPtrLock.Unlock()
delete(funcPtrStore, ptr)
}
func freeFuncPtrs(ptrs []int64) {
funcPtrLock.Lock()
defer funcPtrLock.Unlock()
for _, ptr := range ptrs {
delete(funcPtrStore, ptr)
}
}
//export goProxy
func goProxy(ctx *C.JSContext, thisVal C.JSValueConst, argc C.int, argv *C.JSValueConst) C.JSValue {
// https://github.com/golang/go/wiki/cgo#turning-c-arrays-into-go-slices
refs := unsafe.Slice(argv, argc) // Go 1.17 and later
id := C.int64_t(0)
C.JS_ToInt64(ctx, &id, refs[0])
entry := restoreFuncPtr(int64(id))
args := make([]Value, len(refs)-1)
for i := 0; i < len(args); i++ {
args[i].ctx = entry.ctx
args[i].ref = refs[1+i]
}
result := entry.fn(entry.ctx, Value{ctx: entry.ctx, ref: thisVal}, args)
return result.ref
}
//export goAsyncProxy
func goAsyncProxy(ctx *C.JSContext, thisVal C.JSValueConst, argc C.int, argv *C.JSValueConst) C.JSValue {
// https://github.com/golang/go/wiki/cgo#turning-c-arrays-into-go-slices
refs := unsafe.Slice(argv, argc) // Go 1.17 and later
id := C.int64_t(0)
C.JS_ToInt64(ctx, &id, refs[0])
entry := restoreFuncPtr(int64(id))
args := make([]Value, len(refs)-1)
for i := 0; i < len(args); i++ {
args[i].ctx = entry.ctx
args[i].ref = refs[1+i]
}
promise := args[0]
result := entry.asyncFn(entry.ctx, Value{ctx: entry.ctx, ref: thisVal}, promise, args[1:])
return result.ref
}
//export goInterruptHandler
func goInterruptHandler(rt *C.JSRuntime, handlerArgs unsafe.Pointer) C.int {
handlerArgsStruct := (*C.handlerArgs)(handlerArgs)
hFn := cgo.Handle(handlerArgsStruct.fn)
hFnValue := hFn.Value().(InterruptHandler)
// defer hFn.Delete()
return C.int(hFnValue())
}

23
bridge.h Normal file
View File

@ -0,0 +1,23 @@
#include <stdlib.h>
#include <string.h>
#include "quickjs.h"
extern JSValue JS_NewNull();
extern JSValue JS_NewUndefined();
extern JSValue JS_NewUninitialized();
extern JSValue ThrowSyntaxError(JSContext *ctx, const char *fmt) ;
extern JSValue ThrowTypeError(JSContext *ctx, const char *fmt) ;
extern JSValue ThrowReferenceError(JSContext *ctx, const char *fmt) ;
extern JSValue ThrowRangeError(JSContext *ctx, const char *fmt) ;
extern JSValue ThrowInternalError(JSContext *ctx, const char *fmt) ;
int JS_DeletePropertyInt64(JSContext *ctx, JSValueConst obj, int64_t idx, int flags);
extern JSValue InvokeProxy(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv);
extern JSValue InvokeAsyncProxy(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv);
typedef struct {
uintptr_t fn;
} handlerArgs;
extern void SetInterruptHandler(JSRuntime *rt, void *handlerArgs);

265
collection.go Normal file
View File

@ -0,0 +1,265 @@
package quickjs
import (
"errors"
)
//
// Array
// @Description: simply implement the array structure of js
type Array struct {
arrayValue Value
ctx *Context
}
func NewQjsArray(value Value, ctx *Context) *Array {
return &Array{
arrayValue: value,
ctx: ctx,
}
}
// Push
//
// @Description: add one or more elements after the array,returns the new array length
// @receiver a :
// @param elements :
// @return int64
func (a Array) Push(elements ...Value) int64 {
ret := a.arrayValue.Call("push", elements...)
//defer ret.Free()
return ret.Int64()
}
// Get
//
// @Description: get the specific value by subscript
// @receiver a :
// @param index :
// @return Value
func (a Array) Get(index int64) (Value, error) {
if index < 0 {
return Value{}, errors.New("the input index value is a negative number")
}
if index >= a.arrayValue.Len() {
return Value{}, errors.New("index subscript out of range")
}
return a.arrayValue.GetIdx(index), nil
}
// Set
//
// @Description:
// @receiver a :
// @param index :
// @param value :
// @return error
func (a Array) Set(index int64, value Value) error {
if index < 0 {
return errors.New("the input index value is a negative number")
}
if index >= a.arrayValue.Len() {
return errors.New("index subscript out of range")
}
a.arrayValue.SetIdx(index, value)
return nil
}
func (a Array) Delete(index int64) (bool, error) {
if index < 0 {
return false, errors.New("the input index value is a negative number")
}
if index >= a.arrayValue.Len() {
return false, errors.New("index subscript out of range")
}
removeList := a.arrayValue.Call("splice", a.ctx.Int64(index), a.ctx.Int64(1))
defer removeList.Free()
return removeList.IsArray(), nil
}
// Len
//
// @Description: get the length of the array
// @receiver a :
// @return int64
func (a Array) Len() int64 {
return a.arrayValue.Len()
}
// HasIdx
//
// @Description: Determine whether there is data at the current subscript position
// @receiver a :
// @param i :
// @return bool
func (a Array) HasIdx(i int64) bool {
return a.arrayValue.HasIdx(i)
}
// ToValue
//
// @Description: get the value object of qjs
// @receiver a :
// @return Value
func (a Array) ToValue() Value {
return a.arrayValue
}
func (a Array) Free() {
a.arrayValue.Free()
}
//
// Map
// @Description: simply implement the map structure of js
type Map struct {
mapValue Value
ctx *Context
}
func NewQjsMap(value Value, ctx *Context) *Map {
return &Map{
mapValue: value,
ctx: ctx,
}
}
// Get
//
// @Description: get the value by key
// @receiver m :
// @param key :
// @return Value
func (m Map) Get(key Value) Value {
return m.mapValue.Call("get", key)
}
// Put
//
// @Description:
// @receiver m :
// @param key :
// @param value :
func (m Map) Put(key Value, value Value) {
m.mapValue.Call("set", key, value).Free()
}
// Delete
//
// @Description:delete the value of an element by key
// @receiver m :
// @param key :
func (m Map) Delete(key Value) {
m.mapValue.Call("delete", key).Free()
}
// Has
//
// @Description:determine whether an element exists
// @receiver m :
// @param key :
func (m Map) Has(key Value) bool {
boolValue := m.mapValue.Call("has", key)
defer boolValue.Free()
return boolValue.Bool()
}
// ForEach
//
// @Description: iterate map
// @receiver m :
func (m Map) ForEach(forFn func(key Value, value Value)) {
forEachFn := m.ctx.Function(func(ctx *Context, this Value, args []Value) Value {
forFn(args[1], args[0])
return ctx.Null()
})
value := m.mapValue.Call("forEach", forEachFn)
forEachFn.Free()
defer value.Free()
}
func (m Map) Free() {
m.mapValue.Free()
}
func (m Map) ToValue() Value {
return m.mapValue
}
// Call
//
// @Description: call some internal methods of js
// @receiver a :
// @param funcName :
// @param values :
// @return Value
func (m Map) Call(funcName string, values []Value) Value {
return m.mapValue.Call(funcName, values...)
}
type Set struct {
setValue Value
ctx *Context
}
func NewQjsSet(value Value, ctx *Context) *Set {
return &Set{
setValue: value,
ctx: ctx,
}
}
// Add
//
// @Description: add element
// @receiver s :
// @param value :
func (s Set) Add(value Value) {
v := s.setValue.Call("add", value)
defer v.Free()
}
// Delete
//
// @Description: add element
// @receiver s :
// @param value :
func (s Set) Delete(value Value) {
v := s.setValue.Call("delete", value)
defer v.Free()
}
// Has
//
// @Description: determine whether an element exists in the set
// @receiver s :
// @param value :
// @return bool
func (s Set) Has(value Value) bool {
v := s.setValue.Call("has", value)
return v.Bool()
}
// ForEach
//
// @Description: iterate set
// @receiver m :
func (s Set) ForEach(forFn func(value Value)) {
forEachFn := s.ctx.Function(func(ctx *Context, this Value, args []Value) Value {
forFn(args[0])
return ctx.Null()
})
value := s.setValue.Call("forEach", forEachFn)
forEachFn.Free()
defer value.Free()
}
func (s Set) Free() {
s.setValue.Free()
}
func (s Set) ToValue() Value {
return s.setValue
}

382
context.go Normal file
View File

@ -0,0 +1,382 @@
package quickjs
import (
"fmt"
"runtime/cgo"
"unsafe"
)
/*
#include <stdint.h> // for uintptr_t
#include "bridge.h"
*/
import "C"
// Context represents a Javascript context (or Realm). Each JSContext has its own global objects and system objects. There can be several JSContexts per JSRuntime and they can share objects, similar to frames of the same origin sharing Javascript objects in a web browser.
type Context struct {
runtime *Runtime
ref *C.JSContext
globals *Value
proxy *Value
asyncProxy *Value
funcPtrs []int64
}
// Free will free context and all associated objects.
func (ctx *Context) Close() {
if ctx.proxy != nil {
ctx.proxy.Free()
}
if ctx.asyncProxy != nil {
ctx.asyncProxy.Free()
}
if ctx.globals != nil {
ctx.globals.Free()
}
freeFuncPtrs(ctx.funcPtrs)
C.JS_FreeContext(ctx.ref)
}
// Null return a null value.
func (ctx *Context) Null() Value {
return Value{ctx: ctx, ref: C.JS_NewNull()}
}
// Undefined return a undefined value.
func (ctx *Context) Undefined() Value {
return Value{ctx: ctx, ref: C.JS_NewUndefined()}
}
// Uninitialized returns a uninitialized value.
func (ctx *Context) Uninitialized() Value {
return Value{ctx: ctx, ref: C.JS_NewUninitialized()}
}
// Error returns a new exception value with given message.
func (ctx *Context) Error(err error) Value {
val := Value{ctx: ctx, ref: C.JS_NewError(ctx.ref)}
val.Set("message", ctx.String(err.Error()))
return val
}
// Bool returns a bool value with given bool.
func (ctx *Context) Bool(b bool) Value {
bv := 0
if b {
bv = 1
}
return Value{ctx: ctx, ref: C.JS_NewBool(ctx.ref, C.int(bv))}
}
// Int32 returns a int32 value with given int32.
func (ctx *Context) Int32(v int32) Value {
return Value{ctx: ctx, ref: C.JS_NewInt32(ctx.ref, C.int32_t(v))}
}
// Int64 returns a int64 value with given int64.
func (ctx *Context) Int64(v int64) Value {
return Value{ctx: ctx, ref: C.JS_NewInt64(ctx.ref, C.int64_t(v))}
}
// Uint32 returns a uint32 value with given uint32.
func (ctx *Context) Uint32(v uint32) Value {
return Value{ctx: ctx, ref: C.JS_NewUint32(ctx.ref, C.uint32_t(v))}
}
// BigInt64 returns a int64 value with given uint64.
func (ctx *Context) BigInt64(v int64) Value {
return Value{ctx: ctx, ref: C.JS_NewBigInt64(ctx.ref, C.int64_t(v))}
}
// BigUint64 returns a uint64 value with given uint64.
func (ctx *Context) BigUint64(v uint64) Value {
return Value{ctx: ctx, ref: C.JS_NewBigUint64(ctx.ref, C.uint64_t(v))}
}
// Float64 returns a float64 value with given float64.
func (ctx *Context) Float64(v float64) Value {
return Value{ctx: ctx, ref: C.JS_NewFloat64(ctx.ref, C.double(v))}
}
// String returns a string value with given string.
func (ctx *Context) String(v string) Value {
ptr := C.CString(v)
defer C.free(unsafe.Pointer(ptr))
return Value{ctx: ctx, ref: C.JS_NewString(ctx.ref, ptr)}
}
// ArrayBuffer returns a string value with given binary data.
func (ctx *Context) ArrayBuffer(binaryData []byte) Value {
return Value{ctx: ctx, ref: C.JS_NewArrayBufferCopy(ctx.ref, (*C.uchar)(&binaryData[0]), C.size_t(len(binaryData)))}
}
// Object returns a new object value.
func (ctx *Context) Object() Value {
return Value{ctx: ctx, ref: C.JS_NewObject(ctx.ref)}
}
// ParseJson parses given json string and returns a object value.
func (ctx *Context) ParseJSON(v string) Value {
ptr := C.CString(v)
defer C.free(unsafe.Pointer(ptr))
filenamePtr := C.CString("")
defer C.free(unsafe.Pointer(filenamePtr))
return Value{ctx: ctx, ref: C.JS_ParseJSON(ctx.ref, ptr, C.size_t(len(v)), filenamePtr)}
}
// Array returns a new array value.
func (ctx *Context) Array() *Array {
val := Value{ctx: ctx, ref: C.JS_NewArray(ctx.ref)}
return NewQjsArray(val, ctx)
}
func (ctx *Context) Map() *Map {
ctor := ctx.Globals().Get("Map")
defer ctor.Free()
val := Value{ctx: ctx, ref: C.JS_CallConstructor(ctx.ref, ctor.ref, 0, nil)}
return NewQjsMap(val, ctx)
}
func (ctx *Context) Set() *Set {
ctor := ctx.Globals().Get("Set")
defer ctor.Free()
val := Value{ctx: ctx, ref: C.JS_CallConstructor(ctx.ref, ctor.ref, 0, nil)}
return NewQjsSet(val, ctx)
}
// Function returns a js function value with given function template.
func (ctx *Context) Function(fn func(ctx *Context, this Value, args []Value) Value) Value {
val := ctx.eval(`(invokeGoFunction, id) => function() { return invokeGoFunction.call(this, id, ...arguments); }`)
defer val.Free()
funcPtr := storeFuncPtr(funcEntry{ctx: ctx, fn: fn})
funcPtrVal := ctx.Int64(funcPtr)
ctx.funcPtrs = append(ctx.funcPtrs, funcPtr)
if ctx.proxy == nil {
ctx.proxy = &Value{
ctx: ctx,
ref: C.JS_NewCFunction(ctx.ref, (*C.JSCFunction)(unsafe.Pointer(C.InvokeProxy)), nil, C.int(0)),
}
}
args := []C.JSValue{ctx.proxy.ref, funcPtrVal.ref}
return Value{ctx: ctx, ref: C.JS_Call(ctx.ref, val.ref, ctx.Null().ref, C.int(len(args)), &args[0])}
}
// AsyncFunction returns a js async function value with given function template.
func (ctx *Context) AsyncFunction(asyncFn func(ctx *Context, this Value, promise Value, args []Value) Value) Value {
val := ctx.eval(`(invokeGoFunction, id) => async function(...arguments) {
let resolve, reject;
const promise = new Promise((resolve_, reject_) => {
resolve = resolve_;
reject = reject_;
});
promise.resolve = resolve;
promise.reject = reject;
invokeGoFunction.call(this, id, promise, ...arguments);
return await promise;
}`)
defer val.Free()
funcPtr := storeFuncPtr(funcEntry{ctx: ctx, asyncFn: asyncFn})
funcPtrVal := ctx.Int64(funcPtr)
if ctx.asyncProxy == nil {
ctx.asyncProxy = &Value{
ctx: ctx,
ref: C.JS_NewCFunction(ctx.ref, (*C.JSCFunction)(unsafe.Pointer(C.InvokeAsyncProxy)), nil, C.int(0)),
}
}
args := []C.JSValue{ctx.asyncProxy.ref, funcPtrVal.ref}
return Value{ctx: ctx, ref: C.JS_Call(ctx.ref, val.ref, ctx.Null().ref, C.int(len(args)), &args[0])}
}
// InterruptHandler is a function type for interrupt handler.
/* return != 0 if the JS code needs to be interrupted */
type InterruptHandler func() int
// SetInterruptHandler sets a interrupt handler.
func (ctx *Context) SetInterruptHandler(handler InterruptHandler) {
handlerArgs := C.handlerArgs{
fn: (C.uintptr_t)(cgo.NewHandle(handler)),
}
C.SetInterruptHandler(ctx.runtime.ref, unsafe.Pointer(&handlerArgs))
}
// Atom returns a new Atom value with given string.
func (ctx *Context) Atom(v string) Atom {
ptr := C.CString(v)
defer C.free(unsafe.Pointer(ptr))
return Atom{ctx: ctx, ref: C.JS_NewAtom(ctx.ref, ptr)}
}
// Atom returns a new Atom value with given idx.
func (ctx *Context) AtomIdx(idx int64) Atom {
return Atom{ctx: ctx, ref: C.JS_NewAtomUInt32(ctx.ref, C.uint32_t(idx))}
}
func (ctx *Context) eval(code string) Value { return ctx.evalFile(code, "code", C.JS_EVAL_TYPE_GLOBAL) }
func (ctx *Context) evalFile(code, filename string, evalType C.int) Value {
codePtr := C.CString(code)
defer C.free(unsafe.Pointer(codePtr))
filenamePtr := C.CString(filename)
defer C.free(unsafe.Pointer(filenamePtr))
return Value{ctx: ctx, ref: C.JS_Eval(ctx.ref, codePtr, C.size_t(len(code)), filenamePtr, evalType)}
}
// Invoke invokes a function with given this value and arguments.
func (ctx *Context) Invoke(fn Value, this Value, args ...Value) Value {
cargs := []C.JSValue{}
for _, x := range args {
cargs = append(cargs, x.ref)
}
if len(cargs) == 0 {
return Value{ctx: ctx, ref: C.JS_Call(ctx.ref, fn.ref, this.ref, 0, nil)}
}
return Value{ctx: ctx, ref: C.JS_Call(ctx.ref, fn.ref, this.ref, C.int(len(cargs)), &cargs[0])}
}
// Eval returns a js value with given code.
// Need call Free() `quickjs.Value`'s returned by `Eval()` and `EvalFile()` and `EvalBytecode()`.
func (ctx *Context) Eval(code string) (Value, error) { return ctx.EvalFile(code, "code") }
// EvalFile returns a js value with given code and filename.
// Need call Free() `quickjs.Value`'s returned by `Eval()` and `EvalFile()` and `EvalBytecode()`.
func (ctx *Context) EvalFile(code, filename string) (Value, error) {
val := ctx.evalFile(code, filename, C.JS_EVAL_TYPE_GLOBAL)
if val.IsException() {
return val, ctx.Exception()
}
return val, nil
}
// EvalBytecode returns a js value with given bytecode.
// Need call Free() `quickjs.Value`'s returned by `Eval()` and `EvalFile()` and `EvalBytecode()`.
func (ctx *Context) EvalBytecode(buf []byte) (Value, error) {
cbuf := C.CBytes(buf)
obj := Value{ctx: ctx, ref: C.JS_ReadObject(ctx.ref, (*C.uint8_t)(cbuf), C.size_t(len(buf)), C.JS_READ_OBJ_BYTECODE)}
defer C.js_free(ctx.ref, unsafe.Pointer(cbuf))
if obj.IsException() {
return obj, ctx.Exception()
}
val := Value{ctx: ctx, ref: C.JS_EvalFunction(ctx.ref, obj.ref)}
if val.IsException() {
return val, ctx.Exception()
}
return val, nil
}
// Compile returns a compiled bytecode with given code.
func (ctx *Context) Compile(code string) ([]byte, error) {
return ctx.CompileFile(code, "code")
}
// Compile returns a compiled bytecode with given filename.
func (ctx *Context) CompileFile(code, filename string) ([]byte, error) {
val := ctx.evalFile(code, filename, C.JS_EVAL_FLAG_COMPILE_ONLY)
defer val.Free()
if val.IsException() {
return nil, ctx.Exception()
}
var kSize C.size_t
ptr := C.JS_WriteObject(ctx.ref, &kSize, val.ref, C.JS_WRITE_OBJ_BYTECODE)
defer C.js_free(ctx.ref, unsafe.Pointer(ptr))
if C.int(kSize) <= 0 {
return nil, ctx.Exception()
}
ret := make([]byte, C.int(kSize))
copy(ret, C.GoBytes(unsafe.Pointer(ptr), C.int(kSize)))
return ret, nil
}
// Global returns a context's global object.
func (ctx *Context) Globals() Value {
if ctx.globals == nil {
ctx.globals = &Value{
ctx: ctx,
ref: C.JS_GetGlobalObject(ctx.ref),
}
}
return *ctx.globals
}
// Throw returns a context's exception value.
func (ctx *Context) Throw(v Value) Value {
return Value{ctx: ctx, ref: C.JS_Throw(ctx.ref, v.ref)}
}
// ThrowError returns a context's exception value with given error message.
func (ctx *Context) ThrowError(err error) Value {
return ctx.Throw(ctx.Error(err))
}
// ThrowSyntaxError returns a context's exception value with given error message.
func (ctx *Context) ThrowSyntaxError(format string, args ...interface{}) Value {
cause := fmt.Sprintf(format, args...)
causePtr := C.CString(cause)
defer C.free(unsafe.Pointer(causePtr))
return Value{ctx: ctx, ref: C.ThrowSyntaxError(ctx.ref, causePtr)}
}
// ThrowTypeError returns a context's exception value with given error message.
func (ctx *Context) ThrowTypeError(format string, args ...interface{}) Value {
cause := fmt.Sprintf(format, args...)
causePtr := C.CString(cause)
defer C.free(unsafe.Pointer(causePtr))
return Value{ctx: ctx, ref: C.ThrowTypeError(ctx.ref, causePtr)}
}
// ThrowReferenceError returns a context's exception value with given error message.
func (ctx *Context) ThrowReferenceError(format string, args ...interface{}) Value {
cause := fmt.Sprintf(format, args...)
causePtr := C.CString(cause)
defer C.free(unsafe.Pointer(causePtr))
return Value{ctx: ctx, ref: C.ThrowReferenceError(ctx.ref, causePtr)}
}
// ThrowRangeError returns a context's exception value with given error message.
func (ctx *Context) ThrowRangeError(format string, args ...interface{}) Value {
cause := fmt.Sprintf(format, args...)
causePtr := C.CString(cause)
defer C.free(unsafe.Pointer(causePtr))
return Value{ctx: ctx, ref: C.ThrowRangeError(ctx.ref, causePtr)}
}
// ThrowInternalError returns a context's exception value with given error message.
func (ctx *Context) ThrowInternalError(format string, args ...interface{}) Value {
cause := fmt.Sprintf(format, args...)
causePtr := C.CString(cause)
defer C.free(unsafe.Pointer(causePtr))
return Value{ctx: ctx, ref: C.ThrowInternalError(ctx.ref, causePtr)}
}
// Exception returns a context's exception value.
func (ctx *Context) Exception() error {
val := Value{ctx: ctx, ref: C.JS_GetException(ctx.ref)}
defer val.Free()
return val.Error()
}
// ScheduleJob Schedule a context's job.
func (ctx *Context) ScheduleJob(fn func()) {
ctx.runtime.loop.scheduleJob(fn)
}

473
deps/Makefile vendored Normal file
View File

@ -0,0 +1,473 @@
#
# QuickJS Javascript Engine
#
# Copyright (c) 2017-2021 Fabrice Bellard
# Copyright (c) 2017-2021 Charlie Gordon
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
ifeq ($(shell uname -s),Darwin)
CONFIG_DARWIN=y
endif
# Windows cross compilation from Linux
#CONFIG_WIN32=y
# use link time optimization (smaller and faster executables but slower build)
CONFIG_LTO=y
# consider warnings as errors (for development)
#CONFIG_WERROR=y
# force 32 bit build for some utilities
#CONFIG_M32=y
ifdef CONFIG_DARWIN
# use clang instead of gcc
CONFIG_CLANG=y
CONFIG_DEFAULT_AR=y
endif
# installation directory
prefix=/usr/local
# use the gprof profiler
#CONFIG_PROFILE=y
# use address sanitizer
#CONFIG_ASAN=y
# include the code for BigInt/BigFloat/BigDecimal and math mode
CONFIG_BIGNUM=y
OBJDIR=.obj
ifdef CONFIG_WIN32
ifdef CONFIG_M32
CROSS_PREFIX=i686-w64-mingw32-
else
CROSS_PREFIX=x86_64-w64-mingw32-
endif
EXE=.exe
else
CROSS_PREFIX=
EXE=
endif
ifdef CONFIG_CLANG
HOST_CC=clang
CC=$(CROSS_PREFIX)clang
CFLAGS=-g -Wall -MMD -MF $(OBJDIR)/$(@F).d
ifdef CONFIG_DARWIN_ARM64
CFLAGS += -target arm64-apple-macos11
endif
CFLAGS += -Wextra
CFLAGS += -Wno-sign-compare
CFLAGS += -Wno-missing-field-initializers
CFLAGS += -Wundef -Wuninitialized
CFLAGS += -Wunused -Wno-unused-parameter
CFLAGS += -Wwrite-strings
CFLAGS += -Wchar-subscripts -funsigned-char
CFLAGS += -MMD -MF $(OBJDIR)/$(@F).d
ifdef CONFIG_DEFAULT_AR
AR=$(CROSS_PREFIX)ar
else
ifdef CONFIG_LTO
AR=$(CROSS_PREFIX)llvm-ar
else
AR=$(CROSS_PREFIX)ar
endif
endif
else
HOST_CC=gcc
CC=$(CROSS_PREFIX)gcc
CFLAGS=-g -Wall -MMD -MF $(OBJDIR)/$(@F).d
CFLAGS += -Wno-array-bounds -Wno-format-truncation
ifdef CONFIG_LTO
AR=$(CROSS_PREFIX)gcc-ar
else
AR=$(CROSS_PREFIX)ar
endif
endif
STRIP=$(CROSS_PREFIX)strip
ifdef CONFIG_WERROR
CFLAGS+=-Werror
endif
DEFINES:=-D_GNU_SOURCE -DCONFIG_VERSION=\"$(shell cat VERSION)\"
ifdef CONFIG_BIGNUM
DEFINES+=-DCONFIG_BIGNUM
endif
ifdef CONFIG_WIN32
DEFINES+=-D__USE_MINGW_ANSI_STDIO # for standard snprintf behavior
endif
CFLAGS+=$(DEFINES)
CFLAGS_DEBUG=$(CFLAGS) -O0
CFLAGS_SMALL=$(CFLAGS) -Os
CFLAGS_OPT=$(CFLAGS) -O2
CFLAGS_NOLTO:=$(CFLAGS_OPT)
LDFLAGS=-g
ifdef CONFIG_LTO
CFLAGS_SMALL+=-flto
CFLAGS_OPT+=-flto
LDFLAGS+=-flto
endif
ifdef CONFIG_PROFILE
CFLAGS+=-p
LDFLAGS+=-p
endif
ifdef CONFIG_ASAN
CFLAGS+=-fsanitize=address -fno-omit-frame-pointer
LDFLAGS+=-fsanitize=address -fno-omit-frame-pointer
endif
ifdef CONFIG_WIN32
LDEXPORT=
else
LDEXPORT=-rdynamic
endif
PROGS=qjs$(EXE) qjsc$(EXE) run-test262
ifneq ($(CROSS_PREFIX),)
QJSC_CC=gcc
QJSC=./host-qjsc
PROGS+=$(QJSC)
else
QJSC_CC=$(CC)
QJSC=./qjsc$(EXE)
endif
ifndef CONFIG_WIN32
PROGS+=qjscalc
endif
ifdef CONFIG_M32
PROGS+=qjs32 qjs32_s
endif
PROGS+=libquickjs.a
ifdef CONFIG_LTO
PROGS+=libquickjs.lto.a
endif
# examples
ifeq ($(CROSS_PREFIX),)
ifdef CONFIG_ASAN
PROGS+=
else
PROGS+=examples/hello examples/hello_module examples/test_fib
ifndef CONFIG_DARWIN
PROGS+=examples/fib.so examples/point.so
endif
endif
endif
all: $(OBJDIR) $(OBJDIR)/quickjs.check.o $(OBJDIR)/qjs.check.o $(PROGS)
QJS_LIB_OBJS=$(OBJDIR)/quickjs.o $(OBJDIR)/libregexp.o $(OBJDIR)/libunicode.o $(OBJDIR)/cutils.o $(OBJDIR)/quickjs-libc.o
QJS_OBJS=$(OBJDIR)/qjs.o $(OBJDIR)/repl.o $(QJS_LIB_OBJS)
ifdef CONFIG_BIGNUM
QJS_LIB_OBJS+=$(OBJDIR)/libbf.o
QJS_OBJS+=$(OBJDIR)/qjscalc.o
endif
HOST_LIBS=-lm -ldl -lpthread
LIBS=-lm
ifndef CONFIG_WIN32
LIBS+=-ldl -lpthread
endif
LIBS+=$(EXTRA_LIBS)
$(OBJDIR):
mkdir -p $(OBJDIR) $(OBJDIR)/examples $(OBJDIR)/tests
qjs$(EXE): $(QJS_OBJS)
$(CC) $(LDFLAGS) $(LDEXPORT) -o $@ $^ $(LIBS)
qjs-debug$(EXE): $(patsubst %.o, %.debug.o, $(QJS_OBJS))
$(CC) $(LDFLAGS) -o $@ $^ $(LIBS)
qjsc$(EXE): $(OBJDIR)/qjsc.o $(QJS_LIB_OBJS)
$(CC) $(LDFLAGS) -o $@ $^ $(LIBS)
ifneq ($(CROSS_PREFIX),)
$(QJSC): $(OBJDIR)/qjsc.host.o \
$(patsubst %.o, %.host.o, $(QJS_LIB_OBJS))
$(HOST_CC) $(LDFLAGS) -o $@ $^ $(HOST_LIBS)
endif #CROSS_PREFIX
QJSC_DEFINES:=-DCONFIG_CC=\"$(QJSC_CC)\" -DCONFIG_PREFIX=\"$(prefix)\"
ifdef CONFIG_LTO
QJSC_DEFINES+=-DCONFIG_LTO
endif
QJSC_HOST_DEFINES:=-DCONFIG_CC=\"$(HOST_CC)\" -DCONFIG_PREFIX=\"$(prefix)\"
$(OBJDIR)/qjsc.o: CFLAGS+=$(QJSC_DEFINES)
$(OBJDIR)/qjsc.host.o: CFLAGS+=$(QJSC_HOST_DEFINES)
qjs32: $(patsubst %.o, %.m32.o, $(QJS_OBJS))
$(CC) -m32 $(LDFLAGS) $(LDEXPORT) -o $@ $^ $(LIBS)
qjs32_s: $(patsubst %.o, %.m32s.o, $(QJS_OBJS))
$(CC) -m32 $(LDFLAGS) -o $@ $^ $(LIBS)
@size $@
qjscalc: qjs
ln -sf $< $@
ifdef CONFIG_LTO
LTOEXT=.lto
else
LTOEXT=
endif
libquickjs$(LTOEXT).a: $(QJS_LIB_OBJS)
$(AR) rcs $@ $^
ifdef CONFIG_LTO
libquickjs.a: $(patsubst %.o, %.nolto.o, $(QJS_LIB_OBJS))
$(AR) rcs $@ $^
endif # CONFIG_LTO
repl.c: $(QJSC) repl.js
$(QJSC) -c -o $@ -m repl.js
qjscalc.c: $(QJSC) qjscalc.js
$(QJSC) -fbignum -c -o $@ qjscalc.js
ifneq ($(wildcard unicode/UnicodeData.txt),)
$(OBJDIR)/libunicode.o $(OBJDIR)/libunicode.m32.o $(OBJDIR)/libunicode.m32s.o \
$(OBJDIR)/libunicode.nolto.o: libunicode-table.h
libunicode-table.h: unicode_gen
./unicode_gen unicode $@
endif
run-test262: $(OBJDIR)/run-test262.o $(QJS_LIB_OBJS)
$(CC) $(LDFLAGS) -o $@ $^ $(LIBS)
run-test262-debug: $(patsubst %.o, %.debug.o, $(OBJDIR)/run-test262.o $(QJS_LIB_OBJS))
$(CC) $(LDFLAGS) -o $@ $^ $(LIBS)
run-test262-32: $(patsubst %.o, %.m32.o, $(OBJDIR)/run-test262.o $(QJS_LIB_OBJS))
$(CC) -m32 $(LDFLAGS) -o $@ $^ $(LIBS)
# object suffix order: nolto, [m32|m32s]
$(OBJDIR)/%.o: %.c | $(OBJDIR)
$(CC) $(CFLAGS_OPT) -c -o $@ $<
$(OBJDIR)/%.host.o: %.c | $(OBJDIR)
$(HOST_CC) $(CFLAGS_OPT) -c -o $@ $<
$(OBJDIR)/%.pic.o: %.c | $(OBJDIR)
$(CC) $(CFLAGS_OPT) -fPIC -DJS_SHARED_LIBRARY -c -o $@ $<
$(OBJDIR)/%.nolto.o: %.c | $(OBJDIR)
$(CC) $(CFLAGS_NOLTO) -c -o $@ $<
$(OBJDIR)/%.m32.o: %.c | $(OBJDIR)
$(CC) -m32 $(CFLAGS_OPT) -c -o $@ $<
$(OBJDIR)/%.m32s.o: %.c | $(OBJDIR)
$(CC) -m32 $(CFLAGS_SMALL) -c -o $@ $<
$(OBJDIR)/%.debug.o: %.c | $(OBJDIR)
$(CC) $(CFLAGS_DEBUG) -c -o $@ $<
$(OBJDIR)/%.check.o: %.c | $(OBJDIR)
$(CC) $(CFLAGS) -DCONFIG_CHECK_JSVALUE -c -o $@ $<
regexp_test: libregexp.c libunicode.c cutils.c
$(CC) $(LDFLAGS) $(CFLAGS) -DTEST -o $@ libregexp.c libunicode.c cutils.c $(LIBS)
unicode_gen: $(OBJDIR)/unicode_gen.host.o $(OBJDIR)/cutils.host.o libunicode.c unicode_gen_def.h
$(HOST_CC) $(LDFLAGS) $(CFLAGS) -o $@ $(OBJDIR)/unicode_gen.host.o $(OBJDIR)/cutils.host.o
clean:
rm -f repl.c qjscalc.c out.c
rm -f *.a *.o *.d *~ unicode_gen regexp_test $(PROGS)
rm -f hello.c test_fib.c
rm -f examples/*.so tests/*.so
rm -rf $(OBJDIR)/ *.dSYM/ qjs-debug
rm -rf run-test262-debug run-test262-32
install: all
mkdir -p "$(DESTDIR)$(prefix)/bin"
$(STRIP) qjs qjsc
install -m755 qjs qjsc "$(DESTDIR)$(prefix)/bin"
ln -sf qjs "$(DESTDIR)$(prefix)/bin/qjscalc"
mkdir -p "$(DESTDIR)$(prefix)/lib/quickjs"
install -m644 libquickjs.a "$(DESTDIR)$(prefix)/lib/quickjs"
ifdef CONFIG_LTO
install -m644 libquickjs.lto.a "$(DESTDIR)$(prefix)/lib/quickjs"
endif
mkdir -p "$(DESTDIR)$(prefix)/include/quickjs"
install -m644 quickjs.h quickjs-libc.h "$(DESTDIR)$(prefix)/include/quickjs"
###############################################################################
# examples
# example of static JS compilation
HELLO_SRCS=examples/hello.js
HELLO_OPTS=-fno-string-normalize -fno-map -fno-promise -fno-typedarray \
-fno-typedarray -fno-regexp -fno-json -fno-eval -fno-proxy \
-fno-date -fno-module-loader
ifdef CONFIG_BIGNUM
HELLO_OPTS+=-fno-bigint
endif
hello.c: $(QJSC) $(HELLO_SRCS)
$(QJSC) -e $(HELLO_OPTS) -o $@ $(HELLO_SRCS)
ifdef CONFIG_M32
examples/hello: $(OBJDIR)/hello.m32s.o $(patsubst %.o, %.m32s.o, $(QJS_LIB_OBJS))
$(CC) -m32 $(LDFLAGS) -o $@ $^ $(LIBS)
else
examples/hello: $(OBJDIR)/hello.o $(QJS_LIB_OBJS)
$(CC) $(LDFLAGS) -o $@ $^ $(LIBS)
endif
# example of static JS compilation with modules
HELLO_MODULE_SRCS=examples/hello_module.js
HELLO_MODULE_OPTS=-fno-string-normalize -fno-map -fno-promise -fno-typedarray \
-fno-typedarray -fno-regexp -fno-json -fno-eval -fno-proxy \
-fno-date -m
examples/hello_module: $(QJSC) libquickjs$(LTOEXT).a $(HELLO_MODULE_SRCS)
$(QJSC) $(HELLO_MODULE_OPTS) -o $@ $(HELLO_MODULE_SRCS)
# use of an external C module (static compilation)
test_fib.c: $(QJSC) examples/test_fib.js
$(QJSC) -e -M examples/fib.so,fib -m -o $@ examples/test_fib.js
examples/test_fib: $(OBJDIR)/test_fib.o $(OBJDIR)/examples/fib.o libquickjs$(LTOEXT).a
$(CC) $(LDFLAGS) -o $@ $^ $(LIBS)
examples/fib.so: $(OBJDIR)/examples/fib.pic.o
$(CC) $(LDFLAGS) -shared -o $@ $^
examples/point.so: $(OBJDIR)/examples/point.pic.o
$(CC) $(LDFLAGS) -shared -o $@ $^
###############################################################################
# documentation
DOCS=doc/quickjs.pdf doc/quickjs.html doc/jsbignum.pdf doc/jsbignum.html
build_doc: $(DOCS)
clean_doc:
rm -f $(DOCS)
doc/%.pdf: doc/%.texi
texi2pdf --clean -o $@ -q $<
doc/%.html.pre: doc/%.texi
makeinfo --html --no-headers --no-split --number-sections -o $@ $<
doc/%.html: doc/%.html.pre
sed -e 's|</style>|</style>\n<meta name="viewport" content="width=device-width, initial-scale=1.0">|' < $< > $@
###############################################################################
# tests
ifndef CONFIG_DARWIN
test: tests/bjson.so examples/point.so
endif
ifdef CONFIG_M32
test: qjs32
endif
test: qjs
./qjs tests/test_closure.js
./qjs tests/test_language.js
./qjs tests/test_builtin.js
./qjs tests/test_loop.js
./qjs tests/test_std.js
./qjs tests/test_worker.js
ifndef CONFIG_DARWIN
ifdef CONFIG_BIGNUM
./qjs --bignum tests/test_bjson.js
else
./qjs tests/test_bjson.js
endif
./qjs examples/test_point.js
endif
ifdef CONFIG_BIGNUM
./qjs --bignum tests/test_op_overloading.js
./qjs --bignum tests/test_bignum.js
./qjs --qjscalc tests/test_qjscalc.js
endif
ifdef CONFIG_M32
./qjs32 tests/test_closure.js
./qjs32 tests/test_language.js
./qjs32 tests/test_builtin.js
./qjs32 tests/test_loop.js
./qjs32 tests/test_std.js
./qjs32 tests/test_worker.js
ifdef CONFIG_BIGNUM
./qjs32 --bignum tests/test_op_overloading.js
./qjs32 --bignum tests/test_bignum.js
./qjs32 --qjscalc tests/test_qjscalc.js
endif
endif
stats: qjs qjs32
./qjs -qd
./qjs32 -qd
microbench: qjs
./qjs tests/microbench.js
microbench-32: qjs32
./qjs32 tests/microbench.js
# ES5 tests (obsolete)
test2o: run-test262
time ./run-test262 -m -c test262o.conf
test2o-32: run-test262-32
time ./run-test262-32 -m -c test262o.conf
test2o-update: run-test262
./run-test262 -u -c test262o.conf
# Test262 tests
test2-default: run-test262
time ./run-test262 -m -c test262.conf
test2: run-test262
time ./run-test262 -m -c test262.conf -a
test2-32: run-test262-32
time ./run-test262-32 -m -c test262.conf -a
test2-update: run-test262
./run-test262 -u -c test262.conf -a
test2-check: run-test262
time ./run-test262 -m -c test262.conf -E -a
testall: all test microbench test2o test2
testall-32: all test-32 microbench-32 test2o-32 test2-32
testall-complete: testall testall-32
bench-v8: qjs
make -C tests/bench-v8
./qjs -d tests/bench-v8/combined.js
tests/bjson.so: $(OBJDIR)/tests/bjson.pic.o
$(CC) $(LDFLAGS) -shared -o $@ $^ $(LIBS)
-include $(wildcard $(OBJDIR)/*.d)

1049
deps/include/quickjs.h vendored Normal file

File diff suppressed because it is too large Load Diff

Binary file not shown.

BIN
deps/libs/darwin_amd64/libquickjs.a vendored Normal file

Binary file not shown.

BIN
deps/libs/darwin_arm64/libquickjs.a vendored Normal file

Binary file not shown.

BIN
deps/libs/linux_amd64/libquickjs.a vendored Normal file

Binary file not shown.

BIN
deps/libs/linux_arm64/libquickjs.a vendored Normal file

Binary file not shown.

BIN
deps/libs/windows_386/libquickjs.a vendored Normal file

Binary file not shown.

BIN
deps/libs/windows_amd64/libquickjs.a vendored Normal file

Binary file not shown.

11
go.mod Normal file
View File

@ -0,0 +1,11 @@
module apigo.cloud/git/apigo/qjs
go 1.17
require github.com/stretchr/testify v1.8.4
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

51
loop.go Normal file
View File

@ -0,0 +1,51 @@
package quickjs
type Job func()
type Loop struct {
jobChan chan Job
}
func NewLoop() *Loop {
return &Loop{
jobChan: make(chan Job, 1024),
}
}
// AddJob adds a job to the loop.
func (l *Loop) scheduleJob(j Job) error {
l.jobChan <- j
return nil
}
// AddJob adds a job to the loop.
func (l *Loop) isLoopPending() bool {
return len(l.jobChan) > 0
}
// run executes all pending jobs.
func (l *Loop) run() error {
for {
select {
case job, ok := <-l.jobChan:
if !ok {
break
}
job()
default:
// Escape valve!
// If this isn't here, we deadlock...
}
if len(l.jobChan) == 0 {
break
}
}
return nil
}
// stop stops the loop.
func (l *Loop) stop() error {
close(l.jobChan)
return nil
}

15
quickjs.go Normal file
View File

@ -0,0 +1,15 @@
/*
Package quickjs Go bindings to QuickJS: a fast, small, and embeddable ES2020 JavaScript interpreter
*/
package quickjs
/*
#cgo CFLAGS: -I./deps/include
#cgo darwin,amd64 LDFLAGS: -L${SRCDIR}/deps/libs/darwin_amd64 -lquickjs -lm
#cgo darwin,arm64 LDFLAGS: -L${SRCDIR}/deps/libs/darwin_arm64 -lquickjs -lm
#cgo linux,amd64 LDFLAGS: -L${SRCDIR}/deps/libs/linux_amd64 -lquickjs -lm
#cgo linux,arm64 LDFLAGS: -L${SRCDIR}/deps/libs/linux_arm64 -lquickjs -lm
#cgo windows,amd64 LDFLAGS: -L${SRCDIR}/deps/libs/windows_amd64 -lquickjs -lm
#cgo windows,386 LDFLAGS: -L${SRCDIR}/deps/libs/windows_386 -lquickjs -lm
*/
import "C"

681
quickjs_test.go Normal file
View File

@ -0,0 +1,681 @@
package quickjs_test
import (
"errors"
"fmt"
"math/big"
"strings"
"sync"
"testing"
"time"
"apigo.cloud/git/apigo/qjs"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func Example() {
// Create a new runtime
rt := quickjs.NewRuntime()
defer rt.Close()
// Create a new context
ctx := rt.NewContext()
defer ctx.Close()
// Create a new object
test := ctx.Object()
defer test.Free()
// bind properties to the object
test.Set("A", test.Context().String("String A"))
test.Set("B", ctx.Int32(0))
test.Set("C", ctx.Bool(false))
// bind go function to js object
test.Set("hello", ctx.Function(func(ctx *quickjs.Context, this quickjs.Value, args []quickjs.Value) quickjs.Value {
return ctx.String("Hello " + args[0].String())
}))
// bind "test" object to global object
ctx.Globals().Set("test", test)
// call js function by js
js_ret, _ := ctx.Eval(`test.hello("Javascript!")`)
fmt.Println(js_ret.String())
// call js function by go
go_ret := ctx.Globals().Get("test").Call("hello", ctx.String("Golang!"))
fmt.Println(go_ret.String())
//bind go function to Javascript async function
ctx.Globals().Set("testAsync", ctx.AsyncFunction(func(ctx *quickjs.Context, this quickjs.Value, promise quickjs.Value, args []quickjs.Value) quickjs.Value {
return promise.Call("resolve", ctx.String("Hello Async Function!"))
}))
ret, _ := ctx.Eval(`
var ret;
testAsync().then(v => ret = v)
`)
defer ret.Free()
// wait for promise resolve
rt.ExecuteAllPendingJobs()
asyncRet, _ := ctx.Eval("ret")
defer asyncRet.Free()
fmt.Println(asyncRet.String())
// Output:
// Hello Javascript!
// Hello Golang!
// Hello Async Function!
}
func TestRuntimeGC(t *testing.T) {
rt := quickjs.NewRuntime()
defer rt.Close()
// set runtime options
rt.SetGCThreshold(256 * 1024)
ctx := rt.NewContext()
defer ctx.Close()
rt.RunGC()
result, _ := ctx.Eval(`"Hello GC!"`)
defer result.Free()
require.EqualValues(t, "Hello GC!", result.String())
}
func TestRuntimeMemoryLimit(t *testing.T) {
rt := quickjs.NewRuntime()
defer rt.Close()
// set runtime options
rt.SetMemoryLimit(256 * 1024) //512KB
ctx := rt.NewContext()
defer ctx.Close()
result, err := ctx.Eval(`var array = []; while (true) { array.push(null) }`)
defer result.Free()
if assert.Error(t, err, "expected a memory limit violation") {
require.Equal(t, "InternalError: out of memory", err.Error())
}
}
func TestRuntimeStackSize(t *testing.T) {
rt := quickjs.NewRuntime()
defer rt.Close()
rt.SetMaxStackSize(65534)
ctx := rt.NewContext()
defer ctx.Close()
result, err := ctx.Eval(`
function fib(n)
{
if (n <= 0)
return 0;
else if (n == 1)
return 1;
else
return fib(n - 1) + fib(n - 2);
}
fib(128)
`)
defer result.Free()
if assert.Error(t, err, "expected a memory limit violation") {
require.Equal(t, "InternalError: stack overflow", err.Error())
}
}
func TestThrowError(t *testing.T) {
expected := errors.New("custom error")
rt := quickjs.NewRuntime()
defer rt.Close()
ctx := rt.NewContext()
defer ctx.Close()
ctx.Globals().Set("A", ctx.Function(func(ctx *quickjs.Context, this quickjs.Value, args []quickjs.Value) quickjs.Value {
return ctx.ThrowError(expected)
}))
_, actual := ctx.Eval("A()")
require.Error(t, actual)
require.EqualValues(t, "Error: "+expected.Error(), actual.Error())
}
func TestThrowInternalError(t *testing.T) {
rt := quickjs.NewRuntime()
defer rt.Close()
ctx := rt.NewContext()
defer ctx.Close()
ctx.Globals().Set("A", ctx.Function(func(ctx *quickjs.Context, this quickjs.Value, args []quickjs.Value) quickjs.Value {
return ctx.ThrowInternalError("%s", "custom error")
}))
_, actual := ctx.Eval("A()")
require.Error(t, actual)
require.EqualValues(t, "InternalError: custom error", actual.Error())
}
func TestThrowRangeError(t *testing.T) {
rt := quickjs.NewRuntime()
defer rt.Close()
ctx := rt.NewContext()
defer ctx.Close()
ctx.Globals().Set("A", ctx.Function(func(ctx *quickjs.Context, this quickjs.Value, args []quickjs.Value) quickjs.Value {
return ctx.ThrowRangeError("%s", "custom error")
}))
_, actual := ctx.Eval("A()")
require.Error(t, actual)
require.EqualValues(t, "RangeError: custom error", actual.Error())
}
func TestThrowReferenceError(t *testing.T) {
rt := quickjs.NewRuntime()
defer rt.Close()
ctx := rt.NewContext()
defer ctx.Close()
ctx.Globals().Set("A", ctx.Function(func(ctx *quickjs.Context, this quickjs.Value, args []quickjs.Value) quickjs.Value {
return ctx.ThrowReferenceError("%s", "custom error")
}))
_, actual := ctx.Eval("A()")
require.Error(t, actual)
require.EqualValues(t, "ReferenceError: custom error", actual.Error())
}
func TestThrowSyntaxError(t *testing.T) {
rt := quickjs.NewRuntime()
defer rt.Close()
ctx := rt.NewContext()
defer ctx.Close()
ctx.Globals().Set("A", ctx.Function(func(ctx *quickjs.Context, this quickjs.Value, args []quickjs.Value) quickjs.Value {
return ctx.ThrowSyntaxError("%s", "custom error")
}))
_, actual := ctx.Eval("A()")
require.Error(t, actual)
require.EqualValues(t, "SyntaxError: custom error", actual.Error())
}
func TestThrowTypeError(t *testing.T) {
rt := quickjs.NewRuntime()
defer rt.Close()
ctx := rt.NewContext()
defer ctx.Close()
ctx.Globals().Set("A", ctx.Function(func(ctx *quickjs.Context, this quickjs.Value, args []quickjs.Value) quickjs.Value {
return ctx.ThrowTypeError("%s", "custom error")
}))
_, actual := ctx.Eval("A()")
require.Error(t, actual)
require.EqualValues(t, "TypeError: custom error", actual.Error())
}
func TestValue(t *testing.T) {
rt := quickjs.NewRuntime()
defer rt.Close()
ctx := rt.NewContext()
defer ctx.Close()
// require.EqualValues(t, big.NewInt(1), ctx.BigUint64(uint64(1)).)
require.EqualValues(t, true, ctx.Bool(true).IsBool())
require.EqualValues(t, true, ctx.Bool(true).Bool())
require.EqualValues(t, float64(0.1), ctx.Float64(0.1).Float64())
require.EqualValues(t, int32(1), ctx.Int32(1).Int32())
require.EqualValues(t, int64(1), ctx.Int64(1).Int64())
require.EqualValues(t, uint32(1), ctx.Uint32(1).Uint32())
require.EqualValues(t, big.NewInt(1), ctx.BigInt64(1).BigInt())
require.EqualValues(t, big.NewInt(1), ctx.BigUint64(1).BigInt())
require.EqualValues(t, false, ctx.Float64(0.1).IsBigDecimal())
require.EqualValues(t, false, ctx.Float64(0.1).IsBigFloat())
require.EqualValues(t, false, ctx.Float64(0.1).IsBigInt())
a := ctx.Array()
defer a.Free()
//require.True(t, a.IsArray())
o := ctx.Object()
defer o.Free()
require.True(t, o.IsObject())
s := ctx.String("hello")
defer s.Free()
require.EqualValues(t, true, s.IsString())
n := ctx.Null()
defer n.Free()
require.True(t, n.IsNull())
ud := ctx.Undefined()
defer ud.Free()
require.True(t, ud.IsUndefined())
ui := ctx.Uninitialized()
defer ui.Free()
require.True(t, ui.IsUninitialized())
sym, _ := ctx.Eval("Symbol()")
defer sym.Free()
require.True(t, sym.IsSymbol())
err := ctx.Error(errors.New("error"))
defer err.Free()
require.True(t, err.IsError())
}
func TestEvalBytecode(t *testing.T) {
rt := quickjs.NewRuntime()
defer rt.Close()
ctx := rt.NewContext()
defer ctx.Close()
jsStr := `
function fib(n)
{
if (n <= 0)
return 0;
else if (n == 1)
return 1;
else
return fib(n - 1) + fib(n - 2);
}
fib(10)
`
buf, err := ctx.Compile(jsStr)
require.NoError(t, err)
rt2 := quickjs.NewRuntime()
defer rt2.Close()
ctx2 := rt2.NewContext()
defer ctx2.Close()
result, err := ctx2.EvalBytecode(buf)
require.NoError(t, err)
require.EqualValues(t, 55, result.Int32())
}
func TestBadSyntax(t *testing.T) {
rt := quickjs.NewRuntime()
defer rt.Close()
ctx := rt.NewContext()
defer ctx.Close()
_, err := ctx.Compile(`"bad syntax'`)
require.Error(t, err)
}
func TestBadBytecode(t *testing.T) {
rt := quickjs.NewRuntime()
defer rt.Close()
ctx := rt.NewContext()
defer ctx.Close()
buf := make([]byte, 1)
_, err := ctx.EvalBytecode(buf)
require.Error(t, err)
}
func TestArrayBuffer(t *testing.T) {
rt := quickjs.NewRuntime()
defer rt.Close()
ctx := rt.NewContext()
defer ctx.Close()
binaryData := []uint8{1, 2, 3, 4, 5}
value := ctx.ArrayBuffer(binaryData)
defer value.Free()
for i := 1; i <= len(binaryData); i++ {
data, err := value.ToByteArray(uint(i))
assert.NoError(t, err)
//fmt.Println(data)
assert.EqualValues(t, data, binaryData[:i])
}
_, err := value.ToByteArray(uint(len(binaryData)) + 1)
assert.Error(t, err)
assert.True(t, value.IsByteArray())
binaryLen := len(binaryData)
assert.Equal(t, value.ByteLen(), int64(binaryLen))
}
func TestConcurrency(t *testing.T) {
n := 32
m := 10000
var wg sync.WaitGroup
wg.Add(n)
req := make(chan struct{}, n)
res := make(chan int64, m)
for i := 0; i < n; i++ {
go func() {
defer wg.Done()
rt := quickjs.NewRuntime()
defer rt.Close()
ctx := rt.NewContext()
defer ctx.Close()
for range req {
result, err := ctx.Eval(`new Date().getTime()`)
require.NoError(t, err)
res <- result.Int64()
result.Free()
}
}()
}
for i := 0; i < m; i++ {
req <- struct{}{}
}
close(req)
wg.Wait()
for i := 0; i < m; i++ {
<-res
}
}
func TestJson(t *testing.T) {
// Create a new runtime
rt := quickjs.NewRuntime()
defer rt.Close()
// Create a new context
ctx := rt.NewContext()
defer ctx.Close()
// Create a object from json
fooObj := ctx.ParseJSON(`{"foo":"bar"}`)
defer fooObj.Free()
// JSONStringify
jsonStr := fooObj.JSONStringify()
require.EqualValues(t, "{\"foo\":\"bar\"}", jsonStr)
}
func TestObject(t *testing.T) {
// Create a new runtime
rt := quickjs.NewRuntime()
defer rt.Close()
// Create a new context
ctx := rt.NewContext()
defer ctx.Close()
// Create a new object
test := ctx.Object()
test.Set("A", test.Context().String("String A"))
test.Set("B", ctx.Int32(0))
test.Set("C", ctx.Bool(false))
ctx.Globals().Set("test", test)
result, err := ctx.Eval(`Object.keys(test).map(key => test[key]).join(",")`)
require.NoError(t, err)
defer result.Free()
// eval js code
require.EqualValues(t, "String A,0,false", result.String())
// set function
test.Set("F", ctx.Function(func(ctx *quickjs.Context, this quickjs.Value, args []quickjs.Value) quickjs.Value {
arg_x := args[0].Int32()
arg_y := args[1].Int32()
return ctx.Int32(arg_x * arg_y)
}))
// call js function by go
F_ret := test.Call("F", ctx.Int32(2), ctx.Int32(3))
defer F_ret.Free()
require.True(t, F_ret.IsNumber() && F_ret.Int32() == 6)
// invoke js function by go
f_func := test.Get("F")
defer f_func.Free()
ret := ctx.Invoke(f_func, ctx.Null(), ctx.Int32(2), ctx.Int32(3))
require.True(t, ret.IsNumber() && ret.Int32() == 6)
// test error call
F_ret_err := test.Call("A", ctx.Int32(2), ctx.Int32(3))
defer F_ret_err.Free()
require.Error(t, F_ret_err.Error())
// get object property
require.True(t, test.Has("A"))
require.True(t, test.Get("A").String() == "String A")
// get object all property
pNames, _ := test.PropertyNames()
require.True(t, strings.Join(pNames[:], ",") == "A,B,C,F")
// delete object property
test.Delete("C")
pNames, _ = test.PropertyNames()
require.True(t, strings.Join(pNames[:], ",") == "A,B,F")
}
func TestArray(t *testing.T) {
rt := quickjs.NewRuntime()
defer rt.Close()
ctx := rt.NewContext()
defer ctx.Close()
test := ctx.Array()
for i := int64(0); i < 3; i++ {
test.Push(ctx.String(fmt.Sprintf("test %d", i)))
require.True(t, test.HasIdx(i))
}
require.EqualValues(t, 3, test.Len())
for i := int64(0); int64(i) < test.Len(); i++ {
require.EqualValues(t, fmt.Sprintf("test %d", i), test.ToValue().GetIdx(i).String())
}
ctx.Globals().Set("test", test.ToValue())
result, err := ctx.Eval(`test.map(v => v.toUpperCase())`)
require.NoError(t, err)
defer result.Free()
require.EqualValues(t, `TEST 0,TEST 1,TEST 2`, result.String())
dFlag, _ := test.Delete(0)
require.True(t, dFlag)
result, err = ctx.Eval(`test.map(v => v.toUpperCase())`)
require.NoError(t, err)
defer result.Free()
require.EqualValues(t, `TEST 1,TEST 2`, result.String())
first, err := test.Get(0)
if err != nil {
fmt.Println(err)
}
require.EqualValues(t, first.String(), "test 1")
test.Push([]quickjs.Value{ctx.Int32(34), ctx.Bool(false), ctx.String("445")}...)
require.Equal(t, int(test.Len()), 5)
err = test.Set(test.Len()-1, ctx.Int32(2))
require.NoError(t, err)
require.EqualValues(t, test.ToValue().String(), "test 1,test 2,34,false,2")
}
func TestMap(t *testing.T) {
rt := quickjs.NewRuntime()
defer rt.Close()
ctx := rt.NewContext()
defer ctx.Close()
test := ctx.Map()
defer test.Free()
require.True(t, test.ToValue().IsMap())
for i := int64(0); i < 3; i++ {
test.Put(ctx.Int64(i), ctx.String(fmt.Sprintf("test %d", i)))
require.True(t, test.Has(ctx.Int64(i)))
testValue := test.Get(ctx.Int64(i))
require.EqualValues(t, testValue.String(), fmt.Sprintf("test %d", i))
//testValue.Free()
}
count := 0
test.ForEach(func(key quickjs.Value, value quickjs.Value) {
count++
fmt.Println(fmt.Sprintf("key:%s value:%s", key.String(), value.String()))
})
require.EqualValues(t, count, 3)
test.Put(ctx.Int64(3), ctx.Int64(4))
fmt.Println("\nput after the content inside")
count = 0
test.ForEach(func(key quickjs.Value, value quickjs.Value) {
count++
fmt.Println(fmt.Sprintf("key:%s value:%s", key.String(), value.String()))
})
require.EqualValues(t, count, 4)
count = 0
test.Delete(ctx.Int64(3))
fmt.Println("\ndelete after the content inside")
test.ForEach(func(key quickjs.Value, value quickjs.Value) {
if key.String() == "3" {
panic(errors.New("map did not delete the key"))
}
count++
fmt.Println(fmt.Sprintf("key:%s value:%s", key.String(), value.String()))
})
require.EqualValues(t, count, 3)
}
func TestSet(t *testing.T) {
rt := quickjs.NewRuntime()
defer rt.Close()
ctx := rt.NewContext()
defer ctx.Close()
test := ctx.Set()
defer test.Free()
require.True(t, test.ToValue().IsSet())
for i := int64(0); i < 3; i++ {
test.Add(ctx.Int64(i))
require.True(t, test.Has(ctx.Int64(i)))
}
count := 0
test.ForEach(func(key quickjs.Value) {
count++
fmt.Println(fmt.Sprintf("value:%s", key.String()))
})
require.EqualValues(t, count, 3)
test.Delete(ctx.Int64(0))
require.True(t, !test.Has(ctx.Int64(0)))
}
func TestAsyncFunction(t *testing.T) {
rt := quickjs.NewRuntime()
defer rt.Close()
ctx := rt.NewContext()
defer ctx.Close()
ctx.Globals().Set("testAsync", ctx.AsyncFunction(func(ctx *quickjs.Context, this quickjs.Value, promise quickjs.Value, args []quickjs.Value) quickjs.Value {
return promise.Call("resolve", ctx.String(args[0].String()+args[1].String()))
}))
ret1, _ := ctx.Eval(`
var ret = "";
`)
defer ret1.Free()
ctx.ScheduleJob(func() {
ret2, _ := ctx.Eval(`ret = ret + "Job Done: ";`)
defer ret2.Free()
})
// wait for job resolve
rt.ExecuteAllPendingJobs()
// testAsync
ret3, _ := ctx.Eval(`
testAsync('Hello ', 'Async').then(v => ret = ret + v)
`)
defer ret3.Free()
// wait promise execute
rt.ExecuteAllPendingJobs()
ret4, _ := ctx.Eval("ret")
defer ret4.Free()
require.EqualValues(t, "Job Done: Hello Async", ret4.String())
}
func TestSetInterruptHandler(t *testing.T) {
rt := quickjs.NewRuntime()
defer rt.Close()
ctx := rt.NewContext()
defer ctx.Close()
startTime := time.Now().Unix()
ctx.SetInterruptHandler(func() int {
if time.Now().Unix()-startTime > 1 {
return 1
}
return 0
})
ret, err := ctx.Eval(`while(true){}`)
defer ret.Free()
assert.Error(t, err, "expected interrupted by quickjs")
require.Equal(t, "InternalError: interrupted", err.Error())
}

105
runtime.go Normal file
View File

@ -0,0 +1,105 @@
package quickjs
/*
#include "bridge.h"
*/
import "C"
import (
"io"
"runtime"
"time"
)
// Runtime represents a Javascript runtime corresponding to an object heap. Several runtimes can exist at the same time but they cannot exchange objects. Inside a given runtime, no multi-threading is supported.
type Runtime struct {
ref *C.JSRuntime
loop *Loop // only one loop per runtime
}
// NewRuntime creates a new quickjs runtime.
func NewRuntime() Runtime {
runtime.LockOSThread() // prevent multiple quickjs runtime from being created
rt := Runtime{ref: C.JS_NewRuntime(), loop: NewLoop()}
C.JS_SetCanBlock(rt.ref, C.int(1))
return rt
}
// RunGC will call quickjs's garbage collector.
func (r Runtime) RunGC() {
C.JS_RunGC(r.ref)
}
// Close will free the runtime pointer.
func (r Runtime) Close() {
C.JS_FreeRuntime(r.ref)
}
// SetMemoryLimit the runtime memory limit; if not set, it will be unlimit.
func (r Runtime) SetMemoryLimit(limit uint32) {
C.JS_SetMemoryLimit(r.ref, C.size_t(limit))
}
// SetGCThreshold the runtime's GC threshold; use -1 to disable automatic GC.
func (r Runtime) SetGCThreshold(threshold int64) {
C.JS_SetGCThreshold(r.ref, C.size_t(threshold))
}
// SetMaxStackSize will set max runtime's stack size; default is 255
func (r Runtime) SetMaxStackSize(stack_size uint32) {
C.JS_SetMaxStackSize(r.ref, C.size_t(stack_size))
}
// NewContext creates a new JavaScript context.
// enable BigFloat/BigDecimal support and enable .
// enable operator overloading.
func (r Runtime) NewContext() *Context {
ref := C.JS_NewContext(r.ref)
C.JS_AddIntrinsicBigFloat(ref)
C.JS_AddIntrinsicBigDecimal(ref)
C.JS_AddIntrinsicOperators(ref)
C.JS_EnableBignumExt(ref, C.int(1))
return &Context{ref: ref, runtime: &r, funcPtrs: make([]int64, 0)}
}
// ExecutePendingJob will execute all pending jobs.
func (r Runtime) ExecutePendingJob() (Context, error) {
var ctx Context
err := C.JS_ExecutePendingJob(r.ref, &ctx.ref)
if err <= 0 {
if err == 0 {
return ctx, io.EOF
}
return ctx, ctx.Exception()
}
return ctx, nil
}
// IsJobPending returns true if there is a pending job.
func (r Runtime) IsJobPending() bool {
return C.JS_IsJobPending(r.ref) == 1
}
// IsLoopJobPending returns true if there is a pending loop job.
func (r Runtime) IsLoopJobPending() bool {
return r.loop.isLoopPending()
}
func (r Runtime) ExecuteAllPendingJobs() error {
var err error
for r.loop.isLoopPending() || r.IsJobPending() {
// execute loop job
r.loop.run()
// excute promiIs
_, err := r.ExecutePendingJob()
if err == io.EOF {
err = nil
}
time.Sleep(time.Millisecond * 1) // prevent 100% CPU
}
return err
}

360
value.go Normal file
View File

@ -0,0 +1,360 @@
package quickjs
/*
#include "bridge.h"
*/
import "C"
import (
"errors"
"math/big"
"unsafe"
)
type Error struct {
Cause string
Stack string
}
func (err Error) Error() string { return err.Cause }
// Object property names and some strings are stored as Atoms (unique strings) to save memory and allow fast comparison. Atoms are represented as a 32 bit integer. Half of the atom range is reserved for immediate integer literals from 0 to 2^{31}-1.
type Atom struct {
ctx *Context
ref C.JSAtom
}
// Free the value.
func (a Atom) Free() {
C.JS_FreeAtom(a.ctx.ref, a.ref)
}
// String returns the string representation of the value.
func (a Atom) String() string {
ptr := C.JS_AtomToCString(a.ctx.ref, a.ref)
defer C.JS_FreeCString(a.ctx.ref, ptr)
return C.GoString(ptr)
}
// Value returns the value of the Atom object.
func (a Atom) Value() Value {
return Value{ctx: a.ctx, ref: C.JS_AtomToValue(a.ctx.ref, a.ref)}
}
// propertyEnum is a wrapper around JSAtom.
type propertyEnum struct {
IsEnumerable bool
atom Atom
}
// String returns the atom string representation of the value.
func (p propertyEnum) String() string { return p.atom.String() }
// JSValue represents a Javascript value which can be a primitive type or an object. Reference counting is used, so it is important to explicitly duplicate (JS_DupValue(), increment the reference count) or free (JS_FreeValue(), decrement the reference count) JSValues.
type Value struct {
ctx *Context
ref C.JSValue
}
// Free the value.
func (v Value) Free() {
C.JS_FreeValue(v.ctx.ref, v.ref)
}
// Context represents a Javascript context.
func (v Value) Context() *Context {
return v.ctx
}
// Bool returns the boolean value of the value.
func (v Value) Bool() bool {
return C.JS_ToBool(v.ctx.ref, v.ref) == 1
}
// String returns the string representation of the value.
func (v Value) String() string {
ptr := C.JS_ToCString(v.ctx.ref, v.ref)
defer C.JS_FreeCString(v.ctx.ref, ptr)
return C.GoString(ptr)
}
// JSONString returns the JSON string representation of the value.
func (v Value) JSONStringify() string {
ref := C.JS_JSONStringify(v.ctx.ref, v.ref, C.JS_NewNull(), C.JS_NewNull())
ptr := C.JS_ToCString(v.ctx.ref, ref)
defer C.JS_FreeCString(v.ctx.ref, ptr)
return C.GoString(ptr)
}
func (v Value) ToByteArray(size uint) ([]byte, error) {
if v.ByteLen() < int64(size) {
return nil, errors.New("exceeds the maximum length of the current binary array")
}
cSize := C.size_t(size)
outBuf := C.JS_GetArrayBuffer(v.ctx.ref, &cSize, v.ref)
return C.GoBytes(unsafe.Pointer(outBuf), C.int(size)), nil
}
// IsByteArray return true if the value is array buffer
func (v Value) IsByteArray() bool {
return v.IsObject() && v.globalInstanceof("ArrayBuffer") || v.String() == "[object ArrayBuffer]"
}
// Int64 returns the int64 value of the value.
func (v Value) Int64() int64 {
val := C.int64_t(0)
C.JS_ToInt64(v.ctx.ref, &val, v.ref)
return int64(val)
}
// Int32 returns the int32 value of the value.
func (v Value) Int32() int32 {
val := C.int32_t(0)
C.JS_ToInt32(v.ctx.ref, &val, v.ref)
return int32(val)
}
// Uint32 returns the uint32 value of the value.
func (v Value) Uint32() uint32 {
val := C.uint32_t(0)
C.JS_ToUint32(v.ctx.ref, &val, v.ref)
return uint32(val)
}
// Float64 returns the float64 value of the value.
func (v Value) Float64() float64 {
val := C.double(0)
C.JS_ToFloat64(v.ctx.ref, &val, v.ref)
return float64(val)
}
// BigInt returns the big.Int value of the value.
func (v Value) BigInt() *big.Int {
if !v.IsBigInt() {
return nil
}
val, ok := new(big.Int).SetString(v.String(), 10)
if !ok {
return nil
}
return val
}
// BigFloat returns the big.Float value of the value.
func (v Value) BigFloat() *big.Float {
if !v.IsBigDecimal() && !v.IsBigFloat() {
return nil
}
val, ok := new(big.Float).SetString(v.String())
if !ok {
return nil
}
return val
}
// ToArray
//
// @Description: return array object
// @receiver v :
// @return *Array
func (v Value) ToArray() *Array {
if !v.IsArray() {
return nil
}
return NewQjsArray(v, v.ctx)
}
// ToMap
//
// @Description: return map object
// @receiver v :
// @return *Map
func (v Value) ToMap() *Map {
if !v.IsMap() {
return nil
}
return NewQjsMap(v, v.ctx)
}
// ToSet
//
// @Description: return set object
// @receiver v :
// @return *Set
func (v Value) ToSet() *Set {
if v.IsSet() {
return nil
}
return NewQjsSet(v, v.ctx)
}
// IsMap return true if the value is a map
func (v Value) IsMap() bool {
return v.IsObject() && v.globalInstanceof("Map") || v.String() == "[object Map]"
}
// IsSet return true if the value is a set
func (v Value) IsSet() bool {
return v.IsObject() && v.globalInstanceof("Set") || v.String() == "[object Set]"
}
// Len returns the length of the array.
func (v Value) Len() int64 {
return v.Get("length").Int64()
}
// ByteLen returns the length of the ArrayBuffer.
func (v Value) ByteLen() int64 {
return v.Get("byteLength").Int64()
}
// Set sets the value of the property with the given name.
func (v Value) Set(name string, val Value) {
namePtr := C.CString(name)
defer C.free(unsafe.Pointer(namePtr))
C.JS_SetPropertyStr(v.ctx.ref, v.ref, namePtr, val.ref)
}
// SetIdx sets the value of the property with the given index.
func (v Value) SetIdx(idx int64, val Value) {
C.JS_SetPropertyUint32(v.ctx.ref, v.ref, C.uint32_t(idx), val.ref)
}
// Get returns the value of the property with the given name.
func (v Value) Get(name string) Value {
namePtr := C.CString(name)
defer C.free(unsafe.Pointer(namePtr))
return Value{ctx: v.ctx, ref: C.JS_GetPropertyStr(v.ctx.ref, v.ref, namePtr)}
}
// GetIdx returns the value of the property with the given index.
func (v Value) GetIdx(idx int64) Value {
return Value{ctx: v.ctx, ref: C.JS_GetPropertyUint32(v.ctx.ref, v.ref, C.uint32_t(idx))}
}
// Call calls the function with the given arguments.
func (v Value) Call(fname string, args ...Value) Value {
if !v.IsObject() {
return v.ctx.Error(errors.New("Object not a object"))
}
fn := v.Get(fname) // get the function by name
defer fn.Free()
if !fn.IsFunction() {
return v.ctx.Error(errors.New("Object not a function"))
}
cargs := []C.JSValue{}
for _, x := range args {
cargs = append(cargs, x.ref)
}
if len(cargs) == 0 {
return Value{ctx: v.ctx, ref: C.JS_Call(v.ctx.ref, fn.ref, v.ref, C.int(0), nil)}
}
return Value{ctx: v.ctx, ref: C.JS_Call(v.ctx.ref, fn.ref, v.ref, C.int(len(cargs)), &cargs[0])}
}
// Error returns the error value of the value.
func (v Value) Error() error {
if !v.IsError() {
return nil
}
cause := v.String()
stack := v.Get("stack")
defer stack.Free()
if stack.IsUndefined() {
return &Error{Cause: cause}
}
return &Error{Cause: cause, Stack: stack.String()}
}
// propertyEnum is a wrapper around JSValue.
func (v Value) propertyEnum() ([]propertyEnum, error) {
var ptr *C.JSPropertyEnum
var size C.uint32_t
result := int(C.JS_GetOwnPropertyNames(v.ctx.ref, &ptr, &size, v.ref, C.int(1<<0|1<<1|1<<2)))
if result < 0 {
return nil, errors.New("value does not contain properties")
}
defer C.js_free(v.ctx.ref, unsafe.Pointer(ptr))
entries := unsafe.Slice(ptr, size) // Go 1.17 and later
names := make([]propertyEnum, len(entries))
for i := 0; i < len(names); i++ {
names[i].IsEnumerable = entries[i].is_enumerable == 1
names[i].atom = Atom{ctx: v.ctx, ref: entries[i].atom}
names[i].atom.Free()
}
return names, nil
}
// PropertyNames returns the names of the properties of the value.
func (v Value) PropertyNames() ([]string, error) {
pList, err := v.propertyEnum()
if err != nil {
return nil, err
}
names := make([]string, len(pList))
for i := 0; i < len(names); i++ {
names[i] = pList[i].String()
}
return names, nil
}
// Has returns true if the value has the property with the given name.
func (v Value) Has(name string) bool {
prop := v.ctx.Atom(name)
defer prop.Free()
return C.JS_HasProperty(v.ctx.ref, v.ref, prop.ref) == 1
}
// HasIdx returns true if the value has the property with the given index.
func (v Value) HasIdx(idx int64) bool {
prop := v.ctx.AtomIdx(idx)
defer prop.Free()
return C.JS_HasProperty(v.ctx.ref, v.ref, prop.ref) == 1
}
// Delete deletes the property with the given name.
func (v Value) Delete(name string) bool {
prop := v.ctx.Atom(name)
defer prop.Free()
return C.JS_DeleteProperty(v.ctx.ref, v.ref, prop.ref, C.int(1)) == 1
}
// DeleteIdx deletes the property with the given index.
func (v Value) DeleteIdx(idx int64) bool {
return C.JS_DeletePropertyInt64(v.ctx.ref, v.ref, C.int64_t(idx), C.int(1)) == 1
}
// globalInstanceof checks if the value is an instance of the given global constructor
func (v Value) globalInstanceof(name string) bool {
ctor := v.ctx.Globals().Get(name)
defer ctor.Free()
if ctor.IsUndefined() {
return false
}
return C.JS_IsInstanceOf(v.ctx.ref, v.ref, ctor.ref) == 1
}
func (v Value) IsNumber() bool { return C.JS_IsNumber(v.ref) == 1 }
func (v Value) IsBigInt() bool { return C.JS_IsBigInt(v.ctx.ref, v.ref) == 1 }
func (v Value) IsBigFloat() bool { return C.JS_IsBigFloat(v.ref) == 1 }
func (v Value) IsBigDecimal() bool { return C.JS_IsBigDecimal(v.ref) == 1 }
func (v Value) IsBool() bool { return C.JS_IsBool(v.ref) == 1 }
func (v Value) IsNull() bool { return C.JS_IsNull(v.ref) == 1 }
func (v Value) IsUndefined() bool { return C.JS_IsUndefined(v.ref) == 1 }
func (v Value) IsException() bool { return C.JS_IsException(v.ref) == 1 }
func (v Value) IsUninitialized() bool { return C.JS_IsUninitialized(v.ref) == 1 }
func (v Value) IsString() bool { return C.JS_IsString(v.ref) == 1 }
func (v Value) IsSymbol() bool { return C.JS_IsSymbol(v.ref) == 1 }
func (v Value) IsObject() bool { return C.JS_IsObject(v.ref) == 1 }
func (v Value) IsArray() bool { return C.JS_IsArray(v.ctx.ref, v.ref) == 1 }
func (v Value) IsError() bool { return C.JS_IsError(v.ctx.ref, v.ref) == 1 }
func (v Value) IsFunction() bool { return C.JS_IsFunction(v.ctx.ref, v.ref) == 1 }
// func (v Value) IsConstructor() bool { return C.JS_IsConstructor(v.ctx.ref, v.ref) == 1 }