aboutsummaryrefslogtreecommitdiff
path: root/src/zilch
diff options
context:
space:
mode:
authorNathan Reiner <nathan@nathanreiner.xyz>2026-10-12 09:43:19 +0200
committerNathan Reiner <nathan@nathanreiner.xyz>2026-10-12 09:43:19 +0200
commit0b2af471b6d5dfc4eaf53639102c1b854bbb324b (patch)
treeaba3943b8c54d26d8552d0685d4178bc995d91c3 /src/zilch
parent812f547d84b5ce1a2924ae16f6257e4fd19efcc0 (diff)
first version of zilch
Diffstat (limited to 'src/zilch')
-rw-r--r--src/zilch/App/main.js43
-rw-r--r--src/zilch/App/object-store.js210
-rw-r--r--src/zilch/App/root.zig104
-rw-r--r--src/zilch/App/symbols.js2
-rw-r--r--src/zilch/AppBundle.zig49
-rw-r--r--src/zilch/Component.zig196
-rw-r--r--src/zilch/Env/call.zig16
-rw-r--r--src/zilch/Env/future.zig59
-rw-r--r--src/zilch/Env/js.zig22
-rw-r--r--src/zilch/Env/root.zig162
-rw-r--r--src/zilch/Env/value.zig115
-rw-r--r--src/zilch/Object.zig35
-rw-r--r--src/zilch/component.template.js21
-rw-r--r--src/zilch/html/Attribute.zig45
-rw-r--r--src/zilch/html/Document.zig11
-rw-r--r--src/zilch/html/Fragment.zig15
-rw-r--r--src/zilch/html/Tag.zig53
-rw-r--r--src/zilch/html/element.zig30
-rw-r--r--src/zilch/html/parser.zig174
-rw-r--r--src/zilch/html/root.zig6
-rw-r--r--src/zilch/log/js.zig24
-rw-r--r--src/zilch/log/root.zig28
-rw-r--r--src/zilch/root.zig18
23 files changed, 1438 insertions, 0 deletions
diff --git a/src/zilch/App/main.js b/src/zilch/App/main.js
new file mode 100644
index 0000000..265c886
--- /dev/null
+++ b/src/zilch/App/main.js
@@ -0,0 +1,43 @@
+const imports = {
+ object_store: {
+ process: ObjectStore.processWasm,
+ },
+ console: {
+ log(buffer, length) {
+ console.log(ObjectStore.decodeString(buffer, length))
+ },
+ warn(buffer, length) {
+ console.warn(ObjectStore.decodeString(buffer, length))
+ },
+ err(buffer, length) {
+ console.error(ObjectStore.decodeString(buffer, length))
+ },
+ debug(buffer, length) {
+ console.debug(ObjectStore.decodeString(buffer, length))
+ },
+ }
+}
+
+async function wasm_handle_event(target, name, event, pass_event) {
+ await wasm_ready;
+
+ const component = target.getRootNode().host;
+
+ if (pass_event) {
+ const id = ObjectStore.generateFreeId();
+ ObjectStore.registerObject(id, event);
+ wasm.exports[name](component[ZsPtr], id);
+ ObjectStore.free(event);
+ } else {
+ wasm.exports[name](component[ZsPtr]);
+ }
+}
+
+const wasm_ready = WebAssembly.instantiateStreaming(fetch("index.wasm"), imports).then(
+ ({ instance, module }) => {
+ wasm = {
+ exports: instance.exports,
+ memory: instance.exports.memory,
+ }
+ },
+);
diff --git a/src/zilch/App/object-store.js b/src/zilch/App/object-store.js
new file mode 100644
index 0000000..096d085
--- /dev/null
+++ b/src/zilch/App/object-store.js
@@ -0,0 +1,210 @@
+class ObjectStore {
+ static types = Object.freeze({
+ 0: "uninit",
+ 1: "object",
+ 2: "string",
+ 3: "int",
+ 4: "uint",
+ 5: "float",
+ 6: "undefined",
+
+ "uninit": 0,
+ "object": 1,
+ "string": 2,
+ "int": 3,
+ "uint": 4,
+ "float": 5,
+ "undefined": 6,
+ });
+
+ static methods = Object.freeze({
+ 0: 'free',
+ 1: 'getProp',
+ 2: 'setProp',
+ 3: 'delProp',
+ 4: 'callMethod',
+ 5: 'call',
+ 6: 'new',
+ });
+
+ static store = { 0: null };
+
+ static generateFreeId() {
+ let id = 0;
+
+ while (id in ObjectStore.store) {
+ id = Math.floor(Math.random() * (2**32 - 1))
+ }
+
+ return id;
+ }
+
+ static free(target) {
+ const id = target[ZsId];
+ delete target[ZsId];
+ delete ObjectStore.store[id];
+ }
+
+ static getProp(target, key) {
+ return target[key];
+ }
+
+ static setProp(target, key, value) {
+ target[key] = value;
+ }
+
+ static delProp(target, key) {
+ delete target[key];
+ }
+
+ static callMethod(target, method, ...args) {
+ return target[method](...args);
+ }
+
+ static call(target, args) {
+ return target(args);
+ }
+
+ static new(target, ...args) {
+ return new target(...args);
+ }
+
+ static decodeString(base, len) {
+ const slice = new Uint8Array(wasm.memory.buffer, base, len);
+ return new TextDecoder().decode(slice);
+ }
+
+ static decodeCall(view, offset) {
+ const kind = ObjectStore.methods[view.getUint8(offset, true)]
+
+ if (!kind) throw "unknown method, cannot decode";
+
+ return {
+ kind: kind,
+ num_args: view.getUint8(offset + 1, true),
+ }
+ }
+
+ static decodeValue(view, offset) {
+ const kind = ObjectStore.types[view.getUint8(offset, true)];
+
+ if (!kind) throw "unknown type, cannot decode";
+
+ if (kind === 'string') {
+ const ptr = view.getUint32(offset + 8, true)
+ const len = view.getUint32(offset + 12, true)
+ return ObjectStore.decodeString(ptr, len);
+ }
+
+ if (kind === 'int') {
+ return view.getInt32(offset + 8, true);
+ }
+
+ if (kind === 'uint') {
+ return view.getUint32(offset + 8, true);
+ }
+
+ if (kind === 'object') {
+ const id = view.getUint32(offset + 8, true);
+ return ObjectStore.store[id];
+ }
+
+ if (kind === 'float') {
+ return view.getFloat64(offset + 8, true);
+ }
+ }
+
+ static registerObject(id, obj) {
+ ObjectStore.store[id] = obj;
+ Object.defineProperty(obj, ZsId, {
+ enumerable: false,
+ writable: false,
+ configurable: true,
+ value: id,
+ })
+ }
+
+ static writeValue(ptr, value) {
+ const mem = new DataView(wasm.memory.buffer, ptr);
+
+ if (typeof value === 'object' || typeof value === 'function') {
+ mem.setUint8(0, ObjectStore.types['object'], true);
+ let id = value == null ? 0 : value[ZsId];
+
+ if (id === undefined) {
+ id = ObjectStore.generateFreeId();
+ ObjectStore.registerObject(id, value);
+ }
+
+ mem.setUint32(8, id, true);
+
+ return;
+ }
+
+ if (typeof value === 'number' && Number.isInteger(value) && value >= 0) {
+ mem.setUint8(0, ObjectStore.types['uint'], true);
+ mem.setUint32(8, value, true)
+ return;
+ }
+
+ if (typeof value === 'number' && Number.isInteger(value)) {
+ mem.setUint8(0, ObjectStore.types['int'], true);
+ mem.setInt32(8, value, true)
+ return;
+ }
+
+ if (typeof value === 'number') {
+ mem.setUint8(0, ObjectStore.types['float'], true);
+ mem.setFloat64(8, value, true)
+ return;
+ }
+
+ if (typeof value === 'string') {
+ const string_ptr = wasm.exports.valueAllocString(ptr, value.length);
+ const encoder = new TextEncoder();
+ const string = encoder.encode(value);
+ const memory = new Uint8Array(wasm.memory.buffer);
+ memory.set(string, string_ptr);
+ return;
+ }
+
+ if (typeof value === 'undefined') {
+ mem.setUint8(0, ObjectStore.types['undefined'], true);
+ return;
+ }
+ }
+
+ static processWasm(
+ calls_base,
+ values_base,
+ result_base,
+ length,
+ ) {
+ const offset = {
+ call: 0,
+ value: 0,
+ result: 0,
+ }
+
+ const calls_view = new DataView(wasm.memory.buffer, calls_base);
+ const values_view = new DataView(wasm.memory.buffer, values_base);
+ const results_view = new DataView(wasm.memory.buffer, result_base);
+
+ for (let i = 0; i < length; ++i) {
+ const method = ObjectStore.decodeCall(calls_view, offset.call);
+ offset.call += 2;
+
+ let args = new Array(method.num_args).fill().map(_ => {
+ const value = ObjectStore.decodeValue(values_view, offset.value);
+ offset.value += 16;
+ return value;
+ });
+
+ const result = ObjectStore[method.kind](...args);
+ const result_ptr = results_view.getUint32(offset.result, true);
+ offset.result += 4;
+
+ ObjectStore.writeValue(result_ptr, result);
+ }
+ }
+}
diff --git a/src/zilch/App/root.zig b/src/zilch/App/root.zig
new file mode 100644
index 0000000..52cbfc2
--- /dev/null
+++ b/src/zilch/App/root.zig
@@ -0,0 +1,104 @@
+const builtin = @import("builtin");
+const std = @import("std");
+const Element = @import("../root.zig").html.Element;
+const Document = @import("../root.zig").html.Document;
+const Fragment = @import("../root.zig").html.Fragment;
+const Component = @import("../root.zig").Component;
+
+pub const Options = struct {
+ name: []const u8,
+ globals: []const Global,
+ components: []const Component,
+ body: Fragment,
+ theme: []const u8,
+
+ pub const Global = struct {
+ name: []const u8,
+ type: type,
+ };
+};
+
+pub fn App(comptime options: Options) type {
+ if (builtin.target.cpu.arch.isWasm()) {
+ var names: [options.globals.len][]const u8 = undefined;
+ var types: [options.globals.len]type = undefined;
+ var attrs: [options.globals.len]std.builtin.Type.StructField.Attributes = undefined;
+
+ for (options.globals, 0..) |field, index| {
+ names[index] = field.name;
+ types[index] = field.type;
+ attrs[index] = .{};
+ }
+
+ const G = @Struct(.auto, null, &names, &types, &attrs);
+ return struct {
+ globals: G = g: {
+ var gl: G = undefined;
+
+ for (options.globals, 1..) |field, id| {
+ @field(gl, field.name) = @ptrFromInt(id);
+ }
+
+ break :g gl;
+ },
+
+ pub const init: @This() = .{};
+
+ comptime {
+ for (options.components) |component| {
+ component.exportLinks();
+ }
+ }
+ };
+ } else {
+ const components: []const Element = (comp: {
+ var cs: []const Element = &.{};
+
+ for (options.components) |component| {
+ cs = cs ++ component.toElement();
+ }
+
+ break :comp cs;
+ });
+
+ return struct {
+ const node: Document = .{
+ .root = .node("html", .{}, &.{
+ .node("head", .{}, &.{
+ .node("title", .{}, &.{.text(options.name)}),
+ .void("meta", .{
+ .name = "viewport",
+ .content = "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0",
+ }),
+ .node("style", .{}, &.{.text(options.theme)}),
+ .node("script", .{}, &.{.text(@embedFile("symbols.js"))}),
+ .node("script", .{}, &.{.text(@embedFile("object-store.js"))}),
+ .node("script", .{}, &.{.text(@embedFile("main.js"))}),
+ .node("script", .{}, &.{.text(reg: {
+ var register_code: []const u8 = "";
+
+ for (options.globals, 1..) |field, id| {
+ register_code = register_code ++ std.fmt.comptimePrint(
+ "ObjectStore.registerObject({}, {s});",
+ .{ id, field.name },
+ );
+ }
+
+ break :reg register_code;
+ })}),
+ }),
+ .node(
+ "body",
+ .{},
+ &[_]Element{
+ } ++ components ++ options.body.elements,
+ ),
+ }),
+ };
+
+ html: []const u8 = std.fmt.comptimePrint("{f}", .{node}),
+
+ pub const init: @This() = .{};
+ };
+ }
+}
diff --git a/src/zilch/App/symbols.js b/src/zilch/App/symbols.js
new file mode 100644
index 0000000..c0870c5
--- /dev/null
+++ b/src/zilch/App/symbols.js
@@ -0,0 +1,2 @@
+const ZsId = Symbol("zilch::id");
+const ZsPtr = Symbol("zilch::ptr");
diff --git a/src/zilch/AppBundle.zig b/src/zilch/AppBundle.zig
new file mode 100644
index 0000000..233495f
--- /dev/null
+++ b/src/zilch/AppBundle.zig
@@ -0,0 +1,49 @@
+const std = @import("std");
+
+pub const Options = struct {
+ root_source_file: std.Build.LazyPath,
+ target: std.Build.ResolvedTarget,
+};
+
+mod: *std.Build.Module,
+wasm: struct {
+ mod: *std.Build.Module,
+ exe: *std.Build.Step.Compile,
+},
+
+pub fn init(b: *std.Build, options: Options, zilch_mod: *std.Build.Module) @This() {
+ const module = b.addModule("site", .{
+ .root_source_file = options.root_source_file,
+ .target = options.target,
+ .imports = &.{ .{ .name = "zilch", .module = zilch_mod } },
+ });
+
+ const wasm_module = b.createModule(.{
+ .root_source_file = options.root_source_file,
+ .target = b.resolveTargetQuery(.{
+ .cpu_arch = .wasm32,
+ .os_tag = .freestanding,
+ }),
+ .imports = &.{ .{ .name = "zilch", .module = zilch_mod } },
+ });
+
+ const exe = b.addExecutable(.{
+ .name = "runtime",
+ .root_module = wasm_module,
+ });
+
+ exe.rdynamic = true;
+ exe.entry = .disabled;
+
+ return .{
+ .mod = module,
+ .wasm = .{
+ .exe = exe,
+ .mod = wasm_module,
+ },
+ };
+}
+
+pub fn getEmittedWasm(self: *const @This()) std.Build.LazyPath {
+ return self.wasm.exe.getEmittedBin();
+}
diff --git a/src/zilch/Component.zig b/src/zilch/Component.zig
new file mode 100644
index 0000000..35fafbe
--- /dev/null
+++ b/src/zilch/Component.zig
@@ -0,0 +1,196 @@
+const std = @import("std");
+const Fragment = @import("root.zig").html.Fragment;
+const Element = @import("root.zig").html.Element;
+const Attribute = @import("root.zig").html.Attribute;
+const Object = @import("Object.zig");
+
+const Self = @This();
+
+namespace: []const u8 = "app",
+name: []const u8,
+html: Fragment,
+css: []const u8,
+link: type,
+
+fn handlerNeedsEvent(func: anytype) bool {
+ const T = @TypeOf(func);
+ return @typeInfo(T).@"fn".params.len == 2;
+}
+
+fn wrapHandler(ret: anytype) void {
+ const T = @TypeOf(ret);
+ const ret_info = @typeInfo(T);
+
+ if (ret_info == .error_union) {
+ ret catch |err| {
+ std.log.err("error: {}", .{err});
+ };
+ }
+}
+
+fn exportFromHtml(self: *const Self, element: Element) void {
+ comptime {
+ switch (element) {
+ .tag => |tag| for (tag.attributes) |attr| {
+ if (attr.value.len > 0 and attr.value[0] == '@') {
+ const event_handler = @field(self.link, attr.value[1..]);
+
+ const func =
+ if (handlerNeedsEvent(event_handler))
+ struct {
+ pub fn func(obj: *self.link, event: *Object) callconv(.c) void {
+ wrapHandler(event_handler(obj, event));
+ }
+ }.func
+ else
+ struct {
+ pub fn func(obj: *self.link) callconv(.c) void {
+ wrapHandler(event_handler(obj));
+ }
+ }.func;
+
+ @export(
+ &func,
+ .{
+ .name = std.fmt.comptimePrint(
+ "export::{s}::{s}",
+ .{ self.name, attr.value[1..] },
+ ),
+ },
+ );
+ }
+
+ switch (tag.content) {
+ .children => |children| for (children) |child| {
+ self.exportFromHtml(child);
+ },
+ else => {},
+ }
+ },
+ else => {},
+ }
+ }
+}
+
+pub fn exportLinks(self: *const Self) void {
+ const init = struct {
+ pub fn init(element: *Object) callconv(.c) ?*self.link {
+ const obj = std.heap.wasm_allocator.create(self.link) catch return null;
+ if (@hasDecl(self.link, "init")) {
+ wrapHandler(obj.init(element));
+ }
+ return obj;
+ }
+ }.init;
+
+ @export(
+ &init,
+ .{
+ .name = std.fmt.comptimePrint(
+ "export::{s}::init",
+ .{self.name},
+ ),
+ },
+ );
+
+ const deinit = struct {
+ pub fn deinit(obj: *self.link) callconv(.c) void {
+ if (@hasDecl(self.link, "deinit")) {
+ wrapHandler(obj.deinit());
+ }
+ std.heap.wasm_allocator.destroy(obj);
+ }
+ }.deinit;
+
+ @export(
+ &deinit,
+ .{
+ .name = std.fmt.comptimePrint(
+ "export::{s}::deinit",
+ .{self.name},
+ ),
+ },
+ );
+
+ for (self.html.elements) |element| {
+ comptime self.exportFromHtml(element);
+ }
+}
+
+fn linkAttributes(self: *const Self, attributes: []const Attribute) []const Attribute {
+ var linked: []const Attribute = &.{};
+
+ for (attributes) |attr| {
+ if (attr.value.len > 0 and attr.value[0] == '@') {
+ const event_handler = @field(self.link, attr.value[1..]);
+ const attribute: Attribute = .{
+ .name = attr.name,
+ .value = std.fmt.comptimePrint(
+ "wasm_handle_event(this, \"export::{s}::{s}\", event, {})",
+ .{ self.name, attr.value[1..], handlerNeedsEvent(event_handler) },
+ ),
+ };
+ linked = linked ++ .{attribute};
+ } else {
+ linked = linked ++ .{attr};
+ }
+ }
+ return linked;
+}
+
+fn linkHtmlRecursive(self: *const Self, element: Element) Element {
+ comptime {
+ return switch (element) {
+ .tag => |el| .{
+ .tag = .{
+ .name = el.name,
+ .attributes = self.linkAttributes(el.attributes),
+ .content = switch (el.content) {
+ .children => |children| ch: {
+ var elements: []const Element = &.{};
+
+ for (children) |child| {
+ const e: []const Element = &.{self.linkHtmlRecursive(child)};
+ elements = elements ++ e;
+ }
+
+ break :ch .{ .children = elements };
+ },
+ .void => .void,
+ },
+ },
+ },
+ .string => element,
+ };
+ }
+}
+
+pub fn toElement(self: *const Self) []const Element {
+ return &.{
+ .node(
+ "template",
+ .{ .id = "@" ++ self.name },
+ [_]Element{
+ .node("style", .{}, &.{.text(self.css)}),
+ } ++ (html: {
+ var elements: []const Element = &.{};
+
+ for (self.html.elements) |element| {
+ elements = elements ++ .{self.linkHtmlRecursive(element)};
+ }
+
+ break :html elements;
+ }),
+ ),
+ .node(
+ "script",
+ .{},
+ &.{.text(
+ std.fmt.comptimePrint(
+ @embedFile("component.template.js"),
+ .{ self.namespace, self.name, self.name, self.name, self.name },
+ ),
+ )},
+ ),
+ };
+}
diff --git a/src/zilch/Env/call.zig b/src/zilch/Env/call.zig
new file mode 100644
index 0000000..a5db835
--- /dev/null
+++ b/src/zilch/Env/call.zig
@@ -0,0 +1,16 @@
+
+pub const Call = extern struct {
+ kind: Kind,
+ num_args: u8,
+
+ const Kind = enum(u8) {
+ free = 0,
+ get_prop = 1,
+ set_prop = 2,
+ del_prop = 3,
+ call_method = 4,
+ call = 5,
+ new = 6,
+ };
+};
+
diff --git a/src/zilch/Env/future.zig b/src/zilch/Env/future.zig
new file mode 100644
index 0000000..a014990
--- /dev/null
+++ b/src/zilch/Env/future.zig
@@ -0,0 +1,59 @@
+const std = @import("std");
+const Env = @import("root.zig");
+const z = @import("../root.zig");
+
+
+pub fn Future(comptime kind: Env.Value.Kind) type {
+ return struct {
+ const Self = @This();
+
+ future: AnyFuture,
+
+ pub fn fromAny(future: AnyFuture) Self {
+ return .{ .future = future };
+ }
+
+ pub fn await(self: *const Self, env: *Env) !kind.asType() {
+ return self.future.await(env, kind);
+ }
+ };
+}
+
+pub const AnyFuture = union(enum) {
+ const Self = @This();
+
+ result: *Env.Value,
+ err: anyerror,
+
+ pub fn await(self: *const Self, env: *Env, comptime kind: Env.Value.Kind) !kind.asType() {
+ const result = try self.awaitAny(env);
+
+ if (kind != result.kind) {
+ std.log.err("unexpected {}, expected {}", .{ result.kind, kind });
+ @panic("type error");
+ }
+
+ return switch (kind) {
+ .uninit => @panic("uninitialized result"),
+ .string => result.value.string.ptr[0..result.value.string.len],
+ else => @field(result.value, @tagName(kind)),
+ };
+ }
+
+ pub fn awaitAny(self: *const Self, env: *Env) !Env.Value {
+ switch (self.*) {
+ .err => |err| return err,
+ .result => |result| {
+ defer env.pool.destroy(result);
+
+ if (result.kind != .uninit) {
+ return result.*;
+ }
+
+ env.flush();
+
+ return result.*;
+ }
+ }
+ }
+};
diff --git a/src/zilch/Env/js.zig b/src/zilch/Env/js.zig
new file mode 100644
index 0000000..c1ff85d
--- /dev/null
+++ b/src/zilch/Env/js.zig
@@ -0,0 +1,22 @@
+const std = @import("std");
+const Env = @import("root.zig");
+
+pub extern "object_store" fn process(
+ [*]const Env.Call,
+ [*]const Env.Value,
+ [*]*Env.Value,
+ length: usize,
+) void;
+
+export fn valueAllocString(value: *Env.Value, len: usize) [*]u8 {
+ const ptr: [*]u8 = @ptrCast(std.heap.wasm_allocator.alloc(u8, len) catch @panic("unable to allocate string"));
+ value.kind = .string;
+ value.value = .{
+ .string = .{
+ .ptr = ptr,
+ .len = len,
+ },
+ };
+
+ return @constCast(value.value.string.ptr);
+}
diff --git a/src/zilch/Env/root.zig b/src/zilch/Env/root.zig
new file mode 100644
index 0000000..6fd2bab
--- /dev/null
+++ b/src/zilch/Env/root.zig
@@ -0,0 +1,162 @@
+const std = @import("std");
+
+const Self = @This();
+
+const js = @import("js.zig");
+const future = @import("future.zig");
+const Object = @import("../Object.zig");
+
+pub const Call = @import("call.zig").Call;
+pub const AnyFuture = future.AnyFuture;
+pub const Future = future.Future;
+pub const Value = @import("value.zig").Value;
+
+calls: std.ArrayList(Call) = .empty,
+values: std.ArrayList(Value) = .empty,
+pool: std.heap.MemoryPool(Value) = .empty,
+results: std.ArrayList(*Value) = .empty,
+gpa: std.mem.Allocator,
+
+pub const default: Self = .{ .gpa = std.heap.wasm_allocator };
+
+pub fn init(gpa: std.mem.Allocator) Self {
+ return .{ .gpa = gpa };
+}
+
+pub fn getProp(self: *Self, object: *Object, key: anytype) AnyFuture {
+ self.calls.append(self.gpa, .{
+ .kind = .get_prop,
+ .num_args = 2,
+ }) catch |err| return .{ .err = err };
+ self.values.append(self.gpa, .from(object)) catch |err| return .{ .err = err };
+ self.values.append(self.gpa, .from(key)) catch |err| return .{ .err = err };
+
+ return self.registerFuture() catch |err| .{ .err = err };
+}
+
+pub fn setProp(
+ self: *Self,
+ object: *Object,
+ key: anytype,
+ value: anytype,
+) Future(.undefined) {
+ self.calls.append(self.gpa, .{
+ .kind = .set_prop,
+ .num_args = 3,
+ }) catch |err| return .fromAny(.{ .err = err });
+
+ self.values.append(self.gpa, .from(object)) catch |err| return .fromAny(.{ .err = err });
+ self.values.append(self.gpa, .from(key)) catch |err| return .fromAny(.{ .err = err });
+ self.values.append(self.gpa, .from(value)) catch |err| return .fromAny(.{ .err = err });
+
+ return .fromAny(self.registerFuture() catch |err| .{ .err = err });
+}
+
+pub fn deleteProp(
+ self: *Self,
+ object: *Object,
+ key: anytype,
+) Future(.undefined) {
+ self.calls.append(self.gpa, .{
+ .kind = .del_prop,
+ .num_args = 2,
+ }) catch |err| return .fromAny(.{ .err = err });
+
+ self.values.append(self.gpa, .from(object)) catch |err| return .fromAny(.{ .err = err });
+ self.values.append(self.gpa, .from(key)) catch |err| return .fromAny(.{ .err = err });
+
+ return .fromAny(self.registerFuture() catch |err| .{ .err = err });
+}
+
+pub fn callMethod(
+ self: *Self,
+ object: *Object,
+ key: []const u8,
+ args: anytype,
+) AnyFuture {
+ self.calls.append(self.gpa, .{
+ .kind = .call_method,
+ .num_args = 2 + args.len,
+ }) catch |err| return .{ .err = err };
+
+ self.values.append(self.gpa, .from(object)) catch |err| return .{ .err = err };
+ self.values.append(self.gpa, .from(key)) catch |err| return .{ .err = err };
+
+ inline for (args) |arg| {
+ self.values.append(self.gpa, .from(arg)) catch |err| return .{ .err = err };
+ }
+
+ return self.registerFuture() catch |err| return .{ .err = err };
+}
+
+pub fn call(self: *Self, object: *Object, args: anytype) AnyFuture {
+ self.calls.append(self.gpa, .{
+ .kind = .call,
+ .num_args = 1 + args.len,
+ }) catch |err| return .{ .err = err };
+
+ self.values.append(self.gpa, .from(object)) catch |err| return .{ .err = err };
+
+ inline for (args) |arg| {
+ self.values.append(self.gpa, .from(arg)) catch |err| return .{ .err = err };
+ }
+
+ return self.registerFuture() catch |err| return .{ .err = err };
+}
+
+pub fn free(self: *Self, object: *Object) Future(.undefined) {
+ self.calls.append(self.gpa, .{
+ .kind = .free,
+ .num_args = 1,
+ }) catch |err| return .fromAny(.{ .err = err });
+
+ self.values.append(self.gpa, .from(object)) catch |err| return .fromAny(.{ .err = err });
+
+ return .fromAny(self.registerFuture() catch |err| .{ .err = err });
+}
+
+pub fn new(self: *Self, object: *Object, args: anytype) Future(.object) {
+ self.calls.append(self.gpa, .{
+ .kind = .new,
+ .num_args = 1 + args.len,
+ }) catch |err| return .fromAny(.{ .err = err });
+
+ self.values.append(self.gpa, .from(object)) catch |err| return .fromAny(.{ .err = err });
+
+ inline for (args) |arg| {
+ self.values.append(self.gpa, .from(arg)) catch |err| return .fromAny(.{ .err = err });
+ }
+
+ return .fromAny(self.registerFuture() catch |err| .{ .err = err });
+}
+
+fn registerFuture(self: *Self) !AnyFuture {
+ const result = try self.pool.create(self.gpa);
+ errdefer self.pool.destroy(result);
+ result.kind = .uninit;
+ try self.results.append(self.gpa, result);
+ return .{ .result = result };
+}
+
+pub fn flush(self: *Self) void {
+ js.process(
+ @ptrCast(self.calls.items),
+ @ptrCast(self.values.items),
+ @ptrCast(self.results.items),
+ self.results.items.len,
+ );
+ self.calls.clearRetainingCapacity();
+ self.values.clearRetainingCapacity();
+ self.results.clearRetainingCapacity();
+}
+
+pub fn deinit(self: *Self) void {
+ self.flush();
+
+ self.calls.deinit(self.gpa);
+ self.values.deinit(self.gpa);
+ self.pool.deinit(self.gpa);
+ self.results.deinit(self.gpa);
+
+ self.* = undefined;
+}
diff --git a/src/zilch/Env/value.zig b/src/zilch/Env/value.zig
new file mode 100644
index 0000000..59b788f
--- /dev/null
+++ b/src/zilch/Env/value.zig
@@ -0,0 +1,115 @@
+const std = @import("std");
+const Object = @import("../Object.zig");
+
+pub fn isString(comptime T: type) bool {
+ return comptime blk: {
+ const info = @typeInfo(T);
+ if (info != .pointer) break :blk false;
+
+ const ptr = &info.pointer;
+ if (ptr.is_volatile or ptr.is_allowzero) break :blk false;
+
+ if (ptr.size == .slice) {
+ break :blk ptr.child == u8;
+ }
+
+ if (ptr.size == .one) {
+ const child = @typeInfo(ptr.child);
+ if (child == .array) {
+ const arr = &child.array;
+ break :blk arr.child == u8;
+ }
+ }
+
+ break :blk false;
+ };
+}
+
+pub const Value = extern struct {
+ kind: Kind,
+ value: extern union {
+ object: *Object,
+ string: extern struct {
+ ptr: [*]const u8,
+ len: usize,
+ },
+ int: isize,
+ uint: usize,
+ float: f64,
+ undefined: void,
+ },
+
+ pub fn from(value: anytype) Value {
+ const T = @TypeOf(value);
+
+ return switch (T) {
+ *Object => .{
+ .kind = .object,
+ .value = .{ .object = value },
+ },
+ comptime_int => if (value >= 0) .{
+ .kind = .uint,
+ .value = .{ .uint = value },
+ } else .{
+ .kind = .int,
+ .value = .{ .int = value },
+ },
+ usize => .{
+ .kind = .uint,
+ .value = .{ .uint = value },
+ },
+ isize => .{
+ .kind = .int,
+ .value = .{ .int = value },
+ },
+ f64, f32, f16 => .{
+ .kind = .float,
+ .value = .{ .float = value },
+ },
+ void => .{
+ .kind = .undefined,
+ .value = .{ .undefined = {} },
+ },
+ else => str: {
+ if (comptime isString(T)) {
+ break :str .{
+ .kind = .string,
+ .value = .{
+ .string = .{
+ .ptr = @ptrCast(value),
+ .len = value.len,
+ },
+ },
+ };
+ } else {
+ @compileError(std.fmt.comptimePrint(
+ "cannot auto convert type '{}'.",
+ .{T},
+ ));
+ }
+ },
+ };
+ }
+
+ pub const Kind = enum(u8) {
+ uninit = 0,
+ object = 1,
+ string = 2,
+ int = 3,
+ uint = 4,
+ float = 5,
+ undefined = 6,
+
+ pub fn asType(comptime self: Kind) type {
+ return switch (self) {
+ .object => return *Object,
+ .string => return []const u8,
+ .int => return isize,
+ .uint => return usize,
+ .float => f64,
+ .undefined => return void,
+ .uninit => @compileError("uninit has no associated type."),
+ };
+ }
+ };
+};
diff --git a/src/zilch/Object.zig b/src/zilch/Object.zig
new file mode 100644
index 0000000..064d48b
--- /dev/null
+++ b/src/zilch/Object.zig
@@ -0,0 +1,35 @@
+const mod = @import("root.zig");
+const Options = mod.Options;
+const Env = mod.Env;
+const AnyFuture = Env.AnyFuture;
+const Future = Env.Future;
+
+const Self = @This();
+
+pub inline fn get(self: *Self, env: *Env, key: anytype) AnyFuture {
+ return env.getProp(self, key);
+}
+
+pub inline fn set(self: *Self, env: *Env, key: anytype, value: anytype) Future(.undefined) {
+ return env.setProp(self, key, value);
+}
+
+pub inline fn delete(self: *Self, env: *Env, key: anytype) Future(.undefined) {
+ return env.deleteProp(self, key);
+}
+
+pub inline fn call(self: *Self, env: *Env, method: []const u8, args: anytype) AnyFuture {
+ return env.callMethod(self, method, args);
+}
+
+pub inline fn free(self: *Self, env: *Env) Future(.undefined) {
+ return env.free(self);
+}
+
+pub fn new(self: *Self, env: *Env) Future(.object) {
+ return env.new(self, .{});
+}
+
+pub fn global(tag: @EnumLiteral()) Options.Global {
+ return .{ .name = @tagName(tag), .type = *Self };
+}
diff --git a/src/zilch/component.template.js b/src/zilch/component.template.js
new file mode 100644
index 0000000..e8cb914
--- /dev/null
+++ b/src/zilch/component.template.js
@@ -0,0 +1,21 @@
+customElements.define("{s}-{s}", class extends HTMLElement {{
+ constructor() {{
+ super();
+ this.attachShadow({{ mode: 'open' }});
+ const template = document.getElementById("@{s}");
+ const node = document.importNode(template.content, true);
+ this.shadowRoot.appendChild(node);
+ this[ZsPtr] = null;
+ }}
+ connectedCallback() {{
+ wasm_ready.then(() => {{
+ const id = ObjectStore.generateFreeId();
+ ObjectStore.registerObject(id, this);
+ this[ZsPtr] = wasm.exports['export::{s}::init'](id);
+ }});
+ }}
+ disconnectedCallback() {{
+ wasm.exports['export::{s}::deinit'](this[ZsId]);
+ ObjectStore.free(this);
+ }}
+}})
diff --git a/src/zilch/html/Attribute.zig b/src/zilch/html/Attribute.zig
new file mode 100644
index 0000000..1db49a0
--- /dev/null
+++ b/src/zilch/html/Attribute.zig
@@ -0,0 +1,45 @@
+const std = @import("std");
+
+const Self = @This();
+
+name: []const u8,
+value: []const u8,
+
+pub fn from(attributes: anytype) []const Self {
+ const T = @TypeOf(attributes);
+ const info = @typeInfo(T);
+
+ if (info != .@"struct") {
+ @compileError("struct needed");
+ }
+
+ const fields = info.@"struct".fields;
+
+ var attrs: []const Self = &.{};
+
+ for (fields) |field| {
+ const name = field.name;
+ const value = @field(attributes, name);
+
+ const next_attr: []const Self = &.{.{ .name = name, .value = value }};
+ attrs = attrs ++ next_attr;
+ }
+
+ return attrs;
+}
+
+pub fn format(self: *const Self, writer: *std.Io.Writer) !void {
+ try writer.writeAll(self.name);
+ try writer.writeAll("=\"");
+
+ var value: []const u8 = self.value;
+
+ while (std.mem.findScalar(u8, value, '"')) |index| {
+ try writer.writeAll(value[0..index]);
+ try writer.writeAll("&quot;");
+ value = value[index + 1..];
+ }
+
+ try writer.writeAll(value);
+ try writer.writeByte('"');
+}
diff --git a/src/zilch/html/Document.zig b/src/zilch/html/Document.zig
new file mode 100644
index 0000000..b1122e1
--- /dev/null
+++ b/src/zilch/html/Document.zig
@@ -0,0 +1,11 @@
+const std = @import("std");
+
+const Element = @import("root.zig").Element;
+
+const Self = @This();
+
+root: Element,
+
+pub fn format(self: Self, writer: *std.Io.Writer) !void {
+ try writer.print("<!DOCTYPE html>{f}", .{self.root});
+}
diff --git a/src/zilch/html/Fragment.zig b/src/zilch/html/Fragment.zig
new file mode 100644
index 0000000..d05ad4a
--- /dev/null
+++ b/src/zilch/html/Fragment.zig
@@ -0,0 +1,15 @@
+const std = @import("std");
+const mod = @import("root.zig");
+const Element = mod.Element;
+
+const Self = @This();
+
+elements: []const Element,
+
+pub fn format(self: *const Self, writer: *std.Io.Writer) !void {
+ for (self.elements) |element| {
+ try element.format(writer);
+ }
+}
+
+pub const parse = mod.parser.fragment;
diff --git a/src/zilch/html/Tag.zig b/src/zilch/html/Tag.zig
new file mode 100644
index 0000000..90b5641
--- /dev/null
+++ b/src/zilch/html/Tag.zig
@@ -0,0 +1,53 @@
+const std = @import("std");
+const ctutils = @import("ctutils");
+
+const mod = @import("root.zig");
+const Attribute = mod.Attribute;
+const Element = mod.Element;
+
+const Self = @This();
+
+pub const Content = union(enum) {
+ children: []const Element,
+ void: void,
+};
+
+name: []const u8,
+attributes: []const Attribute,
+content: Content,
+
+pub fn tag(name: []const u8, attributes: anytype, children: []const Element) Self {
+ return .{
+ .name = name,
+ .attributes = Attribute.from(attributes),
+ .content = .{ .children = children },
+ };
+}
+
+pub fn @"void"(name: []const u8, attributes: anytype) Self {
+ return .{
+ .name = name,
+ .attributes = Attribute.from(attributes),
+ .content = .void,
+ };
+}
+
+pub fn format(self: *const Self, writer: *std.Io.Writer) !void {
+ try writer.writeByte('<');
+ try writer.writeAll(self.name);
+
+ for (self.attributes) |attribute| {
+ try writer.writeByte(' ');
+ try attribute.format(writer);
+ }
+
+ try writer.writeByte('>');
+
+ switch (self.content) {
+ .children => |children| {
+ for (children) |child| try child.format(writer);
+ try writer.print("</{s}>", .{self.name});
+ },
+ .void => {},
+ }
+}
diff --git a/src/zilch/html/element.zig b/src/zilch/html/element.zig
new file mode 100644
index 0000000..739eb0b
--- /dev/null
+++ b/src/zilch/html/element.zig
@@ -0,0 +1,30 @@
+const std = @import("std");
+const mod = @import("root.zig");
+const Attribute = mod.Attribute;
+const Tag = mod.Tag;
+
+pub const Element = union(enum) {
+ const Self = @This();
+
+ tag: Tag,
+ string: []const u8,
+
+ pub fn node(name: []const u8, attributes: anytype, children: []const Element) Self {
+ return .{ .tag = .tag(name, attributes, children) };
+ }
+
+ pub fn @"void"(name: []const u8, attribute: anytype) Self {
+ return .{ .tag = .void(name, attribute) };
+ }
+
+ pub fn text(content: []const u8) Self {
+ return .{ .string = content };
+ }
+
+ pub fn format(self: *const Self, writer: *std.Io.Writer) !void {
+ try switch (self.*) {
+ .string => |content| writer.writeAll(content),
+ .tag => |n| n.format(writer),
+ };
+ }
+};
diff --git a/src/zilch/html/parser.zig b/src/zilch/html/parser.zig
new file mode 100644
index 0000000..38b28bb
--- /dev/null
+++ b/src/zilch/html/parser.zig
@@ -0,0 +1,174 @@
+const std = @import("std");
+const mod = @import("root.zig");
+const Element = mod.Element;
+const Attribute = mod.Attribute;
+const Tag = mod.Tag;
+const Fragment = mod.Fragment;
+
+const tag_name: []const u8 = std.ascii.letters ++ .{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-' };
+const void_elements: std.StaticStringMap(void) = .initComptime(.{
+ .{"area"},
+ .{"base"},
+ .{"br"},
+ .{"col"},
+ .{"embed"},
+ .{"hr"},
+ .{"img"},
+ .{"input"},
+ .{"link"},
+ .{"meta"},
+ .{"param"},
+ .{"source"},
+ .{"track"},
+ .{"wbr"},
+});
+
+pub fn fragment(buffer: []const u8) Fragment {
+ @setEvalBranchQuota(buffer.len * 1000);
+ var elements: []const Element = &.{};
+ var buf = buffer;
+
+ while (buf.len > 0) {
+ const e, buf = element(buf);
+ elements = elements ++ .{e};
+ }
+
+ return .{ .elements = elements };
+}
+
+pub fn element(buffer: []const u8) struct { Element, []const u8 } {
+ if (buffer.len == 0) @panic("EOB, expected element");
+
+ switch (buffer[0]) {
+ '<' => {
+ const t, const b = tag(buffer);
+ return .{ .{ .tag = t }, b };
+ },
+ else => {
+ const t, const b = text(buffer);
+ return .{ .{ .string = t }, b };
+ },
+ }
+}
+
+pub fn tag(buffer: []const u8) struct { Tag, []const u8 } {
+ if (buffer.len == 0) @panic("EOB, expected tag");
+
+ if (buffer[0] != '<') @panic("expected '<'");
+
+ var buf: []const u8 = buffer[1..];
+
+ const name = name: {
+ const index = std.mem.findNone(u8, buf, tag_name) orelse @panic("uncosed tag");
+ defer buf = buf[index..];
+ break :name buf[0..index];
+ };
+
+ buf = std.mem.trimStart(u8, buf, &std.ascii.whitespace);
+
+ var attributes: []const Attribute = &.{};
+
+ while (buf.len > 0 and buf[0] != '>') {
+ buf = std.mem.trimStart(u8, buf, &std.ascii.whitespace);
+ const attr, buf = attribute(buf);
+ attributes = attributes ++ .{attr};
+ }
+
+ if (buf.len == 0 or buf[0] != '>') @panic("expected tag-close");
+
+ buf = buf[1..];
+
+ if (void_elements.has(name)) {
+ return .{.{
+ .name = name,
+ .attributes = attributes,
+ .content = .void,
+ }};
+ }
+
+ var children: []const Element = &.{};
+
+ buf = std.mem.trimStart(u8, buf, &std.ascii.whitespace);
+
+ const closing = std.fmt.comptimePrint("</{s}>", .{name});
+
+ while (buf.len > 0 and !std.mem.startsWith(u8, buf, closing)) {
+ const child, buf = element(buf);
+ children = children ++ .{child};
+ buf = std.mem.trimStart(u8, buf, &std.ascii.whitespace);
+ }
+
+ if (!std.mem.startsWith(u8, buf, closing)) @panic("expected closing-tag");
+
+ buf = buf[closing.len..];
+
+ return .{
+ .{
+ .name = name,
+ .attributes = attributes,
+ .content = .{ .children = children },
+ },
+ buf,
+ };
+}
+
+pub fn text(buffer: []const u8) struct { []const u8, []const u8 } {
+ const index = std.mem.findScalar(u8, buffer, '<') orelse buffer.len;
+ return .{
+ std.mem.trim(u8, buffer[0..index], &std.ascii.whitespace),
+ buffer[index..],
+ };
+}
+
+pub fn attribute(buffer: []const u8) struct { Attribute, []const u8 } {
+ var buf = buffer;
+
+ const name = name: {
+ const index = std.mem.findAny(
+ u8,
+ buf,
+ ">=\"'" ++ std.ascii.whitespace,
+ ) orelse @panic("EOB, expected attr-value");
+ defer buf = buf[index..];
+ break :name buf[0..index];
+ };
+
+ if (name.len == 0) @panic("expected attr-name");
+
+ buf = std.mem.trimStart(u8, buf, &std.ascii.whitespace);
+
+ if (buf.len == 0 or buf[0] == '>') {
+ return .{ .{ .name = name, .value = "" }, buf };
+ }
+
+ if (buf[0] != '=') @panic("expected attr-eql");
+
+ buf = std.mem.trimStart(u8, buf[1..], &std.ascii.whitespace);
+
+ const delim = switch (buf[0]) {
+ '"' => "\"",
+ '\'' => "'",
+ else => std.ascii.whitespace ++ "=\"'<>`",
+ };
+
+ if (delim.len == 1) {
+ buf = buf[1..];
+ }
+
+ const value = value: {
+ const index = std.mem.findAny(u8, buf, delim) orelse if (delim.len == 1)
+ @panic("unclosed attr-value")
+ else
+ buf.len;
+ defer buf = buf[index + @intFromBool(delim.len == 1) ..];
+ break :value buf[0..index];
+ };
+
+ return .{
+ .{
+ .name = name,
+ .value = value,
+ },
+ buf,
+ };
+}
diff --git a/src/zilch/html/root.zig b/src/zilch/html/root.zig
new file mode 100644
index 0000000..7bf91e8
--- /dev/null
+++ b/src/zilch/html/root.zig
@@ -0,0 +1,6 @@
+pub const Attribute = @import("Attribute.zig");
+pub const Tag = @import("Tag.zig");
+pub const Element = @import("element.zig").Element;
+pub const Document = @import("Document.zig");
+pub const Fragment = @import("Fragment.zig");
+pub const parser = @import("parser.zig");
diff --git a/src/zilch/log/js.zig b/src/zilch/log/js.zig
new file mode 100644
index 0000000..16f562c
--- /dev/null
+++ b/src/zilch/log/js.zig
@@ -0,0 +1,24 @@
+
+const js = struct {
+ extern "console" fn log(buffer: [*]const u8, len: usize) void;
+ extern "console" fn warn(buffer: [*]const u8, len: usize) void;
+ extern "console" fn err(buffer: [*]const u8, len: usize) void;
+ extern "console" fn debug(buffer: [*]const u8, len: usize) void;
+};
+
+
+pub fn log(buffer: []const u8) void {
+ js.log(@ptrCast(buffer), buffer.len);
+}
+
+pub fn warn(buffer: []const u8) void {
+ js.warn(@ptrCast(buffer), buffer.len);
+}
+
+pub fn err(buffer: []const u8) void {
+ js.err(@ptrCast(buffer), buffer.len);
+}
+
+pub fn debug(buffer: []const u8) void {
+ js.debug(@ptrCast(buffer), buffer.len);
+}
diff --git a/src/zilch/log/root.zig b/src/zilch/log/root.zig
new file mode 100644
index 0000000..ba9141e
--- /dev/null
+++ b/src/zilch/log/root.zig
@@ -0,0 +1,28 @@
+const std = @import("std");
+
+pub const js = @import("js.zig");
+
+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,
+ };
+
+ if (scope != .default) {
+ writer.print("[{s}]: ", .{@tagName(scope)}) catch unreachable;
+ }
+ writer.print(format, args) catch unreachable;
+
+ func(writer.buffered());
+}
+
diff --git a/src/zilch/root.zig b/src/zilch/root.zig
new file mode 100644
index 0000000..321bde4
--- /dev/null
+++ b/src/zilch/root.zig
@@ -0,0 +1,18 @@
+const builtin = @import("builtin");
+const std = @import("std");
+
+pub const log = @import("log/root.zig");
+pub const Env = @import("Env/root.zig");
+pub const Object = @import("Object.zig");
+pub const html = @import("html/root.zig");
+
+pub const App = @import("App/root.zig").App;
+pub const Options = @import("App/root.zig").Options;
+pub const Component = @import("Component.zig");
+
+fn defaultPanic(msg: []const u8, _: ?usize) noreturn {
+ log.js.err(msg);
+ @trap();
+}
+
+pub const panic = std.debug.FullPanic(defaultPanic);