From b1b4df39abb41a4ae71733e2d139dc70cc71acd8 Mon Sep 17 00:00:00 2001 From: Nathan Reiner Date: Sat, 17 Oct 2026 10:13:13 +0200 Subject: zilch: implement callable and promise --- src/zilch/Promise.zig | 54 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 src/zilch/Promise.zig (limited to 'src/zilch/Promise.zig') diff --git a/src/zilch/Promise.zig b/src/zilch/Promise.zig new file mode 100644 index 0000000..09654e3 --- /dev/null +++ b/src/zilch/Promise.zig @@ -0,0 +1,54 @@ +const std = @import("std"); + +const mod = @import("root.zig"); +const Env = mod.Env; +const Future = Env.Future; +const Function = Env.Function; +const Object = mod.Object; +const Value = mod.Value; + +const Self = @This(); + +// NOTE: js runs only on one thread, so this is safe, +// else an allocation would be necessary! +var promise_value: Value = undefined; + +pub inline fn then(self: *Self, env: *Env, func: anytype, ud: *anyopaque) Future(void) { + const wrapper = struct { + fn wrapper(userdata: *anyopaque) callconv(.c) void { + const args = @typeInfo(@TypeOf(func)).@"fn".params; + + const value = promise_value.unwrap(args[1].type orelse void); + + func(@alignCast(@ptrCast(userdata)), value) catch |err| { + std.log.err("{}", .{err}); + @panic("error handling promise"); + }; + } + }.wrapper; + return .fromAny(env.call(bindings.then, .{ + self, + @intFromPtr(&wrapper), + @intFromPtr(&promise_value), + @intFromPtr(ud), + })); +} + +pub fn as(self: *Self, T: type) *T { + return @ptrCast(self); +} + +pub const bindings = struct { + pub const then: Function = .from( + \\function(promise, func, ptr, ud) { + \\ promise.then((value) => { + \\ ObjectStore.writeValue(ptr, value); + \\ wasm.exports.__indirect_function_table.get(func)(ud); + \\ }) + \\} + ); +}; + +pub const functions = [_]Function{ + bindings.then, +}; -- cgit v1.2.3-70-g09d2