@pkmn/engine 0.1.0-dev.a5a9f4b2 → 0.1.0-dev.a77ab8e2

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.
Files changed (62) hide show
  1. package/LICENSE +1 -3
  2. package/README.md +102 -64
  3. package/build/pkg/addon.d.ts +1 -1
  4. package/build/pkg/addon.js +13 -13
  5. package/build/pkg/addon.js.map +1 -1
  6. package/build/pkg/data/ids.json +12 -12
  7. package/build/pkg/data/layout.json +27 -5
  8. package/build/pkg/data/protocol.json +69 -12
  9. package/build/pkg/data.d.ts +4 -4
  10. package/build/pkg/data.js.map +1 -1
  11. package/build/pkg/gen1.d.ts +5 -4
  12. package/build/pkg/gen1.js +48 -32
  13. package/build/pkg/gen1.js.map +1 -1
  14. package/build/pkg/index.d.ts +18 -14
  15. package/build/pkg/index.js.map +1 -1
  16. package/build/pkg/protocol.d.ts +4 -2
  17. package/build/pkg/protocol.js +65 -44
  18. package/build/pkg/protocol.js.map +1 -1
  19. package/build/test/display.js +37 -15
  20. package/build/test/display.js.map +1 -1
  21. package/build/tools/debug.js +5 -4
  22. package/build/tools/debug.js.map +1 -1
  23. package/build.zig +291 -134
  24. package/package.json +58 -25
  25. package/src/bin/install-pkmn-engine +40 -25
  26. package/src/lib/common/array.zig +77 -0
  27. package/src/lib/common/battle.zig +17 -0
  28. package/src/lib/common/data.zig +19 -31
  29. package/src/lib/common/debug.zig +23 -13
  30. package/src/lib/common/js.zig +120 -0
  31. package/src/lib/common/optional.zig +71 -0
  32. package/src/lib/common/options.zig +14 -3
  33. package/src/lib/common/protocol.zig +947 -403
  34. package/src/lib/common/rational.zig +447 -0
  35. package/src/lib/common/rng.zig +31 -22
  36. package/src/lib/common/util.zig +61 -0
  37. package/src/lib/gen1/calc.zig +806 -0
  38. package/src/lib/gen1/chance.zig +1167 -0
  39. package/src/lib/gen1/data/moves.zig +202 -190
  40. package/src/lib/gen1/data/species.zig +5 -5
  41. package/src/lib/gen1/data/types.zig +10 -10
  42. package/src/lib/gen1/data.zig +93 -78
  43. package/src/lib/gen1/helpers.zig +144 -39
  44. package/src/lib/gen1/mechanics.zig +1211 -795
  45. package/src/lib/gen2/calc.zig +161 -0
  46. package/src/lib/gen2/chance.zig +905 -0
  47. package/src/lib/gen2/data/items.zig +14 -20
  48. package/src/lib/gen2/data/moves.zig +664 -570
  49. package/src/lib/gen2/data/species.zig +2 -2
  50. package/src/lib/gen2/data/types.zig +137 -34
  51. package/src/lib/gen2/data.zig +125 -86
  52. package/src/lib/gen2/generated.zig +806 -0
  53. package/src/lib/gen2/helpers.zig +54 -28
  54. package/src/lib/gen2/mechanics.zig +3567 -12
  55. package/src/lib/node.zig +131 -0
  56. package/src/lib/pkmn.zig +85 -9
  57. package/src/lib/wasm.zig +13 -0
  58. package/src/test/display/pkmn.html.tmpl +5 -5
  59. package/src/lib/binding/node.zig +0 -229
  60. package/src/lib/binding/wasm.zig +0 -10
  61. package/src/lib/gen1/README.md +0 -791
  62. package/src/lib/gen2/README.md +0 -309
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pkmn/engine",
3
- "version": "0.1.0-dev.a5a9f4b2",
3
+ "version": "0.1.0-dev.a77ab8e2",
4
4
  "description": "A minimal, complete, Pokémon battle simulation engine optimized for performance",
5
5
  "repository": "github:pkmn/engine",
6
6
  "license": "MIT",
@@ -31,28 +31,38 @@
31
31
  "build/test/display.js",
32
32
  "build/tools/debug.js.map",
33
33
  "build/tools/debug.js",
