From 32a251aa9645de070727a6ec91490d3e9219ec7c Mon Sep 17 00:00:00 2001 From: Nathan Reiner Date: Fri, 9 Oct 2026 14:01:20 +0200 Subject: rename z framework to zeroscript --- src/app/components/icons/root.zig | 8 +- src/app/components/navbutton/root.zig | 16 +-- src/app/components/root.zig | 4 +- src/app/root.zig | 12 +- src/root.zig | 2 +- src/z/App/main.js | 43 ------- src/z/App/object-store.js | 210 ---------------------------------- src/z/App/root.zig | 104 ----------------- src/z/App/symbols.js | 2 - src/z/AppBundle.zig | 49 -------- src/z/Component.zig | 190 ------------------------------ src/z/Env/call.zig | 16 --- src/z/Env/future.zig | 59 ---------- src/z/Env/js.zig | 22 ---- src/z/Env/root.zig | 162 -------------------------- src/z/Env/value.zig | 115 ------------------- src/z/Object.zig | 35 ------ src/z/html/Attribute.zig | 45 -------- src/z/html/Document.zig | 11 -- src/z/html/Fragment.zig | 15 --- src/z/html/Tag.zig | 53 --------- src/z/html/element.zig | 30 ----- src/z/html/parser.zig | 174 ---------------------------- src/z/html/root.zig | 6 - src/z/log/js.zig | 24 ---- src/z/log/root.zig | 28 ----- src/z/root.zig | 18 --- src/zeroscript/App/main.js | 43 +++++++ src/zeroscript/App/object-store.js | 210 ++++++++++++++++++++++++++++++++++ src/zeroscript/App/root.zig | 104 +++++++++++++++++ src/zeroscript/App/symbols.js | 2 + src/zeroscript/AppBundle.zig | 49 ++++++++ src/zeroscript/Component.zig | 190 ++++++++++++++++++++++++++++++ src/zeroscript/Env/call.zig | 16 +++ src/zeroscript/Env/future.zig | 59 ++++++++++ src/zeroscript/Env/js.zig | 22 ++++ src/zeroscript/Env/root.zig | 162 ++++++++++++++++++++++++++ src/zeroscript/Env/value.zig | 115 +++++++++++++++++++ src/zeroscript/Object.zig | 35 ++++++ src/zeroscript/html/Attribute.zig | 45 ++++++++ src/zeroscript/html/Document.zig | 11 ++ src/zeroscript/html/Fragment.zig | 15 +++ src/zeroscript/html/Tag.zig | 53 +++++++++ src/zeroscript/html/element.zig | 30 +++++ src/zeroscript/html/parser.zig | 174 ++++++++++++++++++++++++++++ src/zeroscript/html/root.zig | 6 + src/zeroscript/log/js.zig | 24 ++++ src/zeroscript/log/root.zig | 28 +++++ src/zeroscript/root.zig | 18 +++ 49 files changed, 1432 insertions(+), 1432 deletions(-) delete mode 100644 src/z/App/main.js delete mode 100644 src/z/App/object-store.js delete mode 100644 src/z/App/root.zig delete mode 100644 src/z/App/symbols.js delete mode 100644 src/z/AppBundle.zig delete mode 100644 src/z/Component.zig delete mode 100644 src/z/Env/call.zig delete mode 100644 src/z/Env/future.zig delete mode 100644 src/z/Env/js.zig delete mode 100644 src/z/Env/root.zig delete mode 100644 src/z/Env/value.zig delete mode 100644 src/z/Object.zig delete mode 100644 src/z/html/Attribute.zig delete mode 100644 src/z/html/Document.zig delete mode 100644 src/z/html/Fragment.zig delete mode 100644 src/z/html/Tag.zig delete mode 100644 src/z/html/element.zig delete mode 100644 src/z/html/parser.zig delete mode 100644 src/z/html/root.zig delete mode 100644 src/z/log/js.zig delete mode 100644 src/z/log/root.zig delete mode 100644 src/z/root.zig create mode 100644 src/zeroscript/App/main.js create mode 100644 src/zeroscript/App/object-store.js create mode 100644 src/zeroscript/App/root.zig create mode 100644 src/zeroscript/App/symbols.js create mode 100644 src/zeroscript/AppBundle.zig create mode 100644 src/zeroscript/Component.zig create mode 100644 src/zeroscript/Env/call.zig create mode 100644 src/zeroscript/Env/future.zig create mode 100644 src/zeroscript/Env/js.zig create mode 100644 src/zeroscript/Env/root.zig create mode 100644 src/zeroscript/Env/value.zig create mode 100644 src/zeroscript/Object.zig create mode 100644 src/zeroscript/html/Attribute.zig create mode 100644 src/zeroscript/html/Document.zig create mode 100644 src/zeroscript/html/Fragment.zig create mode 100644 src/zeroscript/html/Tag.zig create mode 100644 src/zeroscript/html/element.zig create mode 100644 src/zeroscript/html/parser.zig create mode 100644 src/zeroscript/html/root.zig create mode 100644 src/zeroscript/log/js.zig create mode 100644 src/zeroscript/log/root.zig create mode 100644 src/zeroscript/root.zig (limited to 'src') diff --git a/src/app/components/icons/root.zig b/src/app/components/icons/root.zig index a2b0fa6..298cfa6 100644 --- a/src/app/components/icons/root.zig +++ b/src/app/components/icons/root.zig @@ -1,16 +1,16 @@ -const z = @import("z"); +const zs = @import("zeroscript"); -pub const icons: []const z.Component = &.{ +pub const icons: []const zs.Component = &.{ icon("menu"), icon("upload"), icon("settings"), }; const Icon = struct { - pub fn init(_: *@This(), _: *z.Object) void {} + pub fn init(_: *@This(), _: *zs.Object) void {} }; -pub fn icon(name: []const u8) z.Component { +pub fn icon(name: []const u8) zs.Component { return .{ .namespace = "icon", .name = name, diff --git a/src/app/components/navbutton/root.zig b/src/app/components/navbutton/root.zig index 1078924..7704b90 100644 --- a/src/app/components/navbutton/root.zig +++ b/src/app/components/navbutton/root.zig @@ -1,23 +1,23 @@ const std = @import("std"); -const z = @import("z"); +const zs = @import("zeroscript"); const Self = @This(); -pub const component: z.Component = .{ +pub const component: zs.Component = .{ .name = "navbutton", .html = .parse(@embedFile("index.html")), .css = @embedFile("index.css"), .link = @This(), }; -element: *z.Object, -shadow_root: *z.Object, +element: *zs.Object, +shadow_root: *zs.Object, button: struct { - classList: *z.Object, + classList: *zs.Object, }, -pub fn init(self: *Self, element: *z.Object) !void { - var env: z.Env = .default; +pub fn init(self: *Self, element: *zs.Object) !void { + var env: zs.Env = .default; defer env.deinit(); self.element = element; @@ -28,7 +28,7 @@ pub fn init(self: *Self, element: *z.Object) !void { } pub fn open(self: *Self) !void { - var env: z.Env = .default; + var env: zs.Env = .default; defer env.deinit(); _ = self.button.classList.call(&env, "toggle", .{"open"}); diff --git a/src/app/components/root.zig b/src/app/components/root.zig index 934279f..131ddb7 100644 --- a/src/app/components/root.zig +++ b/src/app/components/root.zig @@ -1,7 +1,7 @@ -const z = @import("z"); +const zs = @import("zeroscript"); const icons = @import("icons/root.zig").icons; -pub const components: []const z.Component = &[_]z.Component{ +pub const components = &[_]zs.Component{ @import("navbutton/root.zig").component, } ++ icons; diff --git a/src/app/root.zig b/src/app/root.zig index 2b3554c..bbd07d2 100644 --- a/src/app/root.zig +++ b/src/app/root.zig @@ -1,19 +1,19 @@ const builtin = @import("builtin"); const std = @import("std"); -const z = @import("z"); +const zs = @import("zeroscript"); -pub const panic = z.panic; +pub const panic = zs.panic; pub const std_options: std.Options = .{ - .logFn = z.log.default, + .logFn = zs.log.default, }; const components = @import("components/root.zig").components; -pub const app: z.App(.{ +pub const app: zs.App(.{ .name = "Memora", .globals = &.{ - z.Object.global(.window), - z.Object.global(.Object), + zs.Object.global(.window), + zs.Object.global(.Object), }, .components = components, .body = .parse(@embedFile("index.html")), diff --git a/src/root.zig b/src/root.zig index 0cd7c71..dd32a7d 100644 --- a/src/root.zig +++ b/src/root.zig @@ -3,5 +3,5 @@ pub const db = @import("db"); pub const api = @import("api"); pub const html = @import("html"); -pub const z = @import("z"); +pub const zeroscript = @import("zeroscript"); pub const http = @import("http"); diff --git a/src/z/App/main.js b/src/z/App/main.js deleted file mode 100644 index 265c886..0000000 --- a/src/z/App/main.js +++ /dev/null @@ -1,43 +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)) - }, - } -} - -async function wasm_handle_event(target, name, event, pass_event) { - await wasm_ready; - - const component = target.getRootNode().host; - - if (pass_event) { - const id = ObjectStore.generateFreeId(); - ObjectStore.registerObject(id, event); - wasm.exports[name](component[ZsPtr], id); - ObjectStore.free(event); - } else { - wasm.exports[name](component[ZsPtr]); - } -} - -const wasm_ready = WebAssembly.instantiateStreaming(fetch("index.wasm"), imports).then( - ({ instance, module }) => { - wasm = { - exports: instance.exports, - memory: instance.exports.memory, - } - }, -); diff --git a/src/z/App/object-store.js b/src/z/App/object-store.js deleted file mode 100644 index 096d085..0000000 --- a/src/z/App/object-store.js +++ /dev/null @@ -1,210 +0,0 @@ -class ObjectStore { - static types = Object.freeze({ - 0: "uninit", - 1: "object", - 2: "string", - 3: "int", - 4: "uint", - 5: "float", - 6: "undefined", - - "uninit": 0, - "object": 1, - "string": 2, - "int": 3, - "uint": 4, - "float": 5, - "undefined": 6, - }); - - static methods = Object.freeze({ - 0: 'free', - 1: 'getProp', - 2: 'setProp', - 3: 'delProp', - 4: 'callMethod', - 5: 'call', - 6: 'new', - }); - - static store = { 0: null }; - - static generateFreeId() { - let id = 0; - - while (id in ObjectStore.store) { - id = Math.floor(Math.random() * (2**32 - 1)) - } - - return id; - } - - static free(target) { - const id = target[ZsId]; - delete target[ZsId]; - delete ObjectStore.store[id]; - } - - static getProp(target, key) { - return target[key]; - } - - static setProp(target, key, value) { - target[key] = value; - } - - static delProp(target, key) { - delete target[key]; - } - - static callMethod(target, method, ...args) { - return target[method](...args); - } - - static call(target, args) { - return target(args); - } - - static new(target, ...args) { - return new target(...args); - } - - static decodeString(base, len) { - const slice = new Uint8Array(wasm.memory.buffer, base, len); - return new TextDecoder().decode(slice); - } - - static decodeCall(view, offset) { - const kind = ObjectStore.methods[view.getUint8(offset, true)] - - if (!kind) throw "unknown method, cannot decode"; - - return { - kind: kind, - num_args: view.getUint8(offset + 1, true), - } - } - - static decodeValue(view, offset) { - const kind = ObjectStore.types[view.getUint8(offset, true)]; - - if (!kind) throw "unknown type, cannot decode"; - - if (kind === 'string') { - const ptr = view.getUint32(offset + 8, true) - const len = view.getUint32(offset + 12, true) - return ObjectStore.decodeString(ptr, len); - } - - if (kind === 'int') { - return view.getInt32(offset + 8, true); - } - - if (kind === 'uint') { - return view.getUint32(offset + 8, true); - } - - if (kind === 'object') { - const id = view.getUint32(offset + 8, true); - return ObjectStore.store[id]; - } - - if (kind === 'float') { - return view.getFloat64(offset + 8, true); - } - } - - static registerObject(id, obj) { - ObjectStore.store[id] = obj; - Object.defineProperty(obj, ZsId, { - enumerable: false, - writable: false, - configurable: true, - value: id, - }) - } - - static writeValue(ptr, value) { - const mem = new DataView(wasm.memory.buffer, ptr); - - if (typeof value === 'object' || typeof value === 'function') { - mem.setUint8(0, ObjectStore.types['object'], true); - let id = value == null ? 0 : value[ZsId]; - - if (id === undefined) { - id = ObjectStore.generateFreeId(); - ObjectStore.registerObject(id, value); - } - - mem.setUint32(8, id, true); - - return; - } - - if (typeof value === 'number' && Number.isInteger(value) && value >= 0) { - mem.setUint8(0, ObjectStore.types['uint'], true); - mem.setUint32(8, value, true) - return; - } - - if (typeof value === 'number' && Number.isInteger(value)) { - mem.setUint8(0, ObjectStore.types['int'], true); - mem.setInt32(8, value, true) - return; - } - - if (typeof value === 'number') { - mem.setUint8(0, ObjectStore.types['float'], true); - mem.setFloat64(8, value, true) - return; - } - - if (typeof value === 'string') { - const string_ptr = wasm.exports.valueAllocString(ptr, value.length); - const encoder = new TextEncoder(); - const string = encoder.encode(value); - const memory = new Uint8Array(wasm.memory.buffer); - memory.set(string, string_ptr); - return; - } - - if (typeof value === 'undefined') { - mem.setUint8(0, ObjectStore.types['undefined'], true); - return; - } - } - - static processWasm( - calls_base, - values_base, - result_base, - length, - ) { - const offset = { - call: 0, - value: 0, - result: 0, - } - - const calls_view = new DataView(wasm.memory.buffer, calls_base); - const values_view = new DataView(wasm.memory.buffer, values_base); - const results_view = new DataView(wasm.memory.buffer, result_base); - - for (let i = 0; i < length; ++i) { - const method = ObjectStore.decodeCall(calls_view, offset.call); - offset.call += 2; - - let args = new Array(method.num_args).fill().map(_ => { - const value = ObjectStore.decodeValue(values_view, offset.value); - offset.value += 16; - return value; - }); - - const result = ObjectStore[method.kind](...args); - const result_ptr = results_view.getUint32(offset.result, true); - offset.result += 4; - - ObjectStore.writeValue(result_ptr, result); - } - } -} diff --git a/src/z/App/root.zig b/src/z/App/root.zig deleted file mode 100644 index 52cbfc2..0000000 --- a/src/z/App/root.zig +++ /dev/null @@ -1,104 +0,0 @@ -const builtin = @import("builtin"); -const std = @import("std"); -const Element = @import("../root.zig").html.Element; -const Document = @import("../root.zig").html.Document; -const Fragment = @import("../root.zig").html.Fragment; -const Component = @import("../root.zig").Component; - -pub const Options = struct { - name: []const u8, - globals: []const Global, - components: []const Component, - body: Fragment, - theme: []const u8, - - pub const Global = struct { - name: []const u8, - type: type, - }; -}; - -pub fn App(comptime options: Options) type { - if (builtin.target.cpu.arch.isWasm()) { - var names: [options.globals.len][]const u8 = undefined; - var types: [options.globals.len]type = undefined; - var attrs: [options.globals.len]std.builtin.Type.StructField.Attributes = undefined; - - for (options.globals, 0..) |field, index| { - names[index] = field.name; - types[index] = field.type; - attrs[index] = .{}; - } - - const G = @Struct(.auto, null, &names, &types, &attrs); - return struct { - globals: G = g: { - var gl: G = undefined; - - for (options.globals, 1..) |field, id| { - @field(gl, field.name) = @ptrFromInt(id); - } - - break :g gl; - }, - - pub const init: @This() = .{}; - - comptime { - for (options.components) |component| { - component.exportLinks(); - } - } - }; - } else { - const components: []const Element = (comp: { - var cs: []const Element = &.{}; - - for (options.components) |component| { - cs = cs ++ component.toElement(); - } - - break :comp cs; - }); - - return struct { - const node: Document = .{ - .root = .node("html", .{}, &.{ - .node("head", .{}, &.{ - .node("title", .{}, &.{.text(options.name)}), - .void("meta", .{ - .name = "viewport", - .content = "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0", - }), - .node("style", .{}, &.{.text(options.theme)}), - .node("script", .{}, &.{.text(@embedFile("symbols.js"))}), - .node("script", .{}, &.{.text(@embedFile("object-store.js"))}), - .node("script", .{}, &.{.text(@embedFile("main.js"))}), - .node("script", .{}, &.{.text(reg: { - var register_code: []const u8 = ""; - - for (options.globals, 1..) |field, id| { - register_code = register_code ++ std.fmt.comptimePrint( - "ObjectStore.registerObject({}, {s});", - .{ id, field.name }, - ); - } - - break :reg register_code; - })}), - }), - .node( - "body", - .{}, - &[_]Element{ - } ++ components ++ options.body.elements, - ), - }), - }; - - html: []const u8 = std.fmt.comptimePrint("{f}", .{node}), - - pub const init: @This() = .{}; - }; - } -} diff --git a/src/z/App/symbols.js b/src/z/App/symbols.js deleted file mode 100644 index 3df42b4..0000000 --- a/src/z/App/symbols.js +++ /dev/null @@ -1,2 +0,0 @@ -const ZsId = Symbol("zeroscript::id"); -const ZsPtr = Symbol("zeroscript::ptr"); diff --git a/src/z/AppBundle.zig b/src/z/AppBundle.zig deleted file mode 100644 index a99de2c..0000000 --- a/src/z/AppBundle.zig +++ /dev/null @@ -1,49 +0,0 @@ -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, 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 = wasm_module, - }); - - exe.rdynamic = true; - exe.entry = .disabled; - - return .{ - .mod = module, - .wasm = .{ - .exe = exe, - .mod = wasm_module, - }, - }; -} - -pub fn getEmittedWasm(self: *const @This()) std.Build.LazyPath { - return self.wasm.exe.getEmittedBin(); -} diff --git a/src/z/Component.zig b/src/z/Component.zig deleted file mode 100644 index 2f92b70..0000000 --- a/src/z/Component.zig +++ /dev/null @@ -1,190 +0,0 @@ -const std = @import("std"); -const Fragment = @import("root.zig").html.Fragment; -const Element = @import("root.zig").html.Element; -const Attribute = @import("root.zig").html.Attribute; -const Object = @import("Object.zig"); - -const Self = @This(); - -namespace: []const u8 = "app", -name: []const u8, -html: Fragment, -css: []const u8, -link: type, - -fn handlerNeedsEvent(func: anytype) bool { - const T = @TypeOf(func); - return @typeInfo(T).@"fn".params.len == 2; -} - -fn wrapHandler(ret: anytype) void { - const T = @TypeOf(ret); - const ret_info = @typeInfo(T); - - if (ret_info == .error_union) { - ret catch |err| { - std.log.err("error: {}", .{err}); - }; - } -} - -fn exportFromHtml(self: *const Self, element: Element) void { - comptime { - switch (element) { - .tag => |tag| for (tag.attributes) |attr| { - if (attr.value.len > 0 and attr.value[0] == '@') { - const event_handler = @field(self.link, attr.value[1..]); - - const func = - if (handlerNeedsEvent(event_handler)) - struct { - pub fn func(obj: *self.link, event: *Object) callconv(.c) void { - wrapHandler(event_handler(obj, event)); - } - }.func - else - struct { - pub fn func(obj: *self.link) callconv(.c) void { - wrapHandler(event_handler(obj)); - } - }.func; - - @export( - &func, - .{ - .name = std.fmt.comptimePrint( - "export::{s}::{s}", - .{ self.name, attr.value[1..] }, - ), - }, - ); - } - - switch (tag.content) { - .children => |children| for (children) |child| { - self.exportFromHtml(child); - }, - else => {}, - } - }, - else => {}, - } - } -} - -pub fn exportLinks(self: *const Self) void { - const init = struct { - pub fn init(element: *Object) callconv(.c) ?*self.link { - const obj = std.heap.wasm_allocator.create(self.link) catch return null; - 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( - \\customElements.define("{s}-{s}", class extends HTMLElement {{ - \\ constructor() {{ - \\ super(); - \\ this.attachShadow({{ mode: 'open' }}); - \\ const template = document.getElementById("@{s}"); - \\ const node = document.importNode(template.content, true); - \\ this.shadowRoot.appendChild(node); - \\ this[ZsPtr] = null; - \\ }} - \\ connectedCallback() {{ - \\ wasm_ready.then(() => {{ - \\ const id = ObjectStore.generateFreeId(); - \\ ObjectStore.registerObject(id, this); - \\ this[ZsPtr] = wasm.exports['export::{s}::init'](id) - \\ }}); - \\ }} - \\}}) - , .{ self.namespace, self.name, self.name, self.name }), - )}, - ), - }; -} diff --git a/src/z/Env/call.zig b/src/z/Env/call.zig deleted file mode 100644 index a5db835..0000000 --- a/src/z/Env/call.zig +++ /dev/null @@ -1,16 +0,0 @@ - -pub const Call = extern struct { - kind: Kind, - num_args: u8, - - const Kind = enum(u8) { - free = 0, - get_prop = 1, - set_prop = 2, - del_prop = 3, - call_method = 4, - call = 5, - new = 6, - }; -}; - diff --git a/src/z/Env/future.zig b/src/z/Env/future.zig deleted file mode 100644 index a014990..0000000 --- a/src/z/Env/future.zig +++ /dev/null @@ -1,59 +0,0 @@ -const std = @import("std"); -const Env = @import("root.zig"); -const z = @import("../root.zig"); - - -pub fn Future(comptime kind: Env.Value.Kind) type { - return struct { - const Self = @This(); - - future: AnyFuture, - - pub fn fromAny(future: AnyFuture) Self { - return .{ .future = future }; - } - - pub fn await(self: *const Self, env: *Env) !kind.asType() { - return self.future.await(env, kind); - } - }; -} - -pub const AnyFuture = union(enum) { - const Self = @This(); - - result: *Env.Value, - err: anyerror, - - pub fn await(self: *const Self, env: *Env, comptime kind: Env.Value.Kind) !kind.asType() { - const result = try self.awaitAny(env); - - if (kind != result.kind) { - std.log.err("unexpected {}, expected {}", .{ result.kind, kind }); - @panic("type error"); - } - - return switch (kind) { - .uninit => @panic("uninitialized result"), - .string => result.value.string.ptr[0..result.value.string.len], - else => @field(result.value, @tagName(kind)), - }; - } - - pub fn awaitAny(self: *const Self, env: *Env) !Env.Value { - switch (self.*) { - .err => |err| return err, - .result => |result| { - defer env.pool.destroy(result); - - if (result.kind != .uninit) { - return result.*; - } - - env.flush(); - - return result.*; - } - } - } -}; diff --git a/src/z/Env/js.zig b/src/z/Env/js.zig deleted file mode 100644 index c1ff85d..0000000 --- a/src/z/Env/js.zig +++ /dev/null @@ -1,22 +0,0 @@ -const std = @import("std"); -const Env = @import("root.zig"); - -pub extern "object_store" fn process( - [*]const Env.Call, - [*]const Env.Value, - [*]*Env.Value, - length: usize, -) void; - -export fn valueAllocString(value: *Env.Value, len: usize) [*]u8 { - const ptr: [*]u8 = @ptrCast(std.heap.wasm_allocator.alloc(u8, len) catch @panic("unable to allocate string")); - value.kind = .string; - value.value = .{ - .string = .{ - .ptr = ptr, - .len = len, - }, - }; - - return @constCast(value.value.string.ptr); -} diff --git a/src/z/Env/root.zig b/src/z/Env/root.zig deleted file mode 100644 index 6fd2bab..0000000 --- a/src/z/Env/root.zig +++ /dev/null @@ -1,162 +0,0 @@ -const std = @import("std"); - -const Self = @This(); - -const js = @import("js.zig"); -const future = @import("future.zig"); -const Object = @import("../Object.zig"); - -pub const Call = @import("call.zig").Call; -pub const AnyFuture = future.AnyFuture; -pub const Future = future.Future; -pub const Value = @import("value.zig").Value; - -calls: std.ArrayList(Call) = .empty, -values: std.ArrayList(Value) = .empty, -pool: std.heap.MemoryPool(Value) = .empty, -results: std.ArrayList(*Value) = .empty, -gpa: std.mem.Allocator, - -pub const default: Self = .{ .gpa = std.heap.wasm_allocator }; - -pub fn init(gpa: std.mem.Allocator) Self { - return .{ .gpa = gpa }; -} - -pub fn getProp(self: *Self, object: *Object, key: anytype) AnyFuture { - self.calls.append(self.gpa, .{ - .kind = .get_prop, - .num_args = 2, - }) catch |err| return .{ .err = err }; - self.values.append(self.gpa, .from(object)) catch |err| return .{ .err = err }; - self.values.append(self.gpa, .from(key)) catch |err| return .{ .err = err }; - - return self.registerFuture() catch |err| .{ .err = err }; -} - -pub fn setProp( - self: *Self, - object: *Object, - key: anytype, - value: anytype, -) Future(.undefined) { - self.calls.append(self.gpa, .{ - .kind = .set_prop, - .num_args = 3, - }) catch |err| return .fromAny(.{ .err = err }); - - self.values.append(self.gpa, .from(object)) catch |err| return .fromAny(.{ .err = err }); - self.values.append(self.gpa, .from(key)) catch |err| return .fromAny(.{ .err = err }); - self.values.append(self.gpa, .from(value)) catch |err| return .fromAny(.{ .err = err }); - - return .fromAny(self.registerFuture() catch |err| .{ .err = err }); -} - -pub fn deleteProp( - self: *Self, - object: *Object, - key: anytype, -) Future(.undefined) { - self.calls.append(self.gpa, .{ - .kind = .del_prop, - .num_args = 2, - }) catch |err| return .fromAny(.{ .err = err }); - - self.values.append(self.gpa, .from(object)) catch |err| return .fromAny(.{ .err = err }); - self.values.append(self.gpa, .from(key)) catch |err| return .fromAny(.{ .err = err }); - - return .fromAny(self.registerFuture() catch |err| .{ .err = err }); -} - -pub fn callMethod( - self: *Self, - object: *Object, - key: []const u8, - args: anytype, -) AnyFuture { - self.calls.append(self.gpa, .{ - .kind = .call_method, - .num_args = 2 + args.len, - }) catch |err| return .{ .err = err }; - - self.values.append(self.gpa, .from(object)) catch |err| return .{ .err = err }; - self.values.append(self.gpa, .from(key)) catch |err| return .{ .err = err }; - - inline for (args) |arg| { - self.values.append(self.gpa, .from(arg)) catch |err| return .{ .err = err }; - } - - return self.registerFuture() catch |err| return .{ .err = err }; -} - -pub fn call(self: *Self, object: *Object, args: anytype) AnyFuture { - self.calls.append(self.gpa, .{ - .kind = .call, - .num_args = 1 + args.len, - }) catch |err| return .{ .err = err }; - - self.values.append(self.gpa, .from(object)) catch |err| return .{ .err = err }; - - inline for (args) |arg| { - self.values.append(self.gpa, .from(arg)) catch |err| return .{ .err = err }; - } - - return self.registerFuture() catch |err| return .{ .err = err }; -} - -pub fn free(self: *Self, object: *Object) Future(.undefined) { - self.calls.append(self.gpa, .{ - .kind = .free, - .num_args = 1, - }) catch |err| return .fromAny(.{ .err = err }); - - self.values.append(self.gpa, .from(object)) catch |err| return .fromAny(.{ .err = err }); - - return .fromAny(self.registerFuture() catch |err| .{ .err = err }); -} - -pub fn new(self: *Self, object: *Object, args: anytype) Future(.object) { - self.calls.append(self.gpa, .{ - .kind = .new, - .num_args = 1 + args.len, - }) catch |err| return .fromAny(.{ .err = err }); - - self.values.append(self.gpa, .from(object)) catch |err| return .fromAny(.{ .err = err }); - - inline for (args) |arg| { - self.values.append(self.gpa, .from(arg)) catch |err| return .fromAny(.{ .err = err }); - } - - return .fromAny(self.registerFuture() catch |err| .{ .err = err }); -} - -fn registerFuture(self: *Self) !AnyFuture { - const result = try self.pool.create(self.gpa); - errdefer self.pool.destroy(result); - result.kind = .uninit; - try self.results.append(self.gpa, result); - return .{ .result = result }; -} - -pub fn flush(self: *Self) void { - js.process( - @ptrCast(self.calls.items), - @ptrCast(self.values.items), - @ptrCast(self.results.items), - self.results.items.len, - ); - self.calls.clearRetainingCapacity(); - self.values.clearRetainingCapacity(); - self.results.clearRetainingCapacity(); -} - -pub fn deinit(self: *Self) void { - self.flush(); - - self.calls.deinit(self.gpa); - self.values.deinit(self.gpa); - self.pool.deinit(self.gpa); - self.results.deinit(self.gpa); - - self.* = undefined; -} diff --git a/src/z/Env/value.zig b/src/z/Env/value.zig deleted file mode 100644 index 59b788f..0000000 --- a/src/z/Env/value.zig +++ /dev/null @@ -1,115 +0,0 @@ -const std = @import("std"); -const Object = @import("../Object.zig"); - -pub fn isString(comptime T: type) bool { - return comptime blk: { - const info = @typeInfo(T); - if (info != .pointer) break :blk false; - - const ptr = &info.pointer; - if (ptr.is_volatile or ptr.is_allowzero) break :blk false; - - if (ptr.size == .slice) { - break :blk ptr.child == u8; - } - - if (ptr.size == .one) { - const child = @typeInfo(ptr.child); - if (child == .array) { - const arr = &child.array; - break :blk arr.child == u8; - } - } - - break :blk false; - }; -} - -pub const Value = extern struct { - kind: Kind, - value: extern union { - object: *Object, - string: extern struct { - ptr: [*]const u8, - len: usize, - }, - int: isize, - uint: usize, - float: f64, - undefined: void, - }, - - pub fn from(value: anytype) Value { - const T = @TypeOf(value); - - return switch (T) { - *Object => .{ - .kind = .object, - .value = .{ .object = value }, - }, - comptime_int => if (value >= 0) .{ - .kind = .uint, - .value = .{ .uint = value }, - } else .{ - .kind = .int, - .value = .{ .int = value }, - }, - usize => .{ - .kind = .uint, - .value = .{ .uint = value }, - }, - isize => .{ - .kind = .int, - .value = .{ .int = value }, - }, - f64, f32, f16 => .{ - .kind = .float, - .value = .{ .float = value }, - }, - void => .{ - .kind = .undefined, - .value = .{ .undefined = {} }, - }, - else => str: { - if (comptime isString(T)) { - break :str .{ - .kind = .string, - .value = .{ - .string = .{ - .ptr = @ptrCast(value), - .len = value.len, - }, - }, - }; - } else { - @compileError(std.fmt.comptimePrint( - "cannot auto convert type '{}'.", - .{T}, - )); - } - }, - }; - } - - pub const Kind = enum(u8) { - uninit = 0, - object = 1, - string = 2, - int = 3, - uint = 4, - float = 5, - undefined = 6, - - pub fn asType(comptime self: Kind) type { - return switch (self) { - .object => return *Object, - .string => return []const u8, - .int => return isize, - .uint => return usize, - .float => f64, - .undefined => return void, - .uninit => @compileError("uninit has no associated type."), - }; - } - }; -}; diff --git a/src/z/Object.zig b/src/z/Object.zig deleted file mode 100644 index 064d48b..0000000 --- a/src/z/Object.zig +++ /dev/null @@ -1,35 +0,0 @@ -const mod = @import("root.zig"); -const Options = mod.Options; -const Env = mod.Env; -const AnyFuture = Env.AnyFuture; -const Future = Env.Future; - -const Self = @This(); - -pub inline fn get(self: *Self, env: *Env, key: anytype) AnyFuture { - return env.getProp(self, key); -} - -pub inline fn set(self: *Self, env: *Env, key: anytype, value: anytype) Future(.undefined) { - return env.setProp(self, key, value); -} - -pub inline fn delete(self: *Self, env: *Env, key: anytype) Future(.undefined) { - return env.deleteProp(self, key); -} - -pub inline fn call(self: *Self, env: *Env, method: []const u8, args: anytype) AnyFuture { - return env.callMethod(self, method, args); -} - -pub inline fn free(self: *Self, env: *Env) Future(.undefined) { - return env.free(self); -} - -pub fn new(self: *Self, env: *Env) Future(.object) { - return env.new(self, .{}); -} - -pub fn global(tag: @EnumLiteral()) Options.Global { - return .{ .name = @tagName(tag), .type = *Self }; -} diff --git a/src/z/html/Attribute.zig b/src/z/html/Attribute.zig deleted file mode 100644 index 1db49a0..0000000 --- a/src/z/html/Attribute.zig +++ /dev/null @@ -1,45 +0,0 @@ -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("""); - value = value[index + 1..]; - } - - try writer.writeAll(value); - try writer.writeByte('"'); -} diff --git a/src/z/html/Document.zig b/src/z/html/Document.zig deleted file mode 100644 index b1122e1..0000000 --- a/src/z/html/Document.zig +++ /dev/null @@ -1,11 +0,0 @@ -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("{f}", .{self.root}); -} diff --git a/src/z/html/Fragment.zig b/src/z/html/Fragment.zig deleted file mode 100644 index d05ad4a..0000000 --- a/src/z/html/Fragment.zig +++ /dev/null @@ -1,15 +0,0 @@ -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/z/html/Tag.zig b/src/z/html/Tag.zig deleted file mode 100644 index 90b5641..0000000 --- a/src/z/html/Tag.zig +++ /dev/null @@ -1,53 +0,0 @@ -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("", .{self.name}); - }, - .void => {}, - } -} diff --git a/src/z/html/element.zig b/src/z/html/element.zig deleted file mode 100644 index 739eb0b..0000000 --- a/src/z/html/element.zig +++ /dev/null @@ -1,30 +0,0 @@ -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/z/html/parser.zig b/src/z/html/parser.zig deleted file mode 100644 index 38b28bb..0000000 --- a/src/z/html/parser.zig +++ /dev/null @@ -1,174 +0,0 @@ -const std = @import("std"); -const mod = @import("root.zig"); -const Element = mod.Element; -const Attribute = mod.Attribute; -const Tag = mod.Tag; -const Fragment = mod.Fragment; - -const tag_name: []const u8 = std.ascii.letters ++ .{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-' }; -const void_elements: std.StaticStringMap(void) = .initComptime(.{ - .{"area"}, - .{"base"}, - .{"br"}, - .{"col"}, - .{"embed"}, - .{"hr"}, - .{"img"}, - .{"input"}, - .{"link"}, - .{"meta"}, - .{"param"}, - .{"source"}, - .{"track"}, - .{"wbr"}, -}); - -pub fn fragment(buffer: []const u8) Fragment { - @setEvalBranchQuota(buffer.len * 1000); - var elements: []const Element = &.{}; - var buf = buffer; - - while (buf.len > 0) { - const e, buf = element(buf); - elements = elements ++ .{e}; - } - - return .{ .elements = elements }; -} - -pub fn element(buffer: []const u8) struct { Element, []const u8 } { - if (buffer.len == 0) @panic("EOB, expected element"); - - switch (buffer[0]) { - '<' => { - const t, const b = tag(buffer); - return .{ .{ .tag = t }, b }; - }, - else => { - const t, const b = text(buffer); - return .{ .{ .string = t }, b }; - }, - } -} - -pub fn tag(buffer: []const u8) struct { Tag, []const u8 } { - if (buffer.len == 0) @panic("EOB, expected tag"); - - if (buffer[0] != '<') @panic("expected '<'"); - - var buf: []const u8 = buffer[1..]; - - const name = name: { - const index = std.mem.findNone(u8, buf, tag_name) orelse @panic("uncosed tag"); - defer buf = buf[index..]; - break :name buf[0..index]; - }; - - buf = std.mem.trimStart(u8, buf, &std.ascii.whitespace); - - var attributes: []const Attribute = &.{}; - - while (buf.len > 0 and buf[0] != '>') { - buf = std.mem.trimStart(u8, buf, &std.ascii.whitespace); - const attr, buf = attribute(buf); - attributes = attributes ++ .{attr}; - } - - if (buf.len == 0 or buf[0] != '>') @panic("expected tag-close"); - - buf = buf[1..]; - - if (void_elements.has(name)) { - return .{.{ - .name = name, - .attributes = attributes, - .content = .void, - }}; - } - - var children: []const Element = &.{}; - - buf = std.mem.trimStart(u8, buf, &std.ascii.whitespace); - - const closing = std.fmt.comptimePrint("", .{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/z/html/root.zig b/src/z/html/root.zig deleted file mode 100644 index 7bf91e8..0000000 --- a/src/z/html/root.zig +++ /dev/null @@ -1,6 +0,0 @@ -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/z/log/js.zig b/src/z/log/js.zig deleted file mode 100644 index 16f562c..0000000 --- a/src/z/log/js.zig +++ /dev/null @@ -1,24 +0,0 @@ - -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/z/log/root.zig b/src/z/log/root.zig deleted file mode 100644 index ba9141e..0000000 --- a/src/z/log/root.zig +++ /dev/null @@ -1,28 +0,0 @@ -const std = @import("std"); - -pub const js = @import("js.zig"); - -pub fn default( - comptime level: std.log.Level, - comptime scope: @EnumLiteral(), - comptime format: []const u8, - args: anytype, -) void { - var buffer: [1024]u8 = undefined; - var writer: std.Io.Writer = .fixed(&buffer); - - const func = switch (level) { - .err => js.err, - .warn => js.warn, - .info => js.log, - .debug => js.debug, - }; - - if (scope != .default) { - writer.print("[{s}]: ", .{@tagName(scope)}) catch unreachable; - } - writer.print(format, args) catch unreachable; - - func(writer.buffered()); -} - diff --git a/src/z/root.zig b/src/z/root.zig deleted file mode 100644 index 321bde4..0000000 --- a/src/z/root.zig +++ /dev/null @@ -1,18 +0,0 @@ -const builtin = @import("builtin"); -const std = @import("std"); - -pub const log = @import("log/root.zig"); -pub const Env = @import("Env/root.zig"); -pub const Object = @import("Object.zig"); -pub const html = @import("html/root.zig"); - -pub const App = @import("App/root.zig").App; -pub const Options = @import("App/root.zig").Options; -pub const Component = @import("Component.zig"); - -fn defaultPanic(msg: []const u8, _: ?usize) noreturn { - log.js.err(msg); - @trap(); -} - -pub const panic = std.debug.FullPanic(defaultPanic); diff --git a/src/zeroscript/App/main.js b/src/zeroscript/App/main.js new file mode 100644 index 0000000..265c886 --- /dev/null +++ b/src/zeroscript/App/main.js @@ -0,0 +1,43 @@ +const imports = { + object_store: { + process: ObjectStore.processWasm, + }, + console: { + log(buffer, length) { + console.log(ObjectStore.decodeString(buffer, length)) + }, + warn(buffer, length) { + console.warn(ObjectStore.decodeString(buffer, length)) + }, + err(buffer, length) { + console.error(ObjectStore.decodeString(buffer, length)) + }, + debug(buffer, length) { + console.debug(ObjectStore.decodeString(buffer, length)) + }, + } +} + +async function wasm_handle_event(target, name, event, pass_event) { + await wasm_ready; + + const component = target.getRootNode().host; + + if (pass_event) { + const id = ObjectStore.generateFreeId(); + ObjectStore.registerObject(id, event); + wasm.exports[name](component[ZsPtr], id); + ObjectStore.free(event); + } else { + wasm.exports[name](component[ZsPtr]); + } +} + +const wasm_ready = WebAssembly.instantiateStreaming(fetch("index.wasm"), imports).then( + ({ instance, module }) => { + wasm = { + exports: instance.exports, + memory: instance.exports.memory, + } + }, +); diff --git a/src/zeroscript/App/object-store.js b/src/zeroscript/App/object-store.js new file mode 100644 index 0000000..096d085 --- /dev/null +++ b/src/zeroscript/App/object-store.js @@ -0,0 +1,210 @@ +class ObjectStore { + static types = Object.freeze({ + 0: "uninit", + 1: "object", + 2: "string", + 3: "int", + 4: "uint", + 5: "float", + 6: "undefined", + + "uninit": 0, + "object": 1, + "string": 2, + "int": 3, + "uint": 4, + "float": 5, + "undefined": 6, + }); + + static methods = Object.freeze({ + 0: 'free', + 1: 'getProp', + 2: 'setProp', + 3: 'delProp', + 4: 'callMethod', + 5: 'call', + 6: 'new', + }); + + static store = { 0: null }; + + static generateFreeId() { + let id = 0; + + while (id in ObjectStore.store) { + id = Math.floor(Math.random() * (2**32 - 1)) + } + + return id; + } + + static free(target) { + const id = target[ZsId]; + delete target[ZsId]; + delete ObjectStore.store[id]; + } + + static getProp(target, key) { + return target[key]; + } + + static setProp(target, key, value) { + target[key] = value; + } + + static delProp(target, key) { + delete target[key]; + } + + static callMethod(target, method, ...args) { + return target[method](...args); + } + + static call(target, args) { + return target(args); + } + + static new(target, ...args) { + return new target(...args); + } + + static decodeString(base, len) { + const slice = new Uint8Array(wasm.memory.buffer, base, len); + return new TextDecoder().decode(slice); + } + + static decodeCall(view, offset) { + const kind = ObjectStore.methods[view.getUint8(offset, true)] + + if (!kind) throw "unknown method, cannot decode"; + + return { + kind: kind, + num_args: view.getUint8(offset + 1, true), + } + } + + static decodeValue(view, offset) { + const kind = ObjectStore.types[view.getUint8(offset, true)]; + + if (!kind) throw "unknown type, cannot decode"; + + if (kind === 'string') { + const ptr = view.getUint32(offset + 8, true) + const len = view.getUint32(offset + 12, true) + return ObjectStore.decodeString(ptr, len); + } + + if (kind === 'int') { + return view.getInt32(offset + 8, true); + } + + if (kind === 'uint') { + return view.getUint32(offset + 8, true); + } + + if (kind === 'object') { + const id = view.getUint32(offset + 8, true); + return ObjectStore.store[id]; + } + + if (kind === 'float') { + return view.getFloat64(offset + 8, true); + } + } + + static registerObject(id, obj) { + ObjectStore.store[id] = obj; + Object.defineProperty(obj, ZsId, { + enumerable: false, + writable: false, + configurable: true, + value: id, + }) + } + + static writeValue(ptr, value) { + const mem = new DataView(wasm.memory.buffer, ptr); + + if (typeof value === 'object' || typeof value === 'function') { + mem.setUint8(0, ObjectStore.types['object'], true); + let id = value == null ? 0 : value[ZsId]; + + if (id === undefined) { + id = ObjectStore.generateFreeId(); + ObjectStore.registerObject(id, value); + } + + mem.setUint32(8, id, true); + + return; + } + + if (typeof value === 'number' && Number.isInteger(value) && value >= 0) { + mem.setUint8(0, ObjectStore.types['uint'], true); + mem.setUint32(8, value, true) + return; + } + + if (typeof value === 'number' && Number.isInteger(value)) { + mem.setUint8(0, ObjectStore.types['int'], true); + mem.setInt32(8, value, true) + return; + } + + if (typeof value === 'number') { + mem.setUint8(0, ObjectStore.types['float'], true); + mem.setFloat64(8, value, true) + return; + } + + if (typeof value === 'string') { + const string_ptr = wasm.exports.valueAllocString(ptr, value.length); + const encoder = new TextEncoder(); + const string = encoder.encode(value); + const memory = new Uint8Array(wasm.memory.buffer); + memory.set(string, string_ptr); + return; + } + + if (typeof value === 'undefined') { + mem.setUint8(0, ObjectStore.types['undefined'], true); + return; + } + } + + static processWasm( + calls_base, + values_base, + result_base, + length, + ) { + const offset = { + call: 0, + value: 0, + result: 0, + } + + const calls_view = new DataView(wasm.memory.buffer, calls_base); + const values_view = new DataView(wasm.memory.buffer, values_base); + const results_view = new DataView(wasm.memory.buffer, result_base); + + for (let i = 0; i < length; ++i) { + const method = ObjectStore.decodeCall(calls_view, offset.call); + offset.call += 2; + + let args = new Array(method.num_args).fill().map(_ => { + const value = ObjectStore.decodeValue(values_view, offset.value); + offset.value += 16; + return value; + }); + + const result = ObjectStore[method.kind](...args); + const result_ptr = results_view.getUint32(offset.result, true); + offset.result += 4; + + ObjectStore.writeValue(result_ptr, result); + } + } +} diff --git a/src/zeroscript/App/root.zig b/src/zeroscript/App/root.zig new file mode 100644 index 0000000..52cbfc2 --- /dev/null +++ b/src/zeroscript/App/root.zig @@ -0,0 +1,104 @@ +const builtin = @import("builtin"); +const std = @import("std"); +const Element = @import("../root.zig").html.Element; +const Document = @import("../root.zig").html.Document; +const Fragment = @import("../root.zig").html.Fragment; +const Component = @import("../root.zig").Component; + +pub const Options = struct { + name: []const u8, + globals: []const Global, + components: []const Component, + body: Fragment, + theme: []const u8, + + pub const Global = struct { + name: []const u8, + type: type, + }; +}; + +pub fn App(comptime options: Options) type { + if (builtin.target.cpu.arch.isWasm()) { + var names: [options.globals.len][]const u8 = undefined; + var types: [options.globals.len]type = undefined; + var attrs: [options.globals.len]std.builtin.Type.StructField.Attributes = undefined; + + for (options.globals, 0..) |field, index| { + names[index] = field.name; + types[index] = field.type; + attrs[index] = .{}; + } + + const G = @Struct(.auto, null, &names, &types, &attrs); + return struct { + globals: G = g: { + var gl: G = undefined; + + for (options.globals, 1..) |field, id| { + @field(gl, field.name) = @ptrFromInt(id); + } + + break :g gl; + }, + + pub const init: @This() = .{}; + + comptime { + for (options.components) |component| { + component.exportLinks(); + } + } + }; + } else { + const components: []const Element = (comp: { + var cs: []const Element = &.{}; + + for (options.components) |component| { + cs = cs ++ component.toElement(); + } + + break :comp cs; + }); + + return struct { + const node: Document = .{ + .root = .node("html", .{}, &.{ + .node("head", .{}, &.{ + .node("title", .{}, &.{.text(options.name)}), + .void("meta", .{ + .name = "viewport", + .content = "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0", + }), + .node("style", .{}, &.{.text(options.theme)}), + .node("script", .{}, &.{.text(@embedFile("symbols.js"))}), + .node("script", .{}, &.{.text(@embedFile("object-store.js"))}), + .node("script", .{}, &.{.text(@embedFile("main.js"))}), + .node("script", .{}, &.{.text(reg: { + var register_code: []const u8 = ""; + + for (options.globals, 1..) |field, id| { + register_code = register_code ++ std.fmt.comptimePrint( + "ObjectStore.registerObject({}, {s});", + .{ id, field.name }, + ); + } + + break :reg register_code; + })}), + }), + .node( + "body", + .{}, + &[_]Element{ + } ++ components ++ options.body.elements, + ), + }), + }; + + html: []const u8 = std.fmt.comptimePrint("{f}", .{node}), + + pub const init: @This() = .{}; + }; + } +} diff --git a/src/zeroscript/App/symbols.js b/src/zeroscript/App/symbols.js new file mode 100644 index 0000000..3df42b4 --- /dev/null +++ b/src/zeroscript/App/symbols.js @@ -0,0 +1,2 @@ +const ZsId = Symbol("zeroscript::id"); +const ZsPtr = Symbol("zeroscript::ptr"); diff --git a/src/zeroscript/AppBundle.zig b/src/zeroscript/AppBundle.zig new file mode 100644 index 0000000..1d4ebb9 --- /dev/null +++ b/src/zeroscript/AppBundle.zig @@ -0,0 +1,49 @@ +const std = @import("std"); + +pub const Options = struct { + root_source_file: std.Build.LazyPath, + target: std.Build.ResolvedTarget, +}; + +mod: *std.Build.Module, +wasm: struct { + mod: *std.Build.Module, + exe: *std.Build.Step.Compile, +}, + +pub fn init(b: *std.Build, options: Options, zeroscript_mod: *std.Build.Module) @This() { + const module = b.addModule("site", .{ + .root_source_file = options.root_source_file, + .target = options.target, + .imports = &.{ .{ .name = "zeroscript", .module = zeroscript_mod } }, + }); + + const wasm_module = b.createModule(.{ + .root_source_file = options.root_source_file, + .target = b.resolveTargetQuery(.{ + .cpu_arch = .wasm32, + .os_tag = .freestanding, + }), + .imports = &.{ .{ .name = "zeroscript", .module = zeroscript_mod } }, + }); + + const exe = b.addExecutable(.{ + .name = "runtime", + .root_module = wasm_module, + }); + + exe.rdynamic = true; + exe.entry = .disabled; + + return .{ + .mod = module, + .wasm = .{ + .exe = exe, + .mod = wasm_module, + }, + }; +} + +pub fn getEmittedWasm(self: *const @This()) std.Build.LazyPath { + return self.wasm.exe.getEmittedBin(); +} diff --git a/src/zeroscript/Component.zig b/src/zeroscript/Component.zig new file mode 100644 index 0000000..2f92b70 --- /dev/null +++ b/src/zeroscript/Component.zig @@ -0,0 +1,190 @@ +const std = @import("std"); +const Fragment = @import("root.zig").html.Fragment; +const Element = @import("root.zig").html.Element; +const Attribute = @import("root.zig").html.Attribute; +const Object = @import("Object.zig"); + +const Self = @This(); + +namespace: []const u8 = "app", +name: []const u8, +html: Fragment, +css: []const u8, +link: type, + +fn handlerNeedsEvent(func: anytype) bool { + const T = @TypeOf(func); + return @typeInfo(T).@"fn".params.len == 2; +} + +fn wrapHandler(ret: anytype) void { + const T = @TypeOf(ret); + const ret_info = @typeInfo(T); + + if (ret_info == .error_union) { + ret catch |err| { + std.log.err("error: {}", .{err}); + }; + } +} + +fn exportFromHtml(self: *const Self, element: Element) void { + comptime { + switch (element) { + .tag => |tag| for (tag.attributes) |attr| { + if (attr.value.len > 0 and attr.value[0] == '@') { + const event_handler = @field(self.link, attr.value[1..]); + + const func = + if (handlerNeedsEvent(event_handler)) + struct { + pub fn func(obj: *self.link, event: *Object) callconv(.c) void { + wrapHandler(event_handler(obj, event)); + } + }.func + else + struct { + pub fn func(obj: *self.link) callconv(.c) void { + wrapHandler(event_handler(obj)); + } + }.func; + + @export( + &func, + .{ + .name = std.fmt.comptimePrint( + "export::{s}::{s}", + .{ self.name, attr.value[1..] }, + ), + }, + ); + } + + switch (tag.content) { + .children => |children| for (children) |child| { + self.exportFromHtml(child); + }, + else => {}, + } + }, + else => {}, + } + } +} + +pub fn exportLinks(self: *const Self) void { + const init = struct { + pub fn init(element: *Object) callconv(.c) ?*self.link { + const obj = std.heap.wasm_allocator.create(self.link) catch return null; + 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( + \\customElements.define("{s}-{s}", class extends HTMLElement {{ + \\ constructor() {{ + \\ super(); + \\ this.attachShadow({{ mode: 'open' }}); + \\ const template = document.getElementById("@{s}"); + \\ const node = document.importNode(template.content, true); + \\ this.shadowRoot.appendChild(node); + \\ this[ZsPtr] = null; + \\ }} + \\ connectedCallback() {{ + \\ wasm_ready.then(() => {{ + \\ const id = ObjectStore.generateFreeId(); + \\ ObjectStore.registerObject(id, this); + \\ this[ZsPtr] = wasm.exports['export::{s}::init'](id) + \\ }}); + \\ }} + \\}}) + , .{ self.namespace, self.name, self.name, self.name }), + )}, + ), + }; +} diff --git a/src/zeroscript/Env/call.zig b/src/zeroscript/Env/call.zig new file mode 100644 index 0000000..a5db835 --- /dev/null +++ b/src/zeroscript/Env/call.zig @@ -0,0 +1,16 @@ + +pub const Call = extern struct { + kind: Kind, + num_args: u8, + + const Kind = enum(u8) { + free = 0, + get_prop = 1, + set_prop = 2, + del_prop = 3, + call_method = 4, + call = 5, + new = 6, + }; +}; + diff --git a/src/zeroscript/Env/future.zig b/src/zeroscript/Env/future.zig new file mode 100644 index 0000000..a014990 --- /dev/null +++ b/src/zeroscript/Env/future.zig @@ -0,0 +1,59 @@ +const std = @import("std"); +const Env = @import("root.zig"); +const z = @import("../root.zig"); + + +pub fn Future(comptime kind: Env.Value.Kind) type { + return struct { + const Self = @This(); + + future: AnyFuture, + + pub fn fromAny(future: AnyFuture) Self { + return .{ .future = future }; + } + + pub fn await(self: *const Self, env: *Env) !kind.asType() { + return self.future.await(env, kind); + } + }; +} + +pub const AnyFuture = union(enum) { + const Self = @This(); + + result: *Env.Value, + err: anyerror, + + pub fn await(self: *const Self, env: *Env, comptime kind: Env.Value.Kind) !kind.asType() { + const result = try self.awaitAny(env); + + if (kind != result.kind) { + std.log.err("unexpected {}, expected {}", .{ result.kind, kind }); + @panic("type error"); + } + + return switch (kind) { + .uninit => @panic("uninitialized result"), + .string => result.value.string.ptr[0..result.value.string.len], + else => @field(result.value, @tagName(kind)), + }; + } + + pub fn awaitAny(self: *const Self, env: *Env) !Env.Value { + switch (self.*) { + .err => |err| return err, + .result => |result| { + defer env.pool.destroy(result); + + if (result.kind != .uninit) { + return result.*; + } + + env.flush(); + + return result.*; + } + } + } +}; diff --git a/src/zeroscript/Env/js.zig b/src/zeroscript/Env/js.zig new file mode 100644 index 0000000..c1ff85d --- /dev/null +++ b/src/zeroscript/Env/js.zig @@ -0,0 +1,22 @@ +const std = @import("std"); +const Env = @import("root.zig"); + +pub extern "object_store" fn process( + [*]const Env.Call, + [*]const Env.Value, + [*]*Env.Value, + length: usize, +) void; + +export fn valueAllocString(value: *Env.Value, len: usize) [*]u8 { + const ptr: [*]u8 = @ptrCast(std.heap.wasm_allocator.alloc(u8, len) catch @panic("unable to allocate string")); + value.kind = .string; + value.value = .{ + .string = .{ + .ptr = ptr, + .len = len, + }, + }; + + return @constCast(value.value.string.ptr); +} diff --git a/src/zeroscript/Env/root.zig b/src/zeroscript/Env/root.zig new file mode 100644 index 0000000..6fd2bab --- /dev/null +++ b/src/zeroscript/Env/root.zig @@ -0,0 +1,162 @@ +const std = @import("std"); + +const Self = @This(); + +const js = @import("js.zig"); +const future = @import("future.zig"); +const Object = @import("../Object.zig"); + +pub const Call = @import("call.zig").Call; +pub const AnyFuture = future.AnyFuture; +pub const Future = future.Future; +pub const Value = @import("value.zig").Value; + +calls: std.ArrayList(Call) = .empty, +values: std.ArrayList(Value) = .empty, +pool: std.heap.MemoryPool(Value) = .empty, +results: std.ArrayList(*Value) = .empty, +gpa: std.mem.Allocator, + +pub const default: Self = .{ .gpa = std.heap.wasm_allocator }; + +pub fn init(gpa: std.mem.Allocator) Self { + return .{ .gpa = gpa }; +} + +pub fn getProp(self: *Self, object: *Object, key: anytype) AnyFuture { + self.calls.append(self.gpa, .{ + .kind = .get_prop, + .num_args = 2, + }) catch |err| return .{ .err = err }; + self.values.append(self.gpa, .from(object)) catch |err| return .{ .err = err }; + self.values.append(self.gpa, .from(key)) catch |err| return .{ .err = err }; + + return self.registerFuture() catch |err| .{ .err = err }; +} + +pub fn setProp( + self: *Self, + object: *Object, + key: anytype, + value: anytype, +) Future(.undefined) { + self.calls.append(self.gpa, .{ + .kind = .set_prop, + .num_args = 3, + }) catch |err| return .fromAny(.{ .err = err }); + + self.values.append(self.gpa, .from(object)) catch |err| return .fromAny(.{ .err = err }); + self.values.append(self.gpa, .from(key)) catch |err| return .fromAny(.{ .err = err }); + self.values.append(self.gpa, .from(value)) catch |err| return .fromAny(.{ .err = err }); + + return .fromAny(self.registerFuture() catch |err| .{ .err = err }); +} + +pub fn deleteProp( + self: *Self, + object: *Object, + key: anytype, +) Future(.undefined) { + self.calls.append(self.gpa, .{ + .kind = .del_prop, + .num_args = 2, + }) catch |err| return .fromAny(.{ .err = err }); + + self.values.append(self.gpa, .from(object)) catch |err| return .fromAny(.{ .err = err }); + self.values.append(self.gpa, .from(key)) catch |err| return .fromAny(.{ .err = err }); + + return .fromAny(self.registerFuture() catch |err| .{ .err = err }); +} + +pub fn callMethod( + self: *Self, + object: *Object, + key: []const u8, + args: anytype, +) AnyFuture { + self.calls.append(self.gpa, .{ + .kind = .call_method, + .num_args = 2 + args.len, + }) catch |err| return .{ .err = err }; + + self.values.append(self.gpa, .from(object)) catch |err| return .{ .err = err }; + self.values.append(self.gpa, .from(key)) catch |err| return .{ .err = err }; + + inline for (args) |arg| { + self.values.append(self.gpa, .from(arg)) catch |err| return .{ .err = err }; + } + + return self.registerFuture() catch |err| return .{ .err = err }; +} + +pub fn call(self: *Self, object: *Object, args: anytype) AnyFuture { + self.calls.append(self.gpa, .{ + .kind = .call, + .num_args = 1 + args.len, + }) catch |err| return .{ .err = err }; + + self.values.append(self.gpa, .from(object)) catch |err| return .{ .err = err }; + + inline for (args) |arg| { + self.values.append(self.gpa, .from(arg)) catch |err| return .{ .err = err }; + } + + return self.registerFuture() catch |err| return .{ .err = err }; +} + +pub fn free(self: *Self, object: *Object) Future(.undefined) { + self.calls.append(self.gpa, .{ + .kind = .free, + .num_args = 1, + }) catch |err| return .fromAny(.{ .err = err }); + + self.values.append(self.gpa, .from(object)) catch |err| return .fromAny(.{ .err = err }); + + return .fromAny(self.registerFuture() catch |err| .{ .err = err }); +} + +pub fn new(self: *Self, object: *Object, args: anytype) Future(.object) { + self.calls.append(self.gpa, .{ + .kind = .new, + .num_args = 1 + args.len, + }) catch |err| return .fromAny(.{ .err = err }); + + self.values.append(self.gpa, .from(object)) catch |err| return .fromAny(.{ .err = err }); + + inline for (args) |arg| { + self.values.append(self.gpa, .from(arg)) catch |err| return .fromAny(.{ .err = err }); + } + + return .fromAny(self.registerFuture() catch |err| .{ .err = err }); +} + +fn registerFuture(self: *Self) !AnyFuture { + const result = try self.pool.create(self.gpa); + errdefer self.pool.destroy(result); + result.kind = .uninit; + try self.results.append(self.gpa, result); + return .{ .result = result }; +} + +pub fn flush(self: *Self) void { + js.process( + @ptrCast(self.calls.items), + @ptrCast(self.values.items), + @ptrCast(self.results.items), + self.results.items.len, + ); + self.calls.clearRetainingCapacity(); + self.values.clearRetainingCapacity(); + self.results.clearRetainingCapacity(); +} + +pub fn deinit(self: *Self) void { + self.flush(); + + self.calls.deinit(self.gpa); + self.values.deinit(self.gpa); + self.pool.deinit(self.gpa); + self.results.deinit(self.gpa); + + self.* = undefined; +} diff --git a/src/zeroscript/Env/value.zig b/src/zeroscript/Env/value.zig new file mode 100644 index 0000000..59b788f --- /dev/null +++ b/src/zeroscript/Env/value.zig @@ -0,0 +1,115 @@ +const std = @import("std"); +const Object = @import("../Object.zig"); + +pub fn isString(comptime T: type) bool { + return comptime blk: { + const info = @typeInfo(T); + if (info != .pointer) break :blk false; + + const ptr = &info.pointer; + if (ptr.is_volatile or ptr.is_allowzero) break :blk false; + + if (ptr.size == .slice) { + break :blk ptr.child == u8; + } + + if (ptr.size == .one) { + const child = @typeInfo(ptr.child); + if (child == .array) { + const arr = &child.array; + break :blk arr.child == u8; + } + } + + break :blk false; + }; +} + +pub const Value = extern struct { + kind: Kind, + value: extern union { + object: *Object, + string: extern struct { + ptr: [*]const u8, + len: usize, + }, + int: isize, + uint: usize, + float: f64, + undefined: void, + }, + + pub fn from(value: anytype) Value { + const T = @TypeOf(value); + + return switch (T) { + *Object => .{ + .kind = .object, + .value = .{ .object = value }, + }, + comptime_int => if (value >= 0) .{ + .kind = .uint, + .value = .{ .uint = value }, + } else .{ + .kind = .int, + .value = .{ .int = value }, + }, + usize => .{ + .kind = .uint, + .value = .{ .uint = value }, + }, + isize => .{ + .kind = .int, + .value = .{ .int = value }, + }, + f64, f32, f16 => .{ + .kind = .float, + .value = .{ .float = value }, + }, + void => .{ + .kind = .undefined, + .value = .{ .undefined = {} }, + }, + else => str: { + if (comptime isString(T)) { + break :str .{ + .kind = .string, + .value = .{ + .string = .{ + .ptr = @ptrCast(value), + .len = value.len, + }, + }, + }; + } else { + @compileError(std.fmt.comptimePrint( + "cannot auto convert type '{}'.", + .{T}, + )); + } + }, + }; + } + + pub const Kind = enum(u8) { + uninit = 0, + object = 1, + string = 2, + int = 3, + uint = 4, + float = 5, + undefined = 6, + + pub fn asType(comptime self: Kind) type { + return switch (self) { + .object => return *Object, + .string => return []const u8, + .int => return isize, + .uint => return usize, + .float => f64, + .undefined => return void, + .uninit => @compileError("uninit has no associated type."), + }; + } + }; +}; diff --git a/src/zeroscript/Object.zig b/src/zeroscript/Object.zig new file mode 100644 index 0000000..064d48b --- /dev/null +++ b/src/zeroscript/Object.zig @@ -0,0 +1,35 @@ +const mod = @import("root.zig"); +const Options = mod.Options; +const Env = mod.Env; +const AnyFuture = Env.AnyFuture; +const Future = Env.Future; + +const Self = @This(); + +pub inline fn get(self: *Self, env: *Env, key: anytype) AnyFuture { + return env.getProp(self, key); +} + +pub inline fn set(self: *Self, env: *Env, key: anytype, value: anytype) Future(.undefined) { + return env.setProp(self, key, value); +} + +pub inline fn delete(self: *Self, env: *Env, key: anytype) Future(.undefined) { + return env.deleteProp(self, key); +} + +pub inline fn call(self: *Self, env: *Env, method: []const u8, args: anytype) AnyFuture { + return env.callMethod(self, method, args); +} + +pub inline fn free(self: *Self, env: *Env) Future(.undefined) { + return env.free(self); +} + +pub fn new(self: *Self, env: *Env) Future(.object) { + return env.new(self, .{}); +} + +pub fn global(tag: @EnumLiteral()) Options.Global { + return .{ .name = @tagName(tag), .type = *Self }; +} diff --git a/src/zeroscript/html/Attribute.zig b/src/zeroscript/html/Attribute.zig new file mode 100644 index 0000000..1db49a0 --- /dev/null +++ b/src/zeroscript/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("""); + value = value[index + 1..]; + } + + try writer.writeAll(value); + try writer.writeByte('"'); +} diff --git a/src/zeroscript/html/Document.zig b/src/zeroscript/html/Document.zig new file mode 100644 index 0000000..b1122e1 --- /dev/null +++ b/src/zeroscript/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("{f}", .{self.root}); +} diff --git a/src/zeroscript/html/Fragment.zig b/src/zeroscript/html/Fragment.zig new file mode 100644 index 0000000..d05ad4a --- /dev/null +++ b/src/zeroscript/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/zeroscript/html/Tag.zig b/src/zeroscript/html/Tag.zig new file mode 100644 index 0000000..90b5641 --- /dev/null +++ b/src/zeroscript/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("", .{self.name}); + }, + .void => {}, + } +} diff --git a/src/zeroscript/html/element.zig b/src/zeroscript/html/element.zig new file mode 100644 index 0000000..739eb0b --- /dev/null +++ b/src/zeroscript/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/zeroscript/html/parser.zig b/src/zeroscript/html/parser.zig new file mode 100644 index 0000000..38b28bb --- /dev/null +++ b/src/zeroscript/html/parser.zig @@ -0,0 +1,174 @@ +const std = @import("std"); +const mod = @import("root.zig"); +const Element = mod.Element; +const Attribute = mod.Attribute; +const Tag = mod.Tag; +const Fragment = mod.Fragment; + +const tag_name: []const u8 = std.ascii.letters ++ .{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-' }; +const void_elements: std.StaticStringMap(void) = .initComptime(.{ + .{"area"}, + .{"base"}, + .{"br"}, + .{"col"}, + .{"embed"}, + .{"hr"}, + .{"img"}, + .{"input"}, + .{"link"}, + .{"meta"}, + .{"param"}, + .{"source"}, + .{"track"}, + .{"wbr"}, +}); + +pub fn fragment(buffer: []const u8) Fragment { + @setEvalBranchQuota(buffer.len * 1000); + var elements: []const Element = &.{}; + var buf = buffer; + + while (buf.len > 0) { + const e, buf = element(buf); + elements = elements ++ .{e}; + } + + return .{ .elements = elements }; +} + +pub fn element(buffer: []const u8) struct { Element, []const u8 } { + if (buffer.len == 0) @panic("EOB, expected element"); + + switch (buffer[0]) { + '<' => { + const t, const b = tag(buffer); + return .{ .{ .tag = t }, b }; + }, + else => { + const t, const b = text(buffer); + return .{ .{ .string = t }, b }; + }, + } +} + +pub fn tag(buffer: []const u8) struct { Tag, []const u8 } { + if (buffer.len == 0) @panic("EOB, expected tag"); + + if (buffer[0] != '<') @panic("expected '<'"); + + var buf: []const u8 = buffer[1..]; + + const name = name: { + const index = std.mem.findNone(u8, buf, tag_name) orelse @panic("uncosed tag"); + defer buf = buf[index..]; + break :name buf[0..index]; + }; + + buf = std.mem.trimStart(u8, buf, &std.ascii.whitespace); + + var attributes: []const Attribute = &.{}; + + while (buf.len > 0 and buf[0] != '>') { + buf = std.mem.trimStart(u8, buf, &std.ascii.whitespace); + const attr, buf = attribute(buf); + attributes = attributes ++ .{attr}; + } + + if (buf.len == 0 or buf[0] != '>') @panic("expected tag-close"); + + buf = buf[1..]; + + if (void_elements.has(name)) { + return .{.{ + .name = name, + .attributes = attributes, + .content = .void, + }}; + } + + var children: []const Element = &.{}; + + buf = std.mem.trimStart(u8, buf, &std.ascii.whitespace); + + const closing = std.fmt.comptimePrint("", .{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/zeroscript/html/root.zig b/src/zeroscript/html/root.zig new file mode 100644 index 0000000..7bf91e8 --- /dev/null +++ b/src/zeroscript/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/zeroscript/log/js.zig b/src/zeroscript/log/js.zig new file mode 100644 index 0000000..16f562c --- /dev/null +++ b/src/zeroscript/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/zeroscript/log/root.zig b/src/zeroscript/log/root.zig new file mode 100644 index 0000000..ba9141e --- /dev/null +++ b/src/zeroscript/log/root.zig @@ -0,0 +1,28 @@ +const std = @import("std"); + +pub const js = @import("js.zig"); + +pub fn default( + comptime level: std.log.Level, + comptime scope: @EnumLiteral(), + comptime format: []const u8, + args: anytype, +) void { + var buffer: [1024]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buffer); + + const func = switch (level) { + .err => js.err, + .warn => js.warn, + .info => js.log, + .debug => js.debug, + }; + + if (scope != .default) { + writer.print("[{s}]: ", .{@tagName(scope)}) catch unreachable; + } + writer.print(format, args) catch unreachable; + + func(writer.buffered()); +} + diff --git a/src/zeroscript/root.zig b/src/zeroscript/root.zig new file mode 100644 index 0000000..321bde4 --- /dev/null +++ b/src/zeroscript/root.zig @@ -0,0 +1,18 @@ +const builtin = @import("builtin"); +const std = @import("std"); + +pub const log = @import("log/root.zig"); +pub const Env = @import("Env/root.zig"); +pub const Object = @import("Object.zig"); +pub const html = @import("html/root.zig"); + +pub const App = @import("App/root.zig").App; +pub const Options = @import("App/root.zig").Options; +pub const Component = @import("Component.zig"); + +fn defaultPanic(msg: []const u8, _: ?usize) noreturn { + log.js.err(msg); + @trap(); +} + +pub const panic = std.debug.FullPanic(defaultPanic); -- cgit v1.2.3-70-g09d2