aboutsummaryrefslogtreecommitdiff
path: root/src/zilch
diff options
context:
space:
mode:
Diffstat (limited to 'src/zilch')
-rw-r--r--src/zilch/AppBundle.zig50
-rw-r--r--src/zilch/Callable.zig27
-rw-r--r--src/zilch/Component.zig225
-rw-r--r--src/zilch/Env/Function.zig15
-rw-r--r--src/zilch/Env/call.zig5
-rw-r--r--src/zilch/Env/future.zig72
-rw-r--r--src/zilch/Env/js.zig22
-rw-r--r--src/zilch/Env/root.zig77
-rw-r--r--src/zilch/Env/value.sync-conflict-20261030-190805-2JYANE7.zig185
-rw-r--r--src/zilch/Env/value.zig183
-rw-r--r--src/zilch/Object.zig85
-rw-r--r--src/zilch/Promise.zig62
-rw-r--r--src/zilch/app/Options.zig17
-rw-r--r--src/zilch/app/event.js16
-rw-r--r--src/zilch/app/load.js37
-rw-r--r--src/zilch/app/object-store.js185
-rw-r--r--src/zilch/app/root.document.zig87
-rw-r--r--src/zilch/app/root.wasm.zig36
-rw-r--r--src/zilch/app/root.zig15
-rw-r--r--src/zilch/app/symbols.js2
-rw-r--r--src/zilch/bridge/root.zig40
-rw-r--r--src/zilch/bridge/server.root.zig10
-rw-r--r--src/zilch/bridge/wasm.root.zig0
-rw-r--r--src/zilch/component.template.js19
-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.zig55
-rw-r--r--src/zilch/panic.zig9
-rw-r--r--src/zilch/root.zig34
35 files changed, 1928 insertions, 0 deletions
diff --git a/src/zilch/AppBundle.zig b/src/zilch/AppBundle.zig
new file mode 100644
index 0000000..c3e20cf
--- /dev/null
+++ b/src/zilch/AppBundle.zig
@@ -0,0 +1,50 @@
+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;
+ exe.export_table = true;
+
+ 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/Callable.zig b/src/zilch/Callable.zig
new file mode 100644
index 0000000..d668953
--- /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: anytype, 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/Component.zig b/src/zilch/Component.zig
new file mode 100644
index 0000000..592b464
--- /dev/null
+++ b/src/zilch/Component.zig
@@ -0,0 +1,225 @@
+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 Env = @import("root.zig").Env;
+const Function = Env.Function;
+const Future = Env.Future;
+
+const Self = @This();
+
+pub const Options = struct {
+ namespace: []const u8 = "app",
+ name: []const u8,
+ html: Fragment,
+ css: []const u8,
+ link: type,
+};
+
+namespace: []const u8,
+name: []const u8,
+html: Fragment,
+css: []const u8,
+link: type,
+id: u32,
+
+pub fn build(comptime options: Options) Self {
+ return .{
+ .namespace = options.namespace,
+ .name = options.name,
+ .html = options.html,
+ .css = options.css,
+ .link = options.link,
+ .id = std.hash.XxHash32.hash(4654, options.namespace ++ "-" ++ options.name),
+ };
+}
+
+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},
+ ),
+ },
+ );
+
+ 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,
+ },
+ ),
+ )},
+ ),
+ };
+}
+
+pub fn new(self: Self, obj: *self.link, env: *Env) Future(*Object) {
+ return .fromAny(env.call(bindings.new, .{ @as(usize, @intCast(self.id)), @intFromPtr(obj) }));
+}
+
+const bindings = struct {
+ pub const new: Function = .from(
+ \\function(name_id, ptr) {
+ \\ const el = document.createElement(component_registry[name_id]);
+ \\ el[ZsPtr] = ptr;
+ \\ const id = ObjectStore.generateFreeId();
+ \\ ObjectStore.registerObject(id, el);
+ \\ return el;
+ \\}
+ );
+};
+
+pub const functions = [_]Function{
+ bindings.new,
+};
diff --git a/src/zilch/Env/Function.zig b/src/zilch/Env/Function.zig
new file mode 100644
index 0000000..c37b1c7
--- /dev/null
+++ b/src/zilch/Env/Function.zig
@@ -0,0 +1,15 @@
+const std = @import("std");
+
+const Self = @This();
+
+content: []const u8,
+id: u32,
+await: bool,
+
+pub fn from(content: []const u8) Self {
+ return .{
+ .content = content,
+ .id = std.hash.XxHash32.hash(4654, content),
+ .await = std.mem.startsWith(u8, content, "async ") or std.mem.startsWith(u8, content, "async("),
+ };
+}
diff --git a/src/zilch/Env/call.zig b/src/zilch/Env/call.zig
new file mode 100644
index 0000000..1681165
--- /dev/null
+++ b/src/zilch/Env/call.zig
@@ -0,0 +1,5 @@
+
+pub const Call = extern struct {
+ kind: u32,
+ num_args: u8,
+};
diff --git a/src/zilch/Env/future.zig b/src/zilch/Env/future.zig
new file mode 100644
index 0000000..43f46c5
--- /dev/null
+++ b/src/zilch/Env/future.zig
@@ -0,0 +1,72 @@
+const std = @import("std");
+const Env = @import("root.zig");
+const z = @import("../root.zig");
+
+
+pub fn Future(Kind: type) type {
+ return struct {
+ const Self = @This();
+
+ future: AnyFuture,
+
+ pub fn fromAny(future: AnyFuture) Self {
+ return .{ .future = future };
+ }
+
+ pub fn await(self: *Self, env: *Env) !Kind {
+ return self.future.await(env, Kind);
+ }
+
+ pub fn ignore(self: *Self, env: *Env) void {
+ return self.future.ignore(env);
+ }
+ };
+}
+
+pub const AnyFuture = union(enum) {
+ const Self = @This();
+
+ ignored: void,
+ unresolved: struct {
+ id: usize,
+ value: *Env.Value,
+ },
+ resolved: Env.Value,
+ err: anyerror,
+
+ pub fn await(self: *Self, env: *Env, Kind: type) !Kind {
+ const result = try self.awaitAny(env);
+ return result.unwrap(Kind);
+ }
+
+ pub fn awaitAny(self: *Self, env: *Env) !Env.Value {
+ defer self.* = undefined;
+ switch (self.*) {
+ .ignored => {
+ env.flush();
+ return .from({});
+ },
+ .err => |err| return err,
+ .resolved => |result| return result,
+ .unresolved => |result| {
+ const value = result.value;
+ defer env.release(value);
+
+ env.flush();
+
+ self.* = .{ .resolved = value.* };
+
+ return value.*;
+ }
+ }
+ }
+
+ pub fn ignore(self: *Self, env: *Env) void {
+ defer self.* = .ignored;
+
+ switch (self.*) {
+ .unresolved => env.ignore(self),
+ else => {},
+ }
+ }
+};
diff --git a/src/zilch/Env/js.zig b/src/zilch/Env/js.zig
new file mode 100644
index 0000000..a653192
--- /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 u16,
+ [*]const Env.Value,
+ [*]*Env.Value,
+ length: usize,
+) void;
+
+export fn valueAllocBuffer(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..d169b5f
--- /dev/null
+++ b/src/zilch/Env/root.zig
@@ -0,0 +1,77 @@
+const std = @import("std");
+
+const js = @import("js.zig");
+const Object = @import("../Object.zig");
+
+pub const Call = @import("call.zig").Call;
+pub const AnyFuture = @import("future.zig").AnyFuture;
+pub const Future = @import("future.zig").Future;
+pub const Value = @import("value.zig").Value;
+pub const Function = @import("Function.zig");
+
+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,
+
+const Self = @This();
+
+pub const default: Self = .{ .gpa = std.heap.wasm_allocator };
+
+pub fn call(self: *Self, function: Function, args: anytype) AnyFuture {
+ const id = self.calls.items.len;
+
+ self.calls.append(self.gpa, .{
+ .kind = function.id,
+ .num_args = args.len,
+ }) catch |err| return .{ .err = err };
+
+ inline for (args) |arg| {
+ self.values.append(self.gpa, .from(arg)) catch |err| return .{ .err = err };
+ }
+
+ const result = self.pool.create(self.gpa) catch |err| return .{ .err = err };
+ errdefer self.pool.destroy(result);
+ self.results.append(self.gpa, result) catch |err| return .{ .err = err };
+ return .{
+ .unresolved = .{
+ .id = id,
+ .value = 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 release(self: *Self, value: *Value) void {
+ self.pool.destroy(value);
+}
+
+pub fn ignore(self: *Self, future: *const AnyFuture) void {
+ if (self.results.items.len < future.unresolved.id and self.results.items[future.unresolved.id] == future.unresolved.value) {
+ self.pool.destroy(future.unresolved.value);
+ self.results.items[future.unresolved.id] = null;
+ }
+}
+
+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.sync-conflict-20261030-190805-2JYANE7.zig b/src/zilch/Env/value.sync-conflict-20261030-190805-2JYANE7.zig
new file mode 100644
index 0000000..7ce2ce8
--- /dev/null
+++ b/src/zilch/Env/value.sync-conflict-20261030-190805-2JYANE7.zig
@@ -0,0 +1,185 @@
+const std = @import("std");
+const Object = @import("../Object.zig");
+const AnyFuture = @import("future.zig").AnyFuture;
+
+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 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: *anyopaque,
+ string: extern struct {
+ ptr: [*]const u8,
+ len: usize,
+ },
+ int: isize,
+ uint: usize,
+ float: f64,
+ undefined: void,
+ future: usize,
+ },
+
+ pub fn from(value: anytype) Value {
+ const T = @TypeOf(value);
+
+ return switch (T) {
+ 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 = {} },
+ },
+ AnyFuture => .{
+ .kind = .future,
+ .value = .{ .future = value.unresolved.id },
+ },
+ else => blk: {
+ if (comptime isString(T)) {
+ 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 if (@typeInfo(T) == .int) {
+ // TODO: weil kuscheln mit janina.
+ } else {
+ @compileError(std.fmt.comptimePrint(
+ "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},
+ ));
+ }
+ },
+ };
+ }
+
+ pub const Kind = enum(u8) {
+ object = 0,
+ string = 1,
+ int = 2,
+ uint = 3,
+ float = 4,
+ undefined = 5,
+ future = 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,
+ .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/Env/value.zig b/src/zilch/Env/value.zig
new file mode 100644
index 0000000..ea54ff2
--- /dev/null
+++ b/src/zilch/Env/value.zig
@@ -0,0 +1,183 @@
+const std = @import("std");
+const Object = @import("../Object.zig");
+const AnyFuture = @import("future.zig").AnyFuture;
+
+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 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: *anyopaque,
+ string: extern struct {
+ ptr: [*]const u8,
+ len: usize,
+ },
+ int: isize,
+ uint: usize,
+ float: f64,
+ undefined: void,
+ future: usize,
+ },
+
+ pub fn from(value: anytype) Value {
+ const T = @TypeOf(value);
+
+ return switch (T) {
+ 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 = {} },
+ },
+ AnyFuture => .{
+ .kind = .future,
+ .value = .{ .future = value.unresolved.id },
+ },
+ else => blk: {
+ if (comptime isString(T)) {
+ 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},
+ ));
+ }
+ },
+ };
+ }
+
+ 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},
+ ));
+ }
+ },
+ };
+ }
+
+ pub const Kind = enum(u8) {
+ object = 0,
+ string = 1,
+ int = 2,
+ uint = 3,
+ float = 4,
+ undefined = 5,
+ future = 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,
+ .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
new file mode 100644
index 0000000..1d30b8a
--- /dev/null
+++ b/src/zilch/Object.zig
@@ -0,0 +1,85 @@
+const mod = @import("root.zig");
+const Options = mod.Options;
+const Env = mod.Env;
+const AnyFuture = Env.AnyFuture;
+const Future = Env.Future;
+const Function = Env.Function;
+
+const Self = @This();
+
+pub inline fn get(self: anytype, env: *Env, key: anytype) AnyFuture {
+ return env.call(bindings.get, .{ self, key });
+}
+
+pub inline fn set(self: anytype, env: *Env, key: anytype, value: anytype) Future(void) {
+ return .fromAny(env.call(bindings.set, .{ self, key, value }));
+}
+
+pub inline fn delete(self: anytype, env: *Env, key: anytype) Future(void) {
+ return .fromAny(env.call(bindings.delete, .{ self, key }));
+}
+
+pub inline fn call(self: anytype, env: *Env, method: []const u8, args: anytype) AnyFuture {
+ return env.call(bindings.call, .{ self, method } ++ args);
+}
+
+pub inline fn free(self: anytype, env: *Env) Future(void) {
+ return .fromAny(env.call(bindings.free, .{self}));
+}
+
+pub inline fn new(self: anytype, env: *Env) Future(*Self) {
+ return .fromAny(env.call(bindings.new, .{self}));
+}
+
+pub fn global(tag: @EnumLiteral()) Options.Global {
+ return .{ .name = @tagName(tag), .type = *Self };
+}
+
+pub const bindings = struct {
+ pub const get: Function = .from(
+ \\function(target, key) {
+ \\ return target[key];
+ \\}
+ );
+
+ pub const set: Function = .from(
+ \\function(target, key, value) {
+ \\ target[key] = value;
+ \\}
+ );
+
+ pub const delete: Function = .from(
+ \\function(target, key) {
+ \\ delete target[key];
+ \\}
+ );
+
+ pub const call: Function = .from(
+ \\function(target, method, ...args) {
+ \\ return target[method](...args);
+ \\}
+ );
+
+ pub const new: Function = .from(
+ \\function(target, ...args) {
+ \\ return new target(...args);
+ \\}
+ );
+
+ pub const free: Function = .from(
+ \\function(target) {
+ \\ const id = target[ZsId];
+ \\ delete target[ZsId];
+ \\ delete ObjectStore.store[id];
+ \\}
+ );
+};
+
+pub const functions = [_]Function{
+ bindings.get,
+ bindings.set,
+ bindings.delete,
+ bindings.call,
+ bindings.new,
+ bindings.free,
+};
diff --git a/src/zilch/Promise.zig b/src/zilch/Promise.zig
new file mode 100644
index 0000000..7832b66
--- /dev/null
+++ b/src/zilch/Promise.zig
@@ -0,0 +1,62 @@
+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: anytype, 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 inline fn await(self: anytype, env: *Env, T: type) !T {
+ var future = env.call(bindings.await, .{ self });
+ return future.await(env, T);
+}
+
+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 await: Function = .from(
+ \\async function(promise) {
+ \\ return promise;
+ \\}
+ );
+};
+
+pub const functions = [_]Function{
+ bindings.then,
+ bindings.await,
+};
diff --git a/src/zilch/app/Options.zig b/src/zilch/app/Options.zig
new file mode 100644
index 0000000..db1742d
--- /dev/null
+++ b/src/zilch/app/Options.zig
@@ -0,0 +1,17 @@
+const mod = @import("../root.zig");
+const Fragment = mod.html.Fragment;
+const Component = mod.Component;
+const Env = mod.Env;
+
+name: []const u8,
+favicon: []const u8,
+functions: []const Env.Function,
+globals: []const Global,
+components: []const Component,
+body: Fragment,
+theme: []const u8,
+
+pub const Global = struct {
+ name: []const u8,
+ type: type,
+};
diff --git a/src/zilch/app/event.js b/src/zilch/app/event.js
new file mode 100644
index 0000000..9183bb5
--- /dev/null
+++ b/src/zilch/app/event.js
@@ -0,0 +1,16 @@
+async function wasm_handle_event(target, name, event, pass_event) {
+ await wasm_ready;
+
+ const component = target.getRootNode().host;
+
+ const handler = WebAssembly.promising(wasm.exports[name])
+
+ if (pass_event) {
+ const id = ObjectStore.generateFreeId();
+ ObjectStore.registerObject(id, event);
+ handler(component[ZsPtr], id);
+ ObjectStore.free(event);
+ } else {
+ handler(component[ZsPtr]);
+ }
+}
diff --git a/src/zilch/app/load.js b/src/zilch/app/load.js
new file mode 100644
index 0000000..ed3ab85
--- /dev/null
+++ b/src/zilch/app/load.js
@@ -0,0 +1,37 @@
+const imports = {
+ object_store: {
+ process: new WebAssembly.Suspending(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))
+ },
+ },
+};
+
+const wasm_ready = WebAssembly.instantiateStreaming(fetch("index.wasm"), imports).then(
+ ({ instance, module }) => {
+ const view = new DataView(instance.exports.memory.buffer);
+ const type_names = [ 'Call', 'Value', 'Ptr' ];
+ const size_of = {};
+
+ for (const type of type_names) {
+ size_of[type] = view.getUint16(instance.exports[`type::size::${type}`], true);
+ }
+
+ wasm = {
+ exports: instance.exports,
+ memory: instance.exports.memory,
+ size_of: size_of,
+ }
+ },
+);
diff --git a/src/zilch/app/object-store.js b/src/zilch/app/object-store.js
new file mode 100644
index 0000000..8a4715d
--- /dev/null
+++ b/src/zilch/app/object-store.js
@@ -0,0 +1,185 @@
+class ObjectStore {
+ static types = Object.freeze({
+ 0: "object",
+ 1: "string",
+ 2: "int",
+ 3: "uint",
+ 4: "float",
+ 5: "undefined",
+ 6: "future",
+
+ "object": 0,
+ "string": 1,
+ "int": 2,
+ "uint": 3,
+ "float": 4,
+ "undefined": 5,
+ "future": 6,
+ });
+
+ static store = { 0: null };
+ static methods = {};
+
+ static generateFreeId() {
+ let id = 0;
+
+ while (id in ObjectStore.store) {
+ id = Math.floor(Math.random() * (2**32 - 1))
+ }
+
+ return id;
+ }
+
+ static decodeString(base, len) {
+ const slice = new Uint8Array(wasm.memory.buffer, base, len);
+ return new TextDecoder().decode(slice);
+ }
+
+ static decodeCall(view, offset) {
+ const method = ObjectStore.methods[view.getUint32(offset, true)]
+
+ if (!method) throw "unknown method, cannot decode";
+
+ return {
+ method: method,
+ num_args: view.getUint8(offset + 4, true),
+ }
+ }
+
+ static decodeValue(view, offset, results) {
+ 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);
+ }
+
+ if (kind === 'future') {
+ return results[view.getUint32(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) {
+ if (ptr === 0) return;
+
+ 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.valueAllocBuffer(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 async 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);
+ const results = [];
+
+ for (let i = 0; i < length; ++i) {
+ const call = ObjectStore.decodeCall(calls_view, offset.call);
+ offset.call += wasm.size_of.Call;
+
+ let args = new Array(call.num_args).fill().map(_ => {
+ const value = ObjectStore.decodeValue(values_view, offset.value, results);
+ offset.value += wasm.size_of.Value;
+ return value;
+ });
+
+ let result = call.method.fn(...args);
+
+ if (call.method.await) {
+ result = await result;
+ }
+
+ const result_ptr = results_view.getUint32(offset.result, true);
+ offset.result += wasm.size_of.Ptr;
+
+ results.push(result);
+
+ ObjectStore.writeValue(result_ptr, result);
+ }
+ }
+}
diff --git a/src/zilch/app/root.document.zig b/src/zilch/app/root.document.zig
new file mode 100644
index 0000000..6191746
--- /dev/null
+++ b/src/zilch/app/root.document.zig
@@ -0,0 +1,87 @@
+const std = @import("std");
+
+const mod = @import("../root.zig");
+const Element = mod.html.Element;
+const Document = mod.html.Document;
+
+const Options = @import("Options.zig");
+
+pub fn App(comptime options: Options) type {
+ const components: []const Element, const registry: []const u8 = (comp: {
+ var cs: []const Element = &.{};
+ var registry: []const u8 = "const component_registry = {";
+
+ for (options.components) |component| {
+ cs = cs ++ component.toElement();
+ registry = registry ++ std.fmt.comptimePrint("{}: '{s}-{s}',", .{
+ component.id,
+ component.namespace,
+ component.name,
+ });
+ }
+
+ registry = registry ++ "};";
+
+ break :comp .{ cs, registry };
+ });
+
+ const functions: []const u8 = func: {
+ var buf: []const u8 = "ObjectStore.methods = {";
+
+ for (options.functions) |function| {
+ buf = buf ++ std.fmt.comptimePrint("{}: {{await: {}, fn: {s}}},", .{ function.id, function.await, function.content });
+ }
+
+ buf = buf ++ "}";
+
+ break :func buf;
+ };
+
+ return struct {
+ const node: Document = .{
+ .root = .node("html", .{}, &.{
+ .node("head", .{}, &.{
+ .node("title", .{}, &.{.text(options.name)}),
+ .void("link", .{ .rel = "icon", .href = options.favicon }),
+ .void("meta", .{
+ .name = "viewport",
+ .content = "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0",
+ }),
+ .void("meta", .{ .charset = "utf8" }),
+ .node("style", .{}, &.{.text(options.theme)}),
+ .node("script", .{}, &.{.text(@embedFile("symbols.js"))}),
+ .node("script", .{}, &.{.text(@embedFile("object-store.js"))}),
+ .node("script", .{}, &.{.text(functions)}),
+ .node("script", .{}, &.{.text(@embedFile("event.js"))}),
+ .node("script", .{}, &.{.text(@embedFile("load.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{
+ .node("script", .{}, &.{.text(registry)}),
+ } ++ components ++ options.body.elements,
+ ),
+ }),
+ };
+
+ html: []const u8 = str: {
+ @setEvalBranchQuota(100_000);
+ break :str std.fmt.comptimePrint("{f}", .{node});
+ },
+
+ pub const init: @This() = .{};
+ };
+}
diff --git a/src/zilch/app/root.wasm.zig b/src/zilch/app/root.wasm.zig
new file mode 100644
index 0000000..ea04192
--- /dev/null
+++ b/src/zilch/app/root.wasm.zig
@@ -0,0 +1,36 @@
+const std = @import("std");
+
+const Options = @import("Options.zig");
+
+pub fn App(comptime options: Options) type {
+ 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();
+ }
+ }
+ };
+}
diff --git a/src/zilch/app/root.zig b/src/zilch/app/root.zig
new file mode 100644
index 0000000..b2a8863
--- /dev/null
+++ b/src/zilch/app/root.zig
@@ -0,0 +1,15 @@
+const builtin = @import("builtin");
+const std = @import("std");
+
+const wasm = @import("root.wasm.zig");
+const document = @import("root.document.zig");
+
+pub const Options = @import("Options.zig");
+
+pub fn App(comptime options: Options) type {
+ if (builtin.target.cpu.arch.isWasm()) {
+ return wasm.App(options);
+ } else {
+ return document.App(options);
+ }
+}
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/bridge/root.zig b/src/zilch/bridge/root.zig
new file mode 100644
index 0000000..166aadc
--- /dev/null
+++ b/src/zilch/bridge/root.zig
@@ -0,0 +1,40 @@
+const std = @import("std");
+const builtin = @import("builtin");
+
+const mod = @import("../root.zig");
+const Env = mod.Env;
+const Function = Env.Function;
+
+const wasm = @import("wasm.root.zig");
+const server = @import("server.root.zig");
+
+pub fn Bridge(T: type) type {
+ if (builtin.target.cpu.arch.isWasm()) {
+ return wasm.Bridge(T);
+ } else {
+ return server.Bridge(T);
+ }
+}
+
+pub const Context = struct {
+ gpa: std.mem.Allocator,
+ arena: std.mem.Allocator,
+ io: std.Io,
+};
+
+pub const bindings = struct {
+ pub const call: Function = .from(
+ \\async function(ptr, len, result_ptr, len_check) {
+ \\ const response = await fetch("/api", {
+ \\ method: "POST",
+ \\ body: new DateView(wasm.memory.buffer, ptr, len),
+ \\ })
+ \\ const bytes = await response.bytes();
+ \\ if (bytes.length != len_check) {
+ \\ throw "response has incorrect size";
+ \\ }
+ \\ const memory = new Uint8Array(wasm.memory.buffer);
+ \\ memory.set(bytes, result_ptr);
+ \\}
+ );
+};
diff --git a/src/zilch/bridge/server.root.zig b/src/zilch/bridge/server.root.zig
new file mode 100644
index 0000000..504286c
--- /dev/null
+++ b/src/zilch/bridge/server.root.zig
@@ -0,0 +1,10 @@
+const std = @import("std");
+const http = @import("http");
+
+pub fn Bridge(T: type) type {
+ _ = T;
+ return struct {
+ pub fn handle() void {
+ }
+ };
+}
diff --git a/src/zilch/bridge/wasm.root.zig b/src/zilch/bridge/wasm.root.zig
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/src/zilch/bridge/wasm.root.zig
diff --git a/src/zilch/component.template.js b/src/zilch/component.template.js
new file mode 100644
index 0000000..553fe11
--- /dev/null
+++ b/src/zilch/component.template.js
@@ -0,0 +1,19 @@
+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() {{
+ if (this[ZsPtr] === null) {{
+ wasm_ready.then(async () => {{
+ const id = ObjectStore.generateFreeId();
+ ObjectStore.registerObject(id, this);
+ this[ZsPtr] = await WebAssembly.promising(wasm.exports['export::{s}::init'])(id);
+ }});
+ }}
+ }}
+}});
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..186d712
--- /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,
+ }, buf};
+ }
+
+ 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..ac67298
--- /dev/null
+++ b/src/zilch/log/root.zig
@@ -0,0 +1,55 @@
+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 {
+ 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;
+
+ writer.flush() catch unreachable;
+}
+
diff --git a/src/zilch/panic.zig b/src/zilch/panic.zig
new file mode 100644
index 0000000..7163c6d
--- /dev/null
+++ b/src/zilch/panic.zig
@@ -0,0 +1,9 @@
+const log = @import("log/root.zig");
+const std = @import("std");
+
+fn defaultPanic(msg: []const u8, _: ?usize) noreturn {
+ log.js.err(msg);
+ @trap();
+}
+
+pub const panic = std.debug.FullPanic(defaultPanic);
diff --git a/src/zilch/root.zig b/src/zilch/root.zig
new file mode 100644
index 0000000..bf0f1ad
--- /dev/null
+++ b/src/zilch/root.zig
@@ -0,0 +1,34 @@
+const builtin = @import("builtin");
+const std = @import("std");
+
+pub const Env = @import("Env/root.zig");
+pub const Call = Env.Call;
+pub const AnyFuture = Env.AnyFuture;
+pub const Future = Env.Future;
+pub const Value = Env.Value;
+
+pub const log = @import("log/root.zig");
+pub const html = @import("html/root.zig");
+
+pub const bridge = @import("bridge/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");
+
+pub const panic = @import("panic.zig").panic;
+
+const Ptr = struct { o: *anyopaque };
+comptime {
+ const export_sizes = .{ Call, Value, Ptr };
+
+ for (export_sizes) |T| {
+ const size: u16 = @sizeOf(T);
+ const name = @typeName(T)[if (std.mem.findScalarLast(u8, @typeName(T), '.')) |i| i + 1 else 0..];
+ @export(&size, .{ .name = std.fmt.comptimePrint("type::size::{s}", .{name}) });
+ }
+}