@pkmn/engine 0.1.0-dev.02b7f810 → 0.1.0-dev.04a96f24

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 (83) hide show
  1. package/LICENSE +1 -3
  2. package/README.md +110 -72
  3. package/build/pkg/addon/browser.d.ts +3 -0
  4. package/build/pkg/addon/browser.js +44 -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 +97 -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 +21 -0
  11. package/build/pkg/addon/wasm.js.map +1 -0
  12. package/build/pkg/addon.d.ts +24 -2
  13. package/build/pkg/addon.js +38 -60
  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 +27 -5
  17. package/build/pkg/data/protocol.json +69 -12
  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 +5 -4
  21. package/build/pkg/gen1.js +49 -33
  22. package/build/pkg/gen1.js.map +1 -1
  23. package/build/pkg/index.d.ts +39 -22
  24. package/build/pkg/index.js +15 -10
  25. package/build/pkg/index.js.map +1 -1
  26. package/build/pkg/protocol.d.ts +24 -3
  27. package/build/pkg/protocol.js +127 -104
  28. package/build/pkg/protocol.js.map +1 -1
  29. package/build/tools/debug.js +36 -68
  30. package/build/tools/debug.js.map +1 -1
  31. package/build/tools/display/debug.jsx +141 -0
  32. package/build/tools/display/debug.jsx.map +1 -0
  33. package/build/tools/display/index.js +141 -0
  34. package/build/tools/display/index.js.map +1 -0
  35. package/build/tools/display/ui.jsx +349 -0
  36. package/build/tools/display/ui.jsx.map +1 -0
  37. package/build/tools/display/util.js +18 -0
  38. package/build/tools/display/util.js.map +1 -0
  39. package/build.zig +323 -152
  40. package/package.json +82 -32
  41. package/src/bin/install-pkmn-engine +40 -25
  42. package/src/bin/pkmn-debug +1 -1
  43. package/src/lib/common/array.zig +77 -0
  44. package/src/lib/common/battle.zig +17 -0
  45. package/src/lib/common/data.zig +19 -31
  46. package/src/lib/common/debug.zig +58 -17
  47. package/src/lib/common/js.zig +120 -0
  48. package/src/lib/common/optional.zig +71 -0
  49. package/src/lib/common/options.zig +16 -3
  50. package/src/lib/common/protocol.zig +947 -407
  51. package/src/lib/common/rational.zig +449 -0
  52. package/src/lib/common/rng.zig +31 -24
  53. package/src/lib/common/util.zig +61 -0
  54. package/src/lib/gen1/calc.zig +953 -0
  55. package/src/lib/gen1/chance.zig +1185 -0
  56. package/src/lib/gen1/data/moves.zig +203 -193
  57. package/src/lib/gen1/data/species.zig +6 -8
  58. package/src/lib/gen1/data/types.zig +11 -12
  59. package/src/lib/gen1/data.zig +100 -89
  60. package/src/lib/gen1/helpers.zig +139 -50
  61. package/src/lib/gen1/mechanics.zig +1284 -885
  62. package/src/lib/gen2/calc.zig +153 -0
  63. package/src/lib/gen2/chance.zig +902 -0
  64. package/src/lib/gen2/data/items.zig +15 -23
  65. package/src/lib/gen2/data/moves.zig +665 -573
  66. package/src/lib/gen2/data/species.zig +3 -5
  67. package/src/lib/gen2/data/types.zig +138 -36
  68. package/src/lib/gen2/data.zig +134 -99
  69. package/src/lib/gen2/generated.zig +801 -0
  70. package/src/lib/gen2/helpers.zig +59 -44
  71. package/src/lib/gen2/mechanics.zig +3571 -30
  72. package/src/lib/node.zig +129 -0
  73. package/src/lib/pkmn.zig +92 -12
  74. package/src/lib/wasm.zig +12 -0
  75. package/src/tools/display/dom.ts +96 -0
  76. package/src/tools/display/ui.css +354 -0
  77. package/build/test/display.js +0 -382
  78. package/build/test/display.js.map +0 -1
  79. package/src/lib/binding/node.zig +0 -229
  80. package/src/lib/binding/wasm.zig +0 -10
  81. package/src/lib/gen1/README.md +0 -791
  82. package/src/lib/gen2/README.md +0 -309
  83. package/src/test/display/pkmn.html.tmpl +0 -368
package/build.zig CHANGED
@@ -1,23 +1,45 @@
1
- const std = @import("std");
2
1
  const builtin = @import("builtin");
2
+ const std = @import("std");
3
3
 
