From e77cfb67b8728c08208ca6e35341c601760b3730 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sa=C3=BAl=20Ibarra=20Corretg=C3=A9?= Date: Mon, 2 Dec 2024 10:59:01 +0100 Subject: [PATCH] Add "compile_module" and "eval_module" flags to std.evalScript This is preparation for standalone binaries support, we need the ability to compile source as a module and then evaluate it. --- quickjs-libc.c | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/quickjs-libc.c b/quickjs-libc.c index 1f21b464..1b138b51 100644 --- a/quickjs-libc.c +++ b/quickjs-libc.c @@ -865,7 +865,9 @@ static JSValue js_evalScript(JSContext *ctx, JSValue this_val, JSValue options_obj; BOOL backtrace_barrier = FALSE; BOOL eval_function = FALSE; + BOOL eval_module = FALSE; BOOL compile_only = FALSE; + BOOL compile_module = FALSE; BOOL is_async = FALSE; int flags; @@ -877,14 +879,33 @@ static JSValue js_evalScript(JSContext *ctx, JSValue this_val, if (get_bool_option(ctx, &eval_function, options_obj, "eval_function")) return JS_EXCEPTION; + if (get_bool_option(ctx, &eval_module, options_obj, + "eval_module")) + return JS_EXCEPTION; if (get_bool_option(ctx, &compile_only, options_obj, "compile_only")) return JS_EXCEPTION; + if (get_bool_option(ctx, &compile_module, options_obj, + "compile_module")) + return JS_EXCEPTION; if (get_bool_option(ctx, &is_async, options_obj, "async")) return JS_EXCEPTION; } + if (eval_module) { + obj = argv[0]; + if (JS_VALUE_GET_TAG(obj) != JS_TAG_MODULE) + return JS_ThrowTypeError(ctx, "not a module"); + + if (JS_ResolveModule(ctx, obj) < 0) + return JS_EXCEPTION; + + js_module_set_import_meta(ctx, obj, FALSE, FALSE); + + return JS_EvalFunction(ctx, obj); + } + if (!eval_function) { str = JS_ToCStringLen(ctx, &len, argv[0]); if (!str) @@ -894,7 +915,7 @@ static JSValue js_evalScript(JSContext *ctx, JSValue this_val, /* install the interrupt handler */ JS_SetInterruptHandler(JS_GetRuntime(ctx), interrupt_handler, NULL); } - flags = JS_EVAL_TYPE_GLOBAL; + flags = compile_module ? JS_EVAL_TYPE_MODULE : JS_EVAL_TYPE_GLOBAL; if (backtrace_barrier) flags |= JS_EVAL_FLAG_BACKTRACE_BARRIER; if (compile_only)