diff options
Diffstat (limited to 'src/z')
| -rw-r--r-- | src/z/AppBundle.zig | 35 | ||||
| -rw-r--r-- | src/z/Component.zig | 18 | ||||
| -rw-r--r-- | src/z/Env/Future.zig | 29 | ||||
| -rw-r--r-- | src/z/Env/call.zig | 15 | ||||
| -rw-r--r-- | src/z/Env/js.zig | 9 | ||||
| -rw-r--r-- | src/z/Env/root.zig | 64 | ||||
| -rw-r--r-- | src/z/Env/value.zig | 36 | ||||
| -rw-r--r-- | src/z/File.zig | 18 | ||||
| -rw-r--r-- | src/z/Minifier.zig | 168 | ||||
| -rw-r--r-- | src/z/app/main.js | 245 | ||||
| -rw-r--r-- | src/z/app/root.zig | 20 | ||||
| -rw-r--r-- | src/z/env/console.zig | 24 | ||||
| -rw-r--r-- | src/z/env/root.zig | 2 | ||||
| -rw-r--r-- | src/z/root.zig | 59 | ||||
| -rw-r--r-- | src/z/z.js | 82 |
15 files changed, 492 insertions, 332 deletions
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 cd7094f..0000000 --- a/src/z/File.zig +++ /dev/null @@ -1,18 +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/root.zig b/src/z/root.zig index 26bbffc..6ca6302 100644 --- a/src/z/root.zig +++ b/src/z/root.zig @@ -1,52 +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"); +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"))}; - - 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 ba07b9e..0000000 --- a/src/z/z.js +++ /dev/null @@ -1,82 +0,0 @@ -class ZComponent extends HTMLElement { - constructor() { - super(); - this.attachShadow({ mode: 'open' }); - } - - connectedCallback() { - 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)); - } -} - -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); |