4
- pub const Options = struct { showdown: ?bool = null, trace: ?bool = null };
4
+ pub const Options = struct {
5
+ showdown: ?bool = null,
6
+ log: ?bool = null,
7
+ chance: ?bool = null,
8
+ calc: ?bool = null,
9
+ };
10
+
11
+ const Step = if (@hasDecl(std.Build, "Step")) std.Build.Step else .{
12
+ .Compile = std.Build.CompileStep,
13
+ .Options = std.Build.OptionsStep,
14
+ .Run = std.Build.RunStep,
15
+ };
16
+ const has_path = @hasField(std.Build.LazyPath, "path");
17
+ const root_module = @hasField(Step.Compile, "root_module");
18
+ const force_pic = !@hasField(std.Build.SharedLibraryOptions, "pic");
19
+ const ResolvedTarget =
20
+ if (@hasDecl(std.Build, "ResolvedTarget")) std.Build.ResolvedTarget else std.zig.CrossTarget;
5
21
 
6
22
  pub fn module(b: *std.Build, options: Options) *std.Build.Module {
7
23
  const dirname = comptime std.fs.path.dirname(@src().file) orelse ".";
8
24
  const build_options = b.addOptions();
9
25
  build_options.addOption(?bool, "showdown", options.showdown);
10
- build_options.addOption(?bool, "trace", options.trace);
11
- return b.createModule(.{
12
- .source_file = .{ .path = dirname ++ "/src/lib/pkmn.zig" },
13
- .dependencies = &.{.{ .name = "build_options", .module = build_options.createModule() }},
14
- });
26
+ build_options.addOption(?bool, "log", options.log);
27
+ build_options.addOption(?bool, "chance", options.chance);
28
+ build_options.addOption(?bool, "calc", options.calc);
29
+
30
+ const root_source_file = .{ .cwd_relative = dirname ++ "/src/lib/pkmn.zig" };
31
+ const imports = &.{.{ .name = "build_options", .module = build_options.createModule() }};
32
+ return b.createModule(if (@hasDecl(std.Build, "CreateModuleOptions"))
33
+ .{ .source_file = root_source_file, .dependencies = imports }
34
+ else
35
+ .{ .root_source_file = root_source_file, .imports = imports });
15
36
  }
16
37
 
