@pkmn/engine 0.1.0-dev.6ef582f1 → 0.1.0-dev.724afcb1

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 (85) hide show
  1. package/LICENSE +1 -3
  2. package/README.md +69 -26
  3. package/build/pkg/addon/browser.d.ts +3 -0
  4. package/build/pkg/addon/browser.js +47 -0
  5. package/build/pkg/addon/browser.js.map +1 -0
  6. package/build/pkg/addon/node.d.ts +3 -0
  7. package/build/pkg/addon/node.js +110 -0
  8. package/build/pkg/addon/node.js.map +1 -0
  9. package/build/pkg/addon/wasm.d.ts +2 -0
  10. package/build/pkg/addon/wasm.js +53 -0
  11. package/build/pkg/addon/wasm.js.map +1 -0
  12. package/build/pkg/addon.d.ts +26 -4
  13. package/build/pkg/addon.js +39 -71
  14. package/build/pkg/addon.js.map +1 -1
  15. package/build/pkg/data/ids.json +12 -12
  16. package/build/pkg/data/layout.json +17 -4
  17. package/build/pkg/data/protocol.json +84 -13
  18. package/build/pkg/data.d.ts +27 -5
  19. package/build/pkg/data.js.map +1 -1
  20. package/build/pkg/gen1.d.ts +15 -18
  21. package/build/pkg/gen1.js +30 -21
  22. package/build/pkg/gen1.js.map +1 -1
  23. package/build/pkg/index.d.ts +42 -91
  24. package/build/pkg/index.js +23 -70
  25. package/build/pkg/index.js.map +1 -1
  26. package/build/pkg/protocol.d.ts +29 -1
  27. package/build/pkg/protocol.js +123 -102
  28. package/build/pkg/protocol.js.map +1 -1
  29. package/build/tools/debug.js +84 -73
  30. package/build/tools/debug.js.map +1 -1
  31. package/build/tools/display/debug.jsx +66 -0
  32. package/build/tools/display/debug.jsx.map +1 -0
  33. package/build/tools/display/index.js +152 -0
  34. package/build/tools/display/index.js.map +1 -0
  35. package/build/tools/display/ui.jsx +360 -0
  36. package/build/tools/display/ui.jsx.map +1 -0
  37. package/build/tools/display/util.js +157 -0
  38. package/build/tools/display/util.js.map +1 -0
  39. package/build.zig +303 -126
  40. package/package.json +64 -123
  41. package/src/bin/install-pkmn-engine +47 -21
  42. package/src/bin/pkmn-debug +1 -1
  43. package/src/lib/bindings/c.zig +200 -0
  44. package/src/lib/{binding → bindings}/node.zig +15 -32
  45. package/src/lib/bindings/wasm.zig +50 -0
  46. package/src/lib/common/array.zig +70 -0
  47. package/src/lib/common/data.zig +12 -24
  48. package/src/lib/common/debug.zig +33 -28
  49. package/src/lib/common/js.zig +3 -7
  50. package/src/lib/common/optional.zig +19 -18
  51. package/src/lib/common/options.zig +6 -0
  52. package/src/lib/common/protocol.zig +961 -450
  53. package/src/lib/common/rational.zig +341 -254
  54. package/src/lib/common/rng.zig +22 -15
  55. package/src/lib/common/util.zig +33 -1
  56. package/src/lib/gen1/calc.zig +726 -178
  57. package/src/lib/gen1/chance.zig +485 -307
  58. package/src/lib/gen1/data/moves.zig +193 -183
  59. package/src/lib/gen1/data/species.zig +4 -6
  60. package/src/lib/gen1/data/types.zig +9 -10
  61. package/src/lib/gen1/data.zig +60 -75
  62. package/src/lib/gen1/helpers.zig +90 -410
  63. package/src/lib/gen1/mechanics.zig +703 -614
  64. package/src/lib/gen2/calc.zig +150 -0
  65. package/src/lib/gen2/chance.zig +896 -0
  66. package/src/lib/gen2/data/items.zig +13 -21
  67. package/src/lib/gen2/data/moves.zig +664 -572
  68. package/src/lib/gen2/data/species.zig +2 -4
  69. package/src/lib/gen2/data/types.zig +139 -34
  70. package/src/lib/gen2/data.zig +121 -96
  71. package/src/lib/gen2/generated.zig +801 -0
  72. package/src/lib/gen2/helpers.zig +53 -38
  73. package/src/lib/gen2/mechanics.zig +3580 -29
  74. package/src/lib/napi.h +2 -0
  75. package/src/lib/node.zig +14 -0
  76. package/src/lib/pkmn.zig +125 -29
  77. package/src/lib/wasm.zig +13 -0
  78. package/src/tools/display/dom.ts +108 -0
  79. package/src/tools/display/ui.css +354 -0
  80. package/build/test/display.js +0 -400
  81. package/build/test/display.js.map +0 -1
  82. package/src/lib/binding/wasm.zig +0 -12
  83. package/src/lib/gen1/README.md +0 -812
  84. package/src/lib/gen2/README.md +0 -308
  85. package/src/test/display/pkmn.html.tmpl +0 -368
