summaryrefslogtreecommitdiff
path: root/build.zig
blob: 6a44d44c24307259dc4afa3d6a2d03f84ea1d94e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
const std = @import("std");
const builtin = @import("builtin");
const core = @import("build/core.zig");
const patches = @import("build/patches.zig");
const addons = @import("build/addons.zig");
const docs = @import("build/docs.zig");
const gui = @import("build/gui.zig");
const macos = @import("build/macos.zig");
const tools = @import("build/tools.zig");
const tests = @import("build/tests.zig");
const process_build = @import("build/process.zig");
/// The package manifest, imported untyped (build/core.zig has the reason).
const zon = @import("build.zig.zon");


pub const Platform = enum { tui, gui, macos };

pub const PerfBuild = struct {
    compiler: []const u8,
    target: []const u8,
    cpu: []const u8,
    driver_optimize: []const u8,
    core_optimize: []const u8,
    c_optimize: []const u8,
    terminal_optimize: []const u8,
    platform: []const u8,
    grammars: []const u8,
    mupdf: bool,
    jpx: bool,
    tracy: bool,
    terminal_simd: bool,
    prebuilt_shaders: bool,
};

pub const macos_min_version: std.SemanticVersion = .{ .major = 13, .minor = 0, .patch = 0 };

pub const TreeSitterGrammars = enum { disabled, zig, minimal, full };


