From 8dd8f96b24710dc4f2d29065928244a40a432379 Mon Sep 17 00:00:00 2001 From: Nathan Reiner Date: Mon, 26 Oct 2026 16:00:59 +0100 Subject: zilch: update App structure and split-up document and wasm logic --- src/zilch/App/event.js | 14 ---- src/zilch/App/load.js | 37 --------- src/zilch/App/object-store.js | 180 ---------------------------------------- src/zilch/App/root.zig | 136 ------------------------------ src/zilch/App/symbols.js | 2 - src/zilch/app/Options.zig | 17 ++++ src/zilch/app/event.js | 14 ++++ src/zilch/app/load.js | 37 +++++++++ src/zilch/app/object-store.js | 180 ++++++++++++++++++++++++++++++++++++++++ src/zilch/app/root.document.zig | 87 +++++++++++++++++++ src/zilch/app/root.wasm.zig | 36 ++++++++ src/zilch/app/root.zig | 15 ++++ src/zilch/app/symbols.js | 2 + src/zilch/root.zig | 4 +- 14 files changed, 390 insertions(+), 371 deletions(-) delete mode 100644 src/zilch/App/event.js delete mode 100644 src/zilch/App/load.js delete mode 100644 src/zilch/App/object-store.js delete mode 100644 src/zilch/App/root.zig delete mode 100644 src/zilch/App/symbols.js create mode 100644 src/zilch/app/Options.zig create mode 100644 src/zilch/app/event.js create mode 100644 src/zilch/app/load.js create mode 100644 src/zilch/app/object-store.js create mode 100644 src/zilch/app/root.document.zig create mode 100644 src/zilch/app/root.wasm.zig create mode 100644 src/zilch/app/root.zig create mode 100644 src/zilch/app/symbols.js (limited to 'src/zilch') diff --git a/src/zilch/App/event.js b/src/zilch/App/event.js deleted file mode 100644 index c55637c..0000000 --- a/src/zilch/App/event.js +++ /dev/null @@ -1,14 +0,0 @@ -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]); - } -} diff --git a/src/zilch/App/load.js b/src/zilch/App/load.js deleted file mode 100644 index e93a4a6..0000000 --- a/src/zilch/App/load.js +++ /dev/null @@ -1,37 +0,0 @@ -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)) - }, - } -} - -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 deleted file mode 100644 index 9a68478..0000000 --- a/src/zilch/App/object-store.js +++ /dev/null @@ -1,180 +0,0 @@ -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 kind = ObjectStore.methods[view.getUint32(offset, true)] - - if (!kind) throw "unknown method, cannot decode"; - - return { - kind: kind, - 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 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 method = ObjectStore.decodeCall(calls_view, offset.call); - offset.call += wasm.size_of.Call; - - let args = new Array(method.num_args).fill().map(_ => { - const value = ObjectStore.decodeValue(values_view, offset.value, results); - offset.value += wasm.size_of.Value; - return value; - }); - - const result = method.kind(...args); - 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.zig b/src/zilch/App/root.zig deleted file mode 100644 index e40b4e0..0000000 --- a/src/zilch/App/root.zig +++ /dev/null @@ -1,136 +0,0 @@ -const builtin = @import("builtin"); -const std = @import("std"); -const mod = @import("../root.zig"); -const Element = mod.html.Element; -const Document = mod.html.Document; -const Fragment = mod.html.Fragment; -const Component = mod.Component; -const Env = mod.Env; - -pub const Options = struct { - 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, - }; -}; - -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, 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("{}: {s},", .{ function.id, 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/symbols.js b/src/zilch/App/symbols.js deleted file mode 100644 index c0870c5..0000000 --- a/src/zilch/App/symbols.js +++ /dev/null @@ -1,2 +0,0 @@ -const ZsId = Symbol("zilch::id"); -const ZsPtr = Symbol("zilch::ptr"); 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..c55637c --- /dev/null +++ b/src/zilch/app/event.js @@ -0,0 +1,14 @@ +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]); + } +} diff --git a/src/zilch/app/load.js b/src/zilch/app/load.js new file mode 100644 index 0000000..e93a4a6 --- /dev/null +++ b/src/zilch/app/load.js @@ -0,0 +1,37 @@ +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)) + }, + } +} + +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..9a68478 --- /dev/null +++ b/src/zilch/app/object-store.js @@ -0,0 +1,180 @@ +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 kind = ObjectStore.methods[view.getUint32(offset, true)] + + if (!kind) throw "unknown method, cannot decode"; + + return { + kind: kind, + 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 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 method = ObjectStore.decodeCall(calls_view, offset.call); + offset.call += wasm.size_of.Call; + + let args = new Array(method.num_args).fill().map(_ => { + const value = ObjectStore.decodeValue(values_view, offset.value, results); + offset.value += wasm.size_of.Value; + return value; + }); + + const result = method.kind(...args); + 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..8e2ca61 --- /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("{}: {s},", .{ function.id, 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/root.zig b/src/zilch/root.zig index 25dfae7..e6112ae 100644 --- a/src/zilch/root.zig +++ b/src/zilch/root.zig @@ -14,8 +14,8 @@ 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 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; -- cgit v1.2.3-70-g09d2