Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Unbound script #263

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/api.zig
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ const Engine = @import("private_api.zig").Engine;
pub const JSValue = Engine.JSValue;
pub const JSObject = Engine.JSObject;
pub const JSObjectID = Engine.JSObjectID;
pub const JSScript = Engine.JSScript;

pub const Callback = Engine.Callback;
pub const CallbackSync = Engine.CallbackSync;
Expand Down
44 changes: 44 additions & 0 deletions src/engines/v8/v8.zig
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,33 @@ pub const Env = struct {
}
}

// compile a JS script
pub fn compile(
self: Env,
script: []const u8,
name: []const u8,
) anyerror!JSScript {

// compile
const scr_name = v8.String.initUtf8(self.isolate, name);
const script_source = v8.String.initUtf8(self.isolate, script);

const origin = v8.ScriptOrigin.initDefault(self.isolate, scr_name.toValue());

var script_comp_source: v8.ScriptCompilerSource = undefined;
script_comp_source.init(script_source, origin, null);
defer script_comp_source.deinit();

const uboundedscript = v8.ScriptCompiler.CompileUnboundScript(
self.isolate,
&script_comp_source,
.kNoCompileOptions,
.kNoCacheNoReason,
) catch return error.JSCompile;

return .{ .inner = uboundedscript };
}

// compile and run a JS script
// It doesn't wait for callbacks execution
pub fn exec(
Expand Down Expand Up @@ -431,6 +458,23 @@ pub const JSObject = struct {
}
};

pub const JSScript = struct {
inner: v8.UnboundScript,

// Bind the unbounded script to the current context and run it.
pub fn run(self: JSScript, env: Env) anyerror!JSValue {
if (env.js_ctx == null) {
return error.EnvNotStarted;
}

const scr = self.inner.bindToCurrentContext() catch return error.JSExec;

// run
const value = scr.run(env.js_ctx.?) catch return error.JSExec;
return .{ .value = value };
}
};

pub const JSValue = struct {
value: v8.Value,

Expand Down
2 changes: 1 addition & 1 deletion vendor/zig-v8
Loading