commit d7054c4994161617aac4c16b423a311f87cc1af6 Author: Star <> Date: Tue Feb 6 17:39:51 2024 +0800 first diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..829c9cb --- /dev/null +++ b/LICENSE @@ -0,0 +1,24 @@ +MIT License + +Copyright (c) 2022 Brian Wang +Copyright (c) 2020 Kenta Iwasaki +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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..c7e7a18 --- /dev/null +++ b/README.md @@ -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 \ No newline at end of file diff --git a/README_zh-cn.md b/README_zh-cn.md new file mode 100644 index 0000000..94649a7 --- /dev/null +++ b/README_zh-cn.md @@ -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 \ No newline at end of file diff --git a/bridge.c b/bridge.c new file mode 100644 index 0000000..47de658 --- /dev/null +++ b/bridge.c @@ -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); +} \ No newline at end of file diff --git a/bridge.go b/bridge.go new file mode 100644 index 0000000..f4510f3 --- /dev/null +++ b/bridge.go @@ -0,0 +1,114 @@ +package quickjs + +import ( + "runtime/cgo" + "sync" + "sync/atomic" + "unsafe" +) + +/* +#include +#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()) +} diff --git a/bridge.h b/bridge.h new file mode 100644 index 0000000..edc08cf --- /dev/null +++ b/bridge.h @@ -0,0 +1,23 @@ +#include +#include +#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); \ No newline at end of file diff --git a/collection.go b/collection.go new file mode 100644 index 0000000..5e07a66 --- /dev/null +++ b/collection.go @@ -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 +} diff --git a/context.go b/context.go new file mode 100644 index 0000000..170e582 --- /dev/null +++ b/context.go @@ -0,0 +1,382 @@ +package quickjs + +import ( + "fmt" + "runtime/cgo" + "unsafe" +) + +/* +#include // 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) +} diff --git a/deps/Makefile b/deps/Makefile new file mode 100644 index 0000000..70fbd68 --- /dev/null +++ b/deps/Makefile @@ -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||\n|' < $< > $@ + +############################################################################### +# 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) diff --git a/deps/include/quickjs.h b/deps/include/quickjs.h new file mode 100644 index 0000000..d4a5cd3 --- /dev/null +++ b/deps/include/quickjs.h @@ -0,0 +1,1049 @@ +/* + * 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. + */ +#ifndef QUICKJS_H +#define QUICKJS_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(__GNUC__) || defined(__clang__) +#define js_likely(x) __builtin_expect(!!(x), 1) +#define js_unlikely(x) __builtin_expect(!!(x), 0) +#define js_force_inline inline __attribute__((always_inline)) +#define __js_printf_like(f, a) __attribute__((format(printf, f, a))) +#else +#define js_likely(x) (x) +#define js_unlikely(x) (x) +#define js_force_inline inline +#define __js_printf_like(a, b) +#endif + +#define JS_BOOL int + +typedef struct JSRuntime JSRuntime; +typedef struct JSContext JSContext; +typedef struct JSObject JSObject; +typedef struct JSClass JSClass; +typedef uint32_t JSClassID; +typedef uint32_t JSAtom; + +#if INTPTR_MAX >= INT64_MAX +#define JS_PTR64 +#define JS_PTR64_DEF(a) a +#else +#define JS_PTR64_DEF(a) +#endif + +#ifndef JS_PTR64 +#define JS_NAN_BOXING +#endif + +enum { + /* all tags with a reference count are negative */ + JS_TAG_FIRST = -11, /* first negative tag */ + JS_TAG_BIG_DECIMAL = -11, + JS_TAG_BIG_INT = -10, + JS_TAG_BIG_FLOAT = -9, + JS_TAG_SYMBOL = -8, + JS_TAG_STRING = -7, + JS_TAG_MODULE = -3, /* used internally */ + JS_TAG_FUNCTION_BYTECODE = -2, /* used internally */ + JS_TAG_OBJECT = -1, + + JS_TAG_INT = 0, + JS_TAG_BOOL = 1, + JS_TAG_NULL = 2, + JS_TAG_UNDEFINED = 3, + JS_TAG_UNINITIALIZED = 4, + JS_TAG_CATCH_OFFSET = 5, + JS_TAG_EXCEPTION = 6, + JS_TAG_FLOAT64 = 7, + /* any larger tag is FLOAT64 if JS_NAN_BOXING */ +}; + +typedef struct JSRefCountHeader { + int ref_count; +} JSRefCountHeader; + +#define JS_FLOAT64_NAN NAN + +#ifdef CONFIG_CHECK_JSVALUE +/* JSValue consistency : it is not possible to run the code in this + mode, but it is useful to detect simple reference counting + errors. It would be interesting to modify a static C analyzer to + handle specific annotations (clang has such annotations but only + for objective C) */ +typedef struct __JSValue *JSValue; +typedef const struct __JSValue *JSValueConst; + +#define JS_VALUE_GET_TAG(v) (int)((uintptr_t)(v) & 0xf) +/* same as JS_VALUE_GET_TAG, but return JS_TAG_FLOAT64 with NaN boxing */ +#define JS_VALUE_GET_NORM_TAG(v) JS_VALUE_GET_TAG(v) +#define JS_VALUE_GET_INT(v) (int)((intptr_t)(v) >> 4) +#define JS_VALUE_GET_BOOL(v) JS_VALUE_GET_INT(v) +#define JS_VALUE_GET_FLOAT64(v) (double)JS_VALUE_GET_INT(v) +#define JS_VALUE_GET_PTR(v) (void *)((intptr_t)(v) & ~0xf) + +#define JS_MKVAL(tag, val) (JSValue)(intptr_t)(((val) << 4) | (tag)) +#define JS_MKPTR(tag, p) (JSValue)((intptr_t)(p) | (tag)) + +#define JS_TAG_IS_FLOAT64(tag) ((unsigned)(tag) == JS_TAG_FLOAT64) + +#define JS_NAN JS_MKVAL(JS_TAG_FLOAT64, 1) + +static inline JSValue __JS_NewFloat64(JSContext *ctx, double d) +{ + return JS_MKVAL(JS_TAG_FLOAT64, (int)d); +} + +static inline JS_BOOL JS_VALUE_IS_NAN(JSValue v) +{ + return 0; +} + +#elif defined(JS_NAN_BOXING) + +typedef uint64_t JSValue; + +#define JSValueConst JSValue + +#define JS_VALUE_GET_TAG(v) (int)((v) >> 32) +#define JS_VALUE_GET_INT(v) (int)(v) +#define JS_VALUE_GET_BOOL(v) (int)(v) +#define JS_VALUE_GET_PTR(v) (void *)(intptr_t)(v) + +#define JS_MKVAL(tag, val) (((uint64_t)(tag) << 32) | (uint32_t)(val)) +#define JS_MKPTR(tag, ptr) (((uint64_t)(tag) << 32) | (uintptr_t)(ptr)) + +#define JS_FLOAT64_TAG_ADDEND (0x7ff80000 - JS_TAG_FIRST + 1) /* quiet NaN encoding */ + +static inline double JS_VALUE_GET_FLOAT64(JSValue v) +{ + union { + JSValue v; + double d; + } u; + u.v = v; + u.v += (uint64_t)JS_FLOAT64_TAG_ADDEND << 32; + return u.d; +} + +#define JS_NAN (0x7ff8000000000000 - ((uint64_t)JS_FLOAT64_TAG_ADDEND << 32)) + +static inline JSValue __JS_NewFloat64(JSContext *ctx, double d) +{ + union { + double d; + uint64_t u64; + } u; + JSValue v; + u.d = d; + /* normalize NaN */ + if (js_unlikely((u.u64 & 0x7fffffffffffffff) > 0x7ff0000000000000)) + v = JS_NAN; + else + v = u.u64 - ((uint64_t)JS_FLOAT64_TAG_ADDEND << 32); + return v; +} + +#define JS_TAG_IS_FLOAT64(tag) ((unsigned)((tag) - JS_TAG_FIRST) >= (JS_TAG_FLOAT64 - JS_TAG_FIRST)) + +/* same as JS_VALUE_GET_TAG, but return JS_TAG_FLOAT64 with NaN boxing */ +static inline int JS_VALUE_GET_NORM_TAG(JSValue v) +{ + uint32_t tag; + tag = JS_VALUE_GET_TAG(v); + if (JS_TAG_IS_FLOAT64(tag)) + return JS_TAG_FLOAT64; + else + return tag; +} + +static inline JS_BOOL JS_VALUE_IS_NAN(JSValue v) +{ + uint32_t tag; + tag = JS_VALUE_GET_TAG(v); + return tag == (JS_NAN >> 32); +} + +#else /* !JS_NAN_BOXING */ + +typedef union JSValueUnion { + int32_t int32; + double float64; + void *ptr; +} JSValueUnion; + +typedef struct JSValue { + JSValueUnion u; + int64_t tag; +} JSValue; + +#define JSValueConst JSValue + +#define JS_VALUE_GET_TAG(v) ((int32_t)(v).tag) +/* same as JS_VALUE_GET_TAG, but return JS_TAG_FLOAT64 with NaN boxing */ +#define JS_VALUE_GET_NORM_TAG(v) JS_VALUE_GET_TAG(v) +#define JS_VALUE_GET_INT(v) ((v).u.int32) +#define JS_VALUE_GET_BOOL(v) ((v).u.int32) +#define JS_VALUE_GET_FLOAT64(v) ((v).u.float64) +#define JS_VALUE_GET_PTR(v) ((v).u.ptr) + +#define JS_MKVAL(tag, val) (JSValue){ (JSValueUnion){ .int32 = val }, tag } +#define JS_MKPTR(tag, p) (JSValue){ (JSValueUnion){ .ptr = p }, tag } + +#define JS_TAG_IS_FLOAT64(tag) ((unsigned)(tag) == JS_TAG_FLOAT64) + +#define JS_NAN (JSValue){ .u.float64 = JS_FLOAT64_NAN, JS_TAG_FLOAT64 } + +static inline JSValue __JS_NewFloat64(JSContext *ctx, double d) +{ + JSValue v; + v.tag = JS_TAG_FLOAT64; + v.u.float64 = d; + return v; +} + +static inline JS_BOOL JS_VALUE_IS_NAN(JSValue v) +{ + union { + double d; + uint64_t u64; + } u; + if (v.tag != JS_TAG_FLOAT64) + return 0; + u.d = v.u.float64; + return (u.u64 & 0x7fffffffffffffff) > 0x7ff0000000000000; +} + +#endif /* !JS_NAN_BOXING */ + +#define JS_VALUE_IS_BOTH_INT(v1, v2) ((JS_VALUE_GET_TAG(v1) | JS_VALUE_GET_TAG(v2)) == 0) +#define JS_VALUE_IS_BOTH_FLOAT(v1, v2) (JS_TAG_IS_FLOAT64(JS_VALUE_GET_TAG(v1)) && JS_TAG_IS_FLOAT64(JS_VALUE_GET_TAG(v2))) + +#define JS_VALUE_GET_OBJ(v) ((JSObject *)JS_VALUE_GET_PTR(v)) +#define JS_VALUE_GET_STRING(v) ((JSString *)JS_VALUE_GET_PTR(v)) +#define JS_VALUE_HAS_REF_COUNT(v) ((unsigned)JS_VALUE_GET_TAG(v) >= (unsigned)JS_TAG_FIRST) + +/* special values */ +#define JS_NULL JS_MKVAL(JS_TAG_NULL, 0) +#define JS_UNDEFINED JS_MKVAL(JS_TAG_UNDEFINED, 0) +#define JS_FALSE JS_MKVAL(JS_TAG_BOOL, 0) +#define JS_TRUE JS_MKVAL(JS_TAG_BOOL, 1) +#define JS_EXCEPTION JS_MKVAL(JS_TAG_EXCEPTION, 0) +#define JS_UNINITIALIZED JS_MKVAL(JS_TAG_UNINITIALIZED, 0) + +/* flags for object properties */ +#define JS_PROP_CONFIGURABLE (1 << 0) +#define JS_PROP_WRITABLE (1 << 1) +#define JS_PROP_ENUMERABLE (1 << 2) +#define JS_PROP_C_W_E (JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE | JS_PROP_ENUMERABLE) +#define JS_PROP_LENGTH (1 << 3) /* used internally in Arrays */ +#define JS_PROP_TMASK (3 << 4) /* mask for NORMAL, GETSET, VARREF, AUTOINIT */ +#define JS_PROP_NORMAL (0 << 4) +#define JS_PROP_GETSET (1 << 4) +#define JS_PROP_VARREF (2 << 4) /* used internally */ +#define JS_PROP_AUTOINIT (3 << 4) /* used internally */ + +/* flags for JS_DefineProperty */ +#define JS_PROP_HAS_SHIFT 8 +#define JS_PROP_HAS_CONFIGURABLE (1 << 8) +#define JS_PROP_HAS_WRITABLE (1 << 9) +#define JS_PROP_HAS_ENUMERABLE (1 << 10) +#define JS_PROP_HAS_GET (1 << 11) +#define JS_PROP_HAS_SET (1 << 12) +#define JS_PROP_HAS_VALUE (1 << 13) + +/* throw an exception if false would be returned + (JS_DefineProperty/JS_SetProperty) */ +#define JS_PROP_THROW (1 << 14) +/* throw an exception if false would be returned in strict mode + (JS_SetProperty) */ +#define JS_PROP_THROW_STRICT (1 << 15) + +#define JS_PROP_NO_ADD (1 << 16) /* internal use */ +#define JS_PROP_NO_EXOTIC (1 << 17) /* internal use */ + +#define JS_DEFAULT_STACK_SIZE (256 * 1024) + +/* JS_Eval() flags */ +#define JS_EVAL_TYPE_GLOBAL (0 << 0) /* global code (default) */ +#define JS_EVAL_TYPE_MODULE (1 << 0) /* module code */ +#define JS_EVAL_TYPE_DIRECT (2 << 0) /* direct call (internal use) */ +#define JS_EVAL_TYPE_INDIRECT (3 << 0) /* indirect call (internal use) */ +#define JS_EVAL_TYPE_MASK (3 << 0) + +#define JS_EVAL_FLAG_STRICT (1 << 3) /* force 'strict' mode */ +#define JS_EVAL_FLAG_STRIP (1 << 4) /* force 'strip' mode */ +/* compile but do not run. The result is an object with a + JS_TAG_FUNCTION_BYTECODE or JS_TAG_MODULE tag. It can be executed + with JS_EvalFunction(). */ +#define JS_EVAL_FLAG_COMPILE_ONLY (1 << 5) +/* don't include the stack frames before this eval in the Error() backtraces */ +#define JS_EVAL_FLAG_BACKTRACE_BARRIER (1 << 6) + +typedef JSValue JSCFunction(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv); +typedef JSValue JSCFunctionMagic(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic); +typedef JSValue JSCFunctionData(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic, JSValue *func_data); + +typedef struct JSMallocState { + size_t malloc_count; + size_t malloc_size; + size_t malloc_limit; + void *opaque; /* user opaque */ +} JSMallocState; + +typedef struct JSMallocFunctions { + void *(*js_malloc)(JSMallocState *s, size_t size); + void (*js_free)(JSMallocState *s, void *ptr); + void *(*js_realloc)(JSMallocState *s, void *ptr, size_t size); + size_t (*js_malloc_usable_size)(const void *ptr); +} JSMallocFunctions; + +typedef struct JSGCObjectHeader JSGCObjectHeader; + +JSRuntime *JS_NewRuntime(void); +/* info lifetime must exceed that of rt */ +void JS_SetRuntimeInfo(JSRuntime *rt, const char *info); +void JS_SetMemoryLimit(JSRuntime *rt, size_t limit); +void JS_SetGCThreshold(JSRuntime *rt, size_t gc_threshold); +/* use 0 to disable maximum stack size check */ +void JS_SetMaxStackSize(JSRuntime *rt, size_t stack_size); +/* should be called when changing thread to update the stack top value + used to check stack overflow. */ +void JS_UpdateStackTop(JSRuntime *rt); +JSRuntime *JS_NewRuntime2(const JSMallocFunctions *mf, void *opaque); +void JS_FreeRuntime(JSRuntime *rt); +void *JS_GetRuntimeOpaque(JSRuntime *rt); +void JS_SetRuntimeOpaque(JSRuntime *rt, void *opaque); +typedef void JS_MarkFunc(JSRuntime *rt, JSGCObjectHeader *gp); +void JS_MarkValue(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func); +void JS_RunGC(JSRuntime *rt); +JS_BOOL JS_IsLiveObject(JSRuntime *rt, JSValueConst obj); + +JSContext *JS_NewContext(JSRuntime *rt); +void JS_FreeContext(JSContext *s); +JSContext *JS_DupContext(JSContext *ctx); +void *JS_GetContextOpaque(JSContext *ctx); +void JS_SetContextOpaque(JSContext *ctx, void *opaque); +JSRuntime *JS_GetRuntime(JSContext *ctx); +void JS_SetClassProto(JSContext *ctx, JSClassID class_id, JSValue obj); +JSValue JS_GetClassProto(JSContext *ctx, JSClassID class_id); + +/* the following functions are used to select the intrinsic object to + save memory */ +JSContext *JS_NewContextRaw(JSRuntime *rt); +void JS_AddIntrinsicBaseObjects(JSContext *ctx); +void JS_AddIntrinsicDate(JSContext *ctx); +void JS_AddIntrinsicEval(JSContext *ctx); +void JS_AddIntrinsicStringNormalize(JSContext *ctx); +void JS_AddIntrinsicRegExpCompiler(JSContext *ctx); +void JS_AddIntrinsicRegExp(JSContext *ctx); +void JS_AddIntrinsicJSON(JSContext *ctx); +void JS_AddIntrinsicProxy(JSContext *ctx); +void JS_AddIntrinsicMapSet(JSContext *ctx); +void JS_AddIntrinsicTypedArrays(JSContext *ctx); +void JS_AddIntrinsicPromise(JSContext *ctx); +void JS_AddIntrinsicBigInt(JSContext *ctx); +void JS_AddIntrinsicBigFloat(JSContext *ctx); +void JS_AddIntrinsicBigDecimal(JSContext *ctx); +/* enable operator overloading */ +void JS_AddIntrinsicOperators(JSContext *ctx); +/* enable "use math" */ +void JS_EnableBignumExt(JSContext *ctx, JS_BOOL enable); + +JSValue js_string_codePointRange(JSContext *ctx, JSValueConst this_val, + int argc, JSValueConst *argv); + +void *js_malloc_rt(JSRuntime *rt, size_t size); +void js_free_rt(JSRuntime *rt, void *ptr); +void *js_realloc_rt(JSRuntime *rt, void *ptr, size_t size); +size_t js_malloc_usable_size_rt(JSRuntime *rt, const void *ptr); +void *js_mallocz_rt(JSRuntime *rt, size_t size); + +void *js_malloc(JSContext *ctx, size_t size); +void js_free(JSContext *ctx, void *ptr); +void *js_realloc(JSContext *ctx, void *ptr, size_t size); +size_t js_malloc_usable_size(JSContext *ctx, const void *ptr); +void *js_realloc2(JSContext *ctx, void *ptr, size_t size, size_t *pslack); +void *js_mallocz(JSContext *ctx, size_t size); +char *js_strdup(JSContext *ctx, const char *str); +char *js_strndup(JSContext *ctx, const char *s, size_t n); + +typedef struct JSMemoryUsage { + int64_t malloc_size, malloc_limit, memory_used_size; + int64_t malloc_count; + int64_t memory_used_count; + int64_t atom_count, atom_size; + int64_t str_count, str_size; + int64_t obj_count, obj_size; + int64_t prop_count, prop_size; + int64_t shape_count, shape_size; + int64_t js_func_count, js_func_size, js_func_code_size; + int64_t js_func_pc2line_count, js_func_pc2line_size; + int64_t c_func_count, array_count; + int64_t fast_array_count, fast_array_elements; + int64_t binary_object_count, binary_object_size; +} JSMemoryUsage; + +void JS_ComputeMemoryUsage(JSRuntime *rt, JSMemoryUsage *s); +void JS_DumpMemoryUsage(FILE *fp, const JSMemoryUsage *s, JSRuntime *rt); + +/* atom support */ +#define JS_ATOM_NULL 0 + +JSAtom JS_NewAtomLen(JSContext *ctx, const char *str, size_t len); +JSAtom JS_NewAtom(JSContext *ctx, const char *str); +JSAtom JS_NewAtomUInt32(JSContext *ctx, uint32_t n); +JSAtom JS_DupAtom(JSContext *ctx, JSAtom v); +void JS_FreeAtom(JSContext *ctx, JSAtom v); +void JS_FreeAtomRT(JSRuntime *rt, JSAtom v); +JSValue JS_AtomToValue(JSContext *ctx, JSAtom atom); +JSValue JS_AtomToString(JSContext *ctx, JSAtom atom); +const char *JS_AtomToCString(JSContext *ctx, JSAtom atom); +JSAtom JS_ValueToAtom(JSContext *ctx, JSValueConst val); + +/* object class support */ + +typedef struct JSPropertyEnum { + JS_BOOL is_enumerable; + JSAtom atom; +} JSPropertyEnum; + +typedef struct JSPropertyDescriptor { + int flags; + JSValue value; + JSValue getter; + JSValue setter; +} JSPropertyDescriptor; + +typedef struct JSClassExoticMethods { + /* Return -1 if exception (can only happen in case of Proxy object), + FALSE if the property does not exists, TRUE if it exists. If 1 is + returned, the property descriptor 'desc' is filled if != NULL. */ + int (*get_own_property)(JSContext *ctx, JSPropertyDescriptor *desc, + JSValueConst obj, JSAtom prop); + /* '*ptab' should hold the '*plen' property keys. Return 0 if OK, + -1 if exception. The 'is_enumerable' field is ignored. + */ + int (*get_own_property_names)(JSContext *ctx, JSPropertyEnum **ptab, + uint32_t *plen, + JSValueConst obj); + /* return < 0 if exception, or TRUE/FALSE */ + int (*delete_property)(JSContext *ctx, JSValueConst obj, JSAtom prop); + /* return < 0 if exception or TRUE/FALSE */ + int (*define_own_property)(JSContext *ctx, JSValueConst this_obj, + JSAtom prop, JSValueConst val, + JSValueConst getter, JSValueConst setter, + int flags); + /* The following methods can be emulated with the previous ones, + so they are usually not needed */ + /* return < 0 if exception or TRUE/FALSE */ + int (*has_property)(JSContext *ctx, JSValueConst obj, JSAtom atom); + JSValue (*get_property)(JSContext *ctx, JSValueConst obj, JSAtom atom, + JSValueConst receiver); + /* return < 0 if exception or TRUE/FALSE */ + int (*set_property)(JSContext *ctx, JSValueConst obj, JSAtom atom, + JSValueConst value, JSValueConst receiver, int flags); +} JSClassExoticMethods; + +typedef void JSClassFinalizer(JSRuntime *rt, JSValue val); +typedef void JSClassGCMark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func); +#define JS_CALL_FLAG_CONSTRUCTOR (1 << 0) +typedef JSValue JSClassCall(JSContext *ctx, JSValueConst func_obj, + JSValueConst this_val, int argc, JSValueConst *argv, + int flags); + +typedef struct JSClassDef { + const char *class_name; + JSClassFinalizer *finalizer; + JSClassGCMark *gc_mark; + /* if call != NULL, the object is a function. If (flags & + JS_CALL_FLAG_CONSTRUCTOR) != 0, the function is called as a + constructor. In this case, 'this_val' is new.target. A + constructor call only happens if the object constructor bit is + set (see JS_SetConstructorBit()). */ + JSClassCall *call; + /* XXX: suppress this indirection ? It is here only to save memory + because only a few classes need these methods */ + JSClassExoticMethods *exotic; +} JSClassDef; + +JSClassID JS_NewClassID(JSClassID *pclass_id); +int JS_NewClass(JSRuntime *rt, JSClassID class_id, const JSClassDef *class_def); +int JS_IsRegisteredClass(JSRuntime *rt, JSClassID class_id); + +/* value handling */ + +static js_force_inline JSValue JS_NewBool(JSContext *ctx, JS_BOOL val) +{ + return JS_MKVAL(JS_TAG_BOOL, (val != 0)); +} + +static js_force_inline JSValue JS_NewInt32(JSContext *ctx, int32_t val) +{ + return JS_MKVAL(JS_TAG_INT, val); +} + +static js_force_inline JSValue JS_NewCatchOffset(JSContext *ctx, int32_t val) +{ + return JS_MKVAL(JS_TAG_CATCH_OFFSET, val); +} + +static js_force_inline JSValue JS_NewInt64(JSContext *ctx, int64_t val) +{ + JSValue v; + if (val == (int32_t)val) { + v = JS_NewInt32(ctx, val); + } else { + v = __JS_NewFloat64(ctx, val); + } + return v; +} + +static js_force_inline JSValue JS_NewUint32(JSContext *ctx, uint32_t val) +{ + JSValue v; + if (val <= 0x7fffffff) { + v = JS_NewInt32(ctx, val); + } else { + v = __JS_NewFloat64(ctx, val); + } + return v; +} + +JSValue JS_NewBigInt64(JSContext *ctx, int64_t v); +JSValue JS_NewBigUint64(JSContext *ctx, uint64_t v); + +static js_force_inline JSValue JS_NewFloat64(JSContext *ctx, double d) +{ + JSValue v; + int32_t val; + union { + double d; + uint64_t u; + } u, t; + u.d = d; + val = (int32_t)d; + t.d = val; + /* -0 cannot be represented as integer, so we compare the bit + representation */ + if (u.u == t.u) { + v = JS_MKVAL(JS_TAG_INT, val); + } else { + v = __JS_NewFloat64(ctx, d); + } + return v; +} + +static inline JS_BOOL JS_IsNumber(JSValueConst v) +{ + int tag = JS_VALUE_GET_TAG(v); + return tag == JS_TAG_INT || JS_TAG_IS_FLOAT64(tag); +} + +static inline JS_BOOL JS_IsBigInt(JSContext *ctx, JSValueConst v) +{ + int tag = JS_VALUE_GET_TAG(v); + return tag == JS_TAG_BIG_INT; +} + +static inline JS_BOOL JS_IsBigFloat(JSValueConst v) +{ + int tag = JS_VALUE_GET_TAG(v); + return tag == JS_TAG_BIG_FLOAT; +} + +static inline JS_BOOL JS_IsBigDecimal(JSValueConst v) +{ + int tag = JS_VALUE_GET_TAG(v); + return tag == JS_TAG_BIG_DECIMAL; +} + +static inline JS_BOOL JS_IsBool(JSValueConst v) +{ + return JS_VALUE_GET_TAG(v) == JS_TAG_BOOL; +} + +static inline JS_BOOL JS_IsNull(JSValueConst v) +{ + return JS_VALUE_GET_TAG(v) == JS_TAG_NULL; +} + +static inline JS_BOOL JS_IsUndefined(JSValueConst v) +{ + return JS_VALUE_GET_TAG(v) == JS_TAG_UNDEFINED; +} + +static inline JS_BOOL JS_IsException(JSValueConst v) +{ + return js_unlikely(JS_VALUE_GET_TAG(v) == JS_TAG_EXCEPTION); +} + +static inline JS_BOOL JS_IsUninitialized(JSValueConst v) +{ + return js_unlikely(JS_VALUE_GET_TAG(v) == JS_TAG_UNINITIALIZED); +} + +static inline JS_BOOL JS_IsString(JSValueConst v) +{ + return JS_VALUE_GET_TAG(v) == JS_TAG_STRING; +} + +static inline JS_BOOL JS_IsSymbol(JSValueConst v) +{ + return JS_VALUE_GET_TAG(v) == JS_TAG_SYMBOL; +} + +static inline JS_BOOL JS_IsObject(JSValueConst v) +{ + return JS_VALUE_GET_TAG(v) == JS_TAG_OBJECT; +} + +JSValue JS_Throw(JSContext *ctx, JSValue obj); +JSValue JS_GetException(JSContext *ctx); +JS_BOOL JS_IsError(JSContext *ctx, JSValueConst val); +void JS_ResetUncatchableError(JSContext *ctx); +JSValue JS_NewError(JSContext *ctx); +JSValue __js_printf_like(2, 3) JS_ThrowSyntaxError(JSContext *ctx, const char *fmt, ...); +JSValue __js_printf_like(2, 3) JS_ThrowTypeError(JSContext *ctx, const char *fmt, ...); +JSValue __js_printf_like(2, 3) JS_ThrowReferenceError(JSContext *ctx, const char *fmt, ...); +JSValue __js_printf_like(2, 3) JS_ThrowRangeError(JSContext *ctx, const char *fmt, ...); +JSValue __js_printf_like(2, 3) JS_ThrowInternalError(JSContext *ctx, const char *fmt, ...); +JSValue JS_ThrowOutOfMemory(JSContext *ctx); + +void __JS_FreeValue(JSContext *ctx, JSValue v); +static inline void JS_FreeValue(JSContext *ctx, JSValue v) +{ + if (JS_VALUE_HAS_REF_COUNT(v)) { + JSRefCountHeader *p = (JSRefCountHeader *)JS_VALUE_GET_PTR(v); + if (--p->ref_count <= 0) { + __JS_FreeValue(ctx, v); + } + } +} +void __JS_FreeValueRT(JSRuntime *rt, JSValue v); +static inline void JS_FreeValueRT(JSRuntime *rt, JSValue v) +{ + if (JS_VALUE_HAS_REF_COUNT(v)) { + JSRefCountHeader *p = (JSRefCountHeader *)JS_VALUE_GET_PTR(v); + if (--p->ref_count <= 0) { + __JS_FreeValueRT(rt, v); + } + } +} + +static inline JSValue JS_DupValue(JSContext *ctx, JSValueConst v) +{ + if (JS_VALUE_HAS_REF_COUNT(v)) { + JSRefCountHeader *p = (JSRefCountHeader *)JS_VALUE_GET_PTR(v); + p->ref_count++; + } + return (JSValue)v; +} + +static inline JSValue JS_DupValueRT(JSRuntime *rt, JSValueConst v) +{ + if (JS_VALUE_HAS_REF_COUNT(v)) { + JSRefCountHeader *p = (JSRefCountHeader *)JS_VALUE_GET_PTR(v); + p->ref_count++; + } + return (JSValue)v; +} + +int JS_ToBool(JSContext *ctx, JSValueConst val); /* return -1 for JS_EXCEPTION */ +int JS_ToInt32(JSContext *ctx, int32_t *pres, JSValueConst val); +static inline int JS_ToUint32(JSContext *ctx, uint32_t *pres, JSValueConst val) +{ + return JS_ToInt32(ctx, (int32_t*)pres, val); +} +int JS_ToInt64(JSContext *ctx, int64_t *pres, JSValueConst val); +int JS_ToIndex(JSContext *ctx, uint64_t *plen, JSValueConst val); +int JS_ToFloat64(JSContext *ctx, double *pres, JSValueConst val); +/* return an exception if 'val' is a Number */ +int JS_ToBigInt64(JSContext *ctx, int64_t *pres, JSValueConst val); +/* same as JS_ToInt64() but allow BigInt */ +int JS_ToInt64Ext(JSContext *ctx, int64_t *pres, JSValueConst val); + +JSValue JS_NewStringLen(JSContext *ctx, const char *str1, size_t len1); +JSValue JS_NewString(JSContext *ctx, const char *str); +JSValue JS_NewAtomString(JSContext *ctx, const char *str); +JSValue JS_ToString(JSContext *ctx, JSValueConst val); +JSValue JS_ToPropertyKey(JSContext *ctx, JSValueConst val); +const char *JS_ToCStringLen2(JSContext *ctx, size_t *plen, JSValueConst val1, JS_BOOL cesu8); +static inline const char *JS_ToCStringLen(JSContext *ctx, size_t *plen, JSValueConst val1) +{ + return JS_ToCStringLen2(ctx, plen, val1, 0); +} +static inline const char *JS_ToCString(JSContext *ctx, JSValueConst val1) +{ + return JS_ToCStringLen2(ctx, NULL, val1, 0); +} +void JS_FreeCString(JSContext *ctx, const char *ptr); + +JSValue JS_NewObjectProtoClass(JSContext *ctx, JSValueConst proto, JSClassID class_id); +JSValue JS_NewObjectClass(JSContext *ctx, int class_id); +JSValue JS_NewObjectProto(JSContext *ctx, JSValueConst proto); +JSValue JS_NewObject(JSContext *ctx); + +JS_BOOL JS_IsFunction(JSContext* ctx, JSValueConst val); +JS_BOOL JS_IsConstructor(JSContext* ctx, JSValueConst val); +JS_BOOL JS_SetConstructorBit(JSContext *ctx, JSValueConst func_obj, JS_BOOL val); + +JSValue JS_NewArray(JSContext *ctx); +int JS_IsArray(JSContext *ctx, JSValueConst val); + +JSValue JS_GetPropertyInternal(JSContext *ctx, JSValueConst obj, + JSAtom prop, JSValueConst receiver, + JS_BOOL throw_ref_error); +static js_force_inline JSValue JS_GetProperty(JSContext *ctx, JSValueConst this_obj, + JSAtom prop) +{ + return JS_GetPropertyInternal(ctx, this_obj, prop, this_obj, 0); +} +JSValue JS_GetPropertyStr(JSContext *ctx, JSValueConst this_obj, + const char *prop); +JSValue JS_GetPropertyUint32(JSContext *ctx, JSValueConst this_obj, + uint32_t idx); + +int JS_SetPropertyInternal(JSContext *ctx, JSValueConst this_obj, + JSAtom prop, JSValue val, + int flags); +static inline int JS_SetProperty(JSContext *ctx, JSValueConst this_obj, + JSAtom prop, JSValue val) +{ + return JS_SetPropertyInternal(ctx, this_obj, prop, val, JS_PROP_THROW); +} +int JS_SetPropertyUint32(JSContext *ctx, JSValueConst this_obj, + uint32_t idx, JSValue val); +int JS_SetPropertyInt64(JSContext *ctx, JSValueConst this_obj, + int64_t idx, JSValue val); +int JS_SetPropertyStr(JSContext *ctx, JSValueConst this_obj, + const char *prop, JSValue val); +int JS_HasProperty(JSContext *ctx, JSValueConst this_obj, JSAtom prop); +int JS_IsExtensible(JSContext *ctx, JSValueConst obj); +int JS_PreventExtensions(JSContext *ctx, JSValueConst obj); +int JS_DeleteProperty(JSContext *ctx, JSValueConst obj, JSAtom prop, int flags); +int JS_SetPrototype(JSContext *ctx, JSValueConst obj, JSValueConst proto_val); +JSValue JS_GetPrototype(JSContext *ctx, JSValueConst val); + +#define JS_GPN_STRING_MASK (1 << 0) +#define JS_GPN_SYMBOL_MASK (1 << 1) +#define JS_GPN_PRIVATE_MASK (1 << 2) +/* only include the enumerable properties */ +#define JS_GPN_ENUM_ONLY (1 << 4) +/* set theJSPropertyEnum.is_enumerable field */ +#define JS_GPN_SET_ENUM (1 << 5) + +int JS_GetOwnPropertyNames(JSContext *ctx, JSPropertyEnum **ptab, + uint32_t *plen, JSValueConst obj, int flags); +int JS_GetOwnProperty(JSContext *ctx, JSPropertyDescriptor *desc, + JSValueConst obj, JSAtom prop); + +JSValue JS_Call(JSContext *ctx, JSValueConst func_obj, JSValueConst this_obj, + int argc, JSValueConst *argv); +JSValue JS_Invoke(JSContext *ctx, JSValueConst this_val, JSAtom atom, + int argc, JSValueConst *argv); +JSValue JS_CallConstructor(JSContext *ctx, JSValueConst func_obj, + int argc, JSValueConst *argv); +JSValue JS_CallConstructor2(JSContext *ctx, JSValueConst func_obj, + JSValueConst new_target, + int argc, JSValueConst *argv); +JS_BOOL JS_DetectModule(const char *input, size_t input_len); +/* 'input' must be zero terminated i.e. input[input_len] = '\0'. */ +JSValue JS_Eval(JSContext *ctx, const char *input, size_t input_len, + const char *filename, int eval_flags); +/* same as JS_Eval() but with an explicit 'this_obj' parameter */ +JSValue JS_EvalThis(JSContext *ctx, JSValueConst this_obj, + const char *input, size_t input_len, + const char *filename, int eval_flags); +JSValue JS_GetGlobalObject(JSContext *ctx); +int JS_IsInstanceOf(JSContext *ctx, JSValueConst val, JSValueConst obj); +int JS_DefineProperty(JSContext *ctx, JSValueConst this_obj, + JSAtom prop, JSValueConst val, + JSValueConst getter, JSValueConst setter, int flags); +int JS_DefinePropertyValue(JSContext *ctx, JSValueConst this_obj, + JSAtom prop, JSValue val, int flags); +int JS_DefinePropertyValueUint32(JSContext *ctx, JSValueConst this_obj, + uint32_t idx, JSValue val, int flags); +int JS_DefinePropertyValueStr(JSContext *ctx, JSValueConst this_obj, + const char *prop, JSValue val, int flags); +int JS_DefinePropertyGetSet(JSContext *ctx, JSValueConst this_obj, + JSAtom prop, JSValue getter, JSValue setter, + int flags); +void JS_SetOpaque(JSValue obj, void *opaque); +void *JS_GetOpaque(JSValueConst obj, JSClassID class_id); +void *JS_GetOpaque2(JSContext *ctx, JSValueConst obj, JSClassID class_id); + +/* 'buf' must be zero terminated i.e. buf[buf_len] = '\0'. */ +JSValue JS_ParseJSON(JSContext *ctx, const char *buf, size_t buf_len, + const char *filename); +#define JS_PARSE_JSON_EXT (1 << 0) /* allow extended JSON */ +JSValue JS_ParseJSON2(JSContext *ctx, const char *buf, size_t buf_len, + const char *filename, int flags); +JSValue JS_JSONStringify(JSContext *ctx, JSValueConst obj, + JSValueConst replacer, JSValueConst space0); + +typedef void JSFreeArrayBufferDataFunc(JSRuntime *rt, void *opaque, void *ptr); +JSValue JS_NewArrayBuffer(JSContext *ctx, uint8_t *buf, size_t len, + JSFreeArrayBufferDataFunc *free_func, void *opaque, + JS_BOOL is_shared); +JSValue JS_NewArrayBufferCopy(JSContext *ctx, const uint8_t *buf, size_t len); +void JS_DetachArrayBuffer(JSContext *ctx, JSValueConst obj); +uint8_t *JS_GetArrayBuffer(JSContext *ctx, size_t *psize, JSValueConst obj); +JSValue JS_GetTypedArrayBuffer(JSContext *ctx, JSValueConst obj, + size_t *pbyte_offset, + size_t *pbyte_length, + size_t *pbytes_per_element); +typedef struct { + void *(*sab_alloc)(void *opaque, size_t size); + void (*sab_free)(void *opaque, void *ptr); + void (*sab_dup)(void *opaque, void *ptr); + void *sab_opaque; +} JSSharedArrayBufferFunctions; +void JS_SetSharedArrayBufferFunctions(JSRuntime *rt, + const JSSharedArrayBufferFunctions *sf); + +JSValue JS_NewPromiseCapability(JSContext *ctx, JSValue *resolving_funcs); + +/* is_handled = TRUE means that the rejection is handled */ +typedef void JSHostPromiseRejectionTracker(JSContext *ctx, JSValueConst promise, + JSValueConst reason, + JS_BOOL is_handled, void *opaque); +void JS_SetHostPromiseRejectionTracker(JSRuntime *rt, JSHostPromiseRejectionTracker *cb, void *opaque); + +/* return != 0 if the JS code needs to be interrupted */ +typedef int JSInterruptHandler(JSRuntime *rt, void *opaque); +void JS_SetInterruptHandler(JSRuntime *rt, JSInterruptHandler *cb, void *opaque); +/* if can_block is TRUE, Atomics.wait() can be used */ +void JS_SetCanBlock(JSRuntime *rt, JS_BOOL can_block); +/* set the [IsHTMLDDA] internal slot */ +void JS_SetIsHTMLDDA(JSContext *ctx, JSValueConst obj); + +typedef struct JSModuleDef JSModuleDef; + +/* return the module specifier (allocated with js_malloc()) or NULL if + exception */ +typedef char *JSModuleNormalizeFunc(JSContext *ctx, + const char *module_base_name, + const char *module_name, void *opaque); +typedef JSModuleDef *JSModuleLoaderFunc(JSContext *ctx, + const char *module_name, void *opaque); + +/* module_normalize = NULL is allowed and invokes the default module + filename normalizer */ +void JS_SetModuleLoaderFunc(JSRuntime *rt, + JSModuleNormalizeFunc *module_normalize, + JSModuleLoaderFunc *module_loader, void *opaque); +/* return the import.meta object of a module */ +JSValue JS_GetImportMeta(JSContext *ctx, JSModuleDef *m); +JSAtom JS_GetModuleName(JSContext *ctx, JSModuleDef *m); + +/* JS Job support */ + +typedef JSValue JSJobFunc(JSContext *ctx, int argc, JSValueConst *argv); +int JS_EnqueueJob(JSContext *ctx, JSJobFunc *job_func, int argc, JSValueConst *argv); + +JS_BOOL JS_IsJobPending(JSRuntime *rt); +int JS_ExecutePendingJob(JSRuntime *rt, JSContext **pctx); + +/* Object Writer/Reader (currently only used to handle precompiled code) */ +#define JS_WRITE_OBJ_BYTECODE (1 << 0) /* allow function/module */ +#define JS_WRITE_OBJ_BSWAP (1 << 1) /* byte swapped output */ +#define JS_WRITE_OBJ_SAB (1 << 2) /* allow SharedArrayBuffer */ +#define JS_WRITE_OBJ_REFERENCE (1 << 3) /* allow object references to + encode arbitrary object + graph */ +uint8_t *JS_WriteObject(JSContext *ctx, size_t *psize, JSValueConst obj, + int flags); +uint8_t *JS_WriteObject2(JSContext *ctx, size_t *psize, JSValueConst obj, + int flags, uint8_t ***psab_tab, size_t *psab_tab_len); + +#define JS_READ_OBJ_BYTECODE (1 << 0) /* allow function/module */ +#define JS_READ_OBJ_ROM_DATA (1 << 1) /* avoid duplicating 'buf' data */ +#define JS_READ_OBJ_SAB (1 << 2) /* allow SharedArrayBuffer */ +#define JS_READ_OBJ_REFERENCE (1 << 3) /* allow object references */ +JSValue JS_ReadObject(JSContext *ctx, const uint8_t *buf, size_t buf_len, + int flags); +/* instantiate and evaluate a bytecode function. Only used when + reading a script or module with JS_ReadObject() */ +JSValue JS_EvalFunction(JSContext *ctx, JSValue fun_obj); +/* load the dependencies of the module 'obj'. Useful when JS_ReadObject() + returns a module. */ +int JS_ResolveModule(JSContext *ctx, JSValueConst obj); + +/* only exported for os.Worker() */ +JSAtom JS_GetScriptOrModuleName(JSContext *ctx, int n_stack_levels); +/* only exported for os.Worker() */ +JSModuleDef *JS_RunModule(JSContext *ctx, const char *basename, + const char *filename); + +/* C function definition */ +typedef enum JSCFunctionEnum { /* XXX: should rename for namespace isolation */ + JS_CFUNC_generic, + JS_CFUNC_generic_magic, + JS_CFUNC_constructor, + JS_CFUNC_constructor_magic, + JS_CFUNC_constructor_or_func, + JS_CFUNC_constructor_or_func_magic, + JS_CFUNC_f_f, + JS_CFUNC_f_f_f, + JS_CFUNC_getter, + JS_CFUNC_setter, + JS_CFUNC_getter_magic, + JS_CFUNC_setter_magic, + JS_CFUNC_iterator_next, +} JSCFunctionEnum; + +typedef union JSCFunctionType { + JSCFunction *generic; + JSValue (*generic_magic)(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic); + JSCFunction *constructor; + JSValue (*constructor_magic)(JSContext *ctx, JSValueConst new_target, int argc, JSValueConst *argv, int magic); + JSCFunction *constructor_or_func; + double (*f_f)(double); + double (*f_f_f)(double, double); + JSValue (*getter)(JSContext *ctx, JSValueConst this_val); + JSValue (*setter)(JSContext *ctx, JSValueConst this_val, JSValueConst val); + JSValue (*getter_magic)(JSContext *ctx, JSValueConst this_val, int magic); + JSValue (*setter_magic)(JSContext *ctx, JSValueConst this_val, JSValueConst val, int magic); + JSValue (*iterator_next)(JSContext *ctx, JSValueConst this_val, + int argc, JSValueConst *argv, int *pdone, int magic); +} JSCFunctionType; + +JSValue JS_NewCFunction2(JSContext *ctx, JSCFunction *func, + const char *name, + int length, JSCFunctionEnum cproto, int magic); +JSValue JS_NewCFunctionData(JSContext *ctx, JSCFunctionData *func, + int length, int magic, int data_len, + JSValueConst *data); + +static inline JSValue JS_NewCFunction(JSContext *ctx, JSCFunction *func, const char *name, + int length) +{ + return JS_NewCFunction2(ctx, func, name, length, JS_CFUNC_generic, 0); +} + +static inline JSValue JS_NewCFunctionMagic(JSContext *ctx, JSCFunctionMagic *func, + const char *name, + int length, JSCFunctionEnum cproto, int magic) +{ + return JS_NewCFunction2(ctx, (JSCFunction *)func, name, length, cproto, magic); +} +void JS_SetConstructor(JSContext *ctx, JSValueConst func_obj, + JSValueConst proto); + +/* C property definition */ + +typedef struct JSCFunctionListEntry { + const char *name; + uint8_t prop_flags; + uint8_t def_type; + int16_t magic; + union { + struct { + uint8_t length; /* XXX: should move outside union */ + uint8_t cproto; /* XXX: should move outside union */ + JSCFunctionType cfunc; + } func; + struct { + JSCFunctionType get; + JSCFunctionType set; + } getset; + struct { + const char *name; + int base; + } alias; + struct { + const struct JSCFunctionListEntry *tab; + int len; + } prop_list; + const char *str; + int32_t i32; + int64_t i64; + double f64; + } u; +} JSCFunctionListEntry; + +#define JS_DEF_CFUNC 0 +#define JS_DEF_CGETSET 1 +#define JS_DEF_CGETSET_MAGIC 2 +#define JS_DEF_PROP_STRING 3 +#define JS_DEF_PROP_INT32 4 +#define JS_DEF_PROP_INT64 5 +#define JS_DEF_PROP_DOUBLE 6 +#define JS_DEF_PROP_UNDEFINED 7 +#define JS_DEF_OBJECT 8 +#define JS_DEF_ALIAS 9 + +/* Note: c++ does not like nested designators */ +#define JS_CFUNC_DEF(name, length, func1) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_CFUNC, 0, .u = { .func = { length, JS_CFUNC_generic, { .generic = func1 } } } } +#define JS_CFUNC_MAGIC_DEF(name, length, func1, magic) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_CFUNC, magic, .u = { .func = { length, JS_CFUNC_generic_magic, { .generic_magic = func1 } } } } +#define JS_CFUNC_SPECIAL_DEF(name, length, cproto, func1) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_CFUNC, 0, .u = { .func = { length, JS_CFUNC_ ## cproto, { .cproto = func1 } } } } +#define JS_ITERATOR_NEXT_DEF(name, length, func1, magic) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_CFUNC, magic, .u = { .func = { length, JS_CFUNC_iterator_next, { .iterator_next = func1 } } } } +#define JS_CGETSET_DEF(name, fgetter, fsetter) { name, JS_PROP_CONFIGURABLE, JS_DEF_CGETSET, 0, .u = { .getset = { .get = { .getter = fgetter }, .set = { .setter = fsetter } } } } +#define JS_CGETSET_MAGIC_DEF(name, fgetter, fsetter, magic) { name, JS_PROP_CONFIGURABLE, JS_DEF_CGETSET_MAGIC, magic, .u = { .getset = { .get = { .getter_magic = fgetter }, .set = { .setter_magic = fsetter } } } } +#define JS_PROP_STRING_DEF(name, cstr, prop_flags) { name, prop_flags, JS_DEF_PROP_STRING, 0, .u = { .str = cstr } } +#define JS_PROP_INT32_DEF(name, val, prop_flags) { name, prop_flags, JS_DEF_PROP_INT32, 0, .u = { .i32 = val } } +#define JS_PROP_INT64_DEF(name, val, prop_flags) { name, prop_flags, JS_DEF_PROP_INT64, 0, .u = { .i64 = val } } +#define JS_PROP_DOUBLE_DEF(name, val, prop_flags) { name, prop_flags, JS_DEF_PROP_DOUBLE, 0, .u = { .f64 = val } } +#define JS_PROP_UNDEFINED_DEF(name, prop_flags) { name, prop_flags, JS_DEF_PROP_UNDEFINED, 0, .u = { .i32 = 0 } } +#define JS_OBJECT_DEF(name, tab, len, prop_flags) { name, prop_flags, JS_DEF_OBJECT, 0, .u = { .prop_list = { tab, len } } } +#define JS_ALIAS_DEF(name, from) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_ALIAS, 0, .u = { .alias = { from, -1 } } } +#define JS_ALIAS_BASE_DEF(name, from, base) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_ALIAS, 0, .u = { .alias = { from, base } } } + +void JS_SetPropertyFunctionList(JSContext *ctx, JSValueConst obj, + const JSCFunctionListEntry *tab, + int len); + +/* C module definition */ + +typedef int JSModuleInitFunc(JSContext *ctx, JSModuleDef *m); + +JSModuleDef *JS_NewCModule(JSContext *ctx, const char *name_str, + JSModuleInitFunc *func); +/* can only be called before the module is instantiated */ +int JS_AddModuleExport(JSContext *ctx, JSModuleDef *m, const char *name_str); +int JS_AddModuleExportList(JSContext *ctx, JSModuleDef *m, + const JSCFunctionListEntry *tab, int len); +/* can only be called after the module is instantiated */ +int JS_SetModuleExport(JSContext *ctx, JSModuleDef *m, const char *export_name, + JSValue val); +int JS_SetModuleExportList(JSContext *ctx, JSModuleDef *m, + const JSCFunctionListEntry *tab, int len); + +#undef js_unlikely +#undef js_force_inline + +#ifdef __cplusplus +} /* extern "C" { */ +#endif + +#endif /* QUICKJS_H */ diff --git a/deps/libs/darwin_amd64/_fixed_libquickjs.a b/deps/libs/darwin_amd64/_fixed_libquickjs.a new file mode 100644 index 0000000..5998cbd Binary files /dev/null and b/deps/libs/darwin_amd64/_fixed_libquickjs.a differ diff --git a/deps/libs/darwin_amd64/libquickjs.a b/deps/libs/darwin_amd64/libquickjs.a new file mode 100644 index 0000000..c65ec84 Binary files /dev/null and b/deps/libs/darwin_amd64/libquickjs.a differ diff --git a/deps/libs/darwin_arm64/libquickjs.a b/deps/libs/darwin_arm64/libquickjs.a new file mode 100644 index 0000000..91b992a Binary files /dev/null and b/deps/libs/darwin_arm64/libquickjs.a differ diff --git a/deps/libs/linux_amd64/libquickjs.a b/deps/libs/linux_amd64/libquickjs.a new file mode 100644 index 0000000..8bf7a87 Binary files /dev/null and b/deps/libs/linux_amd64/libquickjs.a differ diff --git a/deps/libs/linux_arm64/libquickjs.a b/deps/libs/linux_arm64/libquickjs.a new file mode 100644 index 0000000..9d9fe43 Binary files /dev/null and b/deps/libs/linux_arm64/libquickjs.a differ diff --git a/deps/libs/windows_386/libquickjs.a b/deps/libs/windows_386/libquickjs.a new file mode 100644 index 0000000..4334db1 Binary files /dev/null and b/deps/libs/windows_386/libquickjs.a differ diff --git a/deps/libs/windows_amd64/libquickjs.a b/deps/libs/windows_amd64/libquickjs.a new file mode 100644 index 0000000..4211cfc Binary files /dev/null and b/deps/libs/windows_amd64/libquickjs.a differ diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..93972ac --- /dev/null +++ b/go.mod @@ -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 +) diff --git a/loop.go b/loop.go new file mode 100644 index 0000000..aaacf8f --- /dev/null +++ b/loop.go @@ -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 +} diff --git a/quickjs.go b/quickjs.go new file mode 100644 index 0000000..cb0d294 --- /dev/null +++ b/quickjs.go @@ -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" diff --git a/quickjs_test.go b/quickjs_test.go new file mode 100644 index 0000000..27c69bb --- /dev/null +++ b/quickjs_test.go @@ -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()) +} diff --git a/runtime.go b/runtime.go new file mode 100644 index 0000000..90ddb86 --- /dev/null +++ b/runtime.go @@ -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 +} diff --git a/value.go b/value.go new file mode 100644 index 0000000..818dc39 --- /dev/null +++ b/value.go @@ -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 }