summaryrefslogtreecommitdiff
path: root/build/core.zig
blob: c787fdc8a78b6fa8cd1902e64bbf68981ac5d2b7 (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
659
const std = @import("std");
const Platform = @import("../build.zig").Platform;
const TreeSitterGrammars = @import("../build.zig").TreeSitterGrammars;
const grammar_manifest = @import("../core/grammar_manifest.zig");
const addons = @import("addons.zig");
const patches = @import("patches.zig");
/// The package manifest, imported UNTYPED on purpose — see the `version`
/// option in `buildInfo` for why that word is load-bearing.
const zon = @import("../build.zig.zon");
/// Releases are numbered 0.N; the zon holds "0.N.0" because it must be semver,
/// and what a user sees drops that ".0".
pub const display_version = if (std.mem.endsWith(u8, zon.version, ".0") and std.mem.count(u8, zon.version, ".") == 2)
    zon.version[0 .. zon.version.len - 2]
else
    zon.version;

/// Every dependency the manifest pins, by its content hash: a grammar,
/// ghostty or the Unicode tables steps a core differently, so they are part
/// of a replica's semantics hash (abi/wire.zig `semantics`).
const deps_text = blk: {
    var text: []const u8 = "";
    for (@typeInfo(@TypeOf(zon.dependencies)).@"struct".field_names) |name| {
        const dep = @field(zon.dependencies, name);
        text = text ++ name ++ " " ++ (if (@hasField(@TypeOf(dep), "hash")) dep.hash else "path") ++ "\n";
    }
    break :blk text;
};

/// A file read while configuring, under a package's root. A dependency's is
/// hash-addressed and never changes under the same pin; this repo's are not
/// tracked one by one, since the configure runs again on every build anyway
/// (build.zig poisons its cache).
// ponytail: untracked repo reads; b.dependOnFileContents each one if the configure cache ever stays pure.
pub fn configureRead(b: *std.Build, io: std.Io, root: std.Build.Cache.Path, sub: []const u8, limit: usize) ![]u8 {
    return root.root_dir.handle.readFileAlloc(io, b.pathJoin(&.{ root.subPathOrDot(), sub }), b.allocator, .limited(limit));
}

pub fn gitCommit(b: *std.Build) ?[]const u8 {
    return command(b, &.{ "git", "rev-parse", "--short=12", "HEAD" });
}

/// The jj change git HEAD is in, by its commit (jj 0.46 has no revset for
/// git's HEAD), or null without jj.
pub fn jjChange(b: *std.Build) ?[]const u8 {
    const head = command(b, &.{ "git", "rev-parse", "HEAD" }) orelse return null;
    return command(b, &.{ "jj", "log", "-r", head, "--no-graph", "-T", "change_id.short()" });
}

/// One line a command prints, or null: HEAD, the change, the clock are not
/// files the configure cache can track, so the cache is poisoned.
pub fn command(b: *std.Build, argv: []const []const u8) ?[]const u8 {
    b.graph.poisonCache();
    const out = switch (b.runFallible(argv, .{ .stderr_behavior = .ignore })) {
        .success => |stdout| stdout,
        else => return null,
    };
    const trimmed = std.mem.trim(u8, out, " \t\r\n");
    return if (trimmed.len == 0) null else trimmed;
}

pub const ShellConfig = struct {
    tree_sitter_grammars: TreeSitterGrammars,
    /// -Dtracy's checkout, whose client a core that asks compiles in.
    tracy: ?[]const u8 = null,
    /// null = "the platform's own default": the macOS shell hands the row to
    /// its native menu bar, every other shell keeps the acme topbar.
    workspace_tag: ?bool = null,
    embed_sources: bool = false,
    commit: ?[]const u8 = null,
    /// The jj change git HEAD is in, and when this configure ran: the
    /// `Build` word's, stamped with the commit (see `stamp_commit`).
    change: ?[]const u8 = null,
    built: ?[]const u8 = null,
    /// The library's editor (core/lib_editor.zig): a text with no pane, so
    /// the core is not compiled (core/Editor.zig).
    lib: bool = false,
};

/// `pardes_options`: what a module set varies at compile time, one module
/// a configuration, which `module` makes and the set's modules share.
pub fn options(b: *std.Build, cfg: ShellConfig, c: Core, pdf: bool) *std.Build.Step.Options {
    const o = b.addOptions();
    o.addOption(Platform, "platform", c.platform);
    o.addOption(TreeSitterGrammars, "grammars", cfg.tree_sitter_grammars);
    o.addOption(bool, "terminal", c.terminal);
    o.addOption(bool, "builtin_addons", c.builtin_addons);
    // ...the pdf one only when it is built (-Dpdf=false leaves it out).
    o.addOption(bool, "builtin_pdf", c.builtin_addons and pdf);
    o.addOption(bool, "enable_tracy", cfg.tracy != null);
    o.addOption(bool, "workspace_tag", cfg.workspace_tag orelse (c.platform != .macos));
    o.addOption(bool, "embed_sources", cfg.embed_sources);
    o.addOption(bool, "lib", cfg.lib);
    return o;
}

/// `build_info`: the version, and the commit, change and time a stamped
/// build was made from (see `stamp_commit`, read at configure time), every
/// dependency's hash, and what pardes changes in them (`patchesHash`).
pub fn buildInfo(b: *std.Build, io: std.Io, cfg: ShellConfig) *std.Build.Step.Options {
    const o = b.addOptions();
    o.addOption([]const u8, "version", display_version);
    o.addOption(?[]const u8, "commit", cfg.commit);
    o.addOption(?[]const u8, "change", cfg.change);
    o.addOption(?[]const u8, "built", cfg.built);
    o.addOption([]const u8, "deps", deps_text);
    o.addOption(u64, "patches", patchesHash(b, io));
    return o;
}

/// The text of every edit pardes makes to a fetched dependency
/// (build/patches.zig's tables and the files they append, build/patches/)
/// and of the Unicode tables' configuration (uucode_config.zig), hashed: a
/// dependency's pin is in `deps`, but what pardes changes in it is this
/// tree's, which an unstamped build has no commit to stand for, and it
/// changes how a core steps (ghostty's page size: how many rows its
/// history drops at once; a kitty medium's read; a regex's budget), so it
/// is a replica's semantics too (abi/wire.zig `semantics`).
fn patchesHash(b: *std.Build, io: std.Io) u64 {
    var h: u64 = 0;
    for ([_][]const u8{ "build/patches.zig", "uucode_config.zig" }) |sub|
        h ^= std.hash.Wyhash.hash(0, configureRead(b, io, b.root, sub, 1 << 20) catch @panic(sub));
    var dir = b.root.root_dir.handle.openDir(io, "build/patches", .{ .iterate = true }) catch @panic("open build/patches");
    defer dir.close(io);
    var it = dir.iterate();
    // Each file by its name and text, in whatever order the directory
    // lists them: an xor of each one's hash.
    while (it.next(io) catch @panic("read build/patches")) |e| {
        const sub = b.pathJoin(&.{ "build/patches", e.name });
        h ^= std.hash.Wyhash.hash(std.hash.Wyhash.hash(0, e.name), configureRead(b, io, b.root, sub, 1 << 20) catch @panic(sub));
    }
    return h;
}

/// The theme sources in `sub` of vendor/themes, sorted: the ring's (`.`),
/// or the retired ones kept themes inherit from (`base`, read, never rung).
fn vendoredThemes(b: *std.Build, io: std.Io, sub: []const u8) []const []const u8 {
    var names: std.ArrayList([]const u8) = .empty;
    var dir = b.root.root_dir.handle.openDir(io, b.pathJoin(&.{ "vendor/themes", sub }), .{ .iterate = true }) catch @panic("open vendor/themes");
    defer dir.close(io);
    var it = dir.iterate();
    while (it.next(io) catch @panic("read vendor/themes")) |e| {
        if (!std.mem.endsWith(u8, e.name, ".toml") and !std.mem.endsWith(u8, e.name, ".json")) continue;
        names.append(b.allocator, b.graph.dupeString(e.name)) catch @panic("OOM");
    }
    std.mem.sort([]const u8, names.items, {}, struct {
        fn lt(_: void, a: []const u8, c: []const u8) bool {
            return std.mem.order(u8, a, c) == .lt;
        }
    }.lt);
    return names.items;
}

/// The vendored palettes as the `generated_themes` module colors.zig folds
/// into its ring, written by tools/gen_themes.zig.
pub fn generatedThemes(b: *std.Build, io: std.Io, target: std.Build.ResolvedTarget, optimize: std.lang.Optimize) *std.Build.Module {
    const theme_gen = b.addExecutable(.{
        .name = "pardes-gen-themes",
        .root_module = b.createModule(.{
            .target = b.graph.host,
            .optimize = .debug,
            .root_source_file = b.path("tools/gen_themes.zig"),
        }),
    });
    const run_theme_gen = b.addRunArtifact(theme_gen);
    const themes_out = run_theme_gen.addOutputDirectoryArg("themes");
    for (vendoredThemes(b, io, ".")) |name| run_theme_gen.addFileArg(b.path(b.fmt("vendor/themes/{s}", .{name})));
    for (vendoredThemes(b, io, "base")) |name| run_theme_gen.addPrefixedFileArg("base=", b.path(b.fmt("vendor/themes/base/{s}", .{name})));
    return b.createModule(.{
        .target = target,
        .optimize = optimize,
        .root_source_file = themes_out.path(b, "list.zig"),
    });
}

/// The grammars a build compiles in, a flag each in the manifest's order.
pub const GrammarSet = [grammar_manifest.all.len]bool;

/// A tier's (`-Dgrammars`, a dependent package's `.grammars`).
pub fn tierSet(tier: TreeSitterGrammars) GrammarSet {
    var set: GrammarSet = undefined;
    for (grammar_manifest.all, &set) |g, *in| in.* = tier == .full or (tier == .minimal and g.tier == .minimal);
    return set;
}

pub const TreeSitter = struct {
    mod: *std.Build.Module,
    queries: *std.Build.Step.Options,
    libs: std.ArrayList(*std.Build.Step.Compile),

    /// tree-sitter, the grammars' parsers and their queries, into `m`.
    pub fn wire(ts: TreeSitter, m: *std.Build.Module) void {
        m.addImport("tree-sitter", ts.mod);
        for (ts.libs.items) |lib| m.linkLibrary(lib);
        m.addOptions("ts_queries", ts.queries);
    }
};

/// tree-sitter's bindings, and for each grammar of the set its queries (the
/// `ts_queries` options syntax.zig reads, and by which it knows the set)
/// and its parser, a static library. A grammar not fetched yet is asked for
/// and left out: the configure runs again once it is there.
pub fn treeSitter(b: *std.Build, io: std.Io, target: std.Build.ResolvedTarget, c_optimize: std.lang.Optimize, set: GrammarSet) TreeSitter {
    const tree_sitter_mod = b.dependency("tree_sitter", .{ .target = target, .optimize = c_optimize }).module("tree_sitter");
    var ts_libs: std.ArrayList(*std.Build.Step.Compile) = .empty;
    const ts_queries = b.addOptions();
    inline for (grammar_manifest.all, set) |g, in| {
        if (in) grammar: {
            const dep = b.dependencyLazy(g.dep, .{}) catch break :grammar;
            const upstream = configureRead(b, io, dep.builder.root, g.query, 0x100000) catch @panic("read " ++ g.name ++ " highlights");
            // the patterns that colour, filtered here once and not in
            // every compile, and the whole query, the filter's test's
            const query = std.mem.concat(b.allocator, u8, &.{ upstream, g.highlights_extra }) catch @panic("OOM");
            ts_queries.addOption([]const u8, g.name ++ "_highlights_unfiltered", query);
            ts_queries.addOption([]const u8, g.name ++ "_highlights", grammar_manifest.colorQuery(query, b.allocator.alloc(u8, query.len) catch @panic("OOM")));
            // helix's textobject queries, vendored (vendor/queries); a
            // grammar without one gets none
            const objects = configureRead(b, io, b.root, "vendor/queries/" ++ g.name ++ "/textobjects.scm", 0x100000) catch "";
            ts_queries.addOption([]const u8, g.name ++ "_textobjects", objects);
            // and their indent queries, beside them
            const indents = configureRead(b, io, b.root, "vendor/queries/" ++ g.name ++ "/indents.scm", 0x100000) catch "";
            ts_queries.addOption([]const u8, g.name ++ "_indents", indents);

            const lib = b.addLibrary(.{
                .name = "tree-sitter-" ++ g.name,
                .root_module = b.createModule(.{ .target = target, .optimize = c_optimize, .link_libc = true }),
                .linkage = .static,
            });
            // Every allocation a grammar's external scanner makes goes to the
            // runtime's allocator, which syntax.zig points at a Zig one:
            // TREE_SITTER_REUSE_ALLOCATOR for the scanners that use
            // ts_malloc, and core/tree_sitter_heap.h for the ones that call
            // malloc themselves.
            const ts_cflags = [_][]const u8{
                "-fno-sanitize=function",
                "-DTREE_SITTER_REUSE_ALLOCATOR",
                // From the compiler's working directory, the root
                // package's: pardes's own, or the one that depends on it.
                "-include",
                b.root.joinString(b.allocator, "core/tree_sitter_heap.h") catch @panic("OOM"),
            };
            lib.root_module.addCSourceFile(.{ .file = dep.path(g.src ++ "/parser.c"), .flags = &ts_cflags });
            if (g.scanner) lib.root_module.addCSourceFile(.{ .file = dep.path(g.src ++ "/scanner.c"), .flags = &ts_cflags });
            lib.root_module.addIncludePath(dep.path(g.src));
            ts_libs.append(b.allocator, lib) catch @panic("OOM");
        }
    }
    return .{ .mod = tree_sitter_mod, .queries = ts_queries, .libs = ts_libs };
}

/// uucode with pardes's configuration (uucode_config.zig), which ghostty
/// and vaxis share; null while it is still to be fetched.
pub fn uucodeModule(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) ?*std.Build.Module {
    const uucode_config = b.path("uucode_config.zig");
    const uucode_tables = (b.dependencyLazy("uucode", .{
        .target = target,
        .optimize = optimize,
        .build_config_path = uucode_config,
    }) catch return null).namedLazyPath("tables.zig");
    return (b.dependencyLazy("uucode", .{
        .target = target,
        .optimize = optimize,
        .build_config_path = uucode_config,
        .tables_path = uucode_tables,
    }) catch return null).module("uucode");
}

/// The editor as a library (core/lib_editor.zig, docs/next-editor.md): the
/// text pane's own code built with `lib`, so no pane and no core, over
/// tree-sitter, uucode and mvzr, with pardes-syntax in it as `.syntax`.
/// `library` exports it to a package that asks; hxdiff runs its cases on it.
pub fn editorModule(b: *std.Build, name: ?[]const u8, target: std.Build.ResolvedTarget, optimize: std.lang.Optimize, cfg: ShellConfig, d: struct {
    themes: *std.Build.Module,
    ts: TreeSitter,
    uucode: *std.Build.Module,
    mvzr: *std.Build.Module,
    /// vaxis's, or a module of its grapheme width alone (`library`): a
    /// cell's width for j and k's goal column.
    vaxis: *std.Build.Module,
}) *std.Build.Module {
    const create: std.Build.Module.CreateOptions = .{
        .target = target,
        .optimize = optimize,
        .root_source_file = b.path("core/lib_editor.zig"),
        .link_libc = true,
    };
    const m = if (name) |n| b.addModule(n, create) else b.createModule(create);
    var lib_cfg = cfg;
    lib_cfg.lib = true;
    m.addOptions("pardes_options", options(b, lib_cfg, .{ .root = "core/lib_editor.zig", .platform = .tui, .terminal = false }, false));
    m.addImport("plain", b.createModule(.{ .target = target, .optimize = optimize, .root_source_file = b.path("abi/plain.zig") }));
    m.addImport("generated_themes", d.themes);
    d.ts.wire(m);
    m.addImport("mvzr", d.mvzr);
    m.addImport("c_heap", b.createModule(.{ .target = target, .optimize = optimize, .root_source_file = b.path("core/c_heap.zig") }));
    m.addImport("vaxis", d.vaxis);
    m.addImport("uucode", d.uucode);
    return m;
}

/// What every core module is made of: build.zig makes each once.
pub const Parts = struct {
    target: std.Build.ResolvedTarget,
    optimize: std.lang.Optimize,
    cloud9: *std.Build.Module,
    /// The build's options (-Dtracy's checkout, -Dembed-sources...).
    cfg: ShellConfig,
    /// `build_info`, the same for every set.
    info: *std.Build.Step.Options,
    zstd: *std.Build.Step.Compile,
    /// The addons, for a core that has them compiled in (Addon.zig); the
    /// pdf one only when it is built (-Dpdf=false leaves it out).
    image: *std.Build.Module,
    pdf: ?*std.Build.Module,
    term: *std.Build.Module,
    plain: *std.Build.Module,
    /// The kinds' C ABI (abi/pardes_addon.h), translated, and what an addon
    /// in Zig imports over it (abi/addon.zig: the core's `cSlice` too).
    kind: *std.Build.Module,
    addon: *std.Build.Module,
    themes: *std.Build.Module,
    ts: TreeSitter,
    mvzr: *std.Build.Module,
    c_heap: *std.Build.Module,
    vaxis: *std.Build.Module,
    uucode: *std.Build.Module,
    xitdb: *std.Build.Module,
    doc_typ: *std.Build.Step.Options,
};

/// Which core: its root and the few ways the products differ.
pub const Core = struct {
    /// runtime/main.zig for a shell (runtime/macos.zig for the macOS
    /// library), core/root.zig for the core, runtime/root.zig for the
    /// runtime, or a core file whose tests run on the core's imports.
    root: []const u8,
    /// This build's, or the window's in the bare build.
    platform: Platform,
    /// The terminal module; without it (core-test) a shell boot is a scratch pane.
    terminal: bool = true,
    /// The addons compiled in and registered at start (Addon.zig): the
    /// static step's, and every core off Linux, whose loader has no memfd.
    builtin_addons: bool = false,
    /// Tracy's client with -Dtracy: the shell's and the core's.
    tracy: bool = false,
    /// libutil, for forkpty on the BSDs: the shell's.
    util: bool = false,
};

/// What `module` makes: the core, the devices, the runtime and the replica
/// stream's wire (abi/wire.zig), each naming the others (`core`, `dev`,
/// `runtime`, `wire`), and the module a compile roots at.
pub const Modules = struct {
    /// A product's own file (runtime/main.zig, runtime/macos.zig) naming
    /// both, the runtime, or the core.
    root: *std.Build.Module,
    core: *std.Build.Module,
    dev: *std.Build.Module,
    runtime: *std.Build.Module,
    wire: *std.Build.Module,
};

/// A core and the devices and runtime beside it, everything they import
/// and link named here and nowhere else.
pub fn module(b: *std.Build, p: Parts, c: Core) Modules {
    const in_runtime = std.mem.startsWith(u8, c.root, "runtime/");
    const m = b.createModule(.{ .target = p.target, .optimize = p.optimize, .root_source_file = b.path(if (in_runtime) "core/root.zig" else c.root), .link_libc = true });
    // forkpty: in libc proper on glibc>=2.34 and darwin; the BSDs keep it in libutil
    if (c.util and (p.target.result.os.tag == .freebsd or p.target.result.os.tag == .netbsd or p.target.result.os.tag == .openbsd))
        m.linkSystemLibrary("util", .{});
    if (c.tracy) if (p.cfg.tracy) |tracy_path| {
        m.addIncludePath(.{ .cwd_relative = tracy_path });
        m.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",
            },
        });
        m.link_libcpp = true;
    };
    m.linkLibrary(p.zstd);
    for (p.ts.libs.items) |lib| m.linkLibrary(lib);
    // The /src tree's files that live outside the core's directory
    // (fs.zig embeds them under the names they had there).
    if (p.cfg.embed_sources) for ([_][]const u8{ "runtime/9p.zig", "runtime/9p_io.zig", "runtime/main.zig", "dev/host_io.zig" }) |f|
        m.addAnonymousImport(f, .{ .root_source_file = b.path(f) });
    const runtime = b.createModule(.{ .target = p.target, .optimize = p.optimize, .root_source_file = b.path("runtime/root.zig"), .link_libc = true });
    const dev = b.createModule(.{ .target = p.target, .optimize = p.optimize, .root_source_file = b.path("dev/root.zig"), .link_libc = true });
    const wire = b.createModule(.{ .target = p.target, .optimize = p.optimize, .root_source_file = b.path("abi/wire.zig"), .link_libc = true });
    const root = if (!in_runtime) m else if (std.mem.eql(u8, c.root, "runtime/root.zig")) runtime else b.createModule(.{ .target = p.target, .optimize = p.optimize, .root_source_file = b.path(c.root), .link_libc = true });
    // Each options module once, so that the modules share it: a file is in
    // one module of a compilation.
    const ts_queries = p.ts.queries.createModule();
    const doc_typ = p.doc_typ.createModule();
    const pardes_options = options(b, p.cfg, c, p.pdf != null).createModule();
    const build_info = p.info.createModule();
    for ([_]*std.Build.Module{ m, dev, runtime, wire, root }) |x| {
        x.addImport("cloud9", p.cloud9);
        if (c.builtin_addons) if (p.pdf) |pdf| x.addImport("pdf_addon", pdf);
        if (c.builtin_addons) x.addImport("image_addon", p.image);
        if (c.terminal) x.addImport("term", p.term);
        x.addImport("plain", p.plain);
        x.addImport("pardes_addon", p.kind);
        x.addImport("addon", p.addon);
        x.addImport("generated_themes", p.themes);
        x.addImport("tree-sitter", p.ts.mod);
        x.addImport("ts_queries", ts_queries);
        x.addImport("mvzr", p.mvzr);
        x.addImport("c_heap", p.c_heap);
        x.addImport("vaxis", p.vaxis);
        x.addImport("uucode", p.uucode);
        x.addImport("xitdb", p.xitdb);
        // config.zig's test checks the words and keys docs/typ names exist.
        x.addImport("doc_typ", doc_typ);
        x.addImport("pardes_options", pardes_options);
        x.addImport("build_info", build_info);
        x.addImport("core", m);
        x.addImport("dev", dev);
        x.addImport("runtime", runtime);
        x.addImport("wire", wire);
    }
    return .{ .root = root, .core = m, .dev = dev, .runtime = runtime, .wire = wire };
}

