@pkmn/engine 0.1.0-dev.63cef311 → 0.1.0-dev.683fba11

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