Skip to content

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

Merged
saghul merged 1 commit intomasterfrom
more-eval-flags
Dec 2, 2024
Merged

Add "compile_module" and "eval_module" flags to std.evalScript#732
saghul merged 1 commit intomasterfrom
more-eval-flags

Conversation

@saghul
Copy link
Copy Markdown
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
Copy Markdown
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
@saghul saghul deleted the more-eval-flags branch December 2, 2024 20:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants