Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Add "compile_module" and "eval_module" flags to std.evalScript #732

Merged
merged 1 commit into from
Dec 2, 2024

Conversation

saghul
Copy link
Contributor

@saghul saghul commented Dec 2, 2024

This is preparation for standalone binaries support, we need the ability to compile source as a module and then evaluate it.

This is preparation for standalone binaries support, we need the ability
to compile source as a module and then evaluate it.
@saghul saghul requested a review from bnoordhuis December 2, 2024 10:01
@saghul
Copy link
Contributor Author

saghul commented Dec 2, 2024

Sample usage:

import * as std from "qjs:std";
import * as bjson from "qjs:bjson";

// See quickjs.h
const JS_WRITE_OBJ_BYTECODE = 1 << 0;
const JS_WRITE_OBJ_REFERENCE = 1 << 3;
const JS_WRITE_OBJ_STRIP_SOURCE = 1 << 4;
const JS_READ_OBJ_BYTECODE = 1 << 0;
const JS_READ_OBJ_REFERENCE = 1 << 3;

function compileFile(file) {
  const data = std.loadFile(file);
  const bytecode = std.evalScript(data, {
    compile_only: true,
    compile_module: true
  });
  return bjson.write(bytecode, JS_WRITE_OBJ_BYTECODE | JS_WRITE_OBJ_REFERENCE | JS_WRITE_OBJ_STRIP_SOURCE);
}

function evalBytecode(buffer, byteOffset, length) {
  const bytecode = bjson.read(buffer, byteOffset, length, JS_READ_OBJ_BYTECODE | JS_READ_OBJ_REFERENCE);
  return std.evalScript(bytecode, {
    eval_module: true
  });
}

const buf = compileFile('./t.js');
evalBytecode(buf, 0, buf.byteLength);

@saghul saghul merged commit e77cfb6 into master Dec 2, 2024
59 checks passed
@saghul saghul deleted the more-eval-flags branch December 2, 2024 20:18
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants