@thi.ng/wasm-api 0.14.0 → 0.16.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/codegen.js CHANGED
@@ -1,14 +1,21 @@
1
1
  import { SIZEOF } from "@thi.ng/api/typedarray";
2
- import { align } from "@thi.ng/binary/align";
3
- import { ceilPow2 } from "@thi.ng/binary/pow";
4
2
  import { compareByKey } from "@thi.ng/compare/keys";
5
3
  import { compareNumDesc } from "@thi.ng/compare/numeric";
6
4
  import { DEFAULT, defmulti } from "@thi.ng/defmulti/defmulti";
7
5
  import { illegalArgs } from "@thi.ng/errors/illegal-arguments";
8
- import { PKG_NAME, USIZE_SIZE, } from "./api.js";
9
- import { isNumeric, isWasmString } from "./codegen/utils.js";
6
+ import { PKG_NAME, WASM32, } from "./api.js";
7
+ import { selectAlignment } from "./codegen/align.js";
8
+ import { isBigNumeric, isNumeric, isPointer, isPointerLike, isSlice, isStringSlice, isWasmString, } from "./codegen/utils.js";
9
+ export const DEFAULT_CODEGEN_OPTS = {
10
+ debug: false,
11
+ header: true,
12
+ lineWidth: 80,
13
+ stringType: "slice",
14
+ target: WASM32,
15
+ uppercaseEnums: true,
16
+ };
10
17
  const sizeOf = defmulti((x) => x.type, {}, {
11
- [DEFAULT]: (field, types, opts) => {
18
+ [DEFAULT]: (field, types, align, opts) => {
12
19
  if (field.__size)
13
20
  return field.__size;
14
21
  if (field.pad != null) {
@@ -16,18 +23,20 @@ const sizeOf = defmulti((x) => x.type, {}, {
16
23
  return (field.__size = field.pad);
17
24
  }
18
25
  let size = 0;
19
- if (field.tag === "ptr") {
20
- size = USIZE_SIZE;
26
+ if (isPointer(field)) {
27
+ size = opts.target.usizeBytes;
21
28
  }
22
- else if (field.tag === "slice") {
23
- size = USIZE_SIZE * 2;
29
+ else if (isSlice(field)) {
30
+ size = opts.target.usizeBytes * 2;
24
31
  }
25
32
  else {
26
- size = isNumeric(field.type)
27
- ? SIZEOF[field.type]
28
- : isWasmString(field.type)
29
- ? USIZE_SIZE * (opts.stringType === "slice" ? 2 : 1)
30
- : sizeOf(types[field.type], types, opts);
33
+ size =
34
+ isNumeric(field.type) || isBigNumeric(field.type)
35
+ ? SIZEOF[field.type]
36
+ : isWasmString(field.type)
37
+ ? opts.target.usizeBytes *
38
+ (isStringSlice(opts.stringType) ? 2 : 1)
39
+ : sizeOf(types[field.type], types, align, opts);
31
40
  if (field.tag == "array" || field.tag === "vec") {
32
41
  size *= field.len;
33
42
  if (field.sentinel !== undefined && field.tag === "array") {
@@ -35,79 +44,95 @@ const sizeOf = defmulti((x) => x.type, {}, {
35
44
  }
36
45
  }
37
46
  }
38
- return (field.__size = align(size, field.__align));
47
+ return (field.__size = align.size(size, field.__align));
39
48
  },
40
49
  enum: (type) => {
41
50
  if (type.__size)
42
51
  return type.__size;
43
52
  return (type.__size = SIZEOF[type.tag]);
44
53
  },
45
- struct: (type, types, opts) => {
54
+ struct: (type, types, align, opts) => {
46
55
  if (type.__size)
47
56
  return type.__size;
48
- const struct = type;
49
- let size = 0;
50
- for (let f of struct.fields) {
51
- size = align(size, f.__align);
52
- f.__offset = size;
53
- size += sizeOf(f, types, opts);
57
+ let offset = 0;
58
+ for (let f of type.fields) {
59
+ offset = align.offset(offset, f.__align);
60
+ f.__offset = offset;
61
+ offset += sizeOf(f, types, align, opts);
62
+ }
63
+ return (type.__size = align.size(offset, type.__align));
64
+ },
65
+ union: (type, types, align, opts) => {
66
+ if (type.__size)
67
+ return type.__size;
68
+ let maxSize = 0;
69
+ for (let f of type.fields) {
70
+ f.__offset = 0;
71
+ maxSize = Math.max(maxSize, sizeOf(f, types, align, opts));
54
72
  }
55
- return (type.__size = align(size, type.__align));
73
+ return (type.__size = align.size(maxSize, type.__align));
56
74
  },
57
75
  });
58
76
  const alignOf = defmulti((x) => x.type, {}, {
59
- [DEFAULT]: (field, types) => {
77
+ [DEFAULT]: (field, types, align, opts) => {
60
78
  if (field.__align)
61
79
  return field.__align;
80
+ if (field.type === "usize") {
81
+ field.type = opts.target.usize;
82
+ }
62
83
  if (field.pad)
63
84
  return (field.__align = 1);
64
- let align = isNumeric(field.type)
65
- ? SIZEOF[field.type]
66
- : isWasmString(field.type)
67
- ? USIZE_SIZE
68
- : alignOf(types[field.type], types);
69
- if (field.tag === "vec") {
70
- align *= ceilPow2(field.len);
71
- }
72
- field.__align = align;
73
- return align;
85
+ return (field.__align = isPointerLike(field)
86
+ ? align.align({ type: opts.target.usize })
87
+ : isNumeric(field.type) || isBigNumeric(field.type)
88
+ ? align.align(field)
89
+ : alignOf(types[field.type], types, selectAlignment(types[field.type]), opts));
74
90
  },
75
- enum: (type) => {
91
+ enum: (type, _, align) => {
76
92
  const e = type;
77
93
  if (!e.tag)
78
94
  e.tag = "i32";
79
- return (e.__align = SIZEOF[e.tag]);
95
+ return (e.__align = align.align({
96
+ type: e.tag,
97
+ }));
80
98
  },
81
- struct: (type, types) => {
82
- const struct = type;
83
- let maxAlign = 0;
84
- for (let f of struct.fields) {
85
- maxAlign = Math.max(maxAlign, alignOf(f, types));
99
+ struct: (type, types, align, opts) => {
100
+ let maxAlign = 1;
101
+ for (let f of type.fields) {
102
+ maxAlign = Math.max(maxAlign, alignOf(f, types, align, opts));
103
+ }
104
+ return (type.__align = maxAlign);
105
+ },
106
+ union: (type, types, align, opts) => {
107
+ let maxAlign = 1;
108
+ for (let f of type.fields) {
109
+ maxAlign = Math.max(maxAlign, alignOf(f, types, align, opts));
86
110
  }
87
111
  return (type.__align = maxAlign);
88
112
  },
89
113
  });
90
114
  const prepareType = defmulti((x) => x.type, {}, {
91
- [DEFAULT]: (x, types, opts) => {
115
+ [DEFAULT]: (x, types, alignImpl, opts) => {
92
116
  if (x.__align && x.__size)
93
117
  return;
94
- alignOf(x, types);
95
- sizeOf(x, types, opts);
118
+ alignOf(x, types, alignImpl, opts);
119
+ sizeOf(x, types, alignImpl, opts);
96
120
  },
97
- struct: (x, types, opts) => {
121
+ struct: (x, types, align, opts) => {
98
122
  if (x.__align && x.__size)
99
123
  return;
100
124
  const struct = x;
101
- alignOf(struct, types);
125
+ alignOf(struct, types, align, opts);
102
126
  if (struct.auto) {
103
127
  struct.fields.sort(compareByKey("__align", compareNumDesc));
104
128
  }
105
129
  for (let f of struct.fields) {
106
- if (types[f.type]) {
107
- prepareType(types[f.type], types, opts);
130
+ const type = types[f.type];
131
+ if (type) {
132
+ prepareType(type, types, selectAlignment(type), opts);
108
133
  }
109
134
  }
110
- sizeOf(struct, types, opts);
135
+ sizeOf(struct, types, align, opts);
111
136
  },
112
137
  });
113
138
  /**
@@ -124,8 +149,9 @@ const prepareType = defmulti((x) => x.type, {}, {
124
149
  */
125
150
  export const prepareTypes = (types, opts) => {
126
151
  for (let id in types) {
127
- prepareType(types[id], types, opts);
152
+ prepareType(types[id], types, selectAlignment(types[id]), opts);
128
153
  }
154
+ return types;
129
155
  };
130
156
  /**
131
157
  * Code generator main entry point. Takes an object of {@link TopLevelType}
@@ -144,10 +170,7 @@ export const prepareTypes = (types, opts) => {
144
170
  */
145
171
  export const generateTypes = (types, codegen, opts = {}) => {
146
172
  const $opts = {
147
- header: true,
148
- stringType: "slice",
149
- uppercaseEnums: true,
150
- lineWidth: 80,
173
+ ...DEFAULT_CODEGEN_OPTS,
151
174
  ...opts,
152
175
  };
153
176
  prepareTypes(types, $opts);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thi.ng/wasm-api",
3
- "version": "0.14.0",
3
+ "version": "0.16.0",
4
4
  "description": "Generic, modular, extensible API bridge, polyglot glue code and bindings code generators for hybrid JS & WebAssembly projects",
5
5
  "type": "module",
6
6
  "module": "./index.js",
@@ -33,30 +33,30 @@
33
33
  "doc:stats": "tools:module-stats",
34
34
  "pub": "yarn npm publish --access public",
35
35
  "test": "testament test",
36
- "test:build-zig": "zig build-lib -O ReleaseSmall -target wasm32-freestanding -dynamic --strip --pkg-begin wasmapi include/wasmapi.zig --pkg-end test/custom.zig && wasm-dis -o custom.wast custom.wasm && cp custom.wasm test"
36
+ "test:build-zig": "zig build-lib -O ReleaseSmall -target wasm32-freestanding -dynamic --strip --pkg-begin wasmapi zig/wasmapi.zig --pkg-end test/custom.zig && wasm-dis -o custom.wast custom.wasm && cp custom.wasm test"
37
37
  },
38
38
  "dependencies": {
39
- "@thi.ng/api": "^8.4.3",
40
- "@thi.ng/args": "^2.2.5",
41
- "@thi.ng/binary": "^3.3.6",
42
- "@thi.ng/checks": "^3.3.0",
43
- "@thi.ng/compare": "^2.1.13",
44
- "@thi.ng/defmulti": "^2.1.18",
45
- "@thi.ng/errors": "^2.2.2",
46
- "@thi.ng/file-io": "^0.3.15",
47
- "@thi.ng/hex": "^2.2.1",
48
- "@thi.ng/idgen": "^2.1.15",
49
- "@thi.ng/logger": "^1.4.1",
50
- "@thi.ng/paths": "^5.1.18",
51
- "@thi.ng/strings": "^3.3.14"
39
+ "@thi.ng/api": "^8.4.4",
40
+ "@thi.ng/args": "^2.2.7",
41
+ "@thi.ng/binary": "^3.3.8",
42
+ "@thi.ng/checks": "^3.3.2",
43
+ "@thi.ng/compare": "^2.1.14",
44
+ "@thi.ng/defmulti": "^2.1.19",
45
+ "@thi.ng/errors": "^2.2.3",
46
+ "@thi.ng/file-io": "^0.3.17",
47
+ "@thi.ng/hex": "^2.2.2",
48
+ "@thi.ng/idgen": "^2.1.16",
49
+ "@thi.ng/logger": "^1.4.2",
50
+ "@thi.ng/paths": "^5.1.20",
51
+ "@thi.ng/strings": "^3.3.15"
52
52
  },
53
53
  "devDependencies": {
54
- "@microsoft/api-extractor": "^7.31.1",
55
- "@thi.ng/testament": "^0.3.3",
54
+ "@microsoft/api-extractor": "^7.33.5",
55
+ "@thi.ng/testament": "^0.3.4",
56
56
  "rimraf": "^3.0.2",
57
57
  "tools": "^0.0.1",
58
- "typedoc": "^0.22.17",
59
- "typescript": "^4.8.3"
58
+ "typedoc": "^0.23.18",
59
+ "typescript": "^4.8.4"
60
60
  },
61
61
  "keywords": [
62
62
  "allocator",
@@ -96,7 +96,8 @@
96
96
  "*.d.ts",
97
97
  "bin",
98
98
  "codegen",
99
- "include"
99
+ "include",
100
+ "zig"
100
101
  ],
101
102
  "exports": {
102
103
  ".": {
@@ -108,6 +109,9 @@
108
109
  "./bridge": {
109
110
  "default": "./bridge.js"
110
111
  },
112
+ "./codegen/align": {
113
+ "default": "./codegen/align.js"
114
+ },
111
115
  "./codegen/c11": {
112
116
  "default": "./codegen/c11.js"
113
117
  },
@@ -137,5 +141,5 @@
137
141
  "status": "alpha",
138
142
  "year": 2022
139
143
  },
140
- "gitHead": "612b1b0bdf442473f04c2edac3012975a6ca28bb\n"
144
+ "gitHead": "41e59c7ad9bf24bb0230a5f60d05715e0fc1c1e6\n"
141
145
  }
package/string.d.ts CHANGED
@@ -3,6 +3,10 @@ import type { IWasmMemoryAccess, ReadonlyWasmString } from "./api.js";
3
3
  * Memory mapped string wrapper for Zig-style UTF-8 encoded byte slices (aka
4
4
  * pointer & length pair). The actual JS string can be obtained via
5
5
  * {@link WasmStringSlice.deref} and mutated via {@link WasmStringSlice.set}.
6
+ *
7
+ * @remarks
8
+ * Currently only supports wasm32 target, need alt. solution for 64bit (possibly
9
+ * diff implementation) using bigint addresses (TODO)
6
10
  */
7
11
  export declare class WasmStringSlice implements ReadonlyWasmString {
8
12
  readonly mem: IWasmMemoryAccess;
package/string.js CHANGED
@@ -3,6 +3,10 @@ import { unsupported } from "@thi.ng/errors/unsupported";
3
3
  * Memory mapped string wrapper for Zig-style UTF-8 encoded byte slices (aka
4
4
  * pointer & length pair). The actual JS string can be obtained via
5
5
  * {@link WasmStringSlice.deref} and mutated via {@link WasmStringSlice.set}.
6
+ *
7
+ * @remarks
8
+ * Currently only supports wasm32 target, need alt. solution for 64bit (possibly
9
+ * diff implementation) using bigint addresses (TODO)
6
10
  */
7
11
  export class WasmStringSlice {
8
12
  constructor(mem, base, isConst = true) {
@@ -0,0 +1,223 @@
1
+ const std = @import("std");
2
+ const builtin = @import("builtin");
3
+ const Allocator = std.mem.Allocator;
4
+
5
+ /// `std.Arraylist` based data structure for associating and auto-indexing
6
+ /// newly added items with numeric IDs and managing a pool of free IDs.
7
+ /// Wraps `std.Arraylist` with a simple add()/remove()/get()/has() API and
8
+ /// adds free slot tracking & re-use (depending on value type, potentially
9
+ /// without any memory overhead). Free slots are stored as implicit linked
10
+ /// list within the same array as the actual values/items.
11
+ /// Important: The provided `.remove()` function MUST be used to remove
12
+ /// unused items and mark their slot IDs for re-use.
13
+ pub fn ManagedIndex(comptime T: type, comptime I: type) type {
14
+ const info = @typeInfo(I);
15
+ if (!(info == .Int and info.Int.bits > 0 and info.Int.signedness == std.builtin.Signedness.unsigned)) {
16
+ @compileError("require unsigned int as index type");
17
+ }
18
+ const Item = union(enum) {
19
+ /// Actual user defined value
20
+ value: T,
21
+ /// Free list slot ID. Index of the next avail free slot
22
+ id: ?I,
23
+ };
24
+
25
+ return struct {
26
+ /// backing array list
27
+ list: std.ArrayList(Item),
28
+ /// Index of the head of the implicitly stored list of free slots
29
+ /// Free slots in the array list use `Item.id` fields, each storing
30
+ /// the index of the next available free slot (or null)
31
+ /// The backing array list only grows if `freeID` is null
32
+ freeID: ?I = null,
33
+ /// Number of currently used items
34
+ used: usize = 0,
35
+
36
+ const Self = @This();
37
+
38
+ /// Initializes the underlying array list
39
+ pub fn init(allocator: Allocator) Self {
40
+ return .{
41
+ .list = std.ArrayList(Item).init(allocator),
42
+ };
43
+ }
44
+
45
+ /// De-initializes the underlying array list
46
+ pub fn deinit(self: *Self) void {
47
+ self.list.deinit();
48
+ }
49
+
50
+ /// Clears, frees & resets this list and its backing array list.
51
+ pub fn clear(self: *Self) void {
52
+ self.list.clearAndFree();
53
+ self.freeID = null;
54
+ self.used = 0;
55
+ }
56
+
57
+ /// Adds given `item` to the list and returns slot ID. If possible
58
+ /// re-uses existing free slots, else attempts to allocate a new slot.
59
+ pub fn add(self: *Self, item: T) Allocator.Error!I {
60
+ if (self.freeID) |id| {
61
+ self.freeID = self.list.items[id].id;
62
+ self.list.items[id] = .{ .value = item };
63
+ self.used += 1;
64
+ return @intCast(I, id);
65
+ } else {
66
+ const id = self.list.items.len;
67
+ try self.list.append(.{ .value = item });
68
+ self.used += 1;
69
+ return @intCast(I, id);
70
+ }
71
+ }
72
+
73
+ /// Adds given `id` to the internal free slot list and removes related
74
+ /// value/item
75
+ pub fn remove(self: *Self, id: I) void {
76
+ if (!self.has(id)) return;
77
+ self.list.items[id] = .{ .id = self.freeID };
78
+ self.freeID = id;
79
+ self.used -= 1;
80
+ }
81
+
82
+ /// Checks if given `id` is valid (skipped in unsafe release modes) and
83
+ /// returns item value or null if ID is invalid.
84
+ pub fn get(self: *const Self, id: I) ?T {
85
+ if (builtin.mode == .ReleaseFast or builtin.mode == .ReleaseSmall) {
86
+ return self.list.items[id].value;
87
+ }
88
+ return if (self.has(id)) self.list.items[id].value else null;
89
+ }
90
+
91
+ /// Returns true if given `id` is valid, i.e. is referring to a
92
+ /// currently used item (and isn't part of the list of free slots).
93
+ pub fn has(self: *const Self, id: I) bool {
94
+ if (id >= self.list.items.len) return false;
95
+ var freeID = self.freeID;
96
+ while (true) {
97
+ if (freeID) |fid| {
98
+ if (fid == id) return false;
99
+ freeID = self.list.items[fid].id;
100
+ } else {
101
+ return true;
102
+ }
103
+ }
104
+ }
105
+
106
+ /// Iterator for currently used values (in ascending index order)
107
+ pub const ValueIterator = struct {
108
+ parent: *const Self,
109
+ i: usize = 0,
110
+
111
+ pub fn init(parent: *const Self) @This() {
112
+ return .{ .parent = parent };
113
+ }
114
+
115
+ pub fn next(self: *@This()) ?T {
116
+ const items = self.parent.list.items;
117
+ if (self.i >= items.len) return null;
118
+ while (self.i < items.len) {
119
+ const val = switch (items[self.i]) {
120
+ .value => |value| value,
121
+ .id => null,
122
+ };
123
+ self.i += 1;
124
+ if (val != null) return val;
125
+ }
126
+ return null;
127
+ }
128
+ };
129
+
130
+ /// Returns iterator of currently used values
131
+ pub fn values(self: *const Self) ValueIterator {
132
+ return ValueIterator.init(self);
133
+ }
134
+
135
+ /// Allocates a new slice containing only currently used values and
136
+ /// returns it. Caller owns returned memory.
137
+ pub fn valuesAsSlice(self: *Self, allocator: Allocator) Allocator.Error![]T {
138
+ var slice = try allocator.alloc(T, self.used);
139
+ var iter = self.values();
140
+ var i: usize = 0;
141
+ while (iter.next()) |value| {
142
+ slice[i] = value;
143
+ i += 1;
144
+ }
145
+ return slice;
146
+ }
147
+
148
+ /// Allocates a new slice of all currently free slot IDs and returns it.
149
+ /// Caller owns returned memory.
150
+ /// Internal/debug only.
151
+ fn freeIndicesAsSlice(self: *const Self, allocator: Allocator) Allocator.Error![]I {
152
+ var slice = try allocator.alloc(I, self.list.items.len - self.used);
153
+ var i: I = 0;
154
+ var freeID = self.freeID;
155
+ while (i < slice.len) {
156
+ if (freeID) |fid| {
157
+ slice[i] = fid;
158
+ i += 1;
159
+ freeID = self.list.items[fid].id;
160
+ } else {
161
+ break;
162
+ }
163
+ }
164
+ return slice;
165
+ }
166
+ };
167
+ }
168
+
169
+ test "ManagedIndex" {
170
+ const allocator = std.testing.allocator;
171
+ const expect = std.testing.expect;
172
+ const expectEqualSlices = std.testing.expectEqualSlices;
173
+
174
+ var list = ManagedIndex(f64, u8).init(allocator);
175
+ defer list.deinit();
176
+ try expect(try list.add(123) == 0);
177
+ try expect(try list.add(123) == 1);
178
+
179
+ try expect(list.has(0));
180
+ try expect(list.has(1));
181
+ try expect(list.used == 2);
182
+
183
+ list.remove(0);
184
+ try expect(!list.has(0));
185
+ try expect(!list.has(2));
186
+ try expect(list.used == 1);
187
+
188
+ try expect(try list.add(123) == 0);
189
+ try expect(try list.add(123) == 2);
190
+ try expect(list.has(2));
191
+ try expect(list.used == 3);
192
+
193
+ list.remove(1);
194
+ list.remove(2);
195
+
196
+ var ids = try list.freeIndicesAsSlice(allocator);
197
+ defer allocator.free(ids);
198
+ try expectEqualSlices(u8, &[_]u8{ 2, 1 }, ids);
199
+
200
+ try expect(try list.add(202) == 2);
201
+ list.remove(0);
202
+ try expect(try list.add(200) == 0);
203
+ try expect(try list.add(201) == 1);
204
+ try expect(list.freeID == null);
205
+
206
+ var iter = list.values();
207
+ try expect(if (iter.next()) |v| v == 200 else false);
208
+ try expect(if (iter.next()) |v| v == 201 else false);
209
+ try expect(if (iter.next()) |v| v == 202 else false);
210
+ try expect(iter.next() == null);
211
+
212
+ const slice = try list.valuesAsSlice(allocator);
213
+ defer allocator.free(slice);
214
+ try expectEqualSlices(f64, &[_]f64{ 200, 201, 202 }, slice);
215
+
216
+ list.remove(0);
217
+ list.remove(2);
218
+ list.remove(1);
219
+
220
+ var ids2 = try list.freeIndicesAsSlice(allocator);
221
+ defer allocator.free(ids2);
222
+ try expectEqualSlices(u8, &[_]u8{ 1, 2, 0 }, ids2);
223
+ }
@@ -3,6 +3,8 @@
3
3
  const std = @import("std");
4
4
  const root = @import("root");
5
5
 
6
+ pub const ManagedIndex = @import("managed-index.zig").ManagedIndex;
7
+
6
8
  /// Higher-order slice wrapper for extern struct use cases
7
9
  /// S = slice type
8
10
  /// P = pointer type