diff options
| author | Nathan Reiner <nathan@nathanreiner.xyz> | 2026-10-05 15:33:46 +0200 |
|---|---|---|
| committer | Nathan Reiner <nathan@nathanreiner.xyz> | 2026-10-05 15:33:46 +0200 |
| commit | 02582cc490fc0d753dd153211cc172eb28fbee5d (patch) | |
| tree | 4add149d5e1ecf28cf20ecb497626fef85cdbd75 | |
| parent | 2f3199622d9e7a97da4b5c31a2d81b170b7cdaa6 (diff) | |
first sketch of wasm environment
47 files changed, 537 insertions, 1585 deletions
@@ -1,9 +1,15 @@ const std = @import("std"); +const AppBundle = @import("src/z/AppBundle.zig"); + pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); + const site: AppBundle = .init(b, .{ + .root_source_file = b.path("src/app/root.zig"), + }); + const sqlite_c = b.addTranslateC(.{ .root_source_file = b.path("src/db/sqlite.h"), .target = target, @@ -27,12 +33,6 @@ pub fn build(b: *std.Build) void { .target = target, }); - const z_mod = b.addModule("z", .{ - .root_source_file = b.path("src/z/root.zig"), - .target = target, - }); - z_mod.addImport("html", html_mod); - const http_mod = b.addModule("http", .{ .root_source_file = b.path("src/http/root.zig"), .target = target, @@ -40,6 +40,14 @@ pub fn build(b: *std.Build) void { api_mod.addImport("http", http_mod); + const z_mod = b.addModule("z", .{ + .root_source_file = b.path("src/z/root.zig"), + .target = target, + }); + z_mod.addImport("html", html_mod); + + site.mod.addImport("z", z_mod); + const exe = b.addExecutable(.{ .name = "memora", .root_module = b.createModule(.{ @@ -49,18 +57,21 @@ pub fn build(b: *std.Build) void { .imports = &.{ .{ .name = "db", .module = db_mod }, .{ .name = "api", .module = api_mod }, - .{ .name = "z", .module = z_mod }, .{ .name = "html", .module = html_mod }, .{ .name = "http", .module = http_mod }, - } + .{ .name = "z", .module = z_mod }, + }, }), }); + exe.root_module.addAnonymousImport("wasm", .{ + .root_source_file = site.getEmittedWasm(), + }); + b.installArtifact(exe); const run_step = b.step("run", "Run the app"); - const run_cmd = b.addRunArtifact(exe); run_step.dependOn(&run_cmd.step); run_cmd.step.dependOn(b.getInstallStep()); @@ -76,7 +87,6 @@ pub fn build(b: *std.Build) void { const db_test_step = b.step("test-db", "Run database tests"); db_test_step.dependOn(&run_db_tests.step); - const api_tests = b.addTest(.{ .root_module = api_mod, }); @@ -84,14 +94,6 @@ pub fn build(b: *std.Build) void { const api_test_step = b.step("test-api", "Run api tests"); api_test_step.dependOn(&run_api_tests.step); - - const z_tests = b.addTest(.{ - .root_module = z_mod, - }); - const run_z_tests = b.addRunArtifact(z_tests); - const z_test_step = b.step("test-z", "Run z tests"); - z_test_step.dependOn(&run_z_tests.step); - const html_tests = b.addTest(.{ .root_module = html_mod, }); @@ -99,7 +101,6 @@ pub fn build(b: *std.Build) void { const html_test_step = b.step("test-html", "Run html tests"); html_test_step.dependOn(&run_html_tests.step); - const http_tests = b.addTest(.{ .root_module = http_mod, }); @@ -107,37 +108,31 @@ pub fn build(b: *std.Build) void { const http_test_step = b.step("test-http", "Run http tests"); http_test_step.dependOn(&run_http_tests.step); - const exe_tests = b.addTest(.{ .root_module = exe.root_module, }); const run_exe_tests = b.addRunArtifact(exe_tests); - const test_step = b.step("test", "Run all tests"); test_step.dependOn(&run_db_tests.step); test_step.dependOn(&run_api_tests.step); - test_step.dependOn(&run_z_tests.step); test_step.dependOn(&run_html_tests.step); test_step.dependOn(&run_http_tests.step); test_step.dependOn(&run_exe_tests.step); - const fmt_step = b.step("fmt", "Format"); const do_fmt = b.addFmt(.{ - .paths = &.{ "src" }, + .paths = &.{"src"}, }); fmt_step.dependOn(&do_fmt.step); - const check_fmt_step = b.step("check", "Check format and syntax"); const do_check_fmt = b.addFmt(.{ - .paths = &.{ "src" }, + .paths = &.{"src"}, .check = true, }); check_fmt_step.dependOn(&do_check_fmt.step); - const docs_step = b.step("docs", "Emit documentation"); const docs_install = b.addInstallDirectory(.{ .install_dir = .prefix, @@ -146,7 +141,6 @@ pub fn build(b: *std.Build) void { }); docs_step.dependOn(&docs_install.step); - const hot_cmd = b.addSystemCommand(&.{ "sh", "-c", diff --git a/src/app/root.zig b/src/app/root.zig new file mode 100644 index 0000000..13d26b8 --- /dev/null +++ b/src/app/root.zig @@ -0,0 +1,13 @@ +const std = @import("std"); +pub const z = @import("z"); + +export fn run() void { + var env: z.Env = .init(std.heap.wasm_allocator); + defer env.deinit(); + + var ref = env.getProp(1, "console") catch unreachable; + var buffer: [255]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buffer); + writer.print("hello, wasm: {}", .{ref.await(&env, .object)}) catch unreachable; + z.env.console.log(writer.buffered()); +} diff --git a/src/http/handler/static.zig b/src/http/handler/static.zig index d53f213..df307b7 100644 --- a/src/http/handler/static.zig +++ b/src/http/handler/static.zig @@ -2,10 +2,12 @@ const Interface = @import("Interface.zig"); const Context = @import("context.zig").Context; const Response = @import("../Response.zig"); -pub fn Static(route: anytype, content: []const u8) Context(route) { +pub fn Static(route: anytype, content: []const u8, mime: []const u8) Context(route) { const get = struct { fn get(_: Context(route).Request) Response { - return .ok(.string(content)); + return .withHeaders(.ok, .string(content), &.{ + .{ .name = "Content-Type", .value = mime }, + }); } }.get; diff --git a/src/main.zig b/src/main.zig index 176d3b2..bb8b34d 100644 --- a/src/main.zig +++ b/src/main.zig @@ -7,9 +7,13 @@ const std = @import("std"); const http = @import("http"); const api = @import("api"); -const web = @import("web/root.zig"); +const z = @import("z"); +const wasm = @embedFile("wasm"); -const routes: http.RouteSet = .init(api.interfaces ++ web.interfaces); +const routes: http.RouteSet = .init(&([_]http.handler.Interface{ + http.handler.Static(.index, z.app.create(.{ .name = "Memora" }), "text/html").interface(), + http.handler.Static(.{"index.wasm"}, wasm, "application/wasm").interface(), +}) ++ api.interfaces); pub fn main(init: std.process.Init) !void { try http.serve(init.gpa, routes, .{ diff --git a/src/web/component/image/index.css b/src/web/component/image/index.css deleted file mode 100644 index e69de29..0000000 --- a/src/web/component/image/index.css +++ /dev/null diff --git a/src/web/component/image/index.html b/src/web/component/image/index.html deleted file mode 100644 index 918c5df..0000000 --- a/src/web/component/image/index.html +++ /dev/null @@ -1,2 +0,0 @@ -<div id="image"> -</div> diff --git a/src/web/component/image/index.js b/src/web/component/image/index.js deleted file mode 100644 index d88023d..0000000 --- a/src/web/component/image/index.js +++ /dev/null @@ -1 +0,0 @@ -console.log(Z.by_selector('div')); diff --git a/src/web/component/image/root.zig b/src/web/component/image/root.zig deleted file mode 100644 index 7c8ec77..0000000 --- a/src/web/component/image/root.zig +++ /dev/null @@ -1,8 +0,0 @@ -const z = @import("z"); - -pub const component: z.Component = .{ - .name = .image, - .body = @embedFile("index.html"), - .style = @embedFile("index.css"), - .script = @embedFile("index.js"), -}; diff --git a/src/web/component/navigation/index.css b/src/web/component/navigation/index.css deleted file mode 100644 index 836e3b5..0000000 --- a/src/web/component/navigation/index.css +++ /dev/null @@ -1,66 +0,0 @@ -#toggle { - --radius-open: 200px; - - position: absolute; - right: 10px; - bottom: 10px; - width: 45px; - height: 45px; - border-radius: 100%; - background: red; - z-index: 500; - cursor: pointer; - text-align: center; - align-content: center; - transition: - border-radius 0.1s ease, - right 0.1s ease, - bottom 0.1s ease, - width 0.1s ease, - height 0.1s ease; - - .bi { - baseline-shift: -2px; - } - - .items { - position: relative; - top: 0px; - left: 0px; - right: 0px; - bottom: 0px; - } - - .item { - display: none; - width: 45px; - height: 45px; - border-radius: 100%; - background: blue; - position: absolute; - right: calc(cos(18deg * var(--index)) * var(--radius-open)); - bottom: calc(sin(18deg * var(--index)) * var(--radius-open)); - font-size: calc(var(--index) * 1px); - } - - .item { - --index: sibling-index(); - } -} - -#toggle.open { - width: var(--radius-open); - height: var(--radius-open); - bottom: 0px; - right: 0px; - border-radius: 0px; - border-top-left-radius: 250px; - - .bi { - display: none; - } - - .item { - display: block; - } -} diff --git a/src/web/component/navigation/index.html b/src/web/component/navigation/index.html deleted file mode 100644 index b3b5ce0..0000000 --- a/src/web/component/navigation/index.html +++ /dev/null @@ -1,11 +0,0 @@ -<div id="toggle"> - <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-three-dots-vertical" viewBox="0 0 16 16"> - <path d="M9.5 13a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0m0-5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0m0-5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0"/> - </svg> - <div class="items"> - <div class="item"></div> - <div class="item"></div> - <div class="item"></div> - <div class="item"></div> - </div> -</div> diff --git a/src/web/component/navigation/index.js b/src/web/component/navigation/index.js deleted file mode 100644 index 2c996a0..0000000 --- a/src/web/component/navigation/index.js +++ /dev/null @@ -1,11 +0,0 @@ - -const toggle = Z.by_id('toggle'); - -toggle.onclick = (event) => { - toggle.classList.toggle('open'); - event.stopPropagation(); -}; - -document.addEventListener('click', () => { - toggle.classList.remove('open'); -}); diff --git a/src/web/component/navigation/root.zig b/src/web/component/navigation/root.zig deleted file mode 100644 index 919cddb..0000000 --- a/src/web/component/navigation/root.zig +++ /dev/null @@ -1,8 +0,0 @@ -const z = @import("z"); - -pub const component: z.Component = .{ - .name = .navigation, - .body = @embedFile("index.html"), - .style = @embedFile("index.css"), - .script = @embedFile("index.js"), -}; diff --git a/src/web/component/root.zig b/src/web/component/root.zig deleted file mode 100644 index ba2f565..0000000 --- a/src/web/component/root.zig +++ /dev/null @@ -1,7 +0,0 @@ -const z = @import("z"); - -pub const components: []const z.Component = &.{ - @import("image/root.zig").component, - @import("timeline/root.zig").component, - @import("navigation/root.zig").component, -}; diff --git a/src/web/component/timeline/index.css b/src/web/component/timeline/index.css deleted file mode 100644 index 6d58f59..0000000 --- a/src/web/component/timeline/index.css +++ /dev/null @@ -1,18 +0,0 @@ -#container { - width: 100%; - display: inline-grid; - gap: 0px; - overflow-y: auto; -} - -.image { - text-align: center; - align-content: center; - font-weight: bold; - font-size: 0.5em; - overflow: hidden; -} - -#container.tiling .image { - aspect-ratio: 1 / 1 !important; -} diff --git a/src/web/component/timeline/index.html b/src/web/component/timeline/index.html deleted file mode 100644 index 41d4617..0000000 --- a/src/web/component/timeline/index.html +++ /dev/null @@ -1,2 +0,0 @@ -<div id="container"> -</div> diff --git a/src/web/component/timeline/index.js b/src/web/component/timeline/index.js deleted file mode 100644 index 81322c6..0000000 --- a/src/web/component/timeline/index.js +++ /dev/null @@ -1,96 +0,0 @@ -const container = Z.by_id('container'); - -function getRandomColor() { - var letters = '0123456789ABCDEF'; - var color = '#'; - for (var i = 0; i < 6; i++) { - color += letters[Math.floor(Math.random() * 16)]; - } - return color; -} - -for (let i = 0; i < 10000; ++i) { - container.appendChild(Z.native('div', { - innerText: i, - className: 'image', - style: { - background: getRandomColor(), - aspectRatio: '1 / ' + (Math.random() + 0.5), - }, - })); -} - -const zoom = new (class { - constructor() { - this.committed = 5; - container.style.gridTemplateColumns = `repeat(5, 1fr)`; - container.classList.toggle('tiling', this.committed != 1); - this.por = { x: 0, y: 0 }; - this.eor = null; - this.y_offset = 0; - this.distance = 0; - } - - update(distance, point) { - const scale = distance / this.distance; - const x = point.x - this.por.x; - container.style.transform = `translate(${x}px, 0px) scale(${scale})`; - } - - set reference({ point, distance }) { - const rect = container.getClientRects()[0]; - - this.por = { x: point.x, y: point.y - rect.y }; - container.style.transformOrigin = `${this.por.x}px ${this.por.y}px`; - this.eor = Z.document.shadowRoot.elementFromPoint(point.x, point.y); - - const box_rect = this.eor.getBoundingClientRect(); - this.y_offset = box_rect.y; - - this.distance = distance; - } - - commit(distance) { - const scale = distance / this.distance; - this.committed = Math.round(Math.min(Math.max(this.committed / scale, 1), 20)); - container.style.gridTemplateColumns = `repeat(${this.committed}, 1fr)`; - container.classList.toggle('tiling', this.committed != 1); - container.style.transform = 'scale(1)'; - - const rect = this.eor.getBoundingClientRect(); - - Z.document.scrollBy({ - top: rect.y - this.y_offset, - behavior: 'instant', - }); - } - - increase_line_by(n) { - this.committed = Math.min(Math.max(this.committed + n, 1), 20); - container.style.gridTemplateColumns = `repeat(${this.committed}, 1fr)`; - container.classList.toggle('tiling', this.committed != 1); - container.style.transform = 'scale(1)'; - } -}); - -Z.document.onwheel = (event) => { - if (!event.ctrlKey) { - return; - } - event.preventDefault(); - zoom.increase_line_by(event.wheelDeltaY / 120); -}; - -const pinch = new Pinch(Z.document); - -pinch.onstart = (event) => { - zoom.reference = event; -}; - -pinch.onpinch = (event) => { - zoom.update(event.distance, event.point); -}; - -pinch.onfinish = (event) => { - zoom.commit(event.distance); -}; diff --git a/src/web/component/timeline/root.zig b/src/web/component/timeline/root.zig deleted file mode 100644 index 9faa40e..0000000 --- a/src/web/component/timeline/root.zig +++ /dev/null @@ -1,8 +0,0 @@ -const z = @import("z"); - -pub const component: z.Component = .{ - .name = .timeline, - .body = @embedFile("index.html"), - .style = @embedFile("index.css"), - .script = @embedFile("index.js"), -}; diff --git a/src/web/index.css b/src/web/index.css deleted file mode 100644 index bcdecae..0000000 --- a/src/web/index.css +++ /dev/null @@ -1,21 +0,0 @@ -html { - height: 100vh; - width: 100vw; - overflow: hidden; -} - -body { - padding: 0; - margin: 0; - width: 100vw; - height: 100vh; - overflow: hidden; - touch-action: pan-y; -} - -#timeline { - display: block; - height: 100vh; - overflow-y: auto; - background: gray; -} diff --git a/src/web/index.html b/src/web/index.html deleted file mode 100644 index bcbb165..0000000 --- a/src/web/index.html +++ /dev/null @@ -1,4 +0,0 @@ -<z-component type="timeline" id="timeline"> -</z-component> -<z-component type="navigation" id="navigation"> -</z-component> diff --git a/src/web/index.js b/src/web/index.js deleted file mode 100644 index e69de29..0000000 --- a/src/web/index.js +++ /dev/null diff --git a/src/web/pinch.js b/src/web/pinch.js deleted file mode 100644 index bb06b0d..0000000 --- a/src/web/pinch.js +++ /dev/null @@ -1,82 +0,0 @@ -class Pinch { - constructor(element) { - this.event_cache = []; - this.onpinch = () => {}; - this.onfinish = () => {}; - this.onstart = () => {}; - - element.onpointerdown = (e) => this.pointer_down_handler(e); - element.onpointermove = (e) => this.pointer_move_handler(e); - element.onpointerup = (e) => this.pointer_up_handler(e); - element.onpointercancel = (e) => this.pointer_up_handler(e); - element.onpointerout = (e) => this.pointer_up_handler(e); - element.onpointerleave = (e) => this.pointer_up_handler(e); - } - - pointer_down_handler(event) { - this.event_cache.push(event); - - if (this.event_cache.length === 2) { - const diff = Math.hypot( - this.event_cache[0].clientX - this.event_cache[1].clientX, - this.event_cache[0].clientY - this.event_cache[1].clientY, - ); - - const point = { - x: (this.event_cache[0].clientX + this.event_cache[1].clientX) / 2, - y: (this.event_cache[0].clientY + this.event_cache[1].clientY) / 2, - }; - - this.onstart({ point, distance: diff }); - } - } - - pointer_move_handler(event) { - const index = this.event_cache.findIndex( - (cached) => cached.pointerId == event.pointerId, - ); - this.event_cache[index] = event; - - if (this.event_cache.length === 2) { - const diff = Math.hypot( - this.event_cache[0].clientX - this.event_cache[1].clientX, - this.event_cache[0].clientY - this.event_cache[1].clientY, - ); - - const point = { - x: (this.event_cache[0].clientX + this.event_cache[1].clientX) / 2, - y: (this.event_cache[0].clientY + this.event_cache[1].clientY) / 2, - }; - - this.onpinch({ distance: diff, point }); - } - } - - pointer_up_handler(event) { - let cleanup = false; - const ev = {}; - - if (this.event_cache.length === 2) { - ev['distance'] = Math.hypot( - this.event_cache[0].clientX - this.event_cache[1].clientX, - this.event_cache[0].clientY - this.event_cache[1].clientY, - ); - - ev['point'] = { - x: (this.event_cache[0].clientX + this.event_cache[1].clientX) / 2, - y: (this.event_cache[0].clientY + this.event_cache[1].clientY) / 2, - }; - - cleanup = true; - } - - const index = this.event_cache.findIndex( - (cached) => cached.pointerId === event.pointerId, - ); - this.event_cache.splice(index, 1); - - if (cleanup) { - this.onfinish(ev); - } - } -} diff --git a/src/web/root.zig b/src/web/root.zig deleted file mode 100644 index d027dc8..0000000 --- a/src/web/root.zig +++ /dev/null @@ -1,26 +0,0 @@ -const z = @import("z"); -const html = @import("html"); -const http = @import("http"); -const Static = http.handler.Static; - -const components = @import("component/root.zig").components; - -const document: html.Element = .native(.html, .{}, .children(&.{ - .native(.head, .{}, .children(&.{ - .native(.title, .{}, .content("Memora")), - .native(.meta, .{ - .name = "viewport", - .content = "width=device-width, initial-scale=1.0", - }, .void), - z.script.load(@embedFile("pinch.js")), - z.style.load(@embedFile("index.css")), - z.env(components), - })), - .native(.body, .{}, .children(&.{ - z.html.load(@embedFile("index.html")), - })), -})); - -pub const interfaces: []const http.handler.Interface = &.{ - Static(.index, document.toDocument()).interface(), -}; diff --git a/src/z/AppBundle.zig b/src/z/AppBundle.zig new file mode 100644 index 0000000..3fec9fb --- /dev/null +++ b/src/z/AppBundle.zig @@ -0,0 +1,35 @@ +const std = @import("std"); + +pub const Options = struct { + root_source_file: std.Build.LazyPath, +}; + +mod: *std.Build.Module, +wasm: *std.Build.Step.Compile, + +pub fn init(b: *std.Build, options: Options) @This() { + const module = b.createModule(.{ + .root_source_file = options.root_source_file, + .target = b.resolveTargetQuery(.{ + .cpu_arch = .wasm32, + .os_tag = .freestanding, + }), + }); + + const exe = b.addExecutable(.{ + .name = "runtime", + .root_module = module, + }); + + exe.rdynamic = true; + exe.entry = .disabled; + + return .{ + .wasm = exe, + .mod = module, + }; +} + +pub fn getEmittedWasm(self: *const @This()) std.Build.LazyPath { + return self.wasm.getEmittedBin(); +} diff --git a/src/z/Component.zig b/src/z/Component.zig deleted file mode 100644 index a6a4923..0000000 --- a/src/z/Component.zig +++ /dev/null @@ -1,18 +0,0 @@ -const std = @import("std"); -const html = @import("html"); -const z = @import("root.zig"); - -name: @EnumLiteral(), -body: []const u8, -style: []const u8, -script: []const u8, - -pub fn toElement(comptime self: @This()) html.Element { - return .transparent(.children(&.{ - .native(.template, .{ .id = "@" ++ @tagName(self.name) }, .children(&.{ - z.style.load(self.style), - z.body.load(self.body), - })), - z.script.load("Zenv.constructors['component__" ++ @tagName(self.name) ++ "'] = async (Z) => {" ++ self.script ++ "}"), - })); -} diff --git a/src/z/Env/Future.zig b/src/z/Env/Future.zig new file mode 100644 index 0000000..17266b9 --- /dev/null +++ b/src/z/Env/Future.zig @@ -0,0 +1,29 @@ +const std = @import("std"); +const Env = @import("root.zig"); + +const Self = @This(); + +result: *Env.Value, + +pub fn await(self: *Self, env: *Env, comptime kind: Env.Value.Kind) kind.asType() { + const result = self.awaitAny(env); + std.debug.assert(kind == result.kind); + + 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: *Self, env: *Env) Env.Value { + defer env.pool.destroy(self.result); + + if (self.result.kind != .uninit) { + return self.result.*; + } + + env.flush(); + + return self.result.*; +} diff --git a/src/z/Env/call.zig b/src/z/Env/call.zig new file mode 100644 index 0000000..bf64392 --- /dev/null +++ b/src/z/Env/call.zig @@ -0,0 +1,15 @@ + +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, + }; +}; + diff --git a/src/z/Env/js.zig b/src/z/Env/js.zig new file mode 100644 index 0000000..b35f6ed --- /dev/null +++ b/src/z/Env/js.zig @@ -0,0 +1,9 @@ +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; diff --git a/src/z/Env/root.zig b/src/z/Env/root.zig new file mode 100644 index 0000000..7b31e84 --- /dev/null +++ b/src/z/Env/root.zig @@ -0,0 +1,64 @@ +const std = @import("std"); + +const mod = @import("../root.zig"); +const js = @import("js.zig"); + +const Self = @This(); +pub const Call = @import("call.zig").Call; +pub const Future = @import("Future.zig"); +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 fn init(gpa: std.mem.Allocator) Self { + return .{ .gpa = gpa }; +} + +pub fn getProp(self: *Self, id: u32, key: []const u8) !Future { + try self.calls.append(self.gpa, .{ + .kind = .get_prop, + .num_args = 2, + }); + try self.values.append(self.gpa, .{ + .kind = .object, + .value = .{ .object = id }, + }); + try self.values.append(self.gpa, .{ + .kind = .string, + .value = .{ + .string = .{ + .ptr = @ptrCast(key), + .len = key.len, + }, + }, + }); + const result = try self.pool.create(self.gpa); + 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.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 new file mode 100644 index 0000000..4630a76 --- /dev/null +++ b/src/z/Env/value.zig @@ -0,0 +1,36 @@ +pub const Value = extern struct { + kind: Kind, + value: extern union { + object: u32, + string: extern struct { + ptr: [*]const u8, + len: usize, + }, + int: isize, + uint: usize, + float: f64, + undefined: void, + }, + + 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 u32, + .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/File.zig b/src/z/File.zig deleted file mode 100644 index cd19dba..0000000 --- a/src/z/File.zig +++ /dev/null @@ -1,17 +0,0 @@ -const Minifier = @import("Minifier.zig"); -const Element = @import("html").Element; - -tag: ?@EnumLiteral(), -minifier: Minifier, - -pub fn load(comptime self: @This(), comptime content: []const u8) Element { - if (self.tag) |tag| { - return .native( - tag, - .{}, - .content(comptime self.minifier.minify(content)), - ); - } else { - return .transparent(.content(comptime self.minifier.minify(content))); - } -} diff --git a/src/z/Minifier.zig b/src/z/Minifier.zig deleted file mode 100644 index 65dd9fb..0000000 --- a/src/z/Minifier.zig +++ /dev/null @@ -1,168 +0,0 @@ -const std = @import("std"); - -/// A string contained in quotes will not be changed in any form. -quotes: []const u8, - -/// This character is used to escape in strings. -escape: ?u8, - -/// A delimiter does not need any padding around it. -delimiters: []const u8, - -/// Kinds of comments, will be removed in the output. -comments: []const struct { []const u8, []const u8 }, - -pub const html: @This() = .{ - .quotes = "\"'", - .escape = null, - .delimiters = "<>", - .comments = &.{.{ "<!--", "-->" }}, -}; - -pub const js: @This() = .{ - .quotes = "\"'`", - .escape = '\\', - .delimiters = "+-*,.:;[](){}=&|^", - .comments = &.{ .{ "//", "\n" }, .{ "/*", "*/" } }, -}; - -pub const css: @This() = .{ - .quotes = "\"'", - .escape = '\\', - .delimiters = ":;{}", - .comments = &.{.{ "/*", "*/" }}, -}; - -fn skip(comptime source: *[]const u8, comptime len: usize) void { - source.* = (source.*)[len..]; -} - -fn push( - comptime source: *[]const u8, - comptime target: *[]const u8, - comptime len: usize, -) void { - target.* = target.* ++ (source.*)[0..len]; - skip(source, len); -} - -pub fn minify( - comptime self: *const @This(), - comptime c: []const u8, -) []const u8 { - @setEvalBranchQuota(c.len * 100); - var content = std.mem.trimStart(u8, c, &std.ascii.whitespace); - var block: []const u8 = ""; - - while (content.len > 0) { - const had_comment: bool = cmt: { - inline for (self.comments) |comment| { - const start, const end = comment; - - if (std.mem.startsWith(u8, content, start)) { - skip(&content, start.len); - skip(&content, if (std.mem.indexOf(u8, content, end)) |l| l + end.len else content.len); - break :cmt true; - } - } - break :cmt false; - }; - - if (had_comment) {} else if (std.mem.indexOfScalar(u8, self.quotes, content[0])) |_| { - const quote = content[0]; - push(&content, &block, 1); - while (content.len > 0) { - if (content[0] == self.escape) { - push(&content, &block, 2); - } else if (content[0] == quote) { - push(&content, &block, 1); - break; - } - push(&content, &block, 1); - } - } else { - push(&content, &block, 1); - } - - const was_trimmed = content.len > 0 and std.ascii.isWhitespace(content[0]); - content = std.mem.trimStart(u8, content, &std.ascii.whitespace); - if (was_trimmed and - block.len > 0 and - content.len > 0 and - std.mem.indexOfScalar(u8, self.delimiters, block[block.len - 1]) == null and - std.mem.indexOfScalar(u8, self.delimiters, content[0]) == null) - { - block = block ++ " "; - } - } - - return block; -} - -test "html" { - const buffer: []const u8 = - \\<html> - \\ <head> - \\ <title>Some Title</title> - \\ </head> - \\ <body> - \\ <z-component type="something here" tag="1 2 3"> 123 </z-component> - \\ <!-- some comment here --> - \\ Hello World! - \\ </body> - \\</html> - ; - - try std.testing.expectEqualStrings( - "<html><head><title>Some Title</title></head><body><z-component type=\"something here\" tag=\"1 2 3\">123</z-component>Hello World!</body></html>", - comptime html.minify(buffer), - ); -} - -test "css" { - const buffer: []const u8 = - \\body { - \\ background: #fff; - \\ color: red; - \\} - \\ - \\#content:first { - \\ user-select: none; - \\ /* comment */ - \\ content: ' '; - \\ padding: 5px 5px; - \\} - ; - - try std.testing.expectEqualStrings( - "body{background:#fff;color:red;}#content:first{user-select:none;content:' ';padding:5px 5px;}", - comptime css.minify(buffer), - ); -} - -test "js" { - const buffer: []const u8 = - \\class extends HTMLElement { - \\ // comment here - \\ constructor() { - \\ super(); - \\ this.attachShadow({ mode: 'open' }); - \\ } - \\ - \\ /* - \\ * Mulitline - \\ */ - \\ connectedCallback() { - \\ const type = this.getAttribute('type'); - \\ const template = document.getElementById(`--${type}`); - \\ const node = document.importNode(template.content, true); - \\ this.shadowRoot.appendChild(node); - \\ } - \\} - ; - - try std.testing.expectEqualStrings( - "class extends HTMLElement{constructor(){super();this.attachShadow({mode:'open'});}connectedCallback(){const type=this.getAttribute('type');const template=document.getElementById(`--${type}`);const node=document.importNode(template.content,true);this.shadowRoot.appendChild(node);}}", - comptime js.minify(buffer), - ); -} diff --git a/src/z/app/main.js b/src/z/app/main.js new file mode 100644 index 0000000..bad4422 --- /dev/null +++ b/src/z/app/main.js @@ -0,0 +1,245 @@ +function decodeString(base, length) { + const slice = new Uint8Array(wasm.memory.buffer, base, length); + return new TextDecoder().decode(slice); +} + +class ObjectStore { + static id_name = "+-store-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', + }); + + static store = { 0: null, 1: window }; + + static generateFreeId() { + let id = 0; + + while (id in ObjectStore.store) { + id = Math.floor(Math.random() * (2**32 - 1)) + } + + return id; + } + + static free(id) { + delete ObjectStore.store[id][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 decodeValue(view, offset) { + if (ObjectStore.types[kind] === 'string') { + const ptr = view.getUint32((offset * 4) * 2, true); + const len = view.getUint32((offset * 4) * 2 + 4, true); + return decodeString(ptr, len); + } + } + + 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 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 writeValue(ptr, value) { + const mem = new DataView(wasm.memory.buffer, ptr); + + if (typeof value === 'object') { + mem.setUint8(0, ObjectStore.types['object'], true); + let id = value == null ? 0 : value[ObjectStore.id_name]; + + if (id === undefined) { + id = ObjectStore.generateFreeId(); + ObjectStore.store[id] = value; + value[ObjectStore.id_name] = id; + } + + mem.setUint32(8, id, true); + + return; + } + + if (typeof value === 'number' && Number.isInteger(value) && value >= 0) { + // uint + throw "unimplemented"; + return; + } + + if (typeof value === 'number' && Number.isInteger(value)) { + // int + throw "unimplemented"; + return; + } + + if (typeof value === 'number') { + // float + throw "unimplemented"; + return; + } + + if (typeof value === 'string') { + // string + throw "unimplemented"; + return; + } + + if (typeof value === 'undefined') { + // undefined + throw "unimplemented"; + 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(decodeString(buffer, length)) + }, + warn(buffer, length) { + console.warn(decodeString(buffer, length)) + }, + error(buffer, length) { + console.error(decodeString(buffer, length)) + }, + debug(buffer, length) { + console.debug(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, + } + + window[ObjectStore.id_name] = 1; + + wasm.exports.run(); + }, +); diff --git a/src/z/app/root.zig b/src/z/app/root.zig new file mode 100644 index 0000000..03760c4 --- /dev/null +++ b/src/z/app/root.zig @@ -0,0 +1,20 @@ +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/env/console.zig b/src/z/env/console.zig new file mode 100644 index 0000000..16f562c --- /dev/null +++ b/src/z/env/console.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/z/env/root.zig b/src/z/env/root.zig new file mode 100644 index 0000000..9e49181 --- /dev/null +++ b/src/z/env/root.zig @@ -0,0 +1,2 @@ + +pub const console = @import("console.zig"); diff --git a/src/z/parser/js/grammar/identifier.zig b/src/z/parser/js/grammar/identifier.zig deleted file mode 100644 index ccc5268..0000000 --- a/src/z/parser/js/grammar/identifier.zig +++ /dev/null @@ -1,60 +0,0 @@ -const std = @import("std"); - -const root = @import("root.zig"); -const Lexer = root.Lexer; -const Token = root.Token; - -pub const Identifier = enum { - public, - private, - - pub inline fn tokenize(comptime lexer: *Lexer) Lexer.Error!void { - comptime { - defer lexer.revert(); - - lexer.context.regex_possible = false; - - const token = tok: { - if (lexer.peekChar() == '#') { - const t = lexer.start(.{ .identifier = .private }); - lexer.skip() catch unreachable; - break :tok t; - } else { - break :tok lexer.start(.{ .identifier = .public }); - } - }; - - switch (try lexer.consume()) { - 'a'...'z', 'A'...'Z', '_' => {}, - else => return Lexer.Error.UnexpectedToken, - } - - while (lexer.peekChar()) |ch| { - switch (ch) { - 'a'...'z', 'A'...'Z', '0'...'9', '_' => {}, - else => break, - } - - try lexer.skip(); - } - - lexer.commit(token); - } - } -}; - -test "simple" { - { - comptime var lexer: Lexer = .init("some_literal9"); - try Identifier.tokenize(&lexer); - try std.testing.expectEqual(1, lexer.tokens.len); - try std.testing.expectEqual(13, lexer.tokens[0].slice.len); - } - - { - comptime var lexer: Lexer = .init("#some_literal9"); - try Identifier.tokenize(&lexer); - try std.testing.expectEqual(1, lexer.tokens.len); - try std.testing.expectEqual(14, lexer.tokens[0].slice.len); - } -} diff --git a/src/z/parser/js/grammar/keyword.zig b/src/z/parser/js/grammar/keyword.zig deleted file mode 100644 index 8e99b4a..0000000 --- a/src/z/parser/js/grammar/keyword.zig +++ /dev/null @@ -1,115 +0,0 @@ -const std = @import("std"); - -const root = @import("root.zig"); -const Lexer = root.Lexer; -const Token = root.Token; - -pub const Keyword = enum { - @"break", - case, - @"catch", - class, - @"const", - @"continue", - debugger, - default, - delete, - do, - @"else", - @"export", - extends, - finally, - @"for", - function, - @"if", - import, - in, - instanceof, - new, - @"return", - super, - @"switch", - this, - throw, - @"try", - typeof, - @"var", - void, - @"while", - with, - yield, - let, - static, - await, - async, - of, - from, - get, - set, - meta, - @"enum", - null, - true, - false, - - const Self = @This(); - - const keywordmap: std.StaticStringMap(Self) = .initComptime(kws: { - var keywords: []const struct { []const u8, Self } = &.{}; - - for (@typeInfo(Self).@"enum".fields) |field| { - const name: []const u8 = field.name; - const value: Self = @field(Self, field.name); - - keywords = keywords ++ .{ .{ name, value } }; - } - - break :kws keywords; - }); - - pub inline fn tokenize(lexer: *Lexer) Lexer.Error!void { - comptime { - @setEvalBranchQuota(10000); - errdefer lexer.revert(); - - lexer.context.regex_possible = true; - - const index = std.mem.findNone(u8, lexer.buffer, std.ascii.lowercase) orelse lexer.buffer.len; - - if (index == 0) return Lexer.Error.UnexpectedToken; - - if (keywordmap.get(lexer.buffer[0..index])) |tag| { - const token = lexer.start(.{ .keyword = tag }); - try lexer.skipTo(index); - lexer.commit(token); - } else { - return Lexer.Error.UnexpectedToken; - } - } - } -}; - -test "simple" { - inline for (comptime Keyword.keywordmap.keys()) |key| { - comptime var lexer: Lexer = .init(key); - try Keyword.tokenize(&lexer); - try std.testing.expectEqual(1, lexer.tokens.len); - try std.testing.expectEqual(key.len, lexer.tokens[0].slice.len); - } -} - -test "ending" { - inline for (comptime Keyword.keywordmap.keys()) |key| { - comptime var lexer: Lexer = .init(key ++ "."); - try Keyword.tokenize(&lexer); - try std.testing.expectEqual(1, lexer.tokens.len); - try std.testing.expectEqual(key.len, lexer.tokens[0].slice.len); - } -} - -test "subword" { - inline for (comptime Keyword.keywordmap.keys()) |key| { - comptime var lexer: Lexer = .init(key ++ "a"); - try std.testing.expectError(Lexer.Error.UnexpectedToken, Keyword.tokenize(&lexer)); - } -} diff --git a/src/z/parser/js/grammar/literal.zig b/src/z/parser/js/grammar/literal.zig deleted file mode 100644 index 4316dee..0000000 --- a/src/z/parser/js/grammar/literal.zig +++ /dev/null @@ -1,192 +0,0 @@ -const std = @import("std"); - -const root = @import("root.zig"); -const Lexer = root.Lexer; -const Token = root.Token; - -pub const Literal = union(enum) { - // NOTE: currently only decimal literals are tokenized - numeric: void, - bigint: void, - string: void, - template: enum { - whole, - start, - middle, - end, - }, - regex: void, - - const digits = "_0123456789abcdef"; - - pub inline fn tokenize(comptime lexer: *Lexer) Lexer.Error!void { - comptime { - errdefer lexer.revert(); - - var token = lexer.start(.{ .literal = undefined }); - - const regex_possible = lexer.context.regex_possible; - lexer.context.regex_possible = false; - - switch (try lexer.consume()) { - '0'...'9', '.' => |c| { - const base = if (c != '0') 10 else switch (lexer.peekChar() orelse 0) { - 'x' => 16, - 'o' => 8, - 'b' => 2, - else => 10, - }; - - if (base != 10) lexer.skip() catch unreachable; - - { - const index = std.mem.findNone( - u8, - lexer.buffer, - digits[0 .. base + 1], - ) orelse lexer.buffer.len; - try lexer.skipTo(index); - - - if (index == 0 and base != 10) return Lexer.Error.UnexpectedToken; - } - - if (base == 10 and lexer.peekChar() == '.') { - try lexer.skip(); - const index = std.mem.findNone( - u8, - lexer.buffer, - digits[0 .. base + 1], - ) orelse lexer.buffer.len; - try lexer.skipTo(index); - } - - if (lexer.peekChar() == 'n') { - lexer.skip() catch unreachable; - token.kind.literal = .bigint; - } else { - token.kind.literal = .numeric; - } - }, - '\'', '"' => |quote| { - token.kind.literal = .string; - while (true) { - switch (try lexer.consume()) { - quote => break, - '\\' => try lexer.skip(), - else => {}, - } - } - }, - '`' => { - token.kind.literal = .{ .template = undefined }; - - while (true) { - switch (try lexer.consume()) { - '`' => { - token.kind.literal.template = .whole; - break; - }, - '\\' => try lexer.skip(), - '$' => if (lexer.peekChar() == '{') { - lexer.skip() catch unreachable; - lexer.context.template_nesting += 1; - token.kind.literal.template = .start; - lexer.context.regex_possible = true; - break; - }, - else => {}, - } - } - }, - '}' => if (lexer.context.template_nesting > 0) { - lexer.context.template_nesting -= 1; - token.kind.literal = .{ .template = undefined }; - - while (true) { - switch (try lexer.consume()) { - '`' => { - token.kind.literal.template = .end; - break; - }, - '\\' => try lexer.skip(), - '$' => if (lexer.peekChar() == '{') { - lexer.skip() catch unreachable; - lexer.context.template_nesting += 1; - token.kind.literal.template = .middle; - lexer.context.regex_possible = true; - break; - }, - else => {}, - } - } - } else return Lexer.Error.UnexpectedToken, - '/' => if (regex_possible) { - token.kind.literal = .regex; - while (true) { - switch (try lexer.consume()) { - '/' => break, - '\\' => try lexer.skip(), - '\n' => return Lexer.Error.UnexpectedToken, - else => {}, - } - } - } else return Lexer.Error.UnexpectedToken, - else => return Lexer.Error.UnexpectedToken, - } - - lexer.commit(token); - } - } -}; - -test "numeric" { - const Simple = struct { - pub fn run(comptime buffer: []const u8, n: usize) !void { - comptime var lexer: Lexer = .init(buffer); - try Literal.tokenize(&lexer); - try std.testing.expectEqual(1, lexer.tokens.len); - try std.testing.expectEqual(n, lexer.tokens[0].slice.len); - } - }; - - try Simple.run("1234", 4); - try Simple.run("1.234", 5); - try Simple.run("1_2_3_4", 7); - try Simple.run("0b101011", 8); - try Simple.run("0xabcf01", 8); - try Simple.run("0o731734", 8); - try Simple.run("0o731734n", 9); -} - -test "string" { - const Simple = struct { - pub fn run(comptime buffer: []const u8, n: usize) !void { - comptime var lexer: Lexer = .init(buffer); - try Literal.tokenize(&lexer); - try std.testing.expectEqual(1, lexer.tokens.len); - try std.testing.expectEqual(n, lexer.tokens[0].slice.len); - } - }; - - try Simple.run("'hello'", 7); - try Simple.run("\"hello\"", 7); - try std.testing.expectError( - Lexer.Error.EndOfBuffer, - Simple.run("'hello", 0), - ); -} - -test "regex" { - const Simple = struct { - pub fn run(comptime buffer: []const u8, n: usize) !void { - comptime var lexer: Lexer = .init(buffer); - try Literal.tokenize(&lexer); - try std.testing.expectEqual(1, lexer.tokens.len); - try std.testing.expectEqual(n, lexer.tokens[0].slice.len); - } - }; - - try Simple.run("/hello/", 7); - try Simple.run("/some string\\/ here/", 20); -} diff --git a/src/z/parser/js/grammar/punctuator.zig b/src/z/parser/js/grammar/punctuator.zig deleted file mode 100644 index b085ce1..0000000 --- a/src/z/parser/js/grammar/punctuator.zig +++ /dev/null @@ -1,122 +0,0 @@ -const std = @import("std"); - -const root = @import("root.zig"); -const Lexer = root.Lexer; -const Token = root.Token; - -pub const Punctuator = enum { - @"+", - @"-", - @"*", - @"/", - @"%", - @"**", - @"++", - @"--", - @"=", - @"+=", - @"-=", - @"*=", - @"/=", - @"%=", - @"**=", - @"&=", - @"|=", - @"^=", - @"<<=", - @">>=", - @">>>=", - @"&&=", - @"||=", - @"??=", - @"==", - @"===", - @"!=", - @"!==", - @"<", - @"<=", - @">", - @">=", - @"&&", - @"||", - @"??", - @"&", - @"|", - @"^", - @"~", - @"<<", - @">>", - @">>>", - @"!", - @"?", - @":", - @";", - @",", - @".", - @"...", - @"=>", - @"(", - @")", - @"[", - @"]", - @"{", - @"}", - @"?.", - @"#", - @"@", - - const Self = @This(); - - const punctuatormap: std.StaticStringMap(Self) = .initComptime(kws: { - var punctuators: []const struct { []const u8, Self } = &.{}; - - for (@typeInfo(Self).@"enum".fields) |field| { - const name: []const u8 = field.name; - const value: Self = @field(Self, field.name); - - punctuators = punctuators ++ .{.{ name, value }}; - } - - break :kws punctuators; - }); - - pub inline fn tokenize(comptime lexer: *Lexer) Lexer.Error!void { - comptime { - @setEvalBranchQuota(10_000); - defer lexer.revert(); - - lexer.context.regex_possible = true; - - if (punctuatormap.getLongestPrefix(lexer.buffer)) |pair| { - - if (std.mem.eql(u8, pair.key, "}") and lexer.context.template_nesting > 0) { - return Lexer.Error.UnexpectedToken; - } - - const token = lexer.start(.{ .punctuator = pair.value }); - try lexer.skipTo(pair.key.len); - lexer.commit(token); - } else { - return Lexer.Error.UnexpectedToken; - } - } - } -}; - -test "simple" { - inline for (comptime Punctuator.punctuatormap.keys()) |key| { - comptime var lexer: Lexer = .init(key); - try Punctuator.tokenize(&lexer); - try std.testing.expectEqual(1, lexer.tokens.len); - try std.testing.expectEqual(key.len, lexer.tokens[0].slice.len); - } -} - -test "ending" { - inline for (comptime Punctuator.punctuatormap.keys()) |key| { - comptime var lexer: Lexer = .init(key ++ "a"); - try Punctuator.tokenize(&lexer); - try std.testing.expectEqual(1, lexer.tokens.len); - try std.testing.expectEqual(key.len, lexer.tokens[0].slice.len); - } -} diff --git a/src/z/parser/js/grammar/root.zig b/src/z/parser/js/grammar/root.zig deleted file mode 100644 index f732b7f..0000000 --- a/src/z/parser/js/grammar/root.zig +++ /dev/null @@ -1,66 +0,0 @@ -//! This is a Javascript parser and tokenizer. -//! It is and probably will never be complete, -//! since js is a very strange language and I want -//! to move forward and code on more interesting things -//! I started something called mujs (micro-js). It's a -//! subset of the javascript language. It does not support -//! the regex literal and currently also not template strings. -//! It is chosen like that to make parsing easier and also less -//! context-dependent. - -const std = @import("std"); - -const parser = @import("../../root.zig"); - -pub const Lexer = parser.Lexer(Grammar); -pub const Token = parser.Token(Grammar); - -pub const Whitespace = @import("whitespace.zig").Whitespace; -pub const Keyword = @import("keyword.zig").Keyword; -pub const Literal = @import("literal.zig").Literal; -pub const Punctuator = @import("punctuator.zig").Punctuator; -pub const Identifier = @import("identifier.zig").Identifier; - -pub const Grammar = union(enum) { - whitespace: Whitespace, - keyword: Keyword, - literal: Literal, - punctuator: Punctuator, - identifier: Identifier, - end_of_file: void, - - pub const Context = struct { - template_nesting: usize = 0, - regex_possible: bool = true, - }; - - pub inline fn tokenize(comptime lexer: *Lexer) Lexer.Error!void { - @setEvalBranchQuota(lexer.buffer.len * 1000); - comptime { - while (lexer.peekChar()) |_| { - Whitespace.tokenize(lexer) catch { - Keyword.tokenize(lexer) catch { - Literal.tokenize(lexer) catch { - Punctuator.tokenize(lexer) catch { - try Identifier.tokenize(lexer); - }; - }; - }; - }; - } - - lexer.commit(lexer.start(.end_of_file)); - } - } -}; - -test { - _ = std.testing.refAllDecls(@This()); -} - -test "z.js" { - comptime var lexer: Lexer = .init(@embedFile("../../../z.js")); - Grammar.tokenize(&lexer) catch |err| { - std.debug.print("error: {} at {s}", .{ err, lexer.buffer }); - }; -} diff --git a/src/z/parser/js/grammar/whitespace.zig b/src/z/parser/js/grammar/whitespace.zig deleted file mode 100644 index 08d031f..0000000 --- a/src/z/parser/js/grammar/whitespace.zig +++ /dev/null @@ -1,102 +0,0 @@ -const std = @import("std"); -const Lexer = @import("root.zig").Lexer; -const Token = @import("root.zig").Token; - -pub const Whitespace = enum { - space, - line_comment, - block_comment, - - pub inline fn tokenize(comptime lexer: *Lexer) Lexer.Error!void { - comptime { - errdefer lexer.revert(); - - var token = lexer.start(.{ .whitespace = undefined }); - - switch (try lexer.consume()) { - ' ', '\t', '\r', '\n' => { - token.kind.whitespace = .space; - - while (lexer.peekChar()) |ch| { - switch (ch) { - ' ', '\t', '\r', '\n' => try lexer.skip(), - else => break, - } - } - }, - '/' => { - switch (lexer.peekChar() orelse 0) { - '*' => { - token.kind.whitespace = .block_comment; - try lexer.skipUntil("*/"); - }, - '/' => { - token.kind.whitespace = .line_comment; - lexer.skipUntil("\n") catch lexer.skipToEnd(); - }, - else => return Lexer.Error.UnexpectedToken, - } - }, - else => return Lexer.Error.UnexpectedToken, - } - - lexer.commit(token); - } - } -}; - -test "space" { - { - comptime var lexer: Lexer = .init(" "); - try Whitespace.tokenize(&lexer); - try std.testing.expectEqual(1, lexer.tokens.len); - try std.testing.expectEqual(1, lexer.tokens[0].slice.len); - } - - { - comptime var lexer: Lexer = .init(" \t\t \n\r "); - try Whitespace.tokenize(&lexer); - try std.testing.expectEqual(1, lexer.tokens.len); - try std.testing.expectEqual(10, lexer.tokens[0].slice.len); - } -} - -test "line-comment" { - { - comptime var lexer: Lexer = .init("// some comment"); - try Whitespace.tokenize(&lexer); - try std.testing.expectEqual(1, lexer.tokens.len); - try std.testing.expectEqualStrings("// some comment", lexer.tokens[0].slice); - } - - { - comptime var lexer: Lexer = .init("// some comment\n"); - try Whitespace.tokenize(&lexer); - try std.testing.expectEqual(1, lexer.tokens.len); - try std.testing.expectEqualStrings("// some comment\n", lexer.tokens[0].slice); - } -} - -test "block-comment" { - { - comptime var lexer: Lexer = .init("/* some comment */"); - try Whitespace.tokenize(&lexer); - try std.testing.expectEqual(1, lexer.tokens.len); - try std.testing.expectEqualStrings("/* some comment */", lexer.tokens[0].slice); - } -} - -test "mixed" { - comptime var lexer: Lexer = .init( - \\ // some comment - \\/* other comment here */ // comment or so - \\ /* multi - \\ * line - \\ * comment - \\ */ - ); - inline while (Whitespace.tokenize(&lexer)) { - } else |_| {} - - try std.testing.expectEqual(7, lexer.tokens.len); -} diff --git a/src/z/parser/js/root.zig b/src/z/parser/js/root.zig deleted file mode 100644 index e604855..0000000 --- a/src/z/parser/js/root.zig +++ /dev/null @@ -1,7 +0,0 @@ -const std = @import("std"); - -pub const grammar = @import("./grammar/root.zig"); - -test { - _ = std.testing.refAllDecls(@This()); -} diff --git a/src/z/parser/lexer.zig b/src/z/parser/lexer.zig deleted file mode 100644 index 5beefde..0000000 --- a/src/z/parser/lexer.zig +++ /dev/null @@ -1,127 +0,0 @@ -const std = @import("std"); - -pub fn Token(TokenKind: type) type { - return struct { - const Self = @This(); - - kind: TokenKind, - slice: []const u8, - - pub fn start(comptime lexer: *const Lexer(TokenKind), kind: TokenKind) Self { - return .{ - .kind = kind, - .slice = lexer.buffer, - }; - } - - pub inline fn stop(comptime self: Self, comptime lexer: *const Lexer(TokenKind)) Self { - comptime { - const length = self.slice.len - lexer.buffer.len; - return .{ - .kind = self.kind, - .slice = self.slice[0..length], - }; - } - } - - pub fn format(self: *const Self, writer: *std.Io.Writer) !void { - try writer.print("Token{}(\"{s}\")", .{self.kind, self.slice}); - } - }; -} - -pub fn Lexer(TokenKind: type) type { - return struct { - const Self = @This(); - - pub const Error = error{ - UnexpectedToken, - EndOfBuffer, - }; - - buffer: []const u8, - last_buffer: []const u8, - tokens: []const Token(TokenKind) = &.{}, - context: TokenKind.Context = .{}, - last_context: TokenKind.Context = .{}, - - pub fn init(buffer: []const u8) Self { - return .{ - .buffer = buffer, - .last_buffer = buffer, - }; - } - - pub inline fn peekChar(self: *Self) ?u8 { - return self.peekCharAt(0); - } - - pub inline fn peekCharAt(self: *Self, n: usize) ?u8 { - return if (n < self.buffer.len) self.buffer[n] else null; - } - - pub fn peekSlice(self: *Self, length: usize) ?[]const u8 { - return self.peekSliceAt(length, 0); - } - - pub fn peekSliceAt(self: *Self, length: usize, offset: usize) ?[]const u8 { - if (length + offset <= self.buffer.len) { - return self.buffer[offset .. offset + length]; - } - return null; - } - - pub fn consume(self: *Self) !u8 { - return (try self.consumeTo(1))[0]; - } - - pub fn consumeTo(self: *Self, n: usize) ![]const u8 { - if (n <= self.buffer.len) { - const slice = self.buffer[0..n]; - self.buffer = self.buffer[n..]; - return slice; - } else { - return Error.EndOfBuffer; - } - } - - pub fn skip(self: *Self) !void { - return self.skipTo(1); - } - - pub fn skipTo(self: *Self, n: usize) Error!void { - if (n <= self.buffer.len) { - self.buffer = self.buffer[n..]; - } else { - return Error.EndOfBuffer; - } - } - - pub fn skipUntil(self: *Self, literal: []const u8) Error!void { - if (std.mem.find(u8, self.buffer, literal)) |index| { - self.buffer = self.buffer[index + literal.len..]; - } else { - return Error.EndOfBuffer; - } - } - - pub fn skipToEnd(self: *Self) void { - self.buffer = self.buffer[self.buffer.len..]; - } - - pub fn start(self: *Self, kind: TokenKind) Token(TokenKind) { - return .start(self, kind); - } - - pub fn revert(self: *Self) void { - self.buffer = self.last_buffer; - self.context = self.last_context; - } - - pub fn commit(self: *Self, tok: Token(TokenKind)) void { - self.tokens = self.tokens ++ [_]Token(TokenKind){tok.stop(self)}; - self.last_buffer = self.buffer; - self.last_context = self.context; - } - }; -} diff --git a/src/z/parser/root.zig b/src/z/parser/root.zig deleted file mode 100644 index e0b67fb..0000000 --- a/src/z/parser/root.zig +++ /dev/null @@ -1,17 +0,0 @@ -const std = @import("std"); - -const lexer = @import("lexer.zig"); -pub const Lexer = lexer.Lexer; -pub const Token = lexer.Token; - -pub const js = @import("js/root.zig"); - -pub fn Parser(TokenType: type) type { - return struct { - buffer: []const TokenType, - }; -} - -test { - _ = std.testing.refAllDecls(@This()); -} diff --git a/src/z/rest.js b/src/z/rest.js deleted file mode 100644 index c14944d..0000000 --- a/src/z/rest.js +++ /dev/null @@ -1,20 +0,0 @@ - -const Rest = { - Request: class { - constructor(base) { - this.base = base; - } - - get(url) { return fetch(url); } - - post(url, body) { - return fetch( - url, - { - method: 'POST', - body: JSON.stringify(body), - } - ); - } - }, -}; diff --git a/src/z/root.zig b/src/z/root.zig index 1fa8d99..6ca6302 100644 --- a/src/z/root.zig +++ b/src/z/root.zig @@ -1,56 +1,19 @@ -const std = @import("std"); +const builtin = @import("builtin"); -pub const Minifier = @import("Minifier.zig"); -pub const Component = @import("Component.zig"); -pub const File = @import("File.zig"); -pub const parser = @import("parser/root.zig"); +const wasm = wasm_struct: { + if (builtin.target.cpu.arch.isWasm()) { + break :wasm_struct struct { + pub const env = @import("env/root.zig"); + pub const Env = @import("Env/root.zig"); -const Element = @import("html").Element; - -pub const script: File = .{ - .tag = .script, - .minifier = .js, -}; -pub const style: File = .{ - .tag = .style, - .minifier = .css, -}; -pub const body: File = .{ - .tag = .body, - .minifier = .html, -}; - -pub const html: File = .{ - .tag = null, - .minifier = .html, -}; - -pub fn env(comptime components: []const Component) Element { - var children: []const Element = &.{ - script.load(@embedFile("z.js")), - script.load(@embedFile("rest.js")), - }; - - inline for (components) |c| { - const child: []const Element = &.{c.toElement()}; - children = children ++ child; + export const bit_length: u8 = @sizeOf(usize); + }; } - return .transparent(.children(children)); -} - -pub fn component(kind: @EnumLiteral(), attrs: anytype, content: Element.Content) Element { - var element: Element = .native(.@"z-component", attrs, content); - - const type_attr: []const Element.Attribute = &.{.{ - .name = "type", - .value = @tagName(kind), - }}; - element.attributes = type_attr ++ element.attributes; + break :wasm_struct struct {}; +}; - return element; -} +pub const env = wasm.env; +pub const Env = wasm.Env; -test { - _ = std.testing.refAllDecls(@This()); -} +pub const app = @import("app/root.zig"); diff --git a/src/z/z.js b/src/z/z.js deleted file mode 100644 index e279f42..0000000 --- a/src/z/z.js +++ /dev/null @@ -1,101 +0,0 @@ -class ZComponent extends HTMLElement { - static observedAttributes = [ 'type' ]; - - constructor() { - super(); - this.attachShadow({ mode: 'open' }); - this.onconnected = () => {}; - this.ondisconnected = () => {}; - } - - build() { - const type = this.getAttribute('type'); - - if (type == null) { - throw `component without any type given.`; - } - - const template = document.getElementById(`@${type}`); - - if (template == null) { - throw `component '${type}' does not exist.`; - } - - const node = document.importNode(template.content, true); - this.shadowRoot.appendChild(node); - - Zenv.constructors[`component__${type}`](new Zenv(this)); - } - - attributeChangedCallback(name, previous, current) { - if (name == 'type') { - this.shadowRoot.innerHTML = ''; - this.build() - } - } - - connectedCallback() { - this.onconnected(); - } - - disconnectedCallback() { - this.ondisconnected(); - } -} - -class Zenv { - static constructors = {}; - - constructor(doc) { - this.document = doc; - } - - component(type, slots) { - const element = document.createElement('z-component'); - element.setAttribute('type', type); - - for (const name in slots) { - const slot = slots[name]; - slot.setAttribute('slot', name); - element.appendChild(slot); - } - - return element; - } - - populate_attributes(obj, attrs) { - for (const attr in attrs) { - if (typeof(obj[attr]) == 'object' && typeof(attrs[attr]) == 'object') { - this.populate_attributes(obj[attr], attrs[attr]); - } else { - obj[attr] = attrs[attr]; - } - } - } - - native(name, options) { - const element = document.createElement(name); - this.populate_attributes(element, options); - return element; - } - - by_id(id) { - return this.document.shadowRoot.getElementById(id); - } - - by_selector(query) { - return this.document.shadowRoot.querySelector(query); - } - - by_selector_all(query) { - return this.document.shadowRoot.querySelectorAll(query); - } - - get body() { - return this.document.shadowRoot; - } -} - -Z = new Zenv(document.body); - -customElements.define("z-component", ZComponent); |