aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorNathan Reiner <nathan@nathanreiner.xyz>2026-10-17 10:13:13 +0200
committerNathan Reiner <nathan@nathanreiner.xyz>2026-10-17 10:13:13 +0200
commitb1b4df39abb41a4ae71733e2d139dc70cc71acd8 (patch)
tree3d72b1dd75841e0b950282099ec9c837aa03d869 /src
parentdd24e86dad0402917b1713d1afeefaf65c3d1e51 (diff)
zilch: implement callable and promise
Diffstat (limited to 'src')
-rw-r--r--src/app/components/navbutton/root.zig29
-rw-r--r--src/app/root.zig5
-rw-r--r--src/zilch/AppBundle.zig1
-rw-r--r--src/zilch/Callable.zig27
-rw-r--r--src/zilch/Env/future.zig19
-rw-r--r--src/zilch/Env/value.zig84
-rw-r--r--src/zilch/Object.zig8
-rw-r--r--src/zilch/Promise.zig54
-rw-r--r--src/zilch/log/root.zig35
-rw-r--r--src/zilch/root.zig7
10 files changed, 230 insertions, 39 deletions
diff --git a/src/app/components/navbutton/root.zig b/src/app/components/navbutton/root.zig
index 6a403cb..8b2b59d 100644
--- a/src/app/components/navbutton/root.zig
+++ b/src/app/components/navbutton/root.zig
@@ -1,6 +1,8 @@
const std = @import("std");
const app = @import("root").app;
const zilch = @import("zilch");
+const Object = zilch.Object;
+const Promise = zilch.Promise;
const object = zilch.Object.bindings;
const Self = @This();
@@ -29,10 +31,10 @@ pub fn init(self: *Self, element: *zilch.Object) !void {
var button = env.call(object.call, .{shadow_root, "getElementById", "button"});
var class_list = env.call(object.get, .{button, "classList"});
- self.button.classList = try class_list.await(&env, .object);
+ self.button.classList = try class_list.await(&env, *Object);
- self.shadow_root = try shadow_root.await(&env, .object);
- _ = (try button.await(&env, .object)).free(&env);
+ self.shadow_root = try shadow_root.await(&env, *Object);
+ _ = (try button.await(&env, *Object)).free(&env);
}
pub fn deinit(self: *Self) !void {
@@ -49,4 +51,25 @@ pub fn open(self: *Self) !void {
defer env.deinit();
_ = self.button.classList.call(&env, "toggle", .{"open"});
+
+ var promise_future = app.globals.fetch.call(&env, .{"/"});
+ const promise = try promise_future.await(&env, *Promise);
+ defer _ = promise.as(Object).free(&env);
+
+ _ = promise.then(&env, handleResponse, self);
+}
+
+fn handleResponse(self: *Self, response: *Object) !void {
+ var env: zilch.Env = .default;
+ defer env.deinit();
+ defer _ = response.free(&env);
+
+ var promise_future = response.call(&env, "text", .{});
+ const promise = try promise_future.await(&env, *Promise);
+ _ = promise.then(&env, handleText, self);
+}
+
+fn handleText(self: *Self, text: []const u8) !void {
+ _ = self;
+ std.log.info("text: {s}", .{text});
}
diff --git a/src/app/root.zig b/src/app/root.zig
index 25865d2..5d56b49 100644
--- a/src/app/root.zig
+++ b/src/app/root.zig
@@ -11,10 +11,13 @@ const components = @import("components/root.zig").components;
pub const app: zilch.App(.{
.name = "Memora",
- .functions = &zilch.Object.functions,
+ .functions = &(zilch.Object.functions ++
+ zilch.Promise.functions ++
+ zilch.Callable.functions),
.globals = &.{
zilch.Object.global(.window),
zilch.Object.global(.Object),
+ zilch.Callable.global(.fetch),
},
.components = components,
.body = .parse(@embedFile("index.html")),
diff --git a/src/zilch/AppBundle.zig b/src/zilch/AppBundle.zig
index 233495f..c3e20cf 100644
--- a/src/zilch/AppBundle.zig
+++ b/src/zilch/AppBundle.zig
@@ -34,6 +34,7 @@ pub fn init(b: *std.Build, options: Options, zilch_mod: *std.Build.Module) @This
exe.rdynamic = true;
exe.entry = .disabled;
+ exe.export_table = true;
return .{
.mod = module,
diff --git a/src/zilch/Callable.zig b/src/zilch/Callable.zig
new file mode 100644
index 0000000..6732c69
--- /dev/null
+++ b/src/zilch/Callable.zig
@@ -0,0 +1,27 @@
+const mod = @import("root.zig");
+const Options = mod.Options;
+const Env = mod.Env;
+const AnyFuture = Env.AnyFuture;
+const Function = Env.Function;
+
+const Self = @This();
+
+pub inline fn call(self: *Self, env: *Env, args: anytype) AnyFuture {
+ return env.call(bindings.call, .{ self } ++ args);
+}
+
+pub const bindings = struct {
+ pub const call: Function = .from(
+ \\function(target, ...args) {
+ \\ return target(...args);
+ \\}
+ );
+};
+
+pub const functions = [_]Function{
+ bindings.call,
+};
+
+pub fn global(tag: @EnumLiteral()) Options.Global {
+ return .{ .name = @tagName(tag), .type = *Self };
+}
diff --git a/src/zilch/Env/future.zig b/src/zilch/Env/future.zig
index 8b88cd8..1b44d85 100644
--- a/src/zilch/Env/future.zig
+++ b/src/zilch/Env/future.zig
@@ -3,7 +3,7 @@ const Env = @import("root.zig");
const z = @import("../root.zig");
-pub fn Future(comptime kind: Env.Value.Kind) type {
+pub fn Future(Kind: type) type {
return struct {
const Self = @This();
@@ -13,8 +13,8 @@ pub fn Future(comptime kind: Env.Value.Kind) type {
return .{ .future = future };
}
- pub fn await(self: *const Self, env: *Env) !kind.asType() {
- return self.future.await(env, kind);
+ pub fn await(self: *const Self, env: *Env) !Kind {
+ return self.future.await(env, Kind);
}
};
}
@@ -29,18 +29,9 @@ pub const AnyFuture = union(enum) {
resolved: Env.Value,
err: anyerror,
- pub fn await(self: *Self, env: *Env, comptime kind: Env.Value.Kind) !kind.asType() {
+ pub fn await(self: *Self, env: *Env, Kind: type) !Kind {
const result = try self.awaitAny(env);
-
- if (kind != result.kind) {
- std.log.err("unexpected {}, expected {}", .{ result.kind, kind });
- @panic("type error");
- }
-
- return switch (kind) {
- .string => result.value.string.ptr[0..result.value.string.len],
- else => @field(result.value, @tagName(kind)),
- };
+ return result.unwrap(Kind);
}
pub fn awaitAny(self: *Self, env: *Env) !Env.Value {
diff --git a/src/zilch/Env/value.zig b/src/zilch/Env/value.zig
index cedaa89..b135366 100644
--- a/src/zilch/Env/value.zig
+++ b/src/zilch/Env/value.zig
@@ -26,10 +26,20 @@ pub fn isString(comptime T: type) bool {
};
}
+pub fn isObjectRef(comptime T: type) bool {
+ comptime {
+ const info = @typeInfo(T);
+ if (info != .pointer) return false;
+
+ const ptr = &info.pointer;
+ return ptr.size == .one and @sizeOf(ptr.child) == 0;
+ }
+}
+
pub const Value = extern struct {
kind: Kind,
value: extern union {
- object: *Object,
+ object: *anyopaque,
string: extern struct {
ptr: [*]const u8,
len: usize,
@@ -45,10 +55,6 @@ pub const Value = extern struct {
const T = @TypeOf(value);
return switch (T) {
- *Object => .{
- .kind = .object,
- .value = .{ .object = value },
- },
comptime_int => if (value >= 0) .{
.kind = .uint,
.value = .{ .uint = value },
@@ -76,21 +82,54 @@ pub const Value = extern struct {
.kind = .future,
.value = .{ .future = value.unresolved.id },
},
- else => str: {
+ else => blk: {
if (comptime isString(T)) {
- break :str .{
+ break :blk .{
.kind = .string,
.value = .{
.string = .{
.ptr = @ptrCast(value),
.len = value.len,
},
- },
- };
+ },
+ };
+ } else if (comptime isObjectRef(T)) {
+ break :blk .{
+ .kind = .object,
+ .value = .{ .object = @ptrCast(value) },
+ };
} else {
@compileError(std.fmt.comptimePrint(
- "cannot auto convert type '{}'.",
- .{T},
+ "cannot auto convert type '{}'.",
+ .{T},
+ ));
+ }
+ },
+ };
+ }
+
+ pub fn unwrap(self: *const Value, T: type) T {
+ if (Kind.fromType(T) != self.kind) {
+ std.log.err("unexpected {}, expected {}", .{ self.kind, T });
+ @panic("type error");
+ }
+
+ return switch (T) {
+ comptime_int => self.value.int,
+ usize => self.value.uint,
+ isize => self.value.int,
+ f64, f32, f16 => self.value.float,
+ void => {},
+ AnyFuture => @panic("unsupported return type"),
+ else => blk: {
+ if (comptime isString(T)) {
+ break :blk self.value.string.ptr[0..self.value.string.len];
+ } else if (comptime isObjectRef(T)) {
+ break :blk @ptrCast(self.value.object);
+ } else {
+ @compileError(std.fmt.comptimePrint(
+ "cannot auto convert type '{}'.",
+ .{T},
));
}
},
@@ -117,5 +156,28 @@ pub const Value = extern struct {
.future => AnyFuture,
};
}
+
+ pub fn fromType(T: type) Kind {
+ return switch (T) {
+ comptime_int => .int,
+ usize => .uint,
+ isize => .int,
+ f64, f32, f16 => .float,
+ void => .undefined,
+ AnyFuture => .future,
+ else => blk: {
+ if (comptime isString(T)) {
+ break :blk .string;
+ } else if (comptime isObjectRef(T)) {
+ break :blk .object;
+ } else {
+ @compileError(std.fmt.comptimePrint(
+ "cannot auto convert type '{}'.",
+ .{T},
+ ));
+ }
+ },
+ };
+ }
};
};
diff --git a/src/zilch/Object.zig b/src/zilch/Object.zig
index 194c43b..b37f40b 100644
--- a/src/zilch/Object.zig
+++ b/src/zilch/Object.zig
@@ -11,11 +11,11 @@ pub inline fn get(self: *Self, env: *Env, key: anytype) AnyFuture {
return env.call(bindings.get, .{ self, key });
}
-pub inline fn set(self: *Self, env: *Env, key: anytype, value: anytype) Future(.undefined) {
+pub inline fn set(self: *Self, env: *Env, key: anytype, value: anytype) Future(void) {
return .fromAny(env.call(bindings.set, .{ self, key, value }));
}
-pub inline fn delete(self: *Self, env: *Env, key: anytype) Future(.undefined) {
+pub inline fn delete(self: *Self, env: *Env, key: anytype) Future(void) {
return .fromAny(env.call(bindings.delete, .{ self, key }));
}
@@ -23,11 +23,11 @@ pub inline fn call(self: *Self, env: *Env, method: []const u8, args: anytype) An
return env.call(bindings.call, .{ self, method } ++ args);
}
-pub inline fn free(self: *Self, env: *Env) Future(.undefined) {
+pub inline fn free(self: *Self, env: *Env) Future(void) {
return .fromAny(env.call(bindings.free, .{self}));
}
-pub fn new(self: *Self, env: *Env) Future(.object) {
+pub inline fn new(self: *Self, env: *Env) Future(*Self) {
return .fromAny(env.call(bindings.new, .{self}));
}
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,
+};
diff --git a/src/zilch/log/root.zig b/src/zilch/log/root.zig
index ba9141e..ac67298 100644
--- a/src/zilch/log/root.zig
+++ b/src/zilch/log/root.zig
@@ -2,27 +2,54 @@ const std = @import("std");
pub const js = @import("js.zig");
+pub fn Writer(func: fn ([]const u8) void, buffer: []u8) std.Io.Writer {
+ return .{
+ .buffer = buffer,
+ .vtable = &.{
+ .drain = &struct {
+ fn drain(w: *std.Io.Writer, data: []const []const u8, splat: usize) std.Io.Writer.Error!usize {
+ func(w.buffer[0..w.end]);
+ w.end = 0;
+
+ var size: usize = 0;
+
+ for (data[0..data.len - 1]) |s| {
+ func(s);
+ size += s.len;
+ }
+
+ size += data[data.len - 1].len * splat;
+ for (0..splat) |_| {
+ func(data[data.len - 1]);
+ }
+
+ return size;
+ }
+ }.drain,
+ }
+ };
+}
+
pub fn default(
comptime level: std.log.Level,
comptime scope: @EnumLiteral(),
comptime format: []const u8,
args: anytype,
) void {
- var buffer: [1024]u8 = undefined;
- var writer: std.Io.Writer = .fixed(&buffer);
-
const func = switch (level) {
.err => js.err,
.warn => js.warn,
.info => js.log,
.debug => js.debug,
};
+ var buffer: [1024]u8 = undefined;
+ var writer = Writer(func, &buffer);
if (scope != .default) {
writer.print("[{s}]: ", .{@tagName(scope)}) catch unreachable;
}
writer.print(format, args) catch unreachable;
- func(writer.buffered());
+ writer.flush() catch unreachable;
}
diff --git a/src/zilch/root.zig b/src/zilch/root.zig
index 4940c77..2a31691 100644
--- a/src/zilch/root.zig
+++ b/src/zilch/root.zig
@@ -5,11 +5,14 @@ pub const Env = @import("Env/root.zig");
pub const Call = Call.Env;
pub const AnyFuture = AnyFuture.Env;
pub const Future = Future.Env;
-pub const Value = Value.Env;
+pub const Value = Env.Value;
pub const log = @import("log/root.zig");
-pub const Object = @import("Object.zig");
pub const html = @import("html/root.zig");
+pub const Object = @import("Object.zig");
+pub const Promise = @import("Promise.zig");
+pub const Callable = @import("Callable.zig");
+
pub const App = @import("App/root.zig").App;
pub const Options = @import("App/root.zig").Options;
pub const Component = @import("Component.zig");