@thi.ng/wasm-api 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bridge.js CHANGED
@@ -1,6 +1,23 @@
1
- import { assert } from "@thi.ng/errors/assert";
2
- import { U16, U32, U8 } from "@thi.ng/hex";
1
+ import { illegalArgs } from "@thi.ng/errors/illegal-arguments";
2
+ import { U16, U32, U64HL, U8 } from "@thi.ng/hex";
3
3
  import { ConsoleLogger } from "@thi.ng/logger/console";
4
+ const B32 = BigInt(32);
5
+ /**
6
+ * The main interop API bridge between the JS host environment and a WebAssembly
7
+ * module. This class provides a small core API with various typed accessors and
8
+ * utils to exchange data (scalars, arrays, strings etc.) via the WASM module's
9
+ * memory.
10
+ *
11
+ * @remarks
12
+ * All typed memory accessors are assuming the given lookup addresses are
13
+ * properly aligned to the corresponding primitive types (e.g. f32 values are
14
+ * aligned to 4 byte boundaries, f64 to 8 bytes etc.) Unaligned access is
15
+ * explicitly **not supported**! If you need such, please refer to other
16
+ * mechanisms like JS `DataView`...
17
+ *
18
+ * 64bit integers are handled via JS `BigInt` and hence require the host env to
19
+ * support it. No polyfill is provided.
20
+ */
4
21
  export class WasmBridge {
5
22
  constructor(modules = {}, logger = new ConsoleLogger("wasm")) {
6
23
  this.modules = modules;
@@ -17,8 +34,11 @@ export class WasmBridge {
17
34
  printU16: logN,
18
35
  printU16Hex: (x) => this.logger.debug(`0x${U16(x)}`),
19
36
  printI32: logN,
20
- printU32: logN,
37
+ printU32: (x) => this.logger.debug(x >>> 0),
21
38
  printU32Hex: (x) => this.logger.debug(`0x${U32(x)}`),
39
+ _printI64: (hi, lo) => this.logger.debug((BigInt(hi) << B32) | BigInt(lo)),
40
+ _printU64: (hi, lo) => this.logger.debug((BigInt(hi >>> 0) << B32) | BigInt(lo >>> 0)),
41
+ _printU64Hex: (hi, lo) => this.logger.debug(`0x${U64HL(hi, lo)}`),
22
42
  printF32: logN,
23
43
  printF64: logN,
24
44
  _printI8Array: logA(this.getI8Array.bind(this)),
@@ -27,21 +47,59 @@ export class WasmBridge {
27
47
  _printU16Array: logA(this.getU16Array.bind(this)),
28
48
  _printI32Array: logA(this.getI32Array.bind(this)),
29
49
  _printU32Array: logA(this.getU32Array.bind(this)),
50
+ _printI64Array: logA(this.getI64Array.bind(this)),
51
+ _printU64Array: logA(this.getU64Array.bind(this)),
30
52
  _printF32Array: logA(this.getF32Array.bind(this)),
31
53
  _printF64Array: logA(this.getF64Array.bind(this)),
32
54
  _printStr0: (addr) => this.logger.debug(this.getString(addr, 0)),
33
55
  _printStr: (addr, len) => this.logger.debug(this.getString(addr, len)),
34
56
  };
35
57
  }
36
- async init(mem) {
37
- this.i8 = new Int8Array(mem.buffer);
38
- this.u8 = new Uint8Array(mem.buffer);
39
- this.i16 = new Int16Array(mem.buffer);
40
- this.u16 = new Uint16Array(mem.buffer);
41
- this.i32 = new Int32Array(mem.buffer);
42
- this.u32 = new Uint32Array(mem.buffer);
43
- this.f32 = new Float32Array(mem.buffer);
44
- this.f64 = new Float64Array(mem.buffer);
58
+ /**
59
+ * Instantiates WASM module from given `src` (and optional provided extra
60
+ * imports), then automatically calls {@link WasmBridge.init} with the
61
+ * modules exports.
62
+ *
63
+ * @remarks
64
+ * If the given `src` is a `Response` or `Promise<Response>`, the module
65
+ * will be instantiated via `WebAssembly.instantiateStreaming()`, otherwise
66
+ * the non-streaming version will be used.
67
+ *
68
+ * @param src
69
+ * @param imports
70
+ */
71
+ async instantiate(src, imports) {
72
+ const $src = await src;
73
+ const $imports = { ...imports, ...this.getImports() };
74
+ let wasm;
75
+ if ($src instanceof Response) {
76
+ wasm = await WebAssembly.instantiateStreaming($src, $imports);
77
+ }
78
+ else {
79
+ wasm = await WebAssembly.instantiate($src, $imports);
80
+ }
81
+ return this.init(wasm.instance.exports);
82
+ }
83
+ /**
84
+ * Receives the WASM module's exports, stores the for future reference and
85
+ * then initializes all declared bridge child API modules. Returns false if
86
+ * any of the module initializations failed.
87
+ *
88
+ * @param exports
89
+ */
90
+ async init(exports) {
91
+ this.exports = exports;
92
+ const buf = exports.memory.buffer;
93
+ this.i8 = new Int8Array(buf);
94
+ this.u8 = new Uint8Array(buf);
95
+ this.i16 = new Int16Array(buf);
96
+ this.u16 = new Uint16Array(buf);
97
+ this.i32 = new Int32Array(buf);
98
+ this.u32 = new Uint32Array(buf);
99
+ this.i64 = new BigInt64Array(buf);
100
+ this.u64 = new BigUint64Array(buf);
101
+ this.f32 = new Float32Array(buf);
102
+ this.f64 = new Float64Array(buf);
45
103
  for (let id in this.modules) {
46
104
  this.logger.debug(`initializing API module: ${id}`);
47
105
  const status = await this.modules[id].init(this);
@@ -51,87 +109,196 @@ export class WasmBridge {
51
109
  return true;
52
110
  }
53
111
  /**
54
- * Returns object of all WASM imports declared in the bridge core API and
55
- * any provided child APIs.
112
+ * Required use for WASM module instantiation to provide JS imports to the
113
+ * module. Returns an object of all WASM imports declared by the bridge core
114
+ * API and any provided bridge API modules.
115
+ *
116
+ * @remarks
117
+ * Since all declared imports will be merged into a single flat namespace,
118
+ * it's recommended to use per-module naming prefixes to avoid clashes. If
119
+ * there're any naming clashes, this function will throw an error.
56
120
  */
57
121
  getImports() {
58
122
  const env = { ...this.core };
59
123
  for (let id in this.modules) {
60
- Object.assign(env, this.modules[id].getImports());
124
+ const imports = this.modules[id].getImports();
125
+ // check for naming clashes
126
+ for (let k in imports) {
127
+ if (env[k] !== undefined) {
128
+ illegalArgs(`attempt to redeclare import: ${k} by API module ${id}`);
129
+ }
130
+ }
131
+ Object.assign(env, imports);
61
132
  }
62
133
  return { env };
63
134
  }
64
- getI8Array(ptr, len) {
65
- return this.i8.subarray(ptr, ptr + len);
135
+ getI8(addr) {
136
+ return this.i8[addr];
137
+ }
138
+ getU8(addr) {
139
+ return this.u8[addr];
140
+ }
141
+ getI16(addr) {
142
+ return this.i16[addr >> 1];
143
+ }
144
+ getU16(addr) {
145
+ return this.u16[addr >> 1];
146
+ }
147
+ getI32(addr) {
148
+ return this.i32[addr >> 2];
149
+ }
150
+ getU32(addr) {
151
+ return this.u32[addr >> 2];
152
+ }
153
+ getI64(addr) {
154
+ return this.i64[addr >> 3];
155
+ }
156
+ getU64(addr) {
157
+ return this.u64[addr >> 3];
158
+ }
159
+ getF32(addr) {
160
+ return this.f32[addr >> 2];
161
+ }
162
+ getF64(addr) {
163
+ return this.f64[addr >> 3];
164
+ }
165
+ setI8(addr, x) {
166
+ this.i8[addr] = x;
167
+ return this;
168
+ }
169
+ setU8(addr, x) {
170
+ this.u8[addr] = x;
171
+ return this;
172
+ }
173
+ setI16(addr, x) {
174
+ this.i16[addr >> 1] = x;
175
+ return this;
176
+ }
177
+ setU16(addr, x) {
178
+ this.u16[addr >> 1] = x;
179
+ return this;
180
+ }
181
+ setI32(addr, x) {
182
+ this.i32[addr >> 2] = x;
183
+ return this;
66
184
  }
67
- getU8Array(ptr, len) {
68
- return this.u8.subarray(ptr, ptr + len);
185
+ setU32(addr, x) {
186
+ this.u32[addr >> 2] = x;
187
+ return this;
69
188
  }
70
- getI16Array(ptr, len) {
71
- ptr >>= 1;
72
- return this.i16.subarray(ptr, ptr + len);
189
+ setI64(addr, x) {
190
+ this.i64[addr >> 3] = x;
191
+ return this;
73
192
  }
74
- getU16Array(ptr, len) {
75
- ptr >>= 1;
76
- return this.u16.subarray(ptr, ptr + len);
193
+ setU64(addr, x) {
194
+ this.u64[addr >> 3] = x;
195
+ return this;
77
196
  }
78
- getI32Array(ptr, len) {
79
- ptr >>= 2;
80
- return this.i32.subarray(ptr, ptr + len);
197
+ setF32(addr, x) {
198
+ this.f32[addr >> 2] = x;
199
+ return this;
81
200
  }
82
- getU32Array(ptr, len) {
83
- ptr >>= 2;
84
- return this.u32.subarray(ptr, ptr + len);
201
+ setF64(addr, x) {
202
+ this.f64[addr >> 3] = x;
203
+ return this;
85
204
  }
86
- getF32Array(ptr, len) {
87
- ptr >>= 2;
88
- return this.f32.subarray(ptr, ptr + len);
205
+ getI8Array(addr, len) {
206
+ return this.i8.subarray(addr, addr + len);
89
207
  }
90
- getF64Array(ptr, len) {
91
- ptr >>= 3;
92
- return this.f64.subarray(ptr, ptr + len);
208
+ getU8Array(addr, len) {
209
+ return this.u8.subarray(addr, addr + len);
93
210
  }
94
- derefI8(ptr) {
95
- return this.i8[ptr];
211
+ getI16Array(addr, len) {
212
+ addr >>= 1;
213
+ return this.i16.subarray(addr, addr + len);
96
214
  }
97
- derefU8(ptr) {
98
- return this.u8[ptr];
215
+ getU16Array(addr, len) {
216
+ addr >>= 1;
217
+ return this.u16.subarray(addr, addr + len);
99
218
  }
100
- derefI16(ptr) {
101
- return this.i16[ptr >> 1];
219
+ getI32Array(addr, len) {
220
+ addr >>= 2;
221
+ return this.i32.subarray(addr, addr + len);
102
222
  }
103
- derefU16(ptr) {
104
- return this.u16[ptr >> 1];
223
+ getU32Array(addr, len) {
224
+ addr >>= 2;
225
+ return this.u32.subarray(addr, addr + len);
105
226
  }
106
- derefI32(ptr) {
107
- return this.i32[ptr >> 2];
227
+ getI64Array(addr, len) {
228
+ addr >>= 3;
229
+ return this.i64.subarray(addr, addr + len);
108
230
  }
109
- derefU32(ptr) {
110
- return this.u32[ptr >> 2];
231
+ getU64Array(addr, len) {
232
+ addr >>= 3;
233
+ return this.u64.subarray(addr, addr + len);
111
234
  }
112
- derefF32(ptr) {
113
- return this.f32[ptr >> 2];
235
+ getF32Array(addr, len) {
236
+ addr >>= 2;
237
+ return this.f32.subarray(addr, addr + len);
114
238
  }
115
- derefF64(ptr) {
116
- return this.f64[ptr >> 3];
239
+ getF64Array(addr, len) {
240
+ addr >>= 3;
241
+ return this.f64.subarray(addr, addr + len);
242
+ }
243
+ setI8Array(addr, buf) {
244
+ this.i8.set(buf, addr);
245
+ return this;
246
+ }
247
+ setU8Array(addr, buf) {
248
+ this.u8.set(buf, addr);
249
+ return this;
250
+ }
251
+ setI16Array(addr, buf) {
252
+ this.i16.set(buf, addr >> 1);
253
+ return this;
254
+ }
255
+ setU16Array(addr, buf) {
256
+ this.u16.set(buf, addr >> 1);
257
+ return this;
258
+ }
259
+ setI32Array(addr, buf) {
260
+ this.i32.set(buf, addr >> 2);
261
+ return this;
262
+ }
263
+ setU32Array(addr, buf) {
264
+ this.u32.set(buf, addr >> 2);
265
+ return this;
266
+ }
267
+ setI64Array(addr, buf) {
268
+ this.i64.set(buf, addr >> 3);
269
+ return this;
270
+ }
271
+ setU64Array(addr, buf) {
272
+ this.u64.set(buf, addr >> 3);
273
+ return this;
274
+ }
275
+ setF32Array(addr, buf) {
276
+ this.f32.set(buf, addr >> 2);
277
+ return this;
278
+ }
279
+ setF64Array(addr, buf) {
280
+ this.f64.set(buf, addr >> 3);
281
+ return this;
117
282
  }
118
283
  getString(addr, len = 0) {
119
284
  return this.utf8Decoder.decode(this.u8.subarray(addr, len > 0 ? addr + len : this.u8.indexOf(0, addr)));
120
285
  }
121
- getElementById(addr, len = 0) {
122
- const id = this.getString(addr, len);
123
- const el = document.getElementById(id);
124
- assert(!!el, `missing DOM element #${id}`);
125
- return el;
126
- }
127
286
  setString(str, addr, maxBytes, terminate = true) {
128
287
  maxBytes = Math.min(maxBytes, this.u8.length - addr);
129
288
  const len = this.utf8Encoder.encodeInto(str, this.u8.subarray(addr, addr + maxBytes)).written;
130
- assert(len != null && len < maxBytes + (terminate ? 0 : 1), `error writing string to 0x${U32(addr)}`);
289
+ if (len != null && len < maxBytes + (terminate ? 0 : 1)) {
290
+ illegalArgs(`error writing string to 0x${U32(addr)}`);
291
+ }
131
292
  if (terminate) {
132
293
  this.u8[addr + len] = 0;
133
294
  return len + 1;
134
295
  }
135
296
  return len;
136
297
  }
298
+ getElementById(addr, len = 0) {
299
+ const id = this.getString(addr, len);
300
+ const el = document.getElementById(id);
301
+ el == null && illegalArgs(`missing DOM element #${id}`);
302
+ return el;
303
+ }
137
304
  }
package/dev/custom.zig CHANGED
@@ -1,3 +1,4 @@
1
+ // Import JS core API
1
2
  const js = @import("wasmapi");
2
3
 
3
4
  /// Fill vec2 with random values
@@ -0,0 +1,135 @@
1
+ const js = @import("wasmapi");
2
+ const std = @import("std");
3
+
4
+ const Foo = struct {
5
+ pos: [2]f32,
6
+ col: [3]f32,
7
+ speed: u8,
8
+ acc: u16,
9
+ };
10
+
11
+ fn writeU32(buf: [*]u8, i: u32, x: u32) void {
12
+ buf[i] = @intCast(u8, x & 0xff);
13
+ buf[i + 1] = @intCast(u8, x >> 8 & 0xff);
14
+ buf[i + 2] = @intCast(u8, x >> 16 & 0xff);
15
+ buf[i + 3] = @intCast(u8, x >> 24);
16
+ }
17
+
18
+ const FieldType = enum(u8) {
19
+ I8,
20
+ U8,
21
+ I16,
22
+ U16,
23
+ I32,
24
+ U32,
25
+ F32,
26
+ F64,
27
+
28
+ pub fn fromTypeInfo(comptime info: std.builtin.TypeInfo) FieldType {
29
+ if (info == .Int) {
30
+ const bits = info.Int.bits;
31
+ if (!(bits == 8 or bits == 16 or bits == 32)) {
32
+ @compileError("unsupported int type (only 8, 16, 32)");
33
+ }
34
+ if (info.Int.signedness == .signed) {
35
+ return switch (bits) {
36
+ 8 => .I8,
37
+ 16 => .I16,
38
+ 32 => .I32,
39
+ else => unreachable,
40
+ };
41
+ } else {
42
+ return switch (bits) {
43
+ 8 => .U8,
44
+ 16 => .U16,
45
+ 32 => .U32,
46
+ else => unreachable,
47
+ };
48
+ }
49
+ } else if (info == .Float) {
50
+ return switch (info.Float.bits) {
51
+ 32 => .F32,
52
+ 64 => .F64,
53
+ else => @compileError("unsupported float type (only f32, f64)"),
54
+ };
55
+ }
56
+ @compileError("unsupported field type");
57
+ }
58
+ };
59
+
60
+ // int
61
+ // float
62
+ // ptr
63
+ // array
64
+ // slice
65
+
66
+ // 8
67
+ // 16
68
+ // 32
69
+ // 64
70
+
71
+ const Field = packed struct {
72
+ name: [15]u8 = [_]u8{0} ** 15,
73
+ tag: FieldType = .U8,
74
+ offset: u32,
75
+ len: u32 = 0,
76
+
77
+ pub fn fromTypeInfo(comptime T: type, comptime field: std.builtin.TypeInfo.StructField) Field {
78
+ const finfo = @typeInfo(field.field_type);
79
+ var ftype: FieldType = .U8;
80
+ var flen = 0;
81
+ if (!(finfo == .Int or finfo == .Float or finfo == .Array)) {
82
+ @compileError("unsupported field type: " ++ @typeName(field.field_type));
83
+ }
84
+ if (finfo == .Array) {
85
+ const cinfo = @typeInfo(finfo.Array.child);
86
+ if (!(cinfo == .Int or cinfo == .Float)) {
87
+ @compileError("unsupported field array type: " ++ @typeName(field.field_type));
88
+ }
89
+ ftype = FieldType.fromTypeInfo(cinfo);
90
+ flen = finfo.Array.len;
91
+ } else {
92
+ ftype = FieldType.fromTypeInfo(finfo);
93
+ }
94
+ var res: Field = .{
95
+ .tag = ftype,
96
+ .offset = @offsetOf(T, field.name),
97
+ .len = flen,
98
+ };
99
+ const len = @minimum(14, field.name.len);
100
+ std.mem.copy(u8, res.name[0..len], field.name[0..len]);
101
+ return res;
102
+ }
103
+ };
104
+
105
+ fn writeTypeInfo(comptime T: type) []u8 {
106
+ const fields = @typeInfo(T).Struct.fields;
107
+ const fsize = @sizeOf(Field);
108
+ var buf: [fields.len * fsize + 4]u8 = undefined;
109
+ var i = 4;
110
+ writeU32(&buf, 0, fields.len);
111
+ for (fields) |field| {
112
+ var f = Field.fromTypeInfo(T, field);
113
+ std.mem.copy(
114
+ u8,
115
+ buf[i .. i + fsize],
116
+ @ptrCast(*[fsize]u8, &f)[0..],
117
+ );
118
+ i += fsize;
119
+ }
120
+ return buf[0..];
121
+ }
122
+
123
+ export var Foo__info = writeTypeInfo(Foo);
124
+ export var Bar__info = writeTypeInfo(struct { x: i16, y: i16 });
125
+
126
+ export var U64: u64 = 0xdecafbadcafebabe;
127
+ export var I64: i64 = -0x8000000000000000;
128
+
129
+ export fn foo() void {
130
+ js.printI64(I64);
131
+ js.printU64(U64);
132
+ js.printI64Array(&[_]i64{ I64, I64 });
133
+ js.printU32(@truncate(u32, U64 >> 32));
134
+ js.printU32Hex(@truncate(u32, U64 >> 32));
135
+ }
@@ -0,0 +1,39 @@
1
+ const std = @import("std");
2
+ /// Zig version. When writing code that supports multiple versions of Zig, prefer
3
+ /// feature detection (i.e. with `@hasDecl` or `@hasField`) over version checks.
4
+ pub const zig_version = std.SemanticVersion.parse("0.10.0-dev.3034+6fab6c3e4") catch unreachable;
5
+ pub const zig_backend = std.builtin.CompilerBackend.stage1;
6
+ /// Temporary until self-hosted supports the `cpu.arch` value.
7
+ pub const stage2_arch: std.Target.Cpu.Arch = .wasm32;
8
+
9
+ pub const output_mode = std.builtin.OutputMode.Lib;
10
+ pub const link_mode = std.builtin.LinkMode.Dynamic;
11
+ pub const is_test = false;
12
+ pub const single_threaded = true;
13
+ pub const abi = std.Target.Abi.musl;
14
+ pub const cpu: std.Target.Cpu = .{
15
+ .arch = .wasm32,
16
+ .model = &std.Target.wasm.cpu.generic,
17
+ .features = std.Target.wasm.featureSet(&[_]std.Target.wasm.Feature{
18
+ }),
19
+ };
20
+ pub const os = std.Target.Os{
21
+ .tag = .freestanding,
22
+ .version_range = .{ .none = {} },
23
+ };
24
+ pub const target = std.Target{
25
+ .cpu = cpu,
26
+ .os = os,
27
+ .abi = abi,
28
+ };
29
+ pub const object_format = std.Target.ObjectFormat.wasm;
30
+ pub const mode = std.builtin.Mode.ReleaseSmall;
31
+ pub const link_libc = false;
32
+ pub const link_libcpp = false;
33
+ pub const have_error_return_tracing = false;
34
+ pub const valgrind_support = false;
35
+ pub const sanitize_thread = false;
36
+ pub const position_independent_code = true;
37
+ pub const position_independent_executable = false;
38
+ pub const strip_debug_info = true;
39
+ pub const code_model = std.builtin.CodeModel.default;