@pkmn/engine 0.1.0-dev.a0447192 → 0.1.0-dev.a19bc07d

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 +29 -18
  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 +55 -12
  26. package/build/tools/debug.js.map +1 -1
  27. package/build/tools/display/debug.jsx +19 -94
  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 +20 -9
  32. package/build/tools/display/ui.jsx.map +1 -1
  33. package/build/tools/display/util.js +140 -1
  34. package/build/tools/display/util.js.map +1 -1
  35. package/build.zig +351 -246
  36. package/package.json +34 -130
  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 -60
  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 +275 -284
  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 +159 -163
  51. package/src/lib/gen1/chance.zig +181 -105
  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 +34 -32
  57. package/src/lib/gen1/mechanics.zig +103 -78
  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 +0 -5
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(),
@@ -255,44 +209,59 @@ pub fn build(b: *std.Build) !void {
255
209
  b.fmt("{s}.ll", .{name}),
256
210
  ).step);
257
211
  }
258
- b.installArtifact(lib);
212
+ const install = b.addInstallArtifact(lib, .{});
213
+ b.getInstallStep().dependOn(&install.step);
214
+ maybeRanlib(b, lib, &install.step);
259
215
  c = true;
260
216
  }
261
217
 
262
218
  if (c) {
263
- const path =
264
- if (has_path) .{ .path = "src/include/pkmn.h" } else b.path("src/include/pkmn.h");
219
+ const path = b.path("src/include/pkmn.h");
265
220
  const header = b.addInstallFileWithDir(path, .header, "pkmn.h");
266
221
  b.getInstallStep().dependOn(&header.step);
267
222
 
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}
223
+ const content = try std.fmt.allocPrint(b.allocator,
224
+ \\prefix=${{pcfiledir}}/../..
280
225
  \\includedir=${{prefix}}/include
281
226
  \\libdir=${{prefix}}/lib
282
227
  \\
283
- \\Name: lib{2s}
284
- \\URL: https://github.com/{3s}
285
- \\Description: {4s}
286
- \\Version: {5s}
228
+ \\Name: lib{0s}
229
+ \\URL: https://github.com/{1s}
230
+ \\Description: {2s}
231
+ \\Version: {3s}
287
232
  \\Cflags: -I${{includedir}}
288
- \\Libs: -L${{libdir}} -l{2s}
289
- , .{ dirname, b.install_path, name, repository.next().?, description, version });
290
- defer pkgconfig_file.close();
233
+ \\Libs: -L${{libdir}} -l{0s}
234
+ , .{ name, repository.next().?, description, version });
291
235
 
292
- b.installFile(file, b.fmt("share/pkgconfig/{s}", .{pc}));
236
+ const pc = b.fmt("lib{s}.pc", .{name});
237
+ if (@hasDecl(std.Build, "FindProgramOptions")) {
238
+ const write_file = b.addWriteFiles();
239
+ const pkgconfig = write_file.add(pc, content);
240
+ b.getInstallStep().dependOn(&b.addInstallFileWithDir(
241
+ pkgconfig,
242
+ .prefix,
243
+ b.fmt("share/pkgconfig/{s}", .{pc}),
244
+ ).step);
245
+ } else {
246
+ const cwd = try std.process.currentPathAlloc(b.graph.io, b.allocator);
247
+ const file = try std.Io.Dir.path.relative(
248
+ b.allocator,
249
+ cwd,
250
+ &b.graph.environ_map,
251
+ cwd,
252
+ try b.cache_root.join(b.allocator, &.{pc}),
253
+ );
254
+ const pkgconfig = try std.Io.Dir.cwd().createFile(b.graph.io, file, .{});
255
+ defer pkgconfig.close(b.graph.io);
256
+
257
+ var writer = pkgconfig.writer(b.graph.io, &.{});
258
+ try writer.interface.writeAll(content);
259
+
260
+ b.installFile(file, b.fmt("share/pkgconfig/{s}", .{pc}));
261
+ }
293
262
  }
294
263
 
295
- const config = .{
264
+ const config: Config = .{
296
265
  .target = target,
297
266
  .optimize = optimize,
298
267
  .pic = pic,
@@ -303,7 +272,7 @@ pub fn build(b: *std.Build) !void {
303
272
  // TODO: tests can be run multiple times due to @imports
304
273
  const tests = TestStep.create(b, options, config);
305
274
 
306
- var exes = std.ArrayList(*Step.Compile).init(b.allocator);
275
+ var exes: ArrayList(*std.Build.Step.Compile) = .empty;
307
276
  const tools: ToolConfig = .{
308
277
  .options = .{
309
278
  .showdown = showdown,
@@ -311,7 +280,6 @@ pub fn build(b: *std.Build) !void {
311
280
  .chance = chance,
312
281
  .calc = calc,
313
282
  },
314
- .module = pkmn,
315
283
  .general = config,
316
284
  .tool = .{
317
285
  .tests = if (tests.build) tests else null,
@@ -343,21 +311,104 @@ pub fn build(b: *std.Build) !void {
343
311
  if (dump) |t| b.step("dump", "Run protocol dump tool").dependOn(&t.step);
344
312
  if (fuzz) |t| b.step("fuzz", "Run fuzz tester").dependOn(&t.step);
345
313
  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);
314
+ b.step("test", "Run all tests").dependOn(tests.step);
315
+ b.step("tools", "Install tools").dependOn(ToolsStep.create(b, &exes).step);
348
316
  if (transitions) |t| {
349
317
  b.step("transitions", "Visualize transitions algorithm search").dependOn(&t.step);
350
318
  }
351
319
  }
352
320
 
321
+ fn buildWasm(
322
+ b: *std.Build,
323
+ name: []const u8,
324
+ root_src_file: []const u8,
325
+ optimize: std.builtin.OptimizeMode,
326
+ strip: ?bool,
327
+ pic: ?bool,
328
+ wasm_stack_size: u64,
329
+ import: ?*std.Build.Module,
330
+ options: anytype,
331
+ ) !void {
332
+ const mode = switch (optimize) {
333
+ .ReleaseFast, .ReleaseSafe => .ReleaseSmall,
334
+ else => optimize,
335
+ };
336
+ // https://webassembly.org/features/
337
+ var features = std.Target.wasm.featureSet(&.{
338
+ .atomics,
339
+ .bulk_memory,
340
+ // .exception_handling,
341
+ .extended_const,
342
+ // .half_precision,
343
+ // .multimemory,
344
+ .mutable_globals,
345
+ .nontrapping_fptoint,
346
+ .reference_types,
347
+ // .relaxed_simd,
348
+ .sign_ext,
349
+ .simd128,
350
+ // .tail_call,
351
+ });
352
+ if (builtin.zig_version.order(try std.SemanticVersion.parse("0.12.0")) != .lt) {
353
+ features.addFeature(@intFromEnum(std.Target.wasm.Feature.multivalue));
354
+ }
355
+ const freestanding = b.resolveTargetQuery(.{
356
+ .cpu_arch = .wasm32,
357
+ .os_tag = .freestanding,
358
+ .cpu_features_add = features,
359
+ });
360
+ const path = b.path(root_src_file);
361
+ const exe = b.addExecutable(.{
362
+ .name = name,
363
+ .root_module = b.createModule(.{
364
+ .root_source_file = path,
365
+ .optimize = mode,
366
+ .target = freestanding,
367
+ .strip = strip,
368
+ .pic = pic,
369
+ }),
370
+ });
371
+
372
+ var file = try std.Io.Dir.cwd().openFile(b.graph.io, root_src_file, .{});
373
+ defer file.close(b.graph.io);
374
+ var reader = file.reader(b.graph.io, &.{});
375
+ const bytes = try reader.interface.allocRemaining(b.allocator, .unlimited);
376
+ exe.root_module.export_symbol_names = try exports(b, bytes);
377
+ exe.entry = .disabled;
378
+
379
+ if (import) |i| {
380
+ exe.root_module.addImport("pkmn", i);
381
+ }
382
+ exe.stack_size = wasm_stack_size;
383
+ exe.root_module.addOptions("build_options", options);
384
+
385
+ const opt = if (@hasDecl(std.Build, "FindProgramOptions")) blk: {
386
+ if (exists(b, "./node_modules/.bin/wasm-opt") catch false) {
387
+ break :blk "./node_modules/.bin/wasm-opt";
388
+ }
389
+ break :blk b.findProgram(.{ .names = &.{"wasm-opt"} });
390
+ } else b.findProgram(&.{"wasm-opt"}, &.{"./node_modules/.bin"}) catch null;
391
+ if (optimize != .Debug and opt != null) {
392
+ const out = b.fmt("build/lib/{s}.wasm", .{name});
393
+ const sh = b.addSystemCommand(&.{ opt.?, "--enable-bulk-memory", "--enable-simd", "-O4" });
394
+ sh.addArtifactArg(exe);
395
+ sh.addArg("-o");
396
+ sh.addFileArg(b.path(out));
397
+ b.getInstallStep().dependOn(&sh.step);
398
+ } else {
399
+ b.getInstallStep().dependOn(&b.addInstallArtifact(exe, .{
400
+ .dest_dir = .{ .override = std.Build.InstallDir{ .lib = {} } },
401
+ }).step);
402
+ }
403
+ }
404
+
353
405
  fn maybeStrip(
354
406
  b: *std.Build,
355
- artifact: *Step.Compile,
407
+ artifact: *std.Build.Step.Compile,
356
408
  step: *std.Build.Step,
357
409
  strip: ?bool,
358
410
  cmd: ?[]const u8,
359
411
  ) void {
360
- if (@hasDecl(@TypeOf(artifact.*), "strip")) artifact.strip = strip orelse false;
361
412
  if (!(strip orelse false) or cmd == null) return;
362
413
  // Using `strip -r -u` for dynamic libraries is supposed to work on macOS but doesn't...
363
414
  const mac = builtin.os.tag == .macos;
@@ -370,7 +421,7 @@ fn maybeStrip(
370
421
  }
371
422
 
372
423
  const Config = struct {
373
- target: ResolvedTarget,
424
+ target: std.Build.ResolvedTarget,
374
425
  optimize: std.builtin.OptimizeMode,
375
426
  pic: ?bool,
376
427
  strip: ?bool,
@@ -378,44 +429,48 @@ const Config = struct {
378
429
  };
379
430
 
380
431
  const TestStep = struct {
381
- step: std.Build.Step,
432
+ step: *std.Build.Step,
382
433
  build: bool,
383
434
 
384
- pub fn create(b: *std.Build, options: *Step.Options, config: Config) *TestStep {
435
+ pub fn create(b: *std.Build, options: *std.Build.Step.Options, config: Config) *TestStep {
385
436
  const coverage = b.option([]const u8, "test-coverage", "Generate test coverage");
386
437
  const test_filter =
387
438
  b.option([]const u8, "test-filter", "Skip tests that do not match filter");
388
439
 
389
440
  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
441
 
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,
442
+ const path = b.path("src/lib/test.zig");
443
+ const tests = b.addTest(.{
444
+ .root_module = b.createModule(.{
445
+ .root_source_file = path,
446
+ .optimize = config.optimize,
447
+ .target = config.target,
448
+ .single_threaded = true,
449
+ .strip = config.strip,
450
+ .pic = config.pic,
451
+ }),
452
+ .filters = if (test_filter) |filter| &.{filter} else &.{},
407
453
  });
408
- (if (root_module) tests.root_module else tests).addOptions("build_options", options);
454
+ tests.root_module.addOptions("build_options", options);
409
455
 
410
456
  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
457
  if (coverage) |c| {
416
458
  tests.setExecCmd(&.{ "kcov", "--include-pattern=src/lib", c, null });
417
459
  }
418
- self.step.dependOn(&b.addRunArtifact(tests).step);
460
+
461
+ if (@hasDecl(std.Build, "FindProgramOptions")) {
462
+ const run_step = b.addRunArtifact(tests);
463
+ self.* = .{ .step = &run_step.step, .build = test_filter == null };
464
+ } else {
465
+ const custom_step = b.allocator.create(std.Build.Step) catch @panic("OOM");
466
+ custom_step.* = std.Build.Step.init(.{
467
+ .id = .custom,
468
+ .name = "Run all tests",
469
+ .owner = b,
470
+ });
471
+ custom_step.dependOn(&b.addRunArtifact(tests).step);
472
+ self.* = .{ .step = custom_step, .build = test_filter == null };
473
+ }
419
474
 
420
475
  return self;
421
476
  }
@@ -423,74 +478,124 @@ const TestStep = struct {
423
478
 
424
479
  const ToolConfig = struct {
425
480
  options: Options,
426
- module: ?*std.Build.Module,
427
481
  general: Config,
428
482
  tool: struct {
429
483
  tests: ?*TestStep,
430
484
  name: ?[]const u8 = null,
431
- exes: *std.ArrayList(*Step.Compile),
485
+ exes: *ArrayList(*std.Build.Step.Compile),
432
486
  },
433
487
  };
434
488
 
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
- };
489
+ fn tool(b: *std.Build, path: []const u8, config: ToolConfig) !?*std.Build.Step.Run {
490
+ if (!try exists(b, path)) return null;
440
491
  var name = config.tool.name orelse std.fs.path.basename(path);
441
492
  const index = std.mem.lastIndexOfScalar(u8, name, '.');
442
493
  if (index) |i| name = name[0..i];
443
494
  if (config.options.showdown orelse false) name = b.fmt("{s}-showdown", .{name});
444
495
 
445
- const exe = b.addExecutable(if (force_pic) .{
496
+ const exe = b.addExecutable(.{
446
497
  .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 .{
451
- .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,
498
+ .root_module = b.createModule(.{
499
+ .root_source_file = b.path(path),
500
+ .target = config.general.target,
501
+ .optimize = config.general.optimize,
502
+ .strip = config.general.strip,
503
+ .pic = config.general.pic,
504
+ }),
458
505
  });
459
506
 
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));
507
+ const import = module(b, config.options, config.general.target, config.general.optimize);
508
+ exe.root_module.addImport("pkmn", import);
509
+ if (config.general.target.result.os.tag == .windows) {
510
+ exe.root_module.linkSystemLibrary("advapi32", .{});
465
511
  }
466
512
 
467
- if (force_pic) {
468
- exe.single_threaded = true;
469
- if (config.general.pic orelse false) exe.force_pic = config.general.pic;
470
- }
471
513
  if (config.tool.tests) |ts| ts.step.dependOn(&exe.step);
472
- config.tool.exes.append(exe) catch @panic("OOM");
514
+ config.tool.exes.append(b.allocator, exe) catch @panic("OOM");
473
515
 
474
516
  const run = b.addRunArtifact(exe);
475
517
  maybeStrip(b, exe, &run.step, config.general.strip, config.general.cmd);
476
- if (b.args) |args| run.addArgs(args);
518
+ if (@hasDecl(std.Build, "FindProgramOptions")) {
519
+ run.addPassthruArgs();
520
+ } else {
521
+ if (b.args) |args| run.addArgs(args);
522
+ }
477
523
 
478
524
  return run;
479
525
  }
480
526
 
527
+ fn exists(b: *std.Build, path: []const u8) !bool {
528
+ std.Io.Dir.cwd().access(b.graph.io, path, .{}) catch |err| switch (err) {
529
+ error.FileNotFound => return false,
530
+ else => |e| return e,
531
+ };
532
+ return true;
533
+ }
534
+
481
535
  const ToolsStep = struct {
482
- step: std.Build.Step,
536
+ step: *std.Build.Step,
483
537
 
484
- pub fn create(b: *std.Build, exes: *std.ArrayList(*Step.Compile)) *ToolsStep {
538
+ pub fn create(b: *std.Build, exes: *ArrayList(*std.Build.Step.Compile)) *ToolsStep {
485
539
  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 };
540
+
541
+ if (@hasDecl(std.Build, "FindProgramOptions")) {
542
+ const step = b.allocator.create(std.Build.Step.TopLevel) catch @panic("OOM");
543
+ step.* = .{
544
+ .step = std.Build.Step.init(.{
545
+ .tag = .top_level,
546
+ .name = "Install tools",
547
+ .owner = b,
548
+ }),
549
+ .description = "Install tools",
550
+ };
551
+ self.* = .{ .step = &step.step };
552
+ } else {
553
+ const step = b.allocator.create(std.Build.Step) catch @panic("OOM");
554
+ step.* = std.Build.Step.init(.{
555
+ .id = .custom,
556
+ .name = "Install tools",
557
+ .owner = b,
558
+ });
559
+ self.* = .{ .step = step };
560
+ }
488
561
  for (exes.items) |t| self.step.dependOn(&b.addInstallArtifact(t, .{}).step);
562
+
489
563
  return self;
490
564
  }
491
565
  };
492
566
 
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;
567
+ pub fn exports(b: *std.Build, bytes: []const u8) ![][]const u8 {
568
+ var symbols: ArrayList([]const u8) = .empty;
569
+
570
+ var it = std.mem.splitSequence(u8, bytes, "export ");
571
+ _ = it.next();
572
+ while (it.next()) |s| {
573
+ if (std.mem.startsWith(u8, s, "const ")) {
574
+ const i = std.mem.indexOf(u8, s[6..], " ").?;
575
+ try symbols.append(b.allocator, s[6 .. 6 + i]);
576
+ } else { // "fn "
577
+ const i = std.mem.indexOf(u8, s[3..], "(").?;
578
+ try symbols.append(b.allocator, s[3 .. 3 + i]);
579
+ }
580
+ }
581
+
582
+ return symbols.items;
583
+ }
584
+
585
+ fn maybeRanlib(
586
+ b: *std.Build,
587
+ artifact: *std.Build.Step.Compile,
588
+ install_step: *std.Build.Step,
589
+ ) void {
590
+ if (builtin.os.tag != .macos) return;
591
+ if (artifact.linkage != .static) return;
592
+
593
+ const ranlib = if (comptime @hasDecl(std.Build, "FindProgramOptions"))
594
+ b.findProgram(.{ .names = &.{"ranlib"} }) orelse return
595
+ else
596
+ b.findProgram(&[_][]const u8{"ranlib"}, &[_][]const u8{}) catch return;
597
+
598
+ const sh = b.addSystemCommand(&[_][]const u8{ranlib});
599
+ sh.addFileArg(artifact.getEmittedBin());
600
+ install_step.dependOn(&sh.step);
496
601
  }