/// What `assemble` makes besides the parts: the addons, and the terminal's pieces the tests and harnesses name.
pub const Assembly = struct {
    parts: Parts,
    /// What an addon in Zig imports (abi/addon.zig).
    addon_mod: *std.Build.Module,
    pdf: addons.Pdf,
    image_addon: *std.Build.Step.Compile,
    /// The window's FreeType, which MuPDF is built against too.
    freetype: ?*std.Build.Step.Compile,
    /// ghostty's emulator, null while it is still to be fetched.
    ghostty_vt: ?*std.Build.Module,
    ghostty_optimize: std.lang.Optimize,
    ghostty_simd: bool,
};

/// Every core's parts and the addons, made once and in this order (the
/// configuration numbers what it generates by it): the one-round lazy
/// fetch, tree-sitter and the themes, the patched packages, zstd, the
/// terminal.
pub fn assemble(b: *std.Build, c: struct {
    target: std.Build.ResolvedTarget,
    optimize: std.lang.Optimize,
    c_optimize: std.lang.Optimize,
    shell_cfg: ShellConfig,
    platform: Platform,
    also_gui: bool,
    pdf: bool,
    enable_jpx: bool,
    doc_typ: *std.Build.Step.Options,
    mupdf_check: *std.Build.Step,
    pdf_pointer_bench_step: *std.Build.Step,
    pdf_scroll_bench_step: *std.Build.Step,
}) Assembly {
    const target = c.target;
    const optimize = c.optimize;
    const c_optimize = c.c_optimize;
    // build-time IO: slurps the grammars' highlights.scm queries, reads
    // vendor/themes to find the theme sources, and walks MuPDF's tree
    var threaded: std.Io.Threaded = .init(b.allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();

    // 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 = treeSitter(b, io, target, c_optimize, tierSet(c.shell_cfg.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.dependencyLazy(name, .{}) catch {};
        };
    }
    // cloud9's module has no target of its own: it compiles for whatever imports it.
    const cloud9 = b.dependency("cloud9", .{}).module("cloud9");

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

    const zstbi_dep = b.dependency("zstbi", .{ .target = target, .optimize = c_optimize });
    const zstbi_mod = zstbi_dep.module("root");
    // vaxis, ghostty, mvzr and zstbi are patched as they are fetched
    // (build/patches.zig), by one tool made once.
    const patch = patches.tool(b);
    // mvzr with a step budget, its group backtracking and `$` before `|`.
    const mvzr_mod = patches.mvzr(b, patch, 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("core/c_heap.zig"),
    });

    // MuPDF and FreeType, lazy (build.zig's `pdf` option has why).
    const mupdf_dep = if (c.pdf) b.dependencyLazy("mupdf", .{}) catch null 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 (c.pdf or c.also_gui or c.platform == .gui) b.dependencyLazy("freetype", .{
        .target = target,
        .optimize = c_optimize,
        .@"enable-libpng" = false,
    }) catch null else null;
    const freetype = if (freetype_dep) |d| d.artifact("freetype") else null;

    // The kinds' C ABI (abi/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("abi/pardes_addon.h"), .target = target, .optimize = optimize }).createModule();
    // ...and what an addon in Zig imports over it (abi/addon.zig).
    const addon_mod = b.createModule(.{ .root_source_file = b.path("abi/addon.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "pardes_addon", .module = kind_mod }} });
    // The C-backed addons' own Zig and bridge at the C's speed, with the
    // checks a release keeps: ReleaseSafe in a Debug build, as in the
    // user's (a page's search without a hit sliced a NULL: only a release
    // build aborted, Debug's addons ran ReleaseFast); MuPDF and stb stay
    // at c_optimize.
    const addon_optimize: std.lang.Optimize = if (optimize == .debug) .safe else c_optimize;
    const pdf_built = addons.pdf(b, .{
        .addon_mod = addon_mod,
        .addon_optimize = addon_optimize,
        .c_optimize = c_optimize,
        .enable_jpx = c.enable_jpx,
        .freetype = freetype,
        .freetype_dep = freetype_dep,
        .io = io,
        .mupdf_check = c.mupdf_check,
        .mupdf_dep = mupdf_dep,
        .pdf_pointer_bench_step = c.pdf_pointer_bench_step,
        .pdf_scroll_bench_step = c.pdf_scroll_bench_step,
        .target = target,
    });

    const uucode_mod = 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, patch, 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.dependencyLazy("ghostty", .{ .target = target, .optimize = ghostty_optimize, .simd = ghostty_simd, .@"app-runtime" = .none, .@"emit-xcframework" = false }) catch null;
    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, patch, dep, 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 (build/patches.zig).
    // The image addon has its own (addons/image).
    const wuffs_mod: ?*std.Build.Module = if (ghostty_vt_for_tests) |vt| vt.import_table.get("wuffs") else null;
    patches.zstbi(b, patch, zstbi_dep, zstbi_mod);

    // One zstd (docs/shared-libs.md): a far replica's stream, compressed by
    // its session and read by its client (core/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 zstd = zstd: {
        const dep = b.dependency("zstd", .{});
        const lib = b.addLibrary(.{
            .name = "zstd",
            .root_module = b.createModule(.{ .target = target, .optimize = c_optimize, .link_libc = true }),
            .linkage = .static,
        });
        lib.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",
            },
        });
        lib.link_function_sections = true;
        lib.link_data_sections = true;
        break :zstd lib;
    };

    // xitdb keeps what pardes writes to disk (core/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, addon_optimize, addon_mod, zstbi_dep);
    // The records the core and the terminal both name (abi/plain.zig).
    const plain_mod = b.createModule(.{ .root_source_file = b.path("abi/plain.zig"), .target = target, .optimize = optimize });
    // The terminal, a module of its own (core/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("core/term/term.zig"), .target = target, .optimize = optimize, .link_libc = true });
    term_mod.addImport("plain", plain_mod);
    if (ghostty_vt_for_tests) |x| term_mod.addImport("ghostty-vt", x);
    if (wuffs_mod) |x| term_mod.addImport("wuffs", x);
    term_mod.addImport("zstbi", zstbi_mod);
    return .{
        .parts = .{
            .target = target,
            .optimize = optimize,
            .cloud9 = cloud9,
            .cfg = c.shell_cfg,
            .info = buildInfo(b, io, c.shell_cfg),
            .zstd = zstd,
            .image = image_addon.root_module,
            .pdf = pdf_built.module,
            .term = term_mod,
            .plain = plain_mod,
            .kind = kind_mod,
            .addon = addon_mod,
            .themes = themes_mod,
            .ts = ts,
            .mvzr = mvzr_mod,
            .c_heap = c_heap_mod,
            .vaxis = vaxis_mod,
            .uucode = uucode_mod,
            .xitdb = xitdb_mod,
            .doc_typ = c.doc_typ,
        },
        .addon_mod = addon_mod,
        .pdf = pdf_built,
        .image_addon = image_addon,
        .freetype = freetype,
        .ghostty_vt = ghostty_vt_for_tests,
        .ghostty_optimize = ghostty_optimize,
        .ghostty_simd = ghostty_simd,
    };
}