#include <quickjs.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void compile_to_bytecode(JSContext *ctx, const char *source, const char *filename)
{
// Compile source to bytecode
JSValue obj = JS_Eval(ctx, source, strlen(source), filename,
JS_EVAL_TYPE_GLOBAL | JS_EVAL_FLAG_COMPILE_ONLY);
if (!JS_IsException(obj)) {
size_t bytecode_size;
uint8_t *bytecode = JS_WriteObject(ctx, &bytecode_size, obj,
JS_WRITE_OBJ_BYTECODE);
if (bytecode) {
// Save to file
FILE *f = fopen("output.qjsc", "wb");
fwrite(bytecode, 1, bytecode_size, f);
fclose(f);
printf("Compiled to output.qjsc (%zu bytes)\n", bytecode_size);
js_free(ctx, bytecode);
}
JS_FreeValue(ctx, obj);
} else {
js_std_dump_error(ctx);
}
}
void execute_bytecode(JSContext *ctx, const char *filename)
{
FILE *f = fopen(filename, "rb");
if (!f) {
fprintf(stderr, "Cannot open %s\n", filename);
return;
}
fseek(f, 0, SEEK_END);
size_t size = ftell(f);
fseek(f, 0, SEEK_SET);
uint8_t *buf = malloc(size);
fread(buf, 1, size, f);
fclose(f);
JSValue obj = JS_ReadObject(ctx, buf, size, JS_READ_OBJ_BYTECODE);
free(buf);
if (!JS_IsException(obj)) {
JSValue result = JS_EvalFunction(ctx, obj);
if (JS_IsException(result)) {
js_std_dump_error(ctx);
}
JS_FreeValue(ctx, result);
} else {
js_std_dump_error(ctx);
}
}