package/build.zig CHANGED
@@ -1,5 +1,9 @@
1
- const std = @import("std");
2
1
  const builtin = @import("builtin");
2
+ const std = @import("std");
3
+
4
+ fn ArrayList(comptime T: type) type {
5
+ return std.array_list.Aligned(T, null);
6
+ }
3
7
 
4
8
  pub const Options = struct {
5
9
  showdown: ?bool = null,
@@ -8,16 +12,26 @@ pub const Options = struct {
8
12
  calc: ?bool = null,
9
13
  };
10
14
 
11
- pub fn module(b: *std.Build, options: Options) *std.Build.Module {
12
- const dirname = comptime std.fs.path.dirname(@src().file) orelse ".";
15
+ pub fn module(
16
+ b: *std.Build,
17
+ options: Options,
18
+ target: std.Build.ResolvedTarget,
19
+ optimize: std.builtin.OptimizeMode,
20
+ ) *std.Build.Module {
13
21
  const build_options = b.addOptions();
14
22
  build_options.addOption(?bool, "showdown", options.showdown);
15
23
  build_options.addOption(?bool, "log", options.log);
16
24
  build_options.addOption(?bool, "chance", options.chance);
17
25
  build_options.addOption(?bool, "calc", options.calc);
26
+
27
+ const root_source_file = b.path("src/lib/pkmn.zig");
28
+ const imports: []const std.Build.Module.Import =
29
+ &.{.{ .name = "build_options", .module = build_options.createModule() }};
18
30
  return b.createModule(.{
19
- .source_file = .{ .path = dirname ++ "/src/lib/pkmn.zig" },
20
- .dependencies = &.{.{ .name = "build_options", .module = build_options.createModule() }},
31
+ .root_source_file = root_source_file,
32
+ .target = target,
33
+ .optimize = optimize,
34
+ .imports = imports,
21
35
  });
22
36
  }
23
37
 
@@ -28,12 +42,16 @@ pub fn build(b: *std.Build) !void {
28
42
  const node_headers = b.option([]const u8, "node-headers", "Path to node-headers");
29
43
  const node_import_lib =
30
44
  b.option([]const u8, "node-import-library", "Path to node import library (Windows)");
45
+ const demo = if (try exists(b, "src/tools/demo.zig"))
46
+ b.option(bool, "demo", "Build the demo library") orelse false
47
+ else
48
+ false;
31
49
  const wasm = b.option(bool, "wasm", "Build a WASM library") orelse false;
32
50
  const wasm_stack_size =
33
51
  b.option(u64, "wasm-stack-size", "The size of WASM stack") orelse std.wasm.page_size;
34
52
  const dynamic = b.option(bool, "dynamic", "Build a dynamic library") orelse false;
35
- const strip = b.option(bool, "strip", "Strip debugging symbols from binary") orelse false;
36
- const pic = b.option(bool, "pic", "Force position independent code") orelse false;
53
+ const strip = b.option(bool, "strip", "Strip debugging symbols from binary");
54
+ const pic = b.option(bool, "pic", "Force position independent code");
37
55
  const emit_asm = b.option(bool, "emit-asm", "Output .s (assembly code)") orelse false;
38
56
  const emit_ll = b.option(bool, "emit-ll", "Output .ll (LLVM IR)") orelse false;
39
57
 
@@ -44,7 +62,7 @@ pub fn build(b: *std.Build) !void {
44
62
  defer parsed.deinit();
45
63
  const version = parsed.value.object.get("version").?.string;
46
64
  const description = parsed.value.object.get("description").?.string;
47
- var repository = std.mem.split(u8, parsed.value.object.get("repository").?.string, ":");
65
+ var repository = std.mem.splitScalar(u8, parsed.value.object.get("repository").?.string, ':');
48
66
  std.debug.assert(std.mem.eql(u8, repository.first(), "github"));
49
67
 
50
68
  const showdown =
@@ -52,6 +70,7 @@ pub fn build(b: *std.Build) !void {
52
70
  const log = b.option(bool, "log", "Enable protocol message logging") orelse false;
53
71
  const chance = b.option(bool, "chance", "Enable update probability tracking") orelse false;
54
72
  const calc = b.option(bool, "calc", "Enable damage calculator support") orelse false;
73
+ const extra = b.option([]const []const u8, "option", "Enable extra option");
55
74
 
56
75
  const options = b.addOptions();
57
76
  options.addOption(?bool, "showdown", showdown);
@@ -59,32 +78,67 @@ pub fn build(b: *std.Build) !void {
59
78
  options.addOption(?bool, "chance", chance);
60
79
  options.addOption(?bool, "calc", calc);
61
80
 
81
+ if (extra) |opts| {
82
+ for (opts) |opt| {
83
+ if (std.mem.indexOfScalar(u8, opt, '=')) |i| {
84
+ options.addOption(?bool, opt[0..i], if (std.mem.eql(u8, opt[i + 1 ..], "true"))
85
+ true
86
+ else if (std.mem.eql(u8, opt[i + 1 ..], "false"))
87
+ false
88
+ else {
89
+ std.log.err("Invalid option: {s}\n", .{opt});
90
+ return error.InvalidOption;
91
+ });
92
+ } else {
93
+ options.addOption(?bool, opt, true);
94
+ }
95
+ }
96
+ }
97
+
62
98
  const name = if (showdown) "pkmn-showdown" else "pkmn";
63
99
 
100
+ const pkmn: *std.Build.Module = b.addModule("pkmn", .{
101
+ .root_source_file = b.path("src/lib/pkmn.zig"),
102
+ .optimize = optimize,
103
+ .target = target,
104
+ .imports = &.{.{ .name = "build_options", .module = options.createModule() }},
105
+ });
106
+
64
107
  var c = false;
65
108
  if (node_headers) |headers| {
109
+ const translate_c = b.addTranslateC(.{
110
+ .root_source_file = b.path("src/lib/napi.h"),
111
+ .target = target,
112
+ .optimize = optimize,
113
+ });
114
+ translate_c.addSystemIncludePath(b.path(headers));
66
115
  const addon = b.fmt("{s}.node", .{name});
67
- const lib = b.addSharedLibrary(.{
116
+ const path = b.path("src/lib/node.zig");
117
+ const lib = b.addLibrary(.{
118
+ .linkage = .dynamic,
68
119
  .name = addon,
69
- .root_source_file = .{ .path = "src/lib/binding/node.zig" },
70
- .optimize = optimize,
71
- .target = target,
120
+ .root_module = b.createModule(.{
121
+ .root_source_file = path,
122
+ .optimize = optimize,
123
+ .target = target,
124
+ .strip = strip,
125
+ .pic = pic,
126
+ }),
72
127
  });
73
- lib.addOptions("build_options", options);
74
- lib.setMainPkgPath("./");
75
- lib.addSystemIncludePath(headers);
76
- lib.linkLibC();
128
+ lib.root_module.addOptions("build_options", options);
129
+ lib.root_module.addImport("napi", translate_c.createModule());
130
+ lib.root_module.link_libc = true;
77
131
  if (node_import_lib) |il| {
78
- lib.addObjectFile(il);
79
- } else if ((try std.zig.system.NativeTargetInfo.detect(target)).target.os.tag == .windows) {
80
- try std.io.getStdErr().writeAll("Must provide --node-import-library path on Windows\n");
132
+ lib.root_module.addObjectFile(b.path(il));
133
+ } else if (target.result.os.tag == .windows) {
134
+ var err = std.Io.File.stderr().writer(b.graph.io, &.{});
135
+ try err.interface.writeAll("Must provide --node-import-library path on Windows\n");
81
136
  std.process.exit(1);
82
137
  }
83
138
  lib.linker_allow_shlib_undefined = true;
84
139
  maybeStrip(b, lib, b.getInstallStep(), strip, cmd);
85
- if (pic) lib.force_pic = pic;
86
140
  // Always emit to build/lib because this is where the driver code expects to find it
87
- // TODO(ziglang/zig#2231): using the following used to work (though was hacky):
141
+ // TODO: ziglang/zig#2231 - using the following used to work (though was hacky):
88
142
  //
89
143
  // lib.emit_bin = .{ .emit_to = b.fmt("build/lib/{s}", .{addon}) };
90
144
  // b.getInstallStep().dependOn(&lib.step);
@@ -93,80 +147,88 @@ pub fn build(b: *std.Build) !void {
93
147
  // rename the file ourself in install-pkmn-engine
94
148
  b.installArtifact(lib);
95
149
  } else if (wasm) {
96
- const lib = b.addSharedLibrary(.{
97
- .name = name,
98
- .root_source_file = .{ .path = "src/lib/binding/wasm.zig" },
99
- .optimize = switch (optimize) {
100
- .ReleaseFast, .ReleaseSafe => .ReleaseSmall,
101
- else => optimize,
102
- },
103
- .target = .{ .cpu_arch = .wasm32, .os_tag = .freestanding },
104
- });
105
- lib.addOptions("build_options", options);
106
- lib.setMainPkgPath("./");
107
- lib.stack_size = wasm_stack_size;
108
- lib.rdynamic = true;
109
- lib.strip = strip;
110
- if (pic) lib.force_pic = pic;
111
- const opt = b.findProgram(&.{"wasm-opt"}, &.{"./node_modules/.bin"}) catch null;
112
- if (optimize != .Debug and opt != null) {
113
- const out = b.fmt("build/lib/{s}.wasm", .{name});
114
- const sh = b.addSystemCommand(&.{ opt.?, "-O4" });
115
- sh.addArtifactArg(lib);
116
- sh.addArg("-o");
117
- sh.addFileSourceArg(.{ .path = out });
118
- b.getInstallStep().dependOn(&sh.step);
119
- }
120
- b.installArtifact(lib);
150
+ const path = "src/lib/wasm.zig";
151
+ try buildWasm(b, name, path, optimize, strip, pic, wasm_stack_size, null, options);
152
+ } else if (demo) {
153
+ const path = "src/tools/demo.zig";
154
+ const n = if (showdown) "demo-showdown" else "demo";
155
+ const mod = pkmn;
156
+ try buildWasm(b, n, path, optimize, strip, pic, wasm_stack_size, mod, options);
121
157
  } else if (dynamic) {
122
- const lib = b.addSharedLibrary(.{
158
+ const path = b.path("src/lib/c.zig");
159
+ const lib = b.addLibrary(.{
160
+ .linkage = .dynamic,
123
161
  .name = name,
124
- .root_source_file = .{ .path = "src/lib/binding/c.zig" },
125
- .version = try std.SemanticVersion.parse(version),
126
- .optimize = optimize,
127
- .target = target,
162
+ .root_module = b.createModule(.{
163
+ .root_source_file = path,
164
+ .optimize = optimize,
165
+ .target = target,
166
+ .strip = strip,
167
+ .pic = pic,
168
+ }),
128
169
  });
129
- lib.addOptions("build_options", options);
130
- lib.setMainPkgPath("./");
131
- lib.addIncludePath("src/include");
170
+ lib.root_module.addOptions("build_options", options);
171
+ lib.root_module.addIncludePath(b.path("src/include"));
132
172
  maybeStrip(b, lib, b.getInstallStep(), strip, cmd);
133
- if (pic) lib.force_pic = pic;
134
173
  b.installArtifact(lib);
135
174
  c = true;
136
175
  } else {
137
- const lib = b.addStaticLibrary(.{
176
+ const path = b.path("src/lib/c.zig");
177
+ const lib = b.addLibrary(.{
178
+ .linkage = .static,
138
179
  .name = name,
139
- .root_source_file = .{ .path = "src/lib/binding/c.zig" },
140
- .optimize = optimize,
141
- .target = target,
180
+ .root_module = b.createModule(.{
181
+ .root_source_file = path,
182
+ .optimize = optimize,
183
+ .target = target,
184
+ .strip = strip,
185
+ .pic = pic,
186
+ }),
142
187
  });
143
- lib.addOptions("build_options", options);
144
- lib.setMainPkgPath("./");
145
- lib.addIncludePath("src/include");
146
- lib.bundle_compiler_rt = true;
188
+ lib.root_module.addOptions("build_options", options);
189
+ lib.root_module.addIncludePath(b.path("src/include"));
190
+ if (target.result.os.tag != .macos) {
191
+ lib.bundle_compiler_rt = true;
192
+ }
147
193
  maybeStrip(b, lib, b.getInstallStep(), strip, cmd);
148
- if (pic) lib.force_pic = pic;
149
- if (emit_asm) lib.emit_asm = .emit;
150
- if (emit_ll) lib.emit_llvm_ir = .emit;
194
+ if (emit_asm) {
195
+ b.getInstallStep().dependOn(&b.addInstallFileWithDir(
196
+ lib.getEmittedAsm(),
197
+ .prefix,
198
+ b.fmt("{s}.s", .{name}),
199
+ ).step);
200
+ }
201
+ if (emit_ll) {
202
+ b.getInstallStep().dependOn(&b.addInstallFileWithDir(
203
+ lib.getEmittedLlvmIr(),
204
+ .prefix,
205
+ b.fmt("{s}.ll", .{name}),
206
+ ).step);
207
+ }
151
208
  b.installArtifact(lib);
152
209
  c = true;
153
210
  }
154
211
 
155
212
  if (c) {
156
- const header = b.addInstallFileWithDir(
157
- .{ .path = "src/include/pkmn.h" },
158
- .header,
159
- "pkmn.h",
160
- );
213
+ const path = b.path("src/include/pkmn.h");
214
+ const header = b.addInstallFileWithDir(path, .header, "pkmn.h");
161
215
  b.getInstallStep().dependOn(&header.step);
162
216
 
163
217
  const pc = b.fmt("lib{s}.pc", .{name});
164
- const file = try b.cache_root.join(b.allocator, &.{pc});
165
- const pkgconfig_file = try std.fs.cwd().createFile(file, .{});
218
+ const cwd = try std.process.currentPathAlloc(b.graph.io, b.allocator);
219
+ const file = try std.Io.Dir.path.relative(
220
+ b.allocator,
221
+ cwd,
222
+ &b.graph.environ_map,
223
+ cwd,
224
+ try b.cache_root.join(b.allocator, &.{pc}),
225
+ );
226
+ const pkgconfig_file = try std.Io.Dir.cwd().createFile(b.graph.io, file, .{});
227
+ defer pkgconfig_file.close(b.graph.io);
166
228
 
167
229
  const dirname = comptime std.fs.path.dirname(@src().file) orelse ".";
168
- const writer = pkgconfig_file.writer();
169
- try writer.print(
230
+ var writer = pkgconfig_file.writer(b.graph.io, &.{});
231
+ try writer.interface.print(
170
232
  \\prefix={0s}/{1s}
171
233
  \\includedir=${{prefix}}/include
172
234
  \\libdir=${{prefix}}/lib
@@ -178,12 +240,11 @@ pub fn build(b: *std.Build) !void {
178
240
  \\Cflags: -I${{includedir}}
179
241
  \\Libs: -L${{libdir}} -l{2s}
180
242
  , .{ dirname, b.install_path, name, repository.next().?, description, version });
181
- defer pkgconfig_file.close();
182
243
 
183
244
  b.installFile(file, b.fmt("share/pkgconfig/{s}", .{pc}));
184
245
  }
185
246
 
186
- const config = .{
247
+ const config: Config = .{
187
248
  .target = target,
188
249
  .optimize = optimize,
189
250
  .pic = pic,
@@ -194,7 +255,7 @@ pub fn build(b: *std.Build) !void {
194
255
  // TODO: tests can be run multiple times due to @imports
195
256
  const tests = TestStep.create(b, options, config);
196
257
 
197
- var exes = std.ArrayList(*std.Build.CompileStep).init(b.allocator);
258
+ var exes: ArrayList(*std.Build.Step.Compile) = .empty;
198
259
  const tools: ToolConfig = .{
199
260
  .options = .{
200
261
  .showdown = showdown,
@@ -212,37 +273,121 @@ pub fn build(b: *std.Build) !void {
212
273
  var benchmark_config = tools;
213
274
  benchmark_config.general.optimize = .ReleaseFast;
214
275
  benchmark_config.general.strip = true;
215
- const benchmark = tool(b, "src/test/benchmark.zig", benchmark_config);
276
+ const benchmark = try tool(b, "src/test/benchmark.zig", benchmark_config);
216
277
 
217
278
  var fuzz_config = tools;
218
279
  fuzz_config.general.strip = false;
219
280
  fuzz_config.tool.name = "fuzz";
220
- const fuzz = tool(b, "src/test/fuzz.zig", fuzz_config);
221
-
222
- const copies = tool(b, "src/tools/copies.zig", tools);
223
- const dump = tool(b, "src/tools/dump.zig", tools);
224
- const serde = tool(b, "src/tools/serde.zig", tools);
225
- const transitions = tool(b, "src/tools/transitions.zig", tools);
226
-
227
- b.step("copies", "Run copy detector").dependOn(&copies.step);
228
- b.step("benchmark", "Run benchmark code").dependOn(&benchmark.step);
229
- b.step("dump", "Run protocol dump tool").dependOn(&dump.step);
230
- b.step("fuzz", "Run fuzz tester").dependOn(&fuzz.step);
231
- b.step("serde", "Run serialization/deserialization tool").dependOn(&serde.step);
281
+ const fuzz = try tool(b, "src/test/fuzz.zig", fuzz_config);
282
+
283
+ const analyze = try tool(b, "src/tools/analyze.zig", tools);
284
+ const dump = try tool(b, "src/tools/dump.zig", tools);
285
+ const transitions = try tool(b, "src/tools/transitions.zig", tools);
286
+
287
+ // FIXME: serde randomly fails to build in some release configurations
288
+ var hack = tools;
289
+ if (optimize != .Debug) hack.tool.tests = null;
290
+ const serde = try tool(b, "src/tools/serde.zig", hack);
291
+
292
+ if (analyze) |t| b.step("analyze", "Run LLVM analysis tool").dependOn(&t.step);
293
+ if (benchmark) |t| b.step("benchmark", "Run benchmark code").dependOn(&t.step);
294
+ if (dump) |t| b.step("dump", "Run protocol dump tool").dependOn(&t.step);
295
+ if (fuzz) |t| b.step("fuzz", "Run fuzz tester").dependOn(&t.step);
296
+ if (serde) |t| b.step("serde", "Run serialization/deserialization tool").dependOn(&t.step);
232
297
  b.step("test", "Run all tests").dependOn(&tests.step);
233
298
  b.step("tools", "Install tools").dependOn(&ToolsStep.create(b, &exes).step);
234
- b.step("transitions", "Visualize transitions algorithm search").dependOn(&transitions.step);
299
+ if (transitions) |t| {
300
+ b.step("transitions", "Visualize transitions algorithm search").dependOn(&t.step);
301
+ }
302
+ }
303
+
304
+ fn buildWasm(
305
+ b: *std.Build,
306
+ name: []const u8,
307
+ root_src_file: []const u8,
308
+ optimize: std.builtin.OptimizeMode,
309
+ strip: ?bool,
310
+ pic: ?bool,
311
+ wasm_stack_size: u64,
312
+ import: ?*std.Build.Module,
313
+ options: anytype,
314
+ ) !void {
315
+ const mode = switch (optimize) {
316
+ .ReleaseFast, .ReleaseSafe => .ReleaseSmall,
317
+ else => optimize,
318
+ };
319
+ // https://webassembly.org/features/
320
+ var features = std.Target.wasm.featureSet(&.{
321
+ .atomics,
322
+ .bulk_memory,
323
+ // .exception_handling,
324
+ .extended_const,
325
+ // .half_precision,
326
+ // .multimemory,
327
+ .mutable_globals,
328
+ .nontrapping_fptoint,
329
+ .reference_types,
330
+ // .relaxed_simd,
331
+ .sign_ext,
332
+ .simd128,
333
+ // .tail_call,
334
+ });
335
+ if (builtin.zig_version.order(try std.SemanticVersion.parse("0.12.0")) != .lt) {
336
+ features.addFeature(@intFromEnum(std.Target.wasm.Feature.multivalue));
337
+ }
338
+ const freestanding = b.resolveTargetQuery(.{
339
+ .cpu_arch = .wasm32,
340
+ .os_tag = .freestanding,
341
+ .cpu_features_add = features,
342
+ });
343
+ const path = b.path(root_src_file);
344
+ const exe = b.addExecutable(.{
345
+ .name = name,
346
+ .root_module = b.createModule(.{
347
+ .root_source_file = path,
348
+ .optimize = mode,
349
+ .target = freestanding,
350
+ .strip = strip,
351
+ .pic = pic,
352
+ }),
353
+ });
354
+
355
+ var file = try std.Io.Dir.cwd().openFile(b.graph.io, root_src_file, .{});
356
+ defer file.close(b.graph.io);
357
+ var reader = file.reader(b.graph.io, &.{});
358
+ const bytes = try reader.interface.allocRemaining(b.allocator, .unlimited);
359
+ exe.root_module.export_symbol_names = try exports(b, bytes);
360
+ exe.entry = .disabled;
361
+
362
+ if (import) |i| {
363
+ exe.root_module.addImport("pkmn", i);
364
+ }
365
+ exe.stack_size = wasm_stack_size;
366
+ exe.root_module.addOptions("build_options", options);
367
+
368
+ const opt = b.findProgram(&.{"wasm-opt"}, &.{"./node_modules/.bin"}) catch null;
369
+ if (optimize != .Debug and opt != null) {
370
+ const out = b.fmt("build/lib/{s}.wasm", .{name});
371
+ const sh = b.addSystemCommand(&.{ opt.?, "--enable-bulk-memory", "--enable-simd", "-O4" });
372
+ sh.addArtifactArg(exe);
373
+ sh.addArg("-o");
374
+ sh.addFileArg(b.path(out));
375
+ b.getInstallStep().dependOn(&sh.step);
376
+ } else {
377
+ b.getInstallStep().dependOn(&b.addInstallArtifact(exe, .{
378
+ .dest_dir = .{ .override = std.Build.InstallDir{ .lib = {} } },
379
+ }).step);
380
+ }
235
381
  }
236
382
 
237
383
  fn maybeStrip(
238
384
  b: *std.Build,
239
- artifact: *std.Build.CompileStep,
385
+ artifact: *std.Build.Step.Compile,
240
386
  step: *std.Build.Step,
241
- strip: bool,
387
+ strip: ?bool,
242
388
  cmd: ?[]const u8,
243
389
  ) void {
244
- artifact.strip = strip;
245
- if (!strip or cmd == null) return;
390
+ if (!(strip orelse false) or cmd == null) return;
246
391
  // Using `strip -r -u` for dynamic libraries is supposed to work on macOS but doesn't...
247
392
  const mac = builtin.os.tag == .macos;
248
393
  if (mac and artifact.isDynamicLibrary()) return;
@@ -254,10 +399,10 @@ fn maybeStrip(
254
399
  }
255
400
 
256
401
  const Config = struct {
257
- target: std.zig.CrossTarget,
402
+ target: std.Build.ResolvedTarget,
258
403
  optimize: std.builtin.OptimizeMode,
259
- pic: bool,
260
- strip: bool,
404
+ pic: ?bool,
405
+ strip: ?bool,
261
406
  cmd: ?[]const u8,
262
407
  };
263
408
 
@@ -265,32 +410,30 @@ const TestStep = struct {
265
410
  step: std.Build.Step,
266
411
  build: bool,
267
412
 
268
- pub fn create(b: *std.Build, options: *std.Build.OptionsStep, config: Config) *TestStep {
413
+ pub fn create(b: *std.Build, options: *std.Build.Step.Options, config: Config) *TestStep {
269
414
  const coverage = b.option([]const u8, "test-coverage", "Generate test coverage");
270
- const test_file = b.option([]const u8, "test-file", "Input file for test");
271
415
  const test_filter =
272
416
  b.option([]const u8, "test-filter", "Skip tests that do not match filter");
273
417
 
274
418
  const self = b.allocator.create(TestStep) catch @panic("OOM");
275
419
  const step = std.Build.Step.init(.{ .id = .custom, .name = "Run all tests", .owner = b });
276
- self.* = TestStep{ .step = step, .build = test_filter == null };
420
+ self.* = .{ .step = step, .build = test_filter == null };
277
421
 
278
- const path = test_file orelse "src/lib/test.zig";
422
+ const path = b.path("src/lib/test.zig");
279
423
  const tests = b.addTest(.{
280
- .name = b.fmt("{s}-{s}", .{
281
- std.fs.path.basename(std.fs.path.dirname(path).?),
282
- std.fs.path.stem(std.fs.path.basename(path)),
424
+ .root_module = b.createModule(.{
425
+ .root_source_file = path,
426
+ .optimize = config.optimize,
427
+ .target = config.target,
428
+ .single_threaded = true,
429
+ .strip = config.strip,
430
+ .pic = config.pic,
283
431
  }),
284
- .root_source_file = .{ .path = path },
285
- .optimize = config.optimize,
286
- .target = config.target,
287
- .filter = test_filter,
432
+ .filters = if (test_filter) |filter| &.{filter} else &.{},
288
433
  });
289
- tests.setMainPkgPath("./");
290
- tests.addOptions("build_options", options);
291
- tests.single_threaded = true;
434
+ tests.root_module.addOptions("build_options", options);
435
+
292
436
  maybeStrip(b, tests, &tests.step, config.strip, config.cmd);
293
- if (config.pic) tests.force_pic = config.pic;
294
437
  if (coverage) |c| {
295
438
  tests.setExecCmd(&.{ "kcov", "--include-pattern=src/lib", c, null });
296
439
  }
@@ -306,11 +449,12 @@ const ToolConfig = struct {
306
449
  tool: struct {
307
450
  tests: ?*TestStep,
308
451
  name: ?[]const u8 = null,
309
- exes: *std.ArrayList(*std.Build.CompileStep),
452
+ exes: *ArrayList(*std.Build.Step.Compile),
310
453
  },
311
454
  };
312
455
 
313
- fn tool(b: *std.Build, path: []const u8, config: ToolConfig) *std.Build.RunStep {
456
+ fn tool(b: *std.Build, path: []const u8, config: ToolConfig) !?*std.Build.Step.Run {
457
+ if (!try exists(b, path)) return null;
314
458
  var name = config.tool.name orelse std.fs.path.basename(path);
315
459
  const index = std.mem.lastIndexOfScalar(u8, name, '.');
316
460
  if (index) |i| name = name[0..i];
@@ -318,16 +462,23 @@ fn tool(b: *std.Build, path: []const u8, config: ToolConfig) *std.Build.RunStep
318
462
 
319
463
  const exe = b.addExecutable(.{
320
464
  .name = name,
321
- .root_source_file = .{ .path = path },
322
- .target = config.general.target,
323
- .optimize = config.general.optimize,
465
+ .root_module = b.createModule(.{
466
+ .root_source_file = b.path(path),
467
+ .target = config.general.target,
468
+ .optimize = config.general.optimize,
469
+ .strip = config.general.strip,
470
+ .pic = config.general.pic,
471
+ }),
324
472
  });
325
- exe.addModule("pkmn", module(b, config.options));
326
473
 
327
- exe.single_threaded = true;
328
- if (config.general.pic) exe.force_pic = config.general.pic;
474
+ const import = module(b, config.options, config.general.target, config.general.optimize);
475
+ exe.root_module.addImport("pkmn", import);
476
+ if (config.general.target.result.os.tag == .windows) {
477
+ exe.root_module.linkSystemLibrary("advapi32", .{});
478
+ }
479
+
329
480
  if (config.tool.tests) |ts| ts.step.dependOn(&exe.step);
330
- config.tool.exes.append(exe) catch @panic("OOM");
481
+ config.tool.exes.append(b.allocator, exe) catch @panic("OOM");
331
482
 
332
483
  const run = b.addRunArtifact(exe);
333
484
  maybeStrip(b, exe, &run.step, config.general.strip, config.general.cmd);
@@ -336,14 +487,40 @@ fn tool(b: *std.Build, path: []const u8, config: ToolConfig) *std.Build.RunStep
336
487
  return run;
337
488
  }
338
489
 
490
+ fn exists(b: *std.Build, path: []const u8) !bool {
491
+ std.Io.Dir.cwd().access(b.graph.io, path, .{}) catch |err| switch (err) {
492
+ error.FileNotFound => return false,
493
+ else => |e| return e,
494
+ };
495
+ return true;
496
+ }
497
+
339
498
  const ToolsStep = struct {
340
499
  step: std.Build.Step,
341
500
 
342
- pub fn create(b: *std.Build, exes: *std.ArrayList(*std.Build.CompileStep)) *ToolsStep {
501
+ pub fn create(b: *std.Build, exes: *ArrayList(*std.Build.Step.Compile)) *ToolsStep {
343
502
  const self = b.allocator.create(ToolsStep) catch @panic("OOM");
344
503
  const step = std.Build.Step.init(.{ .id = .custom, .name = "Install tools", .owner = b });
345
- self.* = ToolsStep{ .step = step };
346
- for (exes.items) |t| self.step.dependOn(&b.addInstallArtifact(t).step);
504
+ self.* = .{ .step = step };
505
+ for (exes.items) |t| self.step.dependOn(&b.addInstallArtifact(t, .{}).step);
347
506
  return self;
348
507
  }
349
508
  };
509
+
510
+ pub fn exports(b: *std.Build, bytes: []const u8) ![][]const u8 {
511
+ var symbols: ArrayList([]const u8) = .empty;
512
+
513
+ var it = std.mem.splitSequence(u8, bytes, "export ");
514
+ _ = it.next();
515
+ while (it.next()) |s| {
516
+ if (std.mem.startsWith(u8, s, "const ")) {
517
+ const i = std.mem.indexOf(u8, s[6..], " ").?;
518
+ try symbols.append(b.allocator, s[6 .. 6 + i]);
519
+ } else { // "fn "
520
+ const i = std.mem.indexOf(u8, s[3..], "(").?;
521
+ try symbols.append(b.allocator, s[3 .. 3 + i]);
522
+ }
523
+ }
524
+
525
+ return symbols.items;
526
+ }