From a4b2398aba2211ce5901ceb46f73057864bd1707 Mon Sep 17 00:00:00 2001 From: Nathan Reiner Date: Tue, 6 Oct 2026 14:12:03 +0200 Subject: add global registry --- src/app/root.zig | 38 +++++-- src/main.zig | 4 +- src/z/App/main.js | 39 +++++++ src/z/App/object-store.js | 212 ++++++++++++++++++++++++++++++++++++++ src/z/App/root.zig | 66 ++++++++++++ src/z/AppBundle.zig | 26 +++-- src/z/Env/Object.zig | 29 ++++++ src/z/Env/root.zig | 7 +- src/z/app/main.js | 254 ---------------------------------------------- src/z/app/root.zig | 20 ---- src/z/root.zig | 14 ++- 11 files changed, 409 insertions(+), 300 deletions(-) create mode 100644 src/z/App/main.js create mode 100644 src/z/App/object-store.js create mode 100644 src/z/App/root.zig create mode 100644 src/z/Env/Object.zig delete mode 100644 src/z/app/main.js delete mode 100644 src/z/app/root.zig (limited to 'src') diff --git a/src/app/root.zig b/src/app/root.zig index 479af45..dcba16f 100644 --- a/src/app/root.zig +++ b/src/app/root.zig @@ -1,3 +1,4 @@ +const builtin = @import("builtin"); const std = @import("std"); const z = @import("z"); @@ -6,24 +7,33 @@ pub const std_options: std.Options = .{ .logFn = z.env.logFn, }; +pub const app: z.App(.{ .name = "Memora" }, .{ + .window = *z.Env.Object, + .Object = *z.Env.Object, +}) = .init; + +const js = struct { + const window = app.globals.window; + const Object = app.globals.Object; +}; + fn run_wrapped() !void { var env: z.Env = .init(std.heap.wasm_allocator); defer env.deinit(); - _ = env.setProp(z.Env.window, "my_prop", 45); - _ = env.deleteProp(z.Env.window, "my_prop"); + _ = js.window.set(&env, "my_prop", 45); + _ = js.window.delete(&env, "my_prop"); - const console = try env.getProp(z.Env.window, "console").await(&env, .object); - const object = try env.getProp(z.Env.window, "Object").await(&env, .object); - const location = try env.getProp(z.Env.window, "location").await(&env, .object); + const console = try app.globals.window.get(&env, "console").await(&env, .object); + const location = try app.globals.window.get(&env, "location").await(&env, .object); - const obj = env.new(object, .{}); - const hostname = try env.getProp(location, "hostname").await(&env, .string); + const obj = app.globals.Object.new(&env); + const hostname = try location.get(&env, "hostname").await(&env, .string); defer std.heap.wasm_allocator.free(hostname); - const call = env.callMethod( - console, - "log", + const call = console.call( + &env, + .log, .{ "hello, wasm!", try obj.await(&env), @@ -36,7 +46,7 @@ fn run_wrapped() !void { _ = env.free(console); } -export fn run() void { +fn run() callconv(.c) void { run_wrapped() catch |e| { var buffer: [1024]u8 = undefined; var writer: std.Io.Writer = .fixed(&buffer); @@ -46,3 +56,9 @@ export fn run() void { z.env.console.log(writer.buffered()); }; } + +comptime { + if (builtin.target.cpu.arch.isWasm()) { + @export(&run, .{ .name = "run" }); + } +} diff --git a/src/main.zig b/src/main.zig index bb8b34d..cb8c2ad 100644 --- a/src/main.zig +++ b/src/main.zig @@ -7,11 +7,11 @@ const std = @import("std"); const http = @import("http"); const api = @import("api"); -const z = @import("z"); +const site = @import("site"); const wasm = @embedFile("wasm"); const routes: http.RouteSet = .init(&([_]http.handler.Interface{ - http.handler.Static(.index, z.app.create(.{ .name = "Memora" }), "text/html").interface(), + http.handler.Static(.index, site.app.html, "text/html").interface(), http.handler.Static(.{"index.wasm"}, wasm, "application/wasm").interface(), }) ++ api.interfaces); diff --git a/src/z/App/main.js b/src/z/App/main.js new file mode 100644 index 0000000..6251a47 --- /dev/null +++ b/src/z/App/main.js @@ -0,0 +1,39 @@ +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)) + }, + } +} + +WebAssembly.instantiateStreaming(fetch("index.wasm"), imports).then( + ({ instance, module }) => { + const is64 = new Uint8Array( + instance.exports.memory.buffer, + instance.exports.bit_length, + 1, + )[0] == 8 + + window.wasm = { + exports: instance.exports, + memory: instance.exports.memory, + is64: is64, + UsizeArray: is64 ? BigUint64Array : Uint32Array, + IsizeArray: is64 ? BigInt64Array : Int32Array, + } + + wasm.exports.run(); + }, +); diff --git a/src/z/App/object-store.js b/src/z/App/object-store.js new file mode 100644 index 0000000..ae581f8 --- /dev/null +++ b/src/z/App/object-store.js @@ -0,0 +1,212 @@ +class ObjectStore { + static id_name = "@id"; + + 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[ObjectStore.id_name]; + delete target[ObjectStore.id_name]; + 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, ObjectStore.id_name, { + 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[ObjectStore.id_name]; + + 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/z/App/root.zig b/src/z/App/root.zig new file mode 100644 index 0000000..d684248 --- /dev/null +++ b/src/z/App/root.zig @@ -0,0 +1,66 @@ +const builtin = @import("builtin"); +const std = @import("std"); +const h = @import("html"); + +pub const Options = struct { name: []const u8 }; + +pub fn App(comptime options: Options, globals: anytype) type { + const info = @typeInfo(@TypeOf(globals)).@"struct"; + + if (builtin.target.cpu.arch.isWasm()) { + var names: [info.fields.len][]const u8 = undefined; + var types: [info.fields.len]type = undefined; + var attrs: [info.fields.len]std.builtin.Type.StructField.Attributes = undefined; + + for (info.fields, 0..) |field, index| { + names[index] = field.name; + types[index] = @field(globals, field.name); + attrs[index] = .{}; + } + + const G = @Struct(.auto, null, &names, &types, &attrs); + return struct { + globals: G = g: { + var gl: G = undefined; + + for (info.fields, 1..) |field, id| { + @field(gl, field.name) = @ptrFromInt(id); + } + + break :g gl; + }, + + pub const init: @This() = .{}; + }; + } else { + return struct { + html: []const u8 = h.Element.native(.html, .{}, .children(&.{ + .native(.head, .{}, .children(&.{ + .native(.title, .{}, .content(options.name)), + .native(.meta, .{ + .name = "viewport", + .content = "width=device-width, initial-scale=1.0", + }, .void), + })), + .native(.body, .{}, .children(&.{ + .native(.script, .{}, .content(@embedFile("object-store.js"))), + .native(.script, .{}, .content(reg: { + var register_code: []const u8 = ""; + + for (info.fields, 1..) |field, id| { + register_code = register_code ++ std.fmt.comptimePrint( + "ObjectStore.registerObject({}, {s});", + .{ id, field.name }, + ); + } + + break :reg register_code; + })), + .native(.script, .{}, .content(@embedFile("main.js"))), + })), + })).toDocument(), + + pub const init: @This() = .{}; + }; + } +} diff --git a/src/z/AppBundle.zig b/src/z/AppBundle.zig index 3fec9fb..a99de2c 100644 --- a/src/z/AppBundle.zig +++ b/src/z/AppBundle.zig @@ -2,34 +2,48 @@ const std = @import("std"); pub const Options = struct { root_source_file: std.Build.LazyPath, + target: std.Build.ResolvedTarget, }; mod: *std.Build.Module, -wasm: *std.Build.Step.Compile, +wasm: struct { + mod: *std.Build.Module, + exe: *std.Build.Step.Compile, +}, -pub fn init(b: *std.Build, options: Options) @This() { - const module = b.createModule(.{ +pub fn init(b: *std.Build, options: Options, z_mod: anytype) @This() { + const module = b.addModule("site", .{ + .root_source_file = options.root_source_file, + .target = options.target, + .imports = &.{ .{ .name = "z", .module = z_mod } }, + }); + + const wasm_module = b.createModule(.{ .root_source_file = options.root_source_file, .target = b.resolveTargetQuery(.{ .cpu_arch = .wasm32, .os_tag = .freestanding, }), + .imports = &.{ .{ .name = "z", .module = z_mod } }, }); const exe = b.addExecutable(.{ .name = "runtime", - .root_module = module, + .root_module = wasm_module, }); exe.rdynamic = true; exe.entry = .disabled; return .{ - .wasm = exe, .mod = module, + .wasm = .{ + .exe = exe, + .mod = wasm_module, + }, }; } pub fn getEmittedWasm(self: *const @This()) std.Build.LazyPath { - return self.wasm.getEmittedBin(); + return self.wasm.exe.getEmittedBin(); } diff --git a/src/z/Env/Object.zig b/src/z/Env/Object.zig new file mode 100644 index 0000000..77afa1f --- /dev/null +++ b/src/z/Env/Object.zig @@ -0,0 +1,29 @@ +const Env = @import("root.zig"); +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: @EnumLiteral(), args: anytype) AnyFuture { + return env.callMethod(self, @tagName(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, .{}); +} diff --git a/src/z/Env/root.zig b/src/z/Env/root.zig index 99b47c5..5a08362 100644 --- a/src/z/Env/root.zig +++ b/src/z/Env/root.zig @@ -1,6 +1,5 @@ const std = @import("std"); -const mod = @import("../root.zig"); const js = @import("js.zig"); const Self = @This(); @@ -10,9 +9,7 @@ const future = @import("future.zig"); pub const AnyFuture = future.AnyFuture; pub const Future = future.Future; pub const Value = @import("value.zig").Value; -pub const Object = extern struct {}; - -pub const window: *Object = @ptrFromInt(1); +pub const Object = @import("Object.zig"); calls: std.ArrayList(Call) = .empty, values: std.ArrayList(Value) = .empty, @@ -56,7 +53,7 @@ pub fn setProp( pub fn deleteProp( self: *Self, object: *Object, - key: []const u8, + key: anytype, ) Future(.undefined) { self.calls.append(self.gpa, .{ .kind = .del_prop, diff --git a/src/z/app/main.js b/src/z/app/main.js deleted file mode 100644 index e15f783..0000000 --- a/src/z/app/main.js +++ /dev/null @@ -1,254 +0,0 @@ -class ObjectStore { - static id_name = "@id"; - - 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[ObjectStore.id_name]; - delete target[ObjectStore.id_name]; - 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, ObjectStore.id_name, { - 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[ObjectStore.id_name]; - - 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); - } - } -} - -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)) - }, - } -} - -WebAssembly.instantiateStreaming(fetch("index.wasm"), imports).then( - ({ instance, module }) => { - const is64 = new Uint8Array( - instance.exports.memory.buffer, - instance.exports.bit_length, - 1, - )[0] == 8 - - window.wasm = { - exports: instance.exports, - memory: instance.exports.memory, - is64: is64, - UsizeArray: is64 ? BigUint64Array : Uint32Array, - IsizeArray: is64 ? BigInt64Array : Int32Array, - } - - ObjectStore.registerObject(1, window); - - wasm.exports.run(); - }, -); diff --git a/src/z/app/root.zig b/src/z/app/root.zig deleted file mode 100644 index 03760c4..0000000 --- a/src/z/app/root.zig +++ /dev/null @@ -1,20 +0,0 @@ -const html = @import("html"); - -pub const Options = struct { - name: []const u8 -}; - -pub fn create(options: Options) []const u8 { - return html.Element.native(.html, .{}, .children(&.{ - .native(.head, .{}, .children(&.{ - .native(.title, .{}, .content(options.name)), - .native(.meta, .{ - .name = "viewport", - .content = "width=device-width, initial-scale=1.0", - }, .void), - })), - .native(.body, .{}, .children(&.{ - .native(.script, .{}, .content(@embedFile("main.js"))), - })), - })).toDocument(); -} diff --git a/src/z/root.zig b/src/z/root.zig index 6ca6302..fc42acd 100644 --- a/src/z/root.zig +++ b/src/z/root.zig @@ -1,4 +1,5 @@ const builtin = @import("builtin"); +const std = @import("std"); const wasm = wasm_struct: { if (builtin.target.cpu.arch.isWasm()) { @@ -10,10 +11,19 @@ const wasm = wasm_struct: { }; } - break :wasm_struct struct {}; + break :wasm_struct struct { + pub const Env = struct { + pub const Object = struct {}; + }; + }; }; pub const env = wasm.env; pub const Env = wasm.Env; -pub const app = @import("app/root.zig"); +pub const App = @import("App/root.zig").App; + +pub const allocator: std.mem.Allocator = if (builtin.target.cpu.arch.isWasm()) .{ + .ptr = undefined, + .vtable = &std.heap.BrkAllocator.vtable, +} else .failing; -- cgit v1.2.3-70-g09d2