@pkmn/engine 0.1.0-dev.ce4c0b2a → 0.1.0-dev.d127cb34

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