17
38
  pub fn build(b: *std.Build) !void {
18
39
  const target = b.standardTargetOptions(.{});
19
40
  const optimize = b.standardOptimizeOption(.{});
20
41
 
42
+ const default: ?bool = if (force_pic) false else null;
21
43
  const node_headers = b.option([]const u8, "node-headers", "Path to node-headers");
22
44
  const node_import_lib =
23
45
  b.option([]const u8, "node-import-library", "Path to node import library (Windows)");
@@ -25,129 +47,164 @@ pub fn build(b: *std.Build) !void {
25
47
  const wasm_stack_size =
26
48
  b.option(u64, "wasm-stack-size", "The size of WASM stack") orelse std.wasm.page_size;
27
49
  const dynamic = b.option(bool, "dynamic", "Build a dynamic library") orelse false;
28
- const strip = b.option(bool, "strip", "Strip debugging symbols from binary") orelse false;
29
- const pic = b.option(bool, "pic", "Force position independent code") orelse false;
50
+ const strip = b.option(bool, "strip", "Strip debugging symbols from binary") orelse default;
51
+ const pic = b.option(bool, "pic", "Force position independent code") orelse default;
52
+ const emit_asm = b.option(bool, "emit-asm", "Output .s (assembly code)") orelse false;
53
+ const emit_ll = b.option(bool, "emit-ll", "Output .ll (LLVM IR)") orelse false;
30
54
 
31
55
  const cmd = b.findProgram(&.{"strip"}, &.{}) catch null;
32
56
 
33
- var parser = std.json.Parser.init(b.allocator, false);
34
- defer parser.deinit();
35
- var tree = try parser.parse(@embedFile("package.json"));
36
- defer tree.deinit();
37
- const version = tree.root.Object.get("version").?.String;
38
- const description = tree.root.Object.get("description").?.String;
39
- var repository = std.mem.split(u8, tree.root.Object.get("repository").?.String, ":");
57
+ const json = @embedFile("package.json");
58
+ var parsed = try std.json.parseFromSlice(std.json.Value, b.allocator, json, .{});
59
+ defer parsed.deinit();
60
+ const version = parsed.value.object.get("version").?.string;
61
+ const description = parsed.value.object.get("description").?.string;
62
+ var repository = std.mem.splitSequence(u8, parsed.value.object.get("repository").?.string, ":");
40
63
  std.debug.assert(std.mem.eql(u8, repository.first(), "github"));
41
64
 
65
+ const fast = try std.SemanticVersion.parse("0.12.0-dev.866+3a47bc715");
66
+ if (optimize != .Debug and fast.order(builtin.zig_version) == .lt) {
67
+ std.log.warn("Release builds are ~10-20% slower than before Zig " ++
68
+ "v0.12.0-dev.866+3a47bc715 due to ziglang/zig#17768", .{});
69
+ }
70
+
42
71
  const showdown =
43
72
  b.option(bool, "showdown", "Enable Pokémon Showdown compatibility mode") orelse false;
44
- const trace = b.option(bool, "trace", "Enable trace logs") orelse false;
73
+ const log = b.option(bool, "log", "Enable protocol message logging") orelse false;
74
+ const chance = b.option(bool, "chance", "Enable update probability tracking") orelse false;
75
+ const calc = b.option(bool, "calc", "Enable damage calculator support") orelse false;
45
76
 
46
77
  const options = b.addOptions();
47
78
  options.addOption(?bool, "showdown", showdown);
48
- options.addOption(?bool, "trace", trace);
79
+ options.addOption(?bool, "log", log);
80
+ options.addOption(?bool, "chance", chance);
81
+ options.addOption(?bool, "calc", calc);
49
82
 
50
83
  const name = if (showdown) "pkmn-showdown" else "pkmn";
51
84
 
85
+ const pkmn = if (@hasDecl(std.Build, "CreateModuleOptions")) null else b.addModule("pkmn", .{
86
+ .root_source_file = if (has_path)
87
+ .{ .path = "src/lib/pkmn.zig" }
88
+ else
89
+ b.path("src/lib/pkmn.zig"),
90
+ .optimize = optimize,
91
+ .target = target,
92
+ .imports = &.{.{ .name = "build_options", .module = options.createModule() }},
93
+ });
94
+
52
95
  var c = false;
53
96
  if (node_headers) |headers| {
54
97
  const addon = b.fmt("{s}.node", .{name});
55
- const lib = b.addSharedLibrary(.{
98
+ const path = if (has_path) .{ .path = "src/lib/node.zig" } else b.path("src/lib/node.zig");
99
+ const lib = b.addSharedLibrary(if (force_pic) .{
100
+ .name = addon,
101
+ .root_source_file = path,
102
+ .optimize = optimize,
103
+ .target = target,
104
+ } else .{
56
105
  .name = addon,
57
- .root_source_file = .{ .path = "src/lib/binding/node.zig" },
106
+ .root_source_file = path,
58
107
  .optimize = optimize,
59
108
  .target = target,
109
+ .strip = strip,
110
+ .pic = pic,
60
111
  });
61
- lib.addOptions("build_options", options);
62
- lib.setMainPkgPath("./");
63
- lib.addSystemIncludePath(headers);
112
+ (if (root_module) lib.root_module else lib).addOptions("build_options", options);
113
+ lib.addSystemIncludePath(if (has_path) .{ .path = headers } else b.path(headers));
64
114
  lib.linkLibC();
65
115
  if (node_import_lib) |il| {
66
- lib.addObjectFile(il);
67
- } else if ((try std.zig.system.NativeTargetInfo.detect(target)).target.os.tag == .windows) {
116
+ lib.addObjectFile(if (has_path) .{ .path = il } else b.path(il));
117
+ } else if (detect(target).os.tag == .windows) {
68
118
  try std.io.getStdErr().writeAll("Must provide --node-import-library path on Windows\n");
69
119
  std.process.exit(1);
70
120
  }
71
121
  lib.linker_allow_shlib_undefined = true;
72
122
  maybeStrip(b, lib, b.getInstallStep(), strip, cmd);
73
- if (pic) lib.force_pic = pic;
123
+ if (force_pic and pic orelse false) lib.force_pic = pic;
74
124
  // Always emit to build/lib because this is where the driver code expects to find it
75
- // TODO(ziglang/zig#2231): using the following used to work (though was hacky):
125
+ // TODO: ziglang/zig#2231 - using the following used to work (though was hacky):
76
126
  //
77
127
  // lib.emit_bin = .{ .emit_to = b.fmt("build/lib/{s}", .{addon}) };
78
128
  // b.getInstallStep().dependOn(&lib.step);
79
129
  //
80
130
  // But ziglang/zig#14647 broke this so we now need to do an install() and then manually
81
131
  // rename the file ourself in install-pkmn-engine
82
- lib.install();
132
+ b.installArtifact(lib);
83
133
  } else if (wasm) {
84
- const lib = b.addSharedLibrary(.{
85
- .name = name,
86
- .root_source_file = .{ .path = "src/lib/binding/wasm.zig" },
87
- .optimize = switch (optimize) {
88
- .ReleaseFast, .ReleaseSafe => .ReleaseSmall,
89
- else => optimize,
90
- },
91
- .target = .{ .cpu_arch = .wasm32, .os_tag = .freestanding },
92
- });
93
- lib.addOptions("build_options", options);
94
- lib.setMainPkgPath("./");
95
- lib.stack_size = wasm_stack_size;
96
- lib.rdynamic = true;
97
- lib.strip = strip;
98
- if (pic) lib.force_pic = pic;
99
- const opt = b.findProgram(&.{"wasm-opt"}, &.{"./node_modules/.bin"}) catch null;
100
- if (optimize != .Debug and opt != null) {
101
- const out = b.fmt("build/lib/{s}.wasm", .{name});
102
- const sh = b.addSystemCommand(&.{ opt.?, "-O4" });
103
- sh.addArtifactArg(lib);
104
- sh.addArg("-o");
105
- sh.addFileSourceArg(.{ .path = out });
106
- b.getInstallStep().dependOn(&sh.step);
107
- }
108
- lib.install();
134
+ try buildWasm(b, name, "src/lib/wasm.zig", optimize, strip, pic, wasm_stack_size, options);
109
135
  } else if (dynamic) {
110
- const lib = b.addSharedLibrary(.{
136
+ const path = if (has_path) .{ .path = "src/lib/c.zig" } else b.path("src/lib/c.zig");
137
+ const lib = b.addSharedLibrary(if (force_pic) .{
138
+ .name = name,
139
+ .root_source_file = path,
140
+ .version = try std.SemanticVersion.parse(version),
141
+ .optimize = optimize,
142
+ .target = target,
143
+ } else .{
111
144
  .name = name,
112
- .root_source_file = .{ .path = "src/lib/binding/c.zig" },
113
- .version = try std.builtin.Version.parse(version),
145
+ .root_source_file = path,
146
+ .version = try std.SemanticVersion.parse(version),
114
147
  .optimize = optimize,
115
148
  .target = target,
149
+ .strip = strip,
150
+ .pic = pic,
116
151
  });
117
- lib.addOptions("build_options", options);
118
- lib.setMainPkgPath("./");
119
- lib.addIncludePath("src/include");
152
+ (if (root_module) lib.root_module else lib).addOptions("build_options", options);
153
+ lib.addIncludePath(if (has_path) .{ .path = "src/include" } else b.path("src/include"));
120
154
  maybeStrip(b, lib, b.getInstallStep(), strip, cmd);
121
- if (pic) lib.force_pic = pic;
122
- lib.install();
155
+ if (force_pic and pic orelse false) lib.force_pic = pic;
156
+ b.installArtifact(lib);
123
157
  c = true;
124
158
  } else {
125
- const lib = b.addStaticLibrary(.{
159
+ const path = if (has_path) .{ .path = "src/lib/c.zig" } else b.path("src/lib/c.zig");
160
+ const lib = b.addStaticLibrary(if (force_pic) .{
126
161
  .name = name,
127
- .root_source_file = .{ .path = "src/lib/binding/c.zig" },
162
+ .root_source_file = path,
128
163
  .optimize = optimize,
129
164
  .target = target,
165
+ } else .{
166
+ .name = name,
167
+ .root_source_file = path,
168
+ .optimize = optimize,
169
+ .target = target,
170
+ .strip = strip,
171
+ .pic = pic,
130
172
  });
131
- lib.addOptions("build_options", options);
132
- lib.setMainPkgPath("./");
133
- lib.addIncludePath("src/include");
173
+ (if (root_module) lib.root_module else lib).addOptions("build_options", options);
174
+ lib.addIncludePath(if (has_path) .{ .path = "src/include" } else b.path("src/include"));
134
175
  lib.bundle_compiler_rt = true;
135
176
  maybeStrip(b, lib, b.getInstallStep(), strip, cmd);
136
- if (pic) lib.force_pic = pic;
137
- lib.install();
177
+ if (force_pic and pic orelse false) lib.force_pic = pic;
178
+ if (emit_asm) {
179
+ b.getInstallStep().dependOn(&b.addInstallFileWithDir(
180
+ lib.getEmittedAsm(),
181
+ .prefix,
182
+ b.fmt("{s}.s", .{name}),
183
+ ).step);
184
+ }
185
+ if (emit_ll) {
186
+ b.getInstallStep().dependOn(&b.addInstallFileWithDir(
187
+ lib.getEmittedLlvmIr(),
188
+ .prefix,
189
+ b.fmt("{s}.ll", .{name}),
190
+ ).step);
191
+ }
192
+ b.installArtifact(lib);
138
193
  c = true;
139
194
  }
140
195
 
141
196
  if (c) {
142
- const header = b.addInstallFileWithDir(
143
- .{ .path = "src/include/pkmn.h" },
144
- .header,
145
- "pkmn.h",
146
- );
197
+ const path =
198
+ if (has_path) .{ .path = "src/include/pkmn.h" } else b.path("src/include/pkmn.h");
199
+ const header = b.addInstallFileWithDir(path, .header, "pkmn.h");
147
200
  b.getInstallStep().dependOn(&header.step);
148
201
 
149
202
  const pc = b.fmt("lib{s}.pc", .{name});
150
- const file = try b.cache_root.join(b.allocator, &.{pc});
203
+ const file = try std.fs.path.relative(
204
+ b.allocator,
205
+ try std.process.getCwdAlloc(b.allocator),
206
+ try b.cache_root.join(b.allocator, &.{pc}),
207
+ );
151
208
  const pkgconfig_file = try std.fs.cwd().createFile(file, .{});
152
209
 
153
210
  const dirname = comptime std.fs.path.dirname(@src().file) orelse ".";
@@ -176,14 +233,21 @@ pub fn build(b: *std.Build) !void {
176
233
  .strip = strip,
177
234
  .cmd = cmd,
178
235
  };
236
+
237
+ // TODO: tests can be run multiple times due to @imports
179
238
  const tests = TestStep.create(b, options, config);
180
239
 
181
- var exes = std.ArrayList(*std.Build.CompileStep).init(b.allocator);
240
+ var exes = std.ArrayList(*Step.Compile).init(b.allocator);
182
241
  const tools: ToolConfig = .{
242
+ .options = .{
243
+ .showdown = showdown,
244
+ .log = log,
245
+ .chance = chance,
246
+ .calc = calc,
247
+ },
248
+ .module = pkmn,
183
249
  .general = config,
184
250
  .tool = .{
185
- .showdown = showdown,
186
- .trace = trace,
187
251
  .tests = if (tests.build) tests else null,
188
252
  .exes = &exes,
189
253
  },
@@ -192,39 +256,115 @@ pub fn build(b: *std.Build) !void {
192
256
  var benchmark_config = tools;
193
257
  benchmark_config.general.optimize = .ReleaseFast;
194
258
  benchmark_config.general.strip = true;
195
- const benchmark = tool(b, "src/test/benchmark.zig", benchmark_config);
259
+ const benchmark = try tool(b, "src/test/benchmark.zig", benchmark_config);
196
260
 
197
261
  var fuzz_config = tools;
198
262
  fuzz_config.general.strip = false;
199
263
  fuzz_config.tool.name = "fuzz";
200
- const fuzz = tool(b, "src/test/benchmark.zig", fuzz_config);
201
-
202
- const serde = tool(b, "src/tools/serde.zig", tools);
203
- const protocol = tool(b, "src/tools/protocol.zig", tools);
204
-
205
- const lint_exe =
206
- b.addExecutable(.{ .name = "lint", .root_source_file = .{ .path = "src/tools/lint.zig" } });
207
- if (tests.build) tests.step.dependOn(&lint_exe.step);
208
- const lint = lint_exe.run();
209
-
210
- b.step("benchmark", "Run benchmark code").dependOn(&benchmark.step);
211
- b.step("fuzz", "Run fuzz tester").dependOn(&fuzz.step);
212
- b.step("lint", "Lint source files").dependOn(&lint.step);
213
- b.step("protocol", "Run protocol dump tool").dependOn(&protocol.step);
214
- b.step("serde", "Run serialization/deserialization tool").dependOn(&serde.step);
264
+ const fuzz = try tool(b, "src/test/fuzz.zig", fuzz_config);
265
+
266
+ const analyze = try tool(b, "src/tools/analyze.zig", tools);
267
+ const dump = try tool(b, "src/tools/dump.zig", tools);
268
+ const transitions = try tool(b, "src/tools/transitions.zig", tools);
269
+
270
+ // FIXME: serde randomly fails to build in some release configurations
271
+ var hack = tools;
272
+ if (optimize != .Debug) hack.tool.tests = null;
273
+ const serde = try tool(b, "src/tools/serde.zig", hack);
274
+
275
+ if (analyze) |t| b.step("analyze", "Run LLVM analysis tool").dependOn(&t.step);
276
+ if (benchmark) |t| b.step("benchmark", "Run benchmark code").dependOn(&t.step);
277
+ if (dump) |t| b.step("dump", "Run protocol dump tool").dependOn(&t.step);
278
+ if (fuzz) |t| b.step("fuzz", "Run fuzz tester").dependOn(&t.step);
279
+ if (serde) |t| b.step("serde", "Run serialization/deserialization tool").dependOn(&t.step);
215
280
  b.step("test", "Run all tests").dependOn(&tests.step);
216
281
  b.step("tools", "Install tools").dependOn(&ToolsStep.create(b, &exes).step);
282
+ if (transitions) |t| {
283
+ b.step("transitions", "Visualize transitions algorithm search").dependOn(&t.step);
284
+ }
285
+ }
286
+
287
+ fn buildWasm(
288
+ b: *std.Build,
289
+ name: []const u8,
290
+ root_src_file: []const u8,
291
+ optimize: std.builtin.OptimizeMode,
292
+ strip: ?bool,
293
+ pic: ?bool,
294
+ wasm_stack_size: u64,
295
+ options: anytype,
296
+ ) !void {
297
+ const entry = @hasDecl(Step.Compile, "Entry");
298
+ const mode = switch (optimize) {
299
+ .ReleaseFast, .ReleaseSafe => .ReleaseSmall,
300
+ else => optimize,
301
+ };
302
+ const freestanding = if (@hasDecl(std.Build, "resolveTargetQuery"))
303
+ b.resolveTargetQuery(.{ .cpu_arch = .wasm32, .os_tag = .freestanding })
304
+ else
305
+ ResolvedTarget{ .cpu_arch = .wasm32, .os_tag = .freestanding };
306
+ const path = if (has_path) .{ .path = root_src_file } else b.path(root_src_file);
307
+ const bin = if (entry) bin: {
308
+ const exe = b.addExecutable(if (force_pic) .{
309
+ .name = name,
310
+ .root_source_file = path,
311
+ .optimize = mode,
312
+ .target = freestanding,
313
+ } else .{
314
+ .name = name,
315
+ .root_source_file = path,
316
+ .optimize = mode,
317
+ .target = freestanding,
318
+ .strip = strip,
319
+ .pic = pic,
320
+ });
321
+ (if (root_module) exe.root_module else exe).export_symbol_names = try exports(b);
322
+ exe.entry = .disabled;
323
+ break :bin exe;
324
+ } else bin: {
325
+ const lib = b.addSharedLibrary(.{
326
+ .name = name,
327
+ .root_source_file = path,
328
+ .optimize = mode,
329
+ .target = freestanding,
330
+ });
331
+ lib.rdynamic = true;
332
+ break :bin lib;
333
+ };
334
+ bin.stack_size = wasm_stack_size;
335
+ if (@hasDecl(@TypeOf(bin.*), "strip")) bin.strip = strip orelse false;
336
+ if (force_pic and pic orelse false) bin.force_pic = pic;
337
+ (if (root_module) bin.root_module else bin).addOptions("build_options", options);
338
+
339
+ const opt = b.findProgram(&.{"wasm-opt"}, &.{"./node_modules/.bin"}) catch null;
340
+ if (optimize != .Debug and opt != null) {
341
+ const out = b.fmt("build/lib/{s}.wasm", .{name});
342
+ const sh = b.addSystemCommand(&.{ opt.?, "-O4" });
343
+ sh.addArtifactArg(bin);
344
+ sh.addArg("-o");
345
+ if (@hasDecl(@TypeOf(sh.*), "addFileSourceArg")) {
346
+ sh.addFileSourceArg(if (has_path) .{ .path = out } else b.path(out));
347
+ } else {
348
+ sh.addFileArg(if (has_path) .{ .path = out } else b.path(out));
349
+ }
350
+ b.getInstallStep().dependOn(&sh.step);
351
+ if (!entry) b.installArtifact(bin);
352
+ } else if (entry) {
353
+ b.getInstallStep().dependOn(&b.addInstallArtifact(bin, .{
354
+ .dest_dir = .{ .override = std.Build.InstallDir{ .lib = {} } },
355
+ }).step);
356
+ }
217
357
  }
218
358
 
219
359
  fn maybeStrip(
220
360
  b: *std.Build,
221
- artifact: *std.Build.CompileStep,
361
+ artifact: *Step.Compile,
222
362
  step: *std.Build.Step,
223
- strip: bool,
363
+ strip: ?bool,
224
364
  cmd: ?[]const u8,
225
365
  ) void {
226
- artifact.strip = strip;
227
- if (!strip or cmd == null) return;
366
+ if (@hasDecl(@TypeOf(artifact.*), "strip")) artifact.strip = strip orelse false;
367
+ if (!(strip orelse false) or cmd == null) return;
228
368
  // Using `strip -r -u` for dynamic libraries is supposed to work on macOS but doesn't...
229
369
  const mac = builtin.os.tag == .macos;
230
370
  if (mac and artifact.isDynamicLibrary()) return;
@@ -236,97 +376,108 @@ fn maybeStrip(
236
376
  }
237
377
 
238
378
  const Config = struct {
239
- target: std.zig.CrossTarget,
379
+ target: ResolvedTarget,
240
380
  optimize: std.builtin.OptimizeMode,
241
- pic: bool,
242
- strip: bool,
381
+ pic: ?bool,
382
+ strip: ?bool,
243
383
  cmd: ?[]const u8,
244
384
  };
245
385
 
246
- const TESTS = .{
247
- "src/lib/common/test.zig",
248
- "src/lib/gen1/test.zig",
249
- "src/lib/gen2/test.zig",
250
- };
251
-
252
386
  const TestStep = struct {
253
387
  step: std.Build.Step,
254
388
  build: bool,
255
389
 
256
- pub fn create(b: *std.Build, options: *std.Build.OptionsStep, config: Config) *TestStep {
390
+ pub fn create(b: *std.Build, options: *Step.Options, config: Config) *TestStep {
257
391
  const coverage = b.option([]const u8, "test-coverage", "Generate test coverage");
258
- const test_file = b.option([]const u8, "test-file", "Input file for test");
259
- const test_bin = b.option([]const u8, "test-bin", "Emit test binary to");
260
392
  const test_filter =
261
393
  b.option([]const u8, "test-filter", "Skip tests that do not match filter");
262
- const test_no_exec =
263
- b.option(bool, "test-no-exec", "Compiles test binary without running it") orelse false;
264
394
 
265
395
  const self = b.allocator.create(TestStep) catch @panic("OOM");
266
396
  const step = std.Build.Step.init(.{ .id = .custom, .name = "Run all tests", .owner = b });
267
- self.* = TestStep{ .step = step, .build = test_filter == null };
268
-
269
- const paths: []const []const u8 =
270
- if (test_file) |t| &.{t} else if (coverage != null) &.{"src/lib/test.zig"} else &TESTS;
271
- for (paths) |path| {
272
- const tests = b.addTest(.{
273
- .name = std.fs.path.basename(std.fs.path.dirname(path).?),
274
- .root_source_file = .{ .path = path },
275
- .optimize = config.optimize,
276
- .target = config.target,
277
- });
278
- tests.setMainPkgPath("./");
279
- tests.setFilter(test_filter);
280
- tests.addOptions("build_options", options);
397
+ self.* = .{ .step = step, .build = test_filter == null };
398
+
399
+ const path = if (has_path) .{ .path = "src/lib/test.zig" } else b.path("src/lib/test.zig");
400
+ const tests = b.addTest(if (force_pic) .{
401
+ .root_source_file = path,
402
+ .optimize = config.optimize,
403
+ .target = config.target,
404
+ .filter = test_filter,
405
+ } else .{
406
+ .root_source_file = path,
407
+ .optimize = config.optimize,
408
+ .target = config.target,
409
+ .filter = test_filter,
410
+ .single_threaded = true,
411
+ .strip = config.strip,
412
+ .pic = config.pic,
413
+ });
414
+ (if (root_module) tests.root_module else tests).addOptions("build_options", options);
415
+
416
+ maybeStrip(b, tests, &tests.step, config.strip, config.cmd);
417
+ if (force_pic) {
281
418
  tests.single_threaded = true;
282
- maybeStrip(b, tests, &tests.step, config.strip, config.cmd);
283
- if (config.pic) tests.force_pic = config.pic;
284
- if (test_bin) |bin| {
285
- tests.name = std.fs.path.basename(bin);
286
- if (std.fs.path.dirname(bin)) |dir| tests.setOutputDir(dir);
287
- }
288
- if (coverage) |c| {
289
- tests.setExecCmd(&.{ "kcov", "--include-pattern=src/lib", c, null });
290
- }
291
- self.step.dependOn(if (test_no_exec) &tests.step else &tests.run().step);
419
+ if (config.pic orelse false) tests.force_pic = config.pic;
292
420
  }
421
+ if (coverage) |c| {
422
+ tests.setExecCmd(&.{ "kcov", "--include-pattern=src/lib", c, null });
423
+ }
424
+ self.step.dependOn(&b.addRunArtifact(tests).step);
425
+
293
426
  return self;
294
427
  }
295
428
  };
296
429
 
297
430
  const ToolConfig = struct {
431
+ options: Options,
432
+ module: ?*std.Build.Module,
298
433
  general: Config,
299
434
  tool: struct {
300
- showdown: bool,
301
- trace: bool,
302
435
  tests: ?*TestStep,
303
436
  name: ?[]const u8 = null,
304
- exes: *std.ArrayList(*std.Build.CompileStep),
437
+ exes: *std.ArrayList(*Step.Compile),
305
438
  },
306
439
  };
307
440
 
308
- fn tool(b: *std.Build, path: []const u8, config: ToolConfig) *std.Build.RunStep {
441
+ fn tool(b: *std.Build, path: []const u8, config: ToolConfig) !?*Step.Run {
442
+ std.fs.cwd().access(path, .{}) catch |err| switch (err) {
443
+ error.FileNotFound => return null,
444
+ else => |e| return e,
445
+ };
309
446
  var name = config.tool.name orelse std.fs.path.basename(path);
310
447
  const index = std.mem.lastIndexOfScalar(u8, name, '.');
311
448
  if (index) |i| name = name[0..i];
312
- if (config.tool.showdown) name = b.fmt("{s}-showdown", .{name});
449
+ if (config.options.showdown orelse false) name = b.fmt("{s}-showdown", .{name});
313
450
 
314
- const exe = b.addExecutable(.{
451
+ const exe = b.addExecutable(if (force_pic) .{
452
+ .name = name,
453
+ .root_source_file = if (has_path) .{ .path = path } else b.path(path),
454
+ .target = config.general.target,
455
+ .optimize = config.general.optimize,
456
+ } else .{
315
457
  .name = name,
316
- .root_source_file = .{ .path = path },
458
+ .root_source_file = if (has_path) .{ .path = path } else b.path(path),
317
459
  .target = config.general.target,
318
460
  .optimize = config.general.optimize,
461
+ .single_threaded = true,
462
+ .strip = config.general.strip,
463
+ .pic = config.general.pic,
319
464
  });
320
- exe.addModule("pkmn", module(b, .{
321
- .showdown = config.tool.showdown,
322
- .trace = config.tool.trace,
323
- }));
324
- exe.single_threaded = true;
325
- if (config.general.pic) exe.force_pic = config.general.pic;
465
+
466
+ if (root_module) {
467
+ const import = if (config.module) |m| m else module(b, config.options);
468
+ exe.root_module.addImport("pkmn", import);
469
+ } else {
470
+ exe.addModule("pkmn", module(b, config.options));
471
+ }
472
+
473
+ if (force_pic) {
474
+ exe.single_threaded = true;
475
+ if (config.general.pic orelse false) exe.force_pic = config.general.pic;
476
+ }
326
477
  if (config.tool.tests) |ts| ts.step.dependOn(&exe.step);
327
478
  config.tool.exes.append(exe) catch @panic("OOM");
328
479
 
329
- const run = exe.run();
480
+ const run = b.addRunArtifact(exe);
330
481
  maybeStrip(b, exe, &run.step, config.general.strip, config.general.cmd);
331
482
  if (b.args) |args| run.addArgs(args);
332
483
 
@@ -336,11 +487,31 @@ fn tool(b: *std.Build, path: []const u8, config: ToolConfig) *std.Build.RunStep
336
487
  const ToolsStep = struct {
337
488
  step: std.Build.Step,
338
489
 
339
- pub fn create(b: *std.Build, exes: *std.ArrayList(*std.Build.CompileStep)) *ToolsStep {
490
+ pub fn create(b: *std.Build, exes: *std.ArrayList(*Step.Compile)) *ToolsStep {
340
491
  const self = b.allocator.create(ToolsStep) catch @panic("OOM");
341
492
  const step = std.Build.Step.init(.{ .id = .custom, .name = "Install tools", .owner = b });
342
- self.* = ToolsStep{ .step = step };
343
- for (exes.items) |t| self.step.dependOn(&b.addInstallArtifact(t).step);
493
+ self.* = .{ .step = step };
494
+ for (exes.items) |t| self.step.dependOn(&b.addInstallArtifact(t, .{}).step);
344
495
  return self;
345
496
  }
346
497
  };
498
+
499
+ fn detect(target: anytype) std.Target {
500
+ if (@hasField(@TypeOf(target), "result")) return target.result;
501
+ return (std.zig.system.NativeTargetInfo.detect(target) catch unreachable).target;
502
+ }
503
+
504
+ const WASM = @embedFile("src/lib/wasm.zig");
505
+
506
+ fn exports(b: *std.Build) ![][]const u8 {
507
+ var symbols = std.ArrayList([]const u8).init(b.allocator);
508
+
509
+ var it = std.mem.splitSequence(u8, WASM, "export const ");
510
+ _ = it.next();
511
+ while (it.next()) |s| {
512
+ const i = std.mem.indexOf(u8, s, " ").?;
513
+ try symbols.append(s[0..i]);
514
+ }
515
+
516
+ return symbols.items;
517
+ }