Skip to content

Commit

Permalink
Feature/module compile (#344)
Browse files Browse the repository at this point in the history
* set EvalFlag function receive boolean argument

* add CompileModule and fixed LoadModuleBytecode
  • Loading branch information
buke authored Aug 20, 2024
1 parent a8f2ecf commit 5b4534e
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 5 deletions.
8 changes: 7 additions & 1 deletion context.go
Original file line number Diff line number Diff line change
Expand Up @@ -394,8 +394,14 @@ func (ctx *Context) LoadModuleFile(filePath string, moduleName string) (Value, e
return ctx.LoadModule(string(b), moduleName)
}

// CompileModule returns a compiled bytecode with given code and module name.
func (ctx *Context) CompileModule(filePath string, moduleName string, opts ...EvalOption) ([]byte, error) {
opts = append(opts, EvalFileName(moduleName))
return ctx.CompileFile(filePath, opts...)
}

// LoadModuleByteCode returns a js value with given bytecode and module name.
func (ctx *Context) LoadModuleBytecode(buf []byte, moduleName string) (Value, error) {
func (ctx *Context) LoadModuleBytecode(buf []byte) (Value, error) {
cbuf := C.CBytes(buf)
cVal := 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))
Expand Down
33 changes: 29 additions & 4 deletions quickjs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -811,11 +811,38 @@ func TestModule(t *testing.T) {

require.EqualValues(t, 89, ctx.Globals().Get("result").Int32())

ctx2 := rt.NewContext()
defer ctx2.Close()
// load module from bytecode
buf, err := ctx.CompileFile("./test/fib_module.js")
buf, err := ctx2.CompileModule("./test/fib_module.js", "fib_foo2")
require.NoError(t, err)

r4, err := ctx2.LoadModuleBytecode(buf)
defer r4.Free()
require.NoError(t, err)

r4, err := ctx.LoadModuleBytecode(buf, "fib_foo")
r5, err := ctx2.Eval(`
import {fib} from 'fib_foo2';
globalThis.result = fib(12);
`)
defer r5.Free()
require.NoError(t, err)

require.EqualValues(t, 144, ctx2.Globals().Get("result").Int32())

}

func TestModule2(t *testing.T) {
// enable module import
rt := quickjs.NewRuntime(quickjs.WithModuleImport(true))
defer rt.Close()
ctx := rt.NewContext()
defer ctx.Close()

// load module from bytecode
buf, err := ctx.CompileModule("./test/fib_module.js", "fib_foo")
require.NoError(t, err)
r4, err := ctx.LoadModuleBytecode(buf)
defer r4.Free()
require.NoError(t, err)

Expand All @@ -825,7 +852,5 @@ func TestModule(t *testing.T) {
`)
defer r5.Free()
require.NoError(t, err)

require.EqualValues(t, 144, ctx.Globals().Get("result").Int32())

}

0 comments on commit 5b4534e

Please sign in to comment.