34
- "src/bin/install-pkmn-engine",
35
- "src/lib/binding/node.zig",
36
- "src/lib/binding/wasm.zig",
34
+ "src/lib/common/battle.zig",
37
35
  "src/lib/common/data.zig",
38
36
  "src/lib/common/debug.zig",
37
+ "src/lib/common/js.zig",
38
+ "src/lib/common/array.zig",
39
+ "src/lib/common/optional.zig",
39
40
  "src/lib/common/options.zig",
40
41
  "src/lib/common/protocol.zig",
42
+ "src/lib/common/rational.zig",
41
43
  "src/lib/common/rng.zig",
44
+ "src/lib/common/util.zig",
45
+ "src/lib/gen1/calc.zig",
46
+ "src/lib/gen1/chance.zig",
42
47
  "src/lib/gen1/data.zig",
43
48
  "src/lib/gen1/data/moves.zig",
44
49
  "src/lib/gen1/data/species.zig",
45
50
  "src/lib/gen1/data/types.zig",
46
51
  "src/lib/gen1/helpers.zig",
47
52
  "src/lib/gen1/mechanics.zig",
53
+ "src/lib/gen2/calc.zig",
54
+ "src/lib/gen2/chance.zig",
48
55
  "src/lib/gen2/data.zig",
49
56
  "src/lib/gen2/data/items.zig",
50
57
  "src/lib/gen2/data/moves.zig",
51
58
  "src/lib/gen2/data/species.zig",
52
59
  "src/lib/gen2/data/types.zig",
60
+ "src/lib/gen2/generated.zig",
53
61
  "src/lib/gen2/helpers.zig",
54
62
  "src/lib/gen2/mechanics.zig",
63
+ "src/lib/node.zig",
55
64
  "src/lib/pkmn.zig",
65
+ "src/lib/wasm.zig",
56
66
  "src/test/display/pkmn.html.tmpl"
57
67
  ],
58
68
  "engines": {
@@ -66,30 +76,33 @@
66
76
  "access": "public"
67
77
  },
68
78
  "dependencies": {
69
- "@pkmn/data": "^0.7.37",
70
- "@pkmn/protocol": "^0.6.11"
79
+ "@pkmn/data": "^0.9.11",
80
+ "@pkmn/protocol": "^0.6.25"
71
81
  },
72
82
  "devDependencies": {
73
- "@pkmn/eslint-config": "^3.0.0",
74
- "@pkmn/img": "^0.2.8",
75
- "@pkmn/sets": "^5.0.4",
76
- "@pkmn/sim": "0.7.37",
77
- "@types/html-minifier": "^4.0.2",
78
- "@types/jest": "^29.5.0",
79
- "@types/minimist": "^1.2.2",
80
- "@types/mustache": "^4.2.2",
81
- "@types/node": "^18.15.11",
82
- "@vitest/coverage-c8": "^0.30.1",
83
- "binaryen": "^112.0.0",
84
- "eslint": "^8.38.0",
83
+ "@pkmn/eslint-config": "^8.1.0",
84
+ "@pkmn/img": "^0.2.31",
85
+ "@pkmn/sets": "^5.1.2",
86
+ "@pkmn/sim": "0.9.11",
87
+ "@types/html-minifier": "^4.0.5",
88
+ "@types/jest": "^29.5.12",
89
+ "@types/minimist": "^1.2.5",
90
+ "@types/mustache": "^4.2.5",
91
+ "@types/node": "^22.0.2",
92
+ "@types/semver": "^7.5.8",
93
+ "@vitest/coverage-v8": "^2.0.5",
94
+ "binaryen": "^118.0.0",
95
+ "eslint": "<=8",
85
96
  "html-minifier": "^4.0.0",
86
97
  "json-stringify-pretty-compact": "4.0.0",
87
98
  "minimist": "^1.2.8",
88
99
  "mustache": "^4.2.0",
100
+ "semver": "^7.6.3",
89
101
  "source-map-support": "^0.5.21",
102
+ "table": "^6.8.2",
90
103
  "trakr": "^0.2.0",
91
- "typescript": "^5.0.4",
92
- "vitest": "^0.30.1"
104
+ "typescript": "^5.5.4",
105
+ "vitest": "^2.0.5"
93
106
  },
94
107
  "scripts": {
95
108
  "lint": "eslint --cache src --ext ts,js && eslint src/bin/*",
@@ -111,7 +124,7 @@
111
124
  "ignorePatterns": [
112
125
  "dist/",
113
126
  "node_modules/",
114
- "src/examples/zig",
127
+ "examples/zig",
115
128
  "build/"
116
129
  ],
117
130
  "env": {
@@ -127,10 +140,18 @@
127
140
  "parserOptions": {
128
141
  "project": [
129
142
  "./tsconfig.json",
130
- "./src/examples/js/tsconfig.json"
143
+ "./examples/js/tsconfig.json"
131
144
  ]
132
145
  }
133
146
  },
147
+ {
148
+ "files": [
149
+ "src/test/display.ts"
150
+ ],
151
+ "rules": {
152
+ "@typescript-eslint/no-unnecessary-type-assertion": "off"
153
+ }
154
+ },
134
155
  {
135
156
  "files": [
136
157
  "src/pkg/index.ts",
@@ -140,7 +161,8 @@
140
161
  "rules": {
141
162
  "no-control-regex": "off",
142
163
  "@typescript-eslint/no-empty-interface": "off",
143
- "@typescript-eslint/no-shadow": "off"
164
+ "@typescript-eslint/no-shadow": "off",
165
+ "@typescript-eslint/no-unsafe-declaration-merging": "off"
144
166
  }
145
167
  },
146
168
  {
@@ -156,12 +178,23 @@
156
178
  "src/test/benchmark*.ts"
157
179
  ],
158
180
  "rules": {
159
- "@typescript-eslint/no-unused-vars": "off"
181
+ "@typescript-eslint/no-unused-vars": "off",
182
+ "@typescript-eslint/no-redundant-type-constituents": "off"
183
+ }
184
+ },
185
+ {
186
+ "files": [
187
+ "src/pkg/protocol.test.ts"
188
+ ],
189
+ "rules": {
190
+ "jest/no-standalone-expect": "off",
191
+ "jest/no-conditional-expect": "off"
160
192
  }
161
193
  },
162
194
  {
163
195
  "files": [
164
- "src/test/*.test.ts"
196
+ "src/test/*.test.ts",
197
+ "src/test/regression/*.test.ts"
165
198
  ],
166
199
  "rules": {
167
200
  "jest/no-standalone-expect": "off"
@@ -10,7 +10,7 @@ const path = require('path');
10
10
  const {pipeline} = require('stream/promises');
11
11
  const tty = require('tty');
12
12
 
13
- const ZIG_VERSION = {major: 0, minor: 11, patch: 0, dev: 2560};
13
+ const ZIG_VERSION = {major: 0, minor: 11, patch: 0};
14
14
  const DEV = ZIG_VERSION.dev ? `-dev.${ZIG_VERSION.dev}` : '';
15
15
  const VERSION = `${ZIG_VERSION.major}.${ZIG_VERSION.minor}.${ZIG_VERSION.patch}${DEV}`;
16
16
  const INDEX = 'https://ziglang.org/download/index.json';
@@ -163,8 +163,10 @@ const install = async () => {
163
163
  }
164
164
 
165
165
  const index = JSON.parse(await fetch(INDEX));
166
- const version = Object.keys(index)[+!ZIG_VERSION.dev];
167
- const release = index[version][`${arch}-${platform}`];
166
+ // TODO: ziglang/zig#17768
167
+ // const version = Object.keys(index)[+!ZIG_VERSION.dev];
168
+ const version = VERSION;
169
+ const release = index[VERSION][`${arch}-${platform}`];
168
170
  const url = release.tarball;
169
171
 
170
172
  let base = path.basename(url);
@@ -283,19 +285,19 @@ const downloadImportLib = async () => {
283
285
  let error = false;
284
286
  for (let i = 2; i < process.argv.length; i++) {
285
287
  switch (process.argv[i]) {
286
- case "--silent": {
287
- SILENT = true;
288
- break;
289
- }
290
- case "--zig": {
291
- if (options || only) error = true;
292
- only = true;
293
- break;
294
- }
295
- default: {
296
- if (options || only || !process.argv[i].startsWith('--options=')) error = true;
297
- options = process.argv[i].slice(10).split(' ');
298
- }
288
+ case "--silent": {
289
+ SILENT = true;
290
+ break;
291
+ }
292
+ case "--zig": {
293
+ if (options || only) error = true;
294
+ only = true;
295
+ break;
296
+ }
297
+ default: {
298
+ if (options || only || !process.argv[i].startsWith('--options=')) error = true;
299
+ options = process.argv[i].slice(10).split(' ');
300
+ }
299
301
  }
300
302
  }
301
303
  if (error) {
@@ -336,14 +338,18 @@ const downloadImportLib = async () => {
336
338
  node = true;
337
339
  if (!options) {
338
340
  const addon = require(copy);
339
- if (addon.options.showdown) opts.push('-Dshowdown');
340
- if (addon.options.trace) opts.push('-Dtrace');
341
+ if (addon.engine.options.showdown) opts.push('-Dshowdown');
342
+ if (addon.engine.options.log) opts.push('-Dlog');
343
+ if (addon.engine.options.chance) opts.push('-Dchance');
344
+ if (addon.engine.options.calc) opts.push('-Dcalc');
341
345
  }
342
346
  } else if (!options) {
343
347
  const addon = await WebAssembly.instantiate(fs.readFileSync(copy));
344
348
  const values = new Uint8Array(addon.instance.exports.memory.buffer);
345
349
  if (values[addon.instance.exports.SHOWDOWN.value]) opts.push('-Dshowdown');
346
- if (values[addon.instance.exports.TRACE.value]) opts.push('-Dtrace');
350
+ if (values[addon.instance.exports.LOG.value]) opts.push('-Dlog');
351
+ if (values[addon.instance.exports.CHANCE.value]) opts.push('-Dchance');
352
+ if (values[addon.instance.exports.CALC.value]) opts.push('-Dcalc');
347
353
  }
348
354
  const key = `${type} ${opts.sort().join(' ')}`;
349
355
  if (!configs.has(key)) configs.set(key, {type, options: opts});
@@ -354,8 +360,9 @@ const downloadImportLib = async () => {
354
360
  // either the default options or whatever was passed in
355
361
  if (!configs.size) {
356
362
  node = true;
357
- configs.set('node', {type: 'node', options: options || ['-Dshowdown']});
358
- configs.set('wasm', {type: 'wasm', options: options || ['-Dshowdown']});
363
+ const DEFAULT = ['-Dshowdown'];
364
+ configs.set('node', {type: 'node', options: options || DEFAULT});
365
+ configs.set('wasm', {type: 'wasm', options: options || DEFAULT});
359
366
  }
360
367
 
361
368
  const headers = node ? await downloadHeaders() : undefined;
@@ -365,8 +372,10 @@ const downloadImportLib = async () => {
365
372
  const args = ['build', '-p', 'build', ...opts];
366
373
  if (!process.env.DEBUG_PKMN_ENGINE) args.push('-Doptimize=ReleaseFast', '-Dstrip');
367
374
  if (config.type === 'node') {
368
- args.push(`-Dnode-headers=${headers}`);
369
- if (process.platform === 'win32') args.push(`-Dnode-import-library=${lib}`);
375
+ args.push(`-Dnode-headers=${path.relative(ROOT, headers)}`);
376
+ if (process.platform === 'win32') {
377
+ args.push(`-Dnode-import-library=${path.relative(ROOT, lib)}`);
378
+ }
370
379
  } else {
371
380
  args.push('-Dwasm');
372
381
  }
@@ -381,8 +390,14 @@ const downloadImportLib = async () => {
381
390
  const prefix = process.platform === 'win32' ? '' : 'lib';
382
391
  const ext = process.platform === 'darwin'
383
392
  ? 'dylib' : process.platform === 'win32' ? 'dll' : 'so';
384
- const actual = path.join('build', 'lib', `${prefix}pkmn${suffix}.node.${ext}`);
385
- fs.renameSync(path.join(ROOT, actual), path.join(ROOT, artifact));
393
+ try {
394
+ const actual = path.join(ROOT, 'build', 'lib', `${prefix}pkmn${suffix}.node.${ext}`);
395
+ fs.renameSync(actual, artifact);
396
+ } catch (err) {
397
+ // ziglang/zig#19743 changed this path
398
+ const actual = path.join(ROOT, 'build', 'bin', `${prefix}pkmn${suffix}.node.${ext}`);
399
+ fs.renameSync(actual, artifact);
400
+ }
386
401
  }
387
402
  }
388
403
  })().catch(e => {
@@ -0,0 +1,77 @@
1
+ const std = @import("std");
2
+
3
+ const expectEqual = std.testing.expectEqual;
4
+ const assert = std.debug.assert;
5
+
6
+ const Int = if (@hasField(std.builtin.Type, "int")) .int else .Int;
7
+ const Enum = if (@hasField(std.builtin.Type, "enum")) .@"enum" else .Enum;
8
+
9
+ /// Helpers for working with bit-packed arrays of non-powers-of-2 types.
10
+ /// NOTE: ziglang/zig#12547
11
+ pub fn Array(comptime n: comptime_int, comptime U: type) type {
12
+ return struct {
13
+ const size = @bitSizeOf(U);
14
+ const options = .{ .signedness = .unsigned, .bits = size * n };
15
+ pub const T = @Type(if (@hasField(std.builtin.Type, "int"))
16
+ .{ .int = options }
17
+ else
18
+ .{ .Int = options });
19
+
20
+ /// Returns the value stored at index `i` in the array `a`.
21
+ pub fn get(a: T, i: usize) U {
22
+ assert(i < n);
23
+ const shift = i * size;
24
+ const mask: T = (1 << size) - 1;
25
+ const result = (a >> @intCast(shift)) & mask;
26
+ return switch (@typeInfo(U)) {
27
+ Enum => @enumFromInt(result),
28
+ Int => @intCast(result),
29
+ else => unreachable,
30
+ };
31
+ }
32
+
33
+ /// Sets the value at index `i` to `val` in the array `a`.
34
+ pub fn set(a: T, i: usize, val: U) T {
35
+ assert(i < n);
36
+ const v: T = switch (@typeInfo(U)) {
37
+ Enum => @intFromEnum(val),
38
+ Int => @intCast(val),
39
+ else => unreachable,
40
+ };
41
+ const shift = i * size;
42
+ const mask: T = @as(T, @intCast((1 << size) - 1)) << @intCast(shift);
43
+ const result: T = a & ~mask;
44
+ return result | (v << @intCast(shift));
45
+ }
46
+ };
47
+ }
48
+
49
+ test Array {
50
+ const A = Array(5, u8);
51
+ var a: A.T = 0;
52
+ try expectEqual(u40, @TypeOf(a));
53
+
54
+ a = A.set(a, 4, 241);
55
+ try expectEqual(@as(u8, 241), A.get(a, 4));
56
+ a = A.set(a, 4, 1);
57
+ try expectEqual(@as(u8, 1), A.get(a, 4));
58
+
59
+ for (0..5) |i| a = A.set(a, i, @intCast(i));
60
+ for (0..5) |i| try expectEqual(@as(u8, @intCast(i)), A.get(a, i));
61
+
62
+ const Optional = @import("optional.zig").Optional;
63
+
64
+ const B = Array(4, Optional(bool));
65
+ var b: B.T = 0;
66
+ try expectEqual(u8, @TypeOf(b));
67
+
68
+ b = B.set(b, 2, .true);
69
+ try expectEqual(Optional(bool).None, B.get(b, 1));
70
+ try expectEqual(Optional(bool).true, B.get(b, 2));
71
+ try expectEqual(@as(u8, 0b00100000), b);
72
+ b = B.set(b, 2, .None);
73
+ b = B.set(b, 0, .false);
74
+ try expectEqual(Optional(bool).None, B.get(b, 2));
75
+ try expectEqual(Optional(bool).false, B.get(b, 0));
76
+ try expectEqual(@as(u8, 0b0000001), b);
77
+ }
@@ -0,0 +1,17 @@
1
+ /// Stores state required by optional features to the engine that can be passed to a generation's
2
+ /// `Battle.update` function. All generations generically support protocol logging (enabled via
3
+ /// `-Dlog`), chance actions and probability tracking (enabled via `-Dchance`), and damage
4
+ /// computation and chance overrides (`-Dcalc`), though the concrete types for these features are
5
+ /// generation dependent.
6
+ pub fn Options(comptime Log: type, comptime Chance: type, comptime Calc: type) type {
7
+ return struct { log: Log, chance: Chance, calc: Calc };
8
+ }
9
+
10
+ /// Helper to create a battle `Options` object with the provided `log`, `chance`, and `calc`.
11
+ pub fn options(
12
+ log: anytype,
13
+ chance: anytype,
14
+ calc: anytype,
15
+ ) Options(@TypeOf(log), @TypeOf(chance), @TypeOf(calc)) {
16
+ return .{ .log = log, .chance = chance, .calc = calc };
17
+ }
@@ -9,12 +9,12 @@ pub const Player = enum(u1) {
9
9
  P2,
10
10
 
11
11
  /// Returns a player's opponent.
12
- pub inline fn foe(self: Player) Player {
13
- return @intToEnum(Player, ~@enumToInt(self));
12
+ pub fn foe(self: Player) Player {
13
+ return @enumFromInt(~@intFromEnum(self));
14
14
  }
15
15
 
16
16
  /// Return's an identifier for the player's Pokémon at the one-indexed `id`.
17
- pub inline fn ident(self: Player, id: u3) ID {
17
+ pub fn ident(self: Player, id: u3) ID {
18
18
  assert(id > 0 and id <= 6);
19
19
  return .{ .id = id, .player = self };
20
20
  }
@@ -22,42 +22,38 @@ pub const Player = enum(u1) {
22
22
 
23
23
  test Player {
24
24
  try expectEqual(Player.P2, Player.P1.foe());
25
- try expectEqual(@as(u8, 0b0001), @bitCast(u8, Player.P1.ident(1)));
26
- try expectEqual(@as(u8, 0b1101), @bitCast(u8, Player.P2.ident(5)));
25
+ try expectEqual(@as(u8, 0b0001), @as(u8, @bitCast(Player.P1.ident(1))));
26
+ try expectEqual(@as(u8, 0b1101), @as(u8, @bitCast(Player.P2.ident(5))));
27
27
  }
28
28
 
29
29
  /// An identifier for a specific Pokémon in battle.
30
- pub const ID = packed struct {
30
+ pub const ID = packed struct(u8) {
31
31
  /// The one-indexed team slot of the Pokémon
32
32
  id: u3 = 0,
33
33
  /// The Pokémon's trainer.
34
34
  player: Player = .P1,
35
35
  _: u4 = 0,
36
36
 
37
- comptime {
38
- assert(@sizeOf(ID) == 1);
39
- }
40
-
41
37
  /// Converts the identifier into a number.
42
- pub inline fn int(self: ID) u4 {
43
- return @intCast(u4, @bitCast(u8, self));
38
+ pub fn int(self: ID) u4 {
39
+ return @intCast(@as(u8, @bitCast(self)));
44
40
  }
45
41
 
46
42
  /// Decodes the identifier from a number.
47
- pub inline fn from(id: u4) ID {
48
- return @bitCast(ID, @as(u8, id));
43
+ pub fn from(id: u4) ID {
44
+ return @bitCast(@as(u8, id));
49
45
  }
50
46
  };
51
47
 
52
48
  test ID {
53
- try expectEqual(@as(u8, 0b0001), @bitCast(u8, ID{ .player = .P1, .id = 1 }));
54
- try expectEqual(@as(u8, 0b1101), @bitCast(u8, ID{ .player = .P2, .id = 5 }));
55
- const id = ID{ .player = .P2, .id = 4 };
49
+ try expectEqual(@as(u8, 0b0001), @as(u8, @bitCast(ID{ .player = .P1, .id = 1 })));
50
+ try expectEqual(@as(u8, 0b1101), @as(u8, @bitCast(ID{ .player = .P2, .id = 5 })));
51
+ const id: ID = .{ .player = .P2, .id = 4 };
56
52
  try expectEqual(id, ID.from(id.int()));
57
53
  }
58
54
 
59
55
  /// A choice made by a player during battle.
60
- pub const Choice = packed struct {
56
+ pub const Choice = packed struct(u8) {
61
57
  /// The choice type.
62
58
  type: Choice.Type = .Pass,
63
59
  /// The choice data:
@@ -73,10 +69,6 @@ pub const Choice = packed struct {
73
69
  Move,
74
70
  Switch,
75
71
  };
76
-
77
- comptime {
78
- assert(@sizeOf(Choice) == 1);
79
- }
80
72
  };
81
73
 
82
74
  test Choice {
@@ -84,12 +76,12 @@ test Choice {
84
76
  const p2: Choice = .{ .type = .Switch, .data = 5 };
85
77
  try expectEqual(5, p2.data);
86
78
  try expectEqual(Choice.Type.Move, p1.type);
87
- try expectEqual(0b0001_0001, @bitCast(u8, p1));
88
- try expectEqual(0b0001_0110, @bitCast(u8, p2));
79
+ try expectEqual(@as(u8, 0b0001_0001), @as(u8, @bitCast(p1)));
80
+ try expectEqual(@as(u8, 0b0001_0110), @as(u8, @bitCast(p2)));
89
81
  }
90
82
 
91
83
  /// The result of the battle - all results other than 'None' should be considered terminal.
92
- pub const Result = packed struct {
84
+ pub const Result = packed struct(u8) {
93
85
  /// The type of result from the perspective of Player 1.
94
86
  /// `Error` is not possible when in Pokémon Showdown compatibility mode.
95
87
  type: Result.Type = .None,
@@ -117,13 +109,9 @@ pub const Result = packed struct {
117
109
  pub const Error: Result = .{ .type = .Error };
118
110
  /// The default result.
119
111
  pub const Default: Result = .{ .p1 = .Move, .p2 = .Move };
120
-
121
- comptime {
122
- assert(@sizeOf(Result) == 1);
123
- }
124
112
  };
125
113
 
126
114
  test Result {
127
- try expectEqual(0b0101_0000, @bitCast(u8, Result.Default));
128
- try expectEqual(0b1000_0000, @bitCast(u8, Result{ .p2 = .Switch }));
115
+ try expectEqual(@as(u8, 0b0101_0000), @as(u8, @bitCast(Result.Default)));
116
+ try expectEqual(@as(u8, 0b1000_0000), @as(u8, @bitCast(Result{ .p2 = .Switch })));
129
117
  }
@@ -4,24 +4,33 @@ const debug = std.debug;
4
4
  const io = std.io;
5
5
 
6
6
  pub fn print(value: anytype) void {
7
- debug.getStderrMutex().lock();
8
- defer debug.getStderrMutex().unlock();
7
+ debug.lockStdErr();
8
+ defer debug.unlockStdErr();
9
9
  const stderr = io.getStdErr().writer();
10
10
 
11
11
  nosuspend {
12
12
  stderr.writeAll("\x1b[41m") catch return;
13
- switch (@typeInfo(@TypeOf(value))) {
14
- .Struct => |info| {
15
- if (info.is_tuple) {
16
- inline for (info.fields, 0..) |f, i| {
17
- inspect(@field(value, f.name));
18
- if (i < info.fields.len - 1) stderr.writeAll(" ") catch return;
13
+ if (@TypeOf(@src()) == @TypeOf(value)) {
14
+ stderr.print("{s} ({s}:{d}:{d})", .{
15
+ value.fn_name,
16
+ value.file,
17
+ value.line,
18
+ value.column,
19
+ }) catch return;
20
+ } else {
21
+ switch (@typeInfo(@TypeOf(value))) {
22
+ .Struct => |info| {
23
+ if (info.is_tuple) {
24
+ inline for (info.fields, 0..) |f, i| {
25
+ inspect(@field(value, f.name));
26
+ if (i < info.fields.len - 1) stderr.writeAll(" ") catch return;
27
+ }
28
+ } else {
29
+ inspect(value);
19
30
  }
20
- } else {
21
- inspect(value);
22
- }
23
- },
24
- else => inspect(value),
31
+ },
32
+ else => inspect(value),
33
+ }
25
34
  }
26
35
  stderr.writeAll("\x1b[K\x1b[0m\n") catch return;
27
36
  }
@@ -58,6 +67,7 @@ fn inspect(value: anytype) void {
58
67
  @compileError(err);
59
68
  },
60
69
  },
70
+ .Optional => stderr.print("{?}", .{value}) catch return,
61
71
  else => stderr.print("{}", .{value}) catch return,
62
72
  }
63
73
  }
@@ -0,0 +1,120 @@
1
+ const std = @import("std");
2
+
3
+ const assert = std.debug.assert;
4
+
5
+ const Int = if (@hasField(std.builtin.Type, "int")) .int else .Int;
6
+
7
+ const c = @cImport({
8
+ @cDefine("NAPI_VERSION", "8");
9
+ @cInclude("node_api.h");
10
+ });
11
+
12
+ pub const Array = struct {
13
+ pub fn init(env: c.napi_env, o: struct { length: ?usize }) c.napi_value {
14
+ var result: c.napi_value = undefined;
15
+ assert(c.napi_ok == if (o.length) |n|
16
+ c.napi_create_array_with_length(env, n, &result)
17
+ else
18
+ c.napi_create_array(env, &result));
19
+ return result;
20
+ }
21
+
22
+ pub fn set(env: c.napi_env, array: c.napi_value, index: u32, value: c.napi_value) void {
23
+ assert(c.napi_set_element(env, array, index, value) == c.napi_ok);
24
+ }
25
+ };
26
+
27
+ pub const Boolean = struct {
28
+ pub fn init(env: c.napi_env, value: bool) c.napi_value {
29
+ var result: c.napi_value = undefined;
30
+ assert(c.napi_get_boolean(env, value, &result) == c.napi_ok);
31
+ return result;
32
+ }
33
+ };
34
+
35
+ pub const Number = struct {
36
+ pub fn init(env: c.napi_env, value: anytype) c.napi_value {
37
+ const T = @TypeOf(value);
38
+ var result: c.napi_value = undefined;
39
+ assert(c.napi_ok == switch (@typeInfo(T)) {
40
+ Int => |info| switch (info.bits) {
41
+ 0...32 => switch (info.signedness) {
42
+ .signed => c.napi_create_int32(env, @as(i32, value), &result),
43
+ .unsigned => c.napi_create_uint32(env, @as(u32, value), &result),
44
+ },
45
+ 33...52 => c.napi_create_int64(env, @as(i64, value), &result),
46
+ else => @compileError("int can't be represented as JS number"),
47
+ },
48
+ else => @compileError("expected number, got: " ++ @typeName(T)),
49
+ });
50
+ return result;
51
+ }
52
+
53
+ pub fn get(env: c.napi_env, value: c.napi_value, comptime T: type) T {
54
+ switch (@typeInfo(T)) {
55
+ Int => |info| switch (info.bits) {
56
+ 0...32 => switch (info.signedness) {
57
+ .signed => {
58
+ var result: i32 = undefined;
59
+ assert(c.napi_get_value_int32(env, value, &result) == c.napi_ok);
60
+ return if (info.bits == 32) result else @intCast(result);
61
+ },
62
+ .unsigned => {
63
+ var result: u32 = undefined;
64
+ assert(c.napi_get_value_uint32(env, value, &result) == c.napi_ok);
65
+ return if (info.bits == 32) result else @intCast(result);
66
+ },
67
+ },
68
+ 33...63 => {
69
+ var result: i64 = undefined;
70
+ assert(c.napi_get_value_int64(env, value, &result) == c.napi_ok);
71
+ return @intCast(result);
72
+ },
73
+ else => {
74
+ var result: i64 = undefined;
75
+ assert(c.napi_get_value_int64(env, value, &result) == c.napi_ok);
76
+ return switch (info.signedness) {
77
+ .signed => value,
78
+ .unsigned => if (0 <= value) @intCast(value) else unreachable,
79
+ };
80
+ },
81
+ },
82
+ else => @compileError("expected number, got: " ++ @typeName(T)),
83
+ }
84
+ }
85
+ };
86
+
87
+ pub const Object = struct {
88
+ pub fn init(env: c.napi_env) c.napi_value {
89
+ var result: c.napi_value = undefined;
90
+ assert(c.napi_create_object(env, &result) == c.napi_ok);
91
+ return result;
92
+ }
93
+ };
94
+
95
+ pub const Property = union(enum) {
96
+ method: c.napi_callback,
97
+ value: c.napi_value,
98
+
99
+ pub fn init(comptime name: [:0]const u8, property: Property) c.napi_property_descriptor {
100
+ return .{
101
+ .utf8name = name,
102
+ .name = null,
103
+ .method = switch (property) {
104
+ .method => |m| m,
105
+ .value => null,
106
+ },
107
+ .getter = null,
108
+ .setter = null,
109
+ .value = switch (property) {
110
+ .method => null,
111
+ .value => |v| v,
112
+ },
113
+ .attributes = switch (property) {
114
+ .method => c.napi_default,
115
+ .value => c.napi_enumerable,
116
+ },
117
+ .data = null,
118
+ };
119
+ }
120
+ };