pub fn build(b: *std.Build) void {
    // A package that depends on pardes takes its library; nothing of the
    // editor is configured for it.
    if (!b.isRoot()) return @import("build/library.zig").build(b);
    const requested_platform = b.option(Platform, "platform", "which shell to build (tui, gui, macos); absent builds the tui cli and the SDL gui together");
    const platform = requested_platform orelse .tui;
    const also_gui = requested_platform == null;
    // A bare `zig build` also copies the binaries into ~/.local/bin. Zig
    // 0.17 keeps the prefix in the maker process, out of this script's
    // reach, so `--prefix` no longer turns it off: -Dhome-install=false does.
    const home_enabled = b.option(bool, "home-install", "install binaries and addons into the user directories (default: true)") orelse true;
    const home_bin: ?[]const u8 = if (also_gui and home_enabled)
        if (b.graph.environ_map.get("HOME")) |home| b.pathJoin(&.{ home, ".local", "bin" }) else null
    else
        null;
    const home_addons: ?[]const u8 = if (!home_enabled) null else if (b.graph.environ_map.get("XDG_DATA_HOME")) |data|
        b.pathJoin(&.{ data, "pardes", "addons" })
    else if (b.graph.environ_map.get("HOME")) |home|
        b.pathJoin(&.{ home, ".local", "share", "pardes", "addons" })
    else
        null;
    const home_install = home_bin != null;
    const target = b.standardTargetOptions(.{
        .default_target = switch (platform) {
            .macos => if (builtin.os.tag.isDarwin()) .{
                .cpu_arch = builtin.target.cpu.arch,
                .os_tag = .macos,
                .os_version_min = .{ .semver = macos_min_version },
            } else .{},
            .tui, .gui => .{
                .cpu_arch = .x86_64,
                .os_tag = .linux,
                .abi = .gnu,
                .glibc_version = .{ .major = 2, .minor = 38, .patch = 0 },
            },
        },
    });
    const optimize = b.standardOptimizeOption(.{});
    // one substring, because that is what a dev loop needs: see the unit-test
    // step for why the whole-binary run is worth narrowing
    const test_filters: []const []const u8 = if (b.option([]const u8, "test-filter", "run only tests whose name contains this")) |f|
        &.{f}
    else
        &.{};
    const enable_jpx = b.option(bool, "jpx", "JPEG 2000 in PDFs, for scanned documents (default on; -Djpx=false drops openjpeg)") orelse true;
    const embed_sources = b.option(bool, "embed-sources", "serve the editor's own sources under /src of its 9P tree (default off)") orelse false;
    const test_build = b.step("test-build", "compile unit-test programs without running them");
    const doc_typ_opts = b.addOptions();
    doc_typ_opts.addOptionPathUntracked("dir", b.path("docs/typ"));
    // The words the shipped addons bring (PdfFit...), which the docs name too.
    doc_typ_opts.addOptionPathUntracked("addons", b.path("addons"));
    const doc_renders = docs.add(b);
    const test_nonce: ?*std.Build.Module = if (b.option(bool, "test-rebuild", "force fresh Zig test compilation while retaining cached C dependencies") orelse false) blk: {
        const files = b.addTempFiles();
        const source = files.add("test_nonce.zig", b.fmt("pub const nonce = {d};\n", .{std.Io.Clock.awake.now(b.graph.io).nanoseconds}));
        break :blk b.createModule(.{ .root_source_file = source, .target = target, .optimize = optimize });
    } else null;
    const unit_profile = b.addExecutable(.{
        .name = "pardes-unit-profile",
        .root_module = b.createModule(.{
            .target = target,
            .optimize = optimize,
            .root_source_file = b.path("test/unit_profile.zig"),
        }),
    });
    const c_optimize: std.lang.Optimize = if (optimize == .debug) .fast else optimize;
    const tree_sitter_grammars = b.option(TreeSitterGrammars, "tree-sitter", "tree-sitter grammar set: disabled, zig, minimal (c/c++/zig), full") orelse .full;
    const tracy = b.option([]const u8, "tracy", "enable Tracy profiling; supply the path to a Tracy source checkout");
    const macos_sdk = b.option([]const u8, "macos-sdk", "the macOS SDK a gui built for macOS from another system takes SDL's headers and frameworks from");
    const macos_identity = b.option([]const u8, "macos-identity", "codesigning identity for pardes.app (default: ad-hoc)") orelse "-";
    const prebuilt_shaders = b.option(bool, "prebuilt-shaders", "embed sketchbook's committed src/gpu/shaders/prebuilt/*.spv instead of running glslc over its GLSL (default: on for a bare `zig build`, off when -Dplatform names a shell)") orelse also_gui;

    const mupdf_check = b.step("mupdf-check", "the pdf addon's check: MuPDF compiles, links, renders and searches docs/design.pdf, and its script runs");
    const pdf_pointer_bench_step = b.step("pdf-pointer-bench", "time PDF hover and selection gestures and prove their pixels (-Doptimize=ReleaseFast -- [--label L] [--reps N] [--path FILE] [--cell WxH])");
    const pdf_scroll_bench_step = b.step("pdf-scroll-bench", "benchmark fast continuous-strip PDF scrolling in ReleaseFast (-Doptimize=ReleaseFast -- [--json] [--reps N] [--warmup N] [--path FILE])");

    // build-time IO: slurps the grammars' highlights.scm queries, and reads
    // vendor/themes to find the theme sources
    var threaded: std.Io.Threaded = .init(b.allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();

    const root_mod = b.createModule(.{
        .target = target,
        .optimize = optimize,
        // The macOS shell is a library whose host owns main(): it roots at
        // its own flat C ABI instead of src/main.zig.
        .root_source_file = b.path(switch (platform) {
            .macos => "src/macos.zig",
            .tui, .gui => "src/main.zig",
        }),
        .link_libc = true,
    });
    const core_module = b.createModule(.{
        .target = target,
        .optimize = optimize,
        .root_source_file = b.path("src/pardes.zig"),
        .link_libc = true,
    });
    // The core without the terminal module (docs/next-terminal.md, Phase 1):
    // what core-test is compiled from. No ghostty-vt, wuffs, zstbi or C++;
    // a shell boot is a scratch pane, a test that needs a terminal skips,
    // and shell-test runs them all with one.
    const core_lean = b.createModule(.{
        .target = target,
        .optimize = optimize,
        .root_source_file = b.path("src/pardes.zig"),
        .link_libc = true,
    });

    const isolated_mod: ?*std.Build.Module = if (platform == .tui) b.createModule(.{
        .target = target,
        .optimize = optimize,
        .root_source_file = b.path("src/main.zig"),
        .link_libc = true,
    }) else null;

    // `zig build static`'s: the addons compiled in (Addon.zig). Linked
    // statically on musl alone, as glibc links only dynamically; the gui's
    // is dynamic (SDL and the GPU need the display's libraries) with the
    // addons in it all the same.
    const static_linkage: ?std.builtin.LinkMode = if (target.result.isMuslLibC()) .static else null;
    const static_mod: ?*std.Build.Module = if ((platform == .tui and static_linkage != null) or platform == .gui) b.createModule(.{
        .target = target,
        .optimize = optimize,
        .root_source_file = b.path("src/main.zig"),
        .link_libc = true,
    }) else null;

    const gui_mod: ?*std.Build.Module = if (also_gui) b.createModule(.{
        .target = target,
        .optimize = optimize,
        .root_source_file = b.path("src/main.zig"),
        .link_libc = true,
    }) else null;

    const CoreMod = struct { mod: ?*std.Build.Module, shell: Platform };
    var core_mods_buf: [6]*std.Build.Module = undefined;
    var core_shells_buf: [6]Platform = undefined;
    var core_mods_len: usize = 0;
    for ([_]CoreMod{
        .{ .mod = root_mod, .shell = platform },
        // hxdiff's headless core and pardes-isolate are the primary shell's
        // configuration compiled two more ways, not two more frontends.
        .{ .mod = core_module, .shell = platform },
        .{ .mod = core_lean, .shell = platform },
        .{ .mod = isolated_mod, .shell = platform },
        .{ .mod = static_mod, .shell = platform },
        .{ .mod = gui_mod, .shell = .gui },
    }) |entry| if (entry.mod) |m| {
        core_mods_buf[core_mods_len] = m;
        core_shells_buf[core_mods_len] = entry.shell;
        core_mods_len += 1;
    };
    const core_mods = core_mods_buf[0..core_mods_len];
    // The manifest marks every dependency lazy but tree-sitter's runtime, so
    // that a package depending on pardes fetches what `library` takes and
    // nothing else. pardes takes these whatever it builds: the missing ones
    // are asked for here in one round, the grammars with them, where each
    // `b.dependency` below would end the configure to fetch its own alone.
    const ts = core.treeSitter(b, io, target, c_optimize, tree_sitter_grammars);
    inline for (.{ "cloud9", "vaxis", "ghostty", "uucode", "zstbi", "mvzr", "zstd", "xitdb" }) |name| {
        // A dependency by path (none of these today) has no hash and is always there.
        const dep = @field(zon.dependencies, name);
        if (@hasField(@TypeOf(dep), "hash")) if (!std.Build.package_map.get(dep.hash).?.available) {
            _ = b.lazyDependency(name, .{});
        };
    }
    const cloud9 = b.dependency("cloud9", .{ .target = target, .optimize = optimize }).module("cloud9");
    for (core_mods) |mod| mod.addImport("cloud9", cloud9);
    const core_shells = core_shells_buf[0..core_mods_len];
    // The modules the addons are compiled into (Addon.zig reads their
    // `pardes_addon`): the static step's, and every one for a system
    // Addon.zig's loader, over a Linux memfd, does not run on.
    const builtin_mods: []const *std.Build.Module = if (target.result.os.tag != .linux) core_mods else if (static_mod) |m| b.allocator.dupe(*std.Build.Module, &.{m}) catch @panic("OOM") else &.{};

    // The conditional dependencies, hoisted so one `wireCore` call at the end
    // can name them all. The unconditional ones are ordinary consts below.
    const ts_mod = ts.mod;
    const ts_queries_opts = ts.queries;
    var ghostty_core_vt: ?*std.Build.Module = null;
    const ts_libs = ts.libs;

    const themes_mod = core.generatedThemes(b, io, target, optimize);

    // forkpty: in libc proper on glibc>=2.34 and darwin; the BSDs keep it in libutil
    if (target.result.os.tag == .freebsd or target.result.os.tag == .netbsd or target.result.os.tag == .openbsd)
        root_mod.linkSystemLibrary("util", .{});

    // The macOS shell carries the workspace tag row's commands in its native
    // menu bar; the row itself goes away. `-Dworkspace-tag=true` puts it back.
    const workspace_tag = b.option(bool, "workspace-tag", "draw the workspace tag row (default: on except on macOS, whose menu bar carries its commands)");
    // The commit is a build input: every `jj new` or `jj commit` moves HEAD,
    // changes the options module and so recompiles every binary that imports
    // it, which is all of them (~0.6 GB of fresh test objects per move). Only
    // builds someone keeps are stamped: release builds and the bare
    // `zig build` that installs into ~/.local. Every other Debug build (any
    // -Dplatform or --prefix, so every test and snapshot run) prints
    // `pardes <version>` alone, like a tarball build; -Dstamp-commit=true
    // stamps one anyway.
    const stamp_commit = b.option(bool, "stamp-commit", "embed the git commit in --version and crash records (default: release builds and the ~/.local install)") orelse
        (optimize != .debug or home_install);
    const shell_cfg: core.ShellConfig = .{
        .tree_sitter_grammars = tree_sitter_grammars,
        .tracy = tracy != null,
        .workspace_tag = workspace_tag,
        .prebuilt_shaders = prebuilt_shaders,
        .embed_sources = embed_sources,
        .commit = if (stamp_commit) core.gitCommit(b) else null,
        .change = if (stamp_commit) core.jjChange(b) else null,
        .built = if (stamp_commit) core.command(b, &.{ "date", "-u", "+%Y-%m-%d %H:%M UTC" }) else null,
    };
    const opts = core.shellOptions(b, shell_cfg, platform);
    const gui_opts: ?*std.Build.Step.Options = if (also_gui) core.shellOptions(b, shell_cfg, .gui) else null;

    if (tracy) |tracy_path| {
        for ([_]*std.Build.Module{ root_mod, core_module }) |mod| {
            mod.addIncludePath(.{ .cwd_relative = tracy_path });
            mod.addCSourceFile(.{
                .file = .{ .cwd_relative = b.pathJoin(&.{ tracy_path, "public", "TracyClient.cpp" }) },
                .flags = &.{
                    "-DTRACY_ENABLE=1",
                    "-DTRACY_NO_SAMPLING",
                    "-DTRACY_NO_CALLSTACK",
                    "-DTRACY_NO_SYSTEM_TRACING",
                    "-DTRACY_NO_CRASH_HANDLER",
                    "-DTRACY_NO_CODE_TRANSFER",
                    "-fno-sanitize=undefined",
                },
            });
            mod.link_libcpp = true;
        }
    }

    const zstbi_dep = b.dependency("zstbi", .{ .target = target, .optimize = c_optimize });
    const zstbi_mod = zstbi_dep.module("root");
    // mvzr backtracks with no bound on its work (its own test "do not make
    // this test any longer": `a?` n times is 2^n steps), and pardes searches
    // with it holding the editor. Its matcher gets a step budget, patched into
    // the fetched source here at build time so that a fresh fetch keeps it:
    // each entry to matchPattern, which its backtracking recurses through,
    // spends a step, and with none left the match fails and says so
    // (src/regexp.zig). A bump that moves the anchor stops the build.
    const mvzr_mod = patches.mvzr(b, io, b.dependency("mvzr", .{ .target = target, .optimize = optimize }), target, optimize);

    // The C heap every C library with an allocator hook is handed: the core's
    // tree-sitter and fonts, and pdf.zig's MuPDF, which is a module of its own.
    const c_heap_mod = b.createModule(.{
        .target = target,
        .optimize = optimize,
        .root_source_file = b.path("src/c_heap.zig"),
    });

    // MuPDF, and the FreeType and zlib it is built against, are lazy: a
    // build asks for them only when it builds the pdf addon (or a window,
    // FreeType). Zig 0.17's configure is told the -D options and never the
    // steps asked for, so "the pdf step's" is an option, on once MuPDF is
    // fetched (and off Linux, where the addons are compiled in): a fresh
    // checkout's plain build fetches none of the three, and -Dpdf fetches
    // MuPDF once.
    const pdf = b.option(bool, "pdf", "build the pdf addon over MuPDF (default: on once MuPDF is fetched, as -Dpdf does)") orelse
        (std.Build.package_map.get(zon.dependencies.mupdf.hash).?.available or target.result.os.tag != .linux);
    const mupdf_dep = if (pdf) b.lazyDependency("mupdf", .{}) else null;
    // One FreeType in a binary: the gui's glyph atlas links it and MuPDF is
    // built against it (see build/mupdf.zig). At c_optimize with the rest of the
    // vendored C, since MuPDF rasterizes a PDF's text through it.
    const freetype_dep = if (pdf or also_gui or platform == .gui) b.lazyDependency("freetype", .{
        .target = target,
        .optimize = c_optimize,
        .@"enable-libpng" = false,
    }) else null;
    const freetype = if (freetype_dep) |d| d.artifact("freetype") else null;

    // The kinds' C ABI (src/kinds/pardes_addon.h), translated once: the core's
    // records are the header's, never a mirror of it.
    const kind_mod = b.addTranslateC(.{ .root_source_file = b.path("src/kinds/pardes_addon.h"), .target = target, .optimize = optimize }).createModule();
    // ...and what an addon in Zig imports over it (src/kinds/addon.zig).
    const addon_mod = b.createModule(.{ .root_source_file = b.path("src/kinds/addon.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "pardes_addon", .module = kind_mod }} });
    const snake_shader_lib = addons.gpu(b, target, optimize, addon_mod);
    const pdf_built = addons.pdf(b, .{
        .addon_mod = addon_mod,
        .builtin_mods = builtin_mods,
        .c_optimize = c_optimize,
        .core_module = core_module,
        .enable_jpx = enable_jpx,
        .freetype = freetype,
        .freetype_dep = freetype_dep,
        .io = io,
        .mupdf_check = mupdf_check,
        .mupdf_dep = mupdf_dep,
        .optimize = optimize,
        .pdf_pointer_bench_step = pdf_pointer_bench_step,
        .pdf_scroll_bench_step = pdf_scroll_bench_step,
        .target = target,
    });
    const pdf_addon = pdf_built.lib;
    const no_pdf = pdf_built.no_pdf;

    const uucode_mod = core.uucodeModule(b, target, optimize).?;

    const vaxis_dep = b.dependency("vaxis", .{
        .target = target,
        .optimize = optimize,
        .external_uucode = true,
    });
    const vaxis_mod = vaxis_dep.module("vaxis");
    patches.vaxis(b, io, vaxis_dep, vaxis_mod);

    var ghostty_vt_for_tests: ?*std.Build.Module = null;
    const ghostty_simd = !target.result.os.tag.isDarwin() or b.graph.host.result.os.tag.isDarwin();
    const ghostty_optimize: std.lang.Optimize = if (optimize == .debug) .safe else optimize;
    const ghostty_dep = b.lazyDependency("ghostty", .{ .target = target, .optimize = ghostty_optimize, .simd = ghostty_simd, .@"app-runtime" = .none, .@"emit-xcframework" = false });
    if (ghostty_dep) |dep| {
        const ghostty_vt = dep.module("ghostty-vt");
        ghostty_vt_for_tests = ghostty_vt;
        ghostty_vt.addImport("uucode", uucode_mod);
        patches.ghosttyKitty(b, io, dep, ghostty_vt);
        ghostty_core_vt = ghostty_vt;
    }
    // override uucode on vaxis LAST so it wins over ghostty's build() wiring.
    vaxis_mod.addImport("uucode", uucode_mod);

    // One PNG decoder (docs/shared-libs.md): ghostty's, wuffs, which
    // ghostty-vt links for kitty graphics whatever pardes does; a terminal's
    // PNG is decoded through it (TerminalImages.zig), and of zstbi only its
    // resize is left, for the PNG's downscale: stb_image and its writer
    // (with the deflate it carries) are patched out, here at build time so
    // a fresh fetch keeps it. The image addon has its own (addons/image).
    const wuffs_mod: ?*std.Build.Module = if (ghostty_core_vt) |vt| vt.import_table.get("wuffs") else null;
    patches.zstbi(b, io, zstbi_dep, zstbi_mod);

    // One zstd (docs/shared-libs.md): a far replica's stream, compressed by
    // its session and read by its client (src/replica.zig). The library's
    // compressor and decompressor alone, single-threaded and without its
    // x86 assembly, each context made with ZSTD_customMem over c_heap; of
    // its block compressors only those of levels 3 (dfast) and 6 (lazy),
    // the two replica.zig asks for, and its unused functions dropped at
    // link. Zig's std has a decompressor, but no compressor.
    {
        const dep = b.dependency("zstd", .{});
        const zstd = b.addLibrary(.{
            .name = "zstd",
            .root_module = b.createModule(.{ .target = target, .optimize = c_optimize, .link_libc = true }),
            .linkage = .static,
        });
        zstd.root_module.addCSourceFiles(.{
            .root = dep.path("lib"),
            .files = &.{
                "common/debug.c",                     "common/entropy_common.c",            "common/error_private.c",
                "common/fse_decompress.c",            "common/pool.c",                      "common/threading.c",
                "common/xxhash.c",                    "common/zstd_common.c",               "compress/fse_compress.c",
                "compress/hist.c",                    "compress/huf_compress.c",            "compress/zstd_compress.c",
                "compress/zstd_compress_literals.c",  "compress/zstd_compress_sequences.c", "compress/zstd_compress_superblock.c",
                "compress/zstd_double_fast.c",        "compress/zstd_fast.c",               "compress/zstd_lazy.c",
                "compress/zstd_ldm.c",                "compress/zstd_opt.c",                "compress/zstd_preSplit.c",
                "decompress/huf_decompress.c",        "decompress/zstd_ddict.c",            "decompress/zstd_decompress.c",
                "decompress/zstd_decompress_block.c",
            },
            .flags = &.{
                "-DXXH_NAMESPACE=ZSTD_",                   "-DZSTD_DISABLE_ASM",                     "-DZSTD_LEGACY_SUPPORT=0",
                "-DDEBUGLEVEL=0",                          "-DZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR", "-DZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR",
                "-DZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR", "-DZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR",  "-DZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR",
            },
        });
        zstd.link_function_sections = true;
        zstd.link_data_sections = true;
        for (core_mods) |m| m.linkLibrary(zstd);
    }

    // xitdb keeps what pardes writes to disk (src/Db.zig): pure Zig, no C
    // library and no allocator hook of its own (it takes Zig allocators).
    const xitdb_mod = b.dependency("xitdb", .{ .target = target, .optimize = optimize }).module("xitdb");

    const image_addon = addons.image(b, target, c_optimize, addon_mod, zstbi_dep);
    const image_mod = image_addon.root_module;
    for (builtin_mods) |m| m.addImport("image_addon", image_mod);
    // The records the core and the terminal both name (src/plain/plain.zig).
    const plain_mod = b.createModule(.{ .root_source_file = b.path("src/plain/plain.zig"), .target = target, .optimize = optimize });
    // The terminal, a module of its own (src/term/term.zig): the emulator and
    // what it brings are its, and every core but core-test's is given it.
    const term_mod = b.createModule(.{ .root_source_file = b.path("src/term/term.zig"), .target = target, .optimize = optimize, .link_libc = true });
    term_mod.addImport("plain", plain_mod);
    if (ghostty_core_vt) |x| term_mod.addImport("ghostty-vt", x);
    if (wuffs_mod) |x| term_mod.addImport("wuffs", x);
    term_mod.addImport("zstbi", zstbi_mod);
    const term_on = b.addOptions();
    term_on.addOption(bool, "terminal", true);
    const term_off = b.addOptions();
    term_off.addOption(bool, "terminal", false);
    for (core_mods) |m| if (m == core_lean) {
        m.addOptions("term_options", term_off);
    } else {
        m.addImport("term", term_mod);
        m.addOptions("term_options", term_on);
    };
    for (core_mods) |m| core.wireCore(m, .{
        .plain = plain_mod,
        .kind = kind_mod,
        .themes = themes_mod,
        .tree_sitter = ts_mod,
        .ts_libs = ts_libs.items,
        .ts_queries = ts_queries_opts,
        .mvzr = mvzr_mod,
        .c_heap = c_heap_mod,
        .vaxis = vaxis_mod,
        .uucode = uucode_mod,
        .xitdb = xitdb_mod,
    });

    const iso_off = b.addOptions();
    iso_off.addOption(bool, "isolated", false);
    const iso_on = b.addOptions();
    iso_on.addOption(bool, "isolated", true);
    const builtin_off = b.addOptions();
    builtin_off.addOption(bool, "on", false);
    const builtin_on = b.addOptions();
    builtin_on.addOption(bool, "on", true);
    // ...the pdf one only when it is built (-Dpdf=false leaves it out).
    builtin_on.addOption(bool, "pdf", pdf_addon != null);

    for (core_mods, core_shells) |mod, shell| {
        // config.zig's test checks the words and keys docs/typ names exist.
        mod.addOptions("doc_typ", doc_typ_opts);
        mod.addOptions("pardes_config", if (also_gui and shell == .gui) gui_opts.? else opts);
        mod.addOptions("pardes_isolation", if (isolated_mod == mod) iso_on else iso_off);
        mod.addOptions("builtin_addons", if (std.mem.indexOfScalar(*std.Build.Module, builtin_mods, mod) != null) builtin_on else builtin_off);
    }

    const builtins_json_step = docs.builtinsJson(b, requested_platform, platform, target, optimize, core_module, doc_renders);

    const gui_tests = gui.add(b, .{
        .freetype = freetype,
        .gui_mod = gui_mod,
        .macos_sdk = macos_sdk,
        .optimize = optimize,
        .platform = platform,
        .prebuilt_shaders = prebuilt_shaders,
        .root_mod = root_mod,
        .static_mod = static_mod,
        .target = target,
        .test_filters = test_filters,
    });
    const cells_test = gui_tests.cells_test;
    const atlas_test = gui_tests.atlas_test;

    if (platform == .macos) macos.add(b, .{
        .macos_identity = macos_identity,
        .optimize = optimize,
        .root_mod = root_mod,
        .target = target,
        .test_build = test_build,
        .test_filters = test_filters,
        .test_nonce = test_nonce,
        .unit_profile = unit_profile,
    }) else {
        var exe_name: []const u8 = if (platform == .gui) "pardes-gui" else "pardes";
        if (target.result.os.tag != .linux or target.result.cpu.arch != .x86_64)
            exe_name = b.fmt("{s}-{s}-{s}", .{ exe_name, @tagName(target.result.os.tag), @tagName(target.result.cpu.arch) });
        const exe = b.addExecutable(.{
            .name = exe_name,
            .root_module = root_mod,
        });
        installHome(b, exe, home_bin);
        if (requested_platform == .tui) docs.commandLine(b, exe, builtins_json_step, doc_renders);
        // The addons, a step each: the default install is the binaries
        // alone, and `zig build image pdf` (or `addons`) puts the libraries
        // where the start scan finds them, <prefix>/lib/pardes/addons (and
        // $XDG_DATA_HOME/pardes/addons unless -Dhome-install=false).
        const addons_step = b.step("addons", "install the image and pdf addons");
        for ([_]?*std.Build.Step.Compile{ image_addon, pdf_addon }, [_][]const u8{ "image", "pdf" }) |lib, name| {
            const step = b.step(name, b.fmt("install the {s} addon, <prefix>/lib/pardes/addons/{s}.so", .{ name, name }));
            addons_step.dependOn(step);
            const l = lib orelse {
                step.dependOn(no_pdf.?);
                continue;
            };
            step.dependOn(&b.addInstallFileWithDir(l.getEmittedBin(), .lib, b.fmt("pardes/addons/{s}.so", .{name})).step);
            if (home_addons) |dir| {
                const copy = b.addUpdateSourceFiles();
                copy.addCopyFileToSource(l.getEmittedBin(), b.pathJoin(&.{ dir, b.fmt("{s}.so", .{name}) }));
                step.dependOn(&copy.step);
            }
        }
        if (gui_mod) |gm| {
            var gui_name: []const u8 = "pardes-gui";
            if (target.result.os.tag != .linux or target.result.cpu.arch != .x86_64)
                gui_name = b.fmt("{s}-{s}-{s}", .{ gui_name, @tagName(target.result.os.tag), @tagName(target.result.cpu.arch) });
            const gui_exe = b.addExecutable(.{
                .name = gui_name,
                .root_module = gm,
            });
            installHome(b, gui_exe, home_bin);
        }
        // One static pardes, never the default: the terminal's, both
        // addons compiled in and registered at start as if loaded. It is
        // also how a build for macOS, whose loader has no memfd, could have
        // image and PDF panes.
        const static_step = b.step("static", "a pardes with the image and pdf addons in it: the terminal's static (-Dplatform=tui -Dtarget=x86_64-linux-musl), the gui's dynamic (-Dplatform=gui)");
        if (no_pdf) |s| static_step.dependOn(s) else if (static_mod) |m|
            static_step.dependOn(&b.addInstallArtifact(b.addExecutable(.{ .name = exe_name, .linkage = if (platform == .gui) null else static_linkage, .root_module = m }), .{}).step)
        else
            static_step.dependOn(&b.addFail("static is the terminal's on musl (-Dplatform=tui -Dtarget=x86_64-linux-musl) or the gui's (-Dplatform=gui)").step);
        const run = b.addRunArtifact(exe);
        b.step("run", "descend to the pardes").dependOn(&run.step);
        if (isolated_mod) |iso| {
            const iso_exe = b.addExecutable(.{
                .name = "pardes-isolate",
                .root_module = iso,
            });
            const run_iso = b.addRunArtifact(iso_exe);
            // Something to look at on arrival, read out of the binary itself.
            run_iso.addPassthruArgs();
            const iso_step = b.step("run-isolated", "descend to a pardes with no host but the terminal");
            iso_step.dependOn(&run_iso.step);
        }

        const addon_libs: []const *std.Build.Step.Compile = if (pdf_addon) |l| b.allocator.dupe(*std.Build.Step.Compile, &.{ image_addon, l }) catch @panic("OOM") else &.{image_addon};
        process_build.add(b, .{
            .exe = exe,
            .addons = addon_libs,
            .target = target,
            .optimize = optimize,
            .ghostty_vt = ghostty_vt_for_tests,
            .cloud9 = cloud9,
            .gui = platform == .gui,
        });

        const t = tools.add(b, .{
            .c_heap_mod = c_heap_mod,
            .c_optimize = c_optimize,
            .core_module = core_module,
            .enable_jpx = enable_jpx,
            .exe = exe,
            .ghostty_optimize = ghostty_optimize,
            .ghostty_simd = ghostty_simd,
            .ghostty_vt_for_tests = ghostty_vt_for_tests,
            .image_addon = image_addon,
            .mvzr_mod = mvzr_mod,
            .no_pdf = no_pdf,
            .optimize = optimize,
            .opts = opts,
            .pdf_addon = pdf_addon,
            .platform = platform,
            .prebuilt_shaders = prebuilt_shaders,
            .shell_cfg = shell_cfg,
            .target = target,
            .term_mod = term_mod,
            .test_filters = test_filters,
            .themes_mod = themes_mod,
            .tracy = tracy,
            .tree_sitter_grammars = tree_sitter_grammars,
            .ts_libs = ts_libs,
            .ts_mod = ts_mod,
            .ts_queries_opts = ts_queries_opts,
            .unit_profile = unit_profile,
            .uucode_mod = uucode_mod,
            .vaxis_mod = vaxis_mod,
        });
        const perf_gate_step = t.perf_gate_step;
        const perf_tests = t.perf_tests;
        const fs_bench_test = t.fs_bench_test;
        const lib_test_step = t.lib_test_step;

        tests.add(b, .{
            .addon_mod = addon_mod,
            .atlas_test = atlas_test,
            .cells_test = cells_test,
            .cloud9 = cloud9,
            .core_lean = core_lean,
            .core_module = core_module,
            .exe = exe,
            .fs_bench_test = fs_bench_test,
            .ghostty_vt_for_tests = ghostty_vt_for_tests,
            .image_addon = image_addon,
            .image_mod = image_mod,
            .lib_test_step = lib_test_step,
            .mupdf_check = mupdf_check,
            .optimize = optimize,
            .pdf_addon = pdf_addon,
            .perf_gate_step = perf_gate_step,
            .perf_tests = perf_tests,
            .plain_mod = plain_mod,
            .platform = platform,
            .root_mod = root_mod,
            .snake_shader_lib = snake_shader_lib,
            .target = target,
            .term_mod = term_mod,
            .test_build = test_build,
            .test_filters = test_filters,
            .test_nonce = test_nonce,
            .unit_profile = unit_profile,
        });
    }

    // The test-build programs installed rather than run, for a machine the
    // build cannot run them on (`-Dtarget=x86_64-freebsd.15.0`): each into
    // <prefix>/test, named for its root file.
    const test_install = b.step("test-install", "install the test-build programs into <prefix>/test, to run elsewhere");
    for (test_build.dependencies.items) |dep| {
        const t = dep.cast(std.Build.Step.Compile) orelse continue;
        const name = switch (t.root_module.root_source_file orelse continue) {
            .src_path => |p| std.fs.path.stem(p.sub_path),
            else => t.name,
        };
        test_install.dependOn(&b.addInstallArtifact(t, .{ .dest_dir = .{ .override = .{ .custom = "test" } }, .dest_sub_path = name }).step);
    }
}

/// Installs `artifact` in the prefix and, given `home_bin`, copies it there
/// too (`install` unlinks first, so a running binary is replaced).
fn installHome(b: *std.Build, artifact: *std.Build.Step.Compile, home_bin: ?[]const u8) void {
    b.installArtifact(artifact);
    const dir = home_bin orelse return;
    const copy = b.addSystemCommand(&.{ "install", "-Dm755" });
    copy.addArtifactArg(artifact);
    copy.addArg(b.pathJoin(&.{ dir, artifact.name }));
    copy.has_side_effects = true;
    b.getInstallStep().dependOn(&copy.step);
}