Something went wrong. Try again.
The Unicode Collation Algorithm (UTS #10) and CLDR locale tailorings in Zig: sort text the way people expect rather than by code point.
Something went wrong. Try again.
zig-collate build.zig
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Most of what this does is generate the Default Unicode Collation Element//! Table. `tools/gen_ducet.zig` reads the three Unicode data files in//! `data/` and writes the Zig source of the table, which is then imported by//! the library as `ducet`.//!//! Those files are committed rather than fetched, which is not the shape the//! rest of these projects use. The reason is narrow: Zig's package manager//! refuses a dependency served as `text/plain` -- `zig fetch` on//! `allkeys.txt` says `unrecognized 'Content-Type' header` -- and Unicode//! publishes the DUCET only as a plain text file. There is no archive of it//! anywhere on unicode.org, and the only git repository that carries one is//! `unicode-org/unicodetools`, whose tarball is 618 MB. So the files are in//! `data/` and `tools/update-ducet.sh` is what refreshes them.
const std = @import("std");
pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{});
const embed_ducet = b.option( bool, "embed-ducet", "Compile the Default Unicode Collation Element Table into the " ++ "library. Off, `Collator.table` starts out empty and every code " ++ "point takes the derived weights of section 10.1, which is only " ++ "useful to a caller supplying a table of its own. The library's " ++ "own tests need the table and fail without it; `zig build check` " ++ "is what this flag is worth running (default: true)", ) orelse true;
const embed_cldr = b.option( bool, "embed-cldr", "Compile the CLDR root collation in as well, as `collate.cldr_root`. " ++ "CLDR regroups DUCET's scripts and narrows which characters count " ++ "as variable before anyone's language is considered, and it is what " ++ "ICU orders by, so it is what most other software agrees with. Off " ++ "by default only because the data is committed for the table and " ++ "the conformance suite for it arrives in a 66 MB archive " ++ "(default: false)", ) orelse false;
const locales_option = b.option( []const u8, "locales", "CLDR collation tailorings to compile in, comma separated, reachable " ++ "as `collate.locales.<name>`: -Dlocales=sv,da,tr. Each is a delta " ++ "over the root table -- tens of kilobytes for most, 2.4 MB for " ++ "Korean -- but the rules arrive in the CLDR archive, so naming " ++ "any of them means fetching it (default: none)", ) orelse "";
// Section 9.3.3 of UTS #10, reducing the repertoire. const repertoire = b.option( []const u8, "repertoire", "Generate tables covering only these Unicode blocks, comma separated: " ++ "-Drepertoire='Basic Latin,Latin-1 Supplement,General Punctuation'. " ++ "A range may be given directly as 0000..024F. Everything outside is " ++ "weighed from its code point by section 10.1.3 and sorts after " ++ "everything that is not, so a restricted table is a different " ++ "collation -- conformant over the repertoire it names and not " ++ "beyond it. Basic Latin alone is 2 KiB of stage-two table against " ++ "376 KiB for the whole of Unicode (default: everything)", ) orelse "";
const docs_port = b.option(u16, "docs-port", "Port for `zig build docs-serve` (default 8000)") orelse 8000;
const test_step = b.step("test", "Run the unit tests"); // "Compile everything without running it", so that a tool nothing else // builds cannot quietly stop compiling. const check_step = b.step("check", "Build every artifact without running anything");
// The shapes a collation element table is made of. A module rather than // a file of the library, because the generated table imports it too and // Zig types are nominal: declared twice, they would be two types. const data_mod = b.createModule(.{ .root_source_file = b.path("src/data.zig"), .target = target, .optimize = optimize, });
// Four fields, which is what the algorithm's first step runs on plus the // one thing section 10.1.3 needs at run time. uucode is configurable at // build time, so naming them is how the rest of the Unicode Character // Database stays out of the binary. const uucode_fields: []const []const u8 = &.{ // Step 1, the canonical ordering algorithm. "canonical_combining_class", // Step 1, and the only way to tell a canonical decomposition from a // compatibility one -- which is the whole difference between NFD and // NFKD. "decomposition_type", "decomposition_mapping", // Section 10.1.3 excludes unassigned code points from the siniform // implicit weight ranges, so an unassigned code point in the middle // of a Tangut block is weighted as unassigned rather than as Tangut. "general_category", };
const uucode = b.dependency("uucode", .{ .target = target, .optimize = optimize, .fields = uucode_fields, }).module("uucode");
const ducet_source = if (embed_ducet) generateTable(b, uucode_fields, check_step, .{ .table = "data/allkeys-17.0.0.txt", .name = "ducet", .repertoire = repertoire, }) else b.path("src/generated/stub.zig");
const cldr_source = if (embed_cldr) generateTable(b, uucode_fields, check_step, .{ .table = "data/allkeys_CLDR-48.2.txt", .name = "cldr", // The CLDR file carries no `@implicitweights` lines of its own, // because section 10.1.3's rule belongs to UTS #10 rather than to // any one table. .implicit_weights_from = "data/allkeys-17.0.0.txt", // And CLDR's Han order, which `allkeys_CLDR.txt` does not carry // and `FractionalUCA.txt` declares. .han_order_from = "data/FractionalUCA_radicals-48.2.txt", .repertoire = repertoire, }) else b.path("src/generated/stub.zig");
// What the *tailoring* generator resolves rules against: the unrestricted // root, even when the library's own table is restricted. // // A tailoring's weights are relative to root weights, and the entries a // restriction leaves behind keep the weights they had, so the deltas it // emits are the same either way. What a restricted root has not got is // the script *groups*: `[reorder Latn Kana Hani]` cannot be resolved // against a table holding only Latin, and Japanese fails the build with // `UnknownReorderCode`. So the full table is generated a second time for // the generator to read -- and only when a restriction asked for one, // since otherwise these are the same tables. const full_ducet_source = if (repertoire.len == 0 or !embed_ducet) ducet_source else generateTable(b, uucode_fields, check_step, .{ .table = "data/allkeys-17.0.0.txt", .name = "ducet-unrestricted", });
const full_cldr_source = if (repertoire.len == 0 or !embed_cldr) cldr_source else generateTable(b, uucode_fields, check_step, .{ .table = "data/allkeys_CLDR-48.2.txt", .name = "cldr-unrestricted", .implicit_weights_from = "data/allkeys-17.0.0.txt", .han_order_from = "data/FractionalUCA_radicals-48.2.txt", });
const mod = b.addModule("collate", .{ .root_source_file = b.path("src/root.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "uucode", .module = uucode }, .{ .name = "data", .module = data_mod }, }, }); for ([_]struct { []const u8, std.Build.LazyPath }{ .{ "ducet", ducet_source }, .{ "cldr", cldr_source }, }) |entry| { mod.addAnonymousImport(entry[0], .{ .root_source_file = entry[1], .target = target, .optimize = optimize, .imports = &.{.{ .name = "data", .module = data_mod }}, }); }
// -- tailorings -----------------------------------------------------------
// One generated module per locale, plus an aggregator so that // `collate.locales.sv` names one. Naming a locale that was not compiled // in is then a compile error rather than a run-time surprise. { var names: std.ArrayList([]const u8) = .empty; var it = std.mem.tokenizeScalar(u8, locales_option, ','); while (it.next()) |name| names.append(b.allocator, name) catch @panic("OOM");
// Collected rather than imported as they are made, because the // aggregator is what has to import them and it does not exist yet. var generated: std.ArrayList(struct { []const u8, std.Build.LazyPath }) = .empty;
var index: std.ArrayList(u8) = .empty; index.appendSlice(b.allocator, \\// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us> \\// SPDX-License-Identifier: MIT \\ \\//! The CLDR collation tailorings this build was asked for, by \\//! `-Dlocales`. Generated by build.zig. \\ \\const data = @import("data"); \\ \\ ) catch @panic("OOM"); var lookup: std.ArrayList(u8) = .empty; var folded_lookup: std.ArrayList(u8) = .empty;
if (names.items.len != 0) { if (b.lazyDependency("cldr", .{})) |cldr| { const gen = b.addExecutable(.{ .name = "gen-tailoring", .root_module = b.createModule(.{ .root_source_file = b.path("tools/gen_tailoring.zig"), .target = b.graph.host, .optimize = .ReleaseSafe, .imports = &.{ // A *host copy* of the library, not `mod`. The // generator resolves a rule's anchor by running // steps 1 and 2 of the algorithm over the root // table, so it needs the library -- but `mod` // imports what this generator writes, and using // it here is a dependency loop the build runner // catches. The copy has no tailorings of its own, // which is exactly right: a rule's anchor is // resolved against the untailored root. .{ .name = "collate", .module = hostCollate(b, uucode_fields, full_ducet_source, full_cldr_source) }, .{ .name = "data", .module = hostData(b) }, // For a target's general category, which is // where a primary insertion takes its case from. .{ .name = "uucode", .module = b.dependency("uucode", .{ .target = b.graph.host, .fields = uucode_fields, }).module("uucode") }, }, }), }); check_step.dependOn(&gen.step); // The rule parser has its own tests, and it has earned them: // three separate misreadings of CLDR's own syntax have come // out of it, each of which produced a tailoring that compiled // and ordered nothing correctly. test_step.dependOn(&b.addRunArtifact( b.addTest(.{ .root_module = gen.root_module }), ).step);
for (names.items) |name| { const run = b.addRunArtifact(gen); run.addArg(name); run.addFileArg(cldr.path(b.fmt("common/collation/{s}.xml", .{name}))); // Where the reordering groups are declared. UTS #35 part // 5 says to take them from here rather than derive them. run.addFileArg(cldr.path("common/uca/FractionalUCA.txt")); const out = run.addOutputFileArg(b.fmt("tailoring_{s}.zig", .{name})); // CLDR writes its rules against CLDR's root collation, so // that is what they should be resolved against when it is // available. DUCET is the fallback, and it works wherever // the two roots agree -- which for the Latin letters they // do, and elsewhere they may not. run.addArg(if (embed_cldr) "--root=cldr" else "--root=ducet"); // `[import hr]` names another locale's rules, so the // generator is given the directory they all live in as // well as the one file it was asked about. Six locales // are written that way, Galician and Bosnian among them. run.addPrefixedDirectoryArg("--collation-dir=", cldr.path("common/collation"));
generated.append(b.allocator, .{ name, out }) catch @panic("OOM"); // Quoted, always. CLDR's locale identifiers include `or` // for Oriya, which is a Zig keyword, and quoting only // the names that collide would mean keeping a list of // them. `@"sv"` is the identifier `sv`, so // `collate.locales.sv` still resolves; Oriya is reached // as `collate.locales.@"or"`, which is what a keyword // costs. index.print( b.allocator, "pub const @\"{s}\": data.Tailoring = @import(\"tailoring_{s}\").tailoring;\n", .{ name, name }, ) catch @panic("OOM"); lookup.print( b.allocator, " if (std.mem.eql(u8, name, \"{s}\")) return &@\"{s}\";\n", .{ name, name }, ) catch @panic("OOM");
// The same table with the names pre-lowered, so that // `match` can fold its input once and compare against // literals rather than doing it per candidate. const lowered = b.allocator.dupe(u8, name) catch @panic("OOM"); for (lowered) |*c| c.* = std.ascii.toLower(c.*); folded_lookup.print( b.allocator, " if (std.mem.eql(u8, folded, \"{s}\")) return &@\"{s}\";\n", .{ lowered, name }, ) catch @panic("OOM"); } } }
// A lookup by string as well as the declarations, because a caller // that reads a language from its input -- `xsl:sort lang=`, an HTTP // header -- has a string and not a name it can write down. index.appendSlice(b.allocator, \\ \\const std = @import("std"); \\ \\/// The tailoring with exactly this identifier, or null. \\/// \\/// Names are CLDR's own file names, so the separator is `_`: \\/// `pt_PT`, not `pt-PT`. `match` is the one to call for a \\/// language tag. \\pub fn byName(name: []const u8) ?*const data.Tailoring { \\ ) catch @panic("OOM"); // A build that named no locales leaves both bodies empty, and an // unused parameter is a compile error. if (lookup.items.len == 0) { index.appendSlice(b.allocator, " _ = name;\n") catch @panic("OOM"); } index.appendSlice(b.allocator, lookup.items) catch @panic("OOM"); index.appendSlice(b.allocator, \\ return null; \\} \\ \\/// The most specific tailoring for a language tag, or null. \\/// \\/// Matches the way a language tag is meant to be matched: the \\/// whole tag first, then with its last subtag dropped, and so \\/// on -- so `de-AT-1996` finds `de_AT` if that was built in and \\/// `de` otherwise. BCP 47 writes subtags with `-` and CLDR \\/// names its files with `_`, so both are accepted. The \\/// comparison is case insensitive, because a language tag's \\/// case carries no meaning. \\/// \\/// Null means no tailoring, which is not a failure: 23 of \\/// CLDR's locales have none because the root collation is \\/// already their answer, and a caller cannot tell that apart \\/// from a locale this build was not asked for. Either way the \\/// root collation is what to use. \\pub fn match(tag: []const u8) ?*const data.Tailoring { \\ var buf: [64]u8 = undefined; \\ if (tag.len > buf.len) return null; \\ for (tag, 0..) |c, i| buf[i] = switch (c) { \\ '-' => '_', \\ 'A'...'Z' => c | 0x20, \\ else => c, \\ }; \\ \\ var len = tag.len; \\ while (len != 0) { \\ if (byNameFolded(buf[0..len])) |t| return t; \\ len = std.mem.findScalarLast(u8, buf[0..len], '_') orelse return null; \\ } \\ return null; \\} \\ \\fn byNameFolded(folded: []const u8) ?*const data.Tailoring { \\ ) catch @panic("OOM"); if (folded_lookup.items.len == 0) { index.appendSlice(b.allocator, " _ = folded;\n") catch @panic("OOM"); } index.appendSlice(b.allocator, folded_lookup.items) catch @panic("OOM"); index.appendSlice(b.allocator, \\ return null; \\} \\ ) catch @panic("OOM");
const write_index = b.addWriteFiles(); const index_file = write_index.add("locales.zig", index.items); const locales_mod = b.createModule(.{ .root_source_file = index_file, .target = target, .optimize = optimize, .imports = &.{.{ .name = "data", .module = data_mod }}, }); for (generated.items) |entry| { locales_mod.addAnonymousImport(b.fmt("tailoring_{s}", .{entry[0]}), .{ .root_source_file = entry[1], .target = target, .optimize = optimize, .imports = &.{.{ .name = "data", .module = data_mod }}, }); } mod.addImport("locales", locales_mod); }
const tests = b.addTest(.{ .root_module = mod }); test_step.dependOn(&b.addRunArtifact(tests).step); check_step.dependOn(&tests.step);
// `src/data.zig` has tests of its own, and they would never run as part // of the library's: a module's tests cover the files it reaches through // imports of *files*, and this one arrives as a module. const data_tests = b.addTest(.{ .root_module = data_mod }); test_step.dependOn(&b.addRunArtifact(data_tests).step); check_step.dependOn(&data_tests.step);
// -- the conformance suite ------------------------------------------------
// UTS #10 section 12.2. Every line of each file must sort at or after // the line before it, at identical strength. This is the acceptance // criterion for the library rather than a smoke test, and it is a step // of its own because the data is five megabytes and a lazy dependency. const conformance_step = b.step( "test-conformance", "Run the UCA conformance suite from unicode.org (downloads 5MB)", ); const conformance = b.addExecutable(.{ .name = "conformance", .root_module = b.createModule(.{ .root_source_file = b.path("tools/conformance.zig"), .target = b.graph.host, // Two hundred thousand lines apiece, each of which is normalized // and weighted twice. A debug build of this is a coffee break. .optimize = .ReleaseSafe, .imports = &.{.{ .name = "collate", .module = mod }}, }), }); check_step.dependOn(&conformance.step); if (b.lazyDependency("collation_test", .{})) |suite| { const run = b.addRunArtifact(conformance); // Read at run time rather than embedded: twenty-one megabytes of // test cases inside a binary is not a trade anybody wants. // Zig's package manager strips a single top-level directory when it // unpacks an archive, so the four files sit at the package root // rather than under `CollationTest/`. run.addDirectoryArg(suite.path("")); run.addArg("ducet"); run.stdio = .inherit; conformance_step.dependOn(&run.step); }
// The same procedure for the CLDR root collation. CLDR ships its own four // files, with a `_CLDR` infix, because its root is a tailoring of DUCET // and therefore orders things differently; they live in the CLDR // repository's `common/uca`. const cldr_conformance_step = b.step( "test-conformance-cldr", "Run the CLDR root conformance suite (downloads a 66MB archive)", ); if (embed_cldr) { if (b.lazyDependency("cldr", .{})) |cldr| { const run = b.addRunArtifact(conformance); run.addDirectoryArg(cldr.path("common/uca")); run.addArg("cldr"); run.stdio = .inherit; cldr_conformance_step.dependOn(&run.step); } } else { // A step that silently does nothing is worse than one that says why. cldr_conformance_step.dependOn(&b.addFail( "test-conformance-cldr needs the CLDR root table: add -Dembed-cldr", ).step); }
// -- fuzzing --------------------------------------------------------------
// A loop of this project's own rather than `zig build test --fuzz`, // which Zig 0.16.0 cannot build: its test runner hands an error return // trace to a function that takes a different kind of stack trace, and // that path is taken only under -ffuzz. The devshell patches that so the // fuzzer *runs*, but nothing in the release populates the coverage // table, so there is no coverage feedback to be had either way. What // this has instead is structure-aware generation through // `std.testing.Smith` and a corpus. const fuzz_exe = b.addExecutable(.{ .name = "fuzz", .root_module = b.createModule(.{ .root_source_file = b.path("tools/fuzz.zig"), .target = b.graph.host, .optimize = optimize, .imports = &.{ .{ .name = "collate", .module = mod }, .{ .name = "targets", .module = b.createModule(.{ .root_source_file = b.path("tests/fuzz.zig"), .target = b.graph.host, .optimize = optimize, .imports = &.{.{ .name = "collate", .module = mod }}, }) }, }, }), }); const run_fuzz = b.addRunArtifact(fuzz_exe); run_fuzz.stdio = .inherit; if (b.args) |args| run_fuzz.addArgs(args); b.step("fuzz", "Run the fuzz loop in tools/fuzz.zig").dependOn(&run_fuzz.step); check_step.dependOn(&fuzz_exe.step);
// -- benchmarks -----------------------------------------------------------
// Built ReleaseFast rather than taking `-Doptimize`, because a number // measured in a Debug build is not a number about this library. const bench_exe = b.addExecutable(.{ .name = "bench", .root_module = b.createModule(.{ .root_source_file = b.path("tools/bench.zig"), .target = b.graph.host, .optimize = .ReleaseFast, .imports = &.{.{ .name = "collate", .module = mod }}, }), }); const run_bench = b.addRunArtifact(bench_exe); run_bench.stdio = .inherit; if (b.args) |args| run_bench.addArgs(args); b.step( "bench", "Time the four steps per corpus (needs -Dembed-cldr; -Dlocales for a tailoring)", ).dependOn(&run_bench.step); check_step.dependOn(&bench_exe.step);
// -- the ICU oracle -------------------------------------------------------
// There is no conformance suite for a tailoring: UTS #10 ships one for // DUCET and CLDR ships one for its root, both of which are run above, and // for the per-locale tailorings there is nothing at all. So the oracle is // ICU, which is the reference implementation of the CLDR collation // algorithm and the thing every other collation is checked against in // turn. // // No pinned dependency: ICU comes from the dev shell and the oracle // prints which release it was. The C++ is compiled by Zig rather than by // a toolchain of its own, so the shell needs ICU and pkg-config and // nothing more -- and `icu-i18n` is spelled the way the `.pc` file names // it rather than the way the linker does, because pkg-config is how Zig // finds it. const oracle_step = b.step( "oracle", "Check the collations against ICU (needs -Dembed-cldr for a like-for-like root)", );
const oracle_dump = b.addExecutable(.{ .name = "oracle-dump", .root_module = b.createModule(.{ .root_source_file = b.path("tools/oracle_dump.zig"), .target = b.graph.host, .optimize = .ReleaseSafe, .imports = &.{.{ .name = "collate", .module = mod }}, }), }); check_step.dependOn(&oracle_dump.step);
const oracle_module = b.createModule(.{ .target = b.graph.host, .optimize = .ReleaseSafe, .link_libcpp = true, }); oracle_module.addCSourceFile(.{ .file = b.path("tools/oracle.cpp"), .language = .cpp, .flags = &.{"-std=c++17"}, }); oracle_module.linkSystemLibrary("icu-i18n", .{}); oracle_module.linkSystemLibrary("icu-uc", .{}); const oracle = b.addExecutable(.{ .name = "oracle", .root_module = oracle_module }); check_step.dependOn(&oracle.step);
const run_oracle_dump = b.addRunArtifact(oracle_dump); // ICU orders by the CLDR root, so that is the like-for-like comparison. // Against DUCET the run measures the distance between the two roots // instead, which is worth knowing and is not a finding about this code. run_oracle_dump.addArg(if (embed_cldr) "--root=cldr" else "--root=ducet");
// Which comparison to ask for. The default is tertiary strength with // non-ignorable handling, which is what the tailorings are about; the // others are different paths through the sort key builder, and `shifted` // in particular is the one the conformance suites cover for the roots and // nothing covers for a tailoring. One mode per run rather than all of // them in one, because any of them writes a 615 MB file of comparisons // and asks ICU thirty million questions. const OracleMode = enum { primary, secondary, tertiary, quaternary, identical, shifted, case_level, upper_first, lower_first, }; const oracle_mode = b.option( OracleMode, "oracle-mode", "Which comparison to ask ICU about (default tertiary)", ) orelse .tertiary; run_oracle_dump.addArg(b.fmt("--mode={t}", .{oracle_mode}));
// The dump is written by the dumper rather than captured from its stdout, // because the build runner holds a captured stdout in memory until the // step finishes and this file is 1.1 GB with every locale in it. On a // four-gigabyte runner that is the difference between a run and a // `SystemResources` failure spawning the next step. const comparisons = run_oracle_dump.addOutputFileArg("comparisons.tsv");
const run_oracle = b.addRunArtifact(oracle); run_oracle.addFileArg(comparisons); run_oracle.stdio = .inherit; oracle_step.dependOn(&run_oracle.step);
// -- documentation --------------------------------------------------------
// Zig writes the documentation as a side effect of compiling, so the // module is built as a library purely to get at it. const library = b.addLibrary(.{ .name = "collate", .root_module = mod }); const install_docs = b.addInstallDirectory(.{ .source_dir = library.getEmittedDocs(), .install_dir = .prefix, .install_subdir = "docs", }); const docs_step = b.step("docs", "Build the API documentation into zig-out/docs"); docs_step.dependOn(&install_docs.step);
// The generated viewer fetches `sources.tar` and `main.wasm` at run // time, which a browser refuses to do from a `file://` page, so reading // the docs locally means serving them. Same reason `zig std` runs a // server rather than opening a file. const docs_server = b.addExecutable(.{ .name = "docs-server", .root_module = b.createModule(.{ .root_source_file = b.path("tools/docs_server.zig"), // Always the machine running the build, never whatever -Dtarget // the library is being built for. .target = b.graph.host, .optimize = .Debug, }), }); const run_docs_server = b.addRunArtifact(docs_server); run_docs_server.step.dependOn(docs_step); run_docs_server.addArg(b.getInstallPath(.prefix, "docs")); run_docs_server.addArg(b.fmt("{d}", .{docs_port})); // It runs until interrupted, so its output has to reach the terminal // rather than being captured by the build runner. run_docs_server.stdio = .inherit; b.step("docs-serve", "Serve the API documentation over HTTP") .dependOn(&run_docs_server.step);
// The server has tests of its own; without this they would never run. test_step.dependOn(&b.addRunArtifact( b.addTest(.{ .root_module = docs_server.root_module }), ).step); check_step.dependOn(&docs_server.step);
b.getInstallStep().dependOn(&library.step);}
/// Runs `tools/gen_ducet.zig` over `data/` and returns the Zig source it/// wrote./// `src/data.zig` built for the build host, memoized so that every host-side/// tool shares one instance -- Zig types are nominal, and two instances would/// be two `Element` types.fn hostData(b: *std.Build) *std.Build.Module { if (host_data_module) |m| return m; const m = b.createModule(.{ .root_source_file = b.path("src/data.zig"), .target = b.graph.host, }); host_data_module = m; return m;}var host_data_module: ?*std.Build.Module = null;
/// The library built for the build host, with the root table and no/// tailorings, for tools that need to run the algorithm while the build is/// still deciding what the target's library will contain.fn hostCollate( b: *std.Build, uucode_fields: []const []const u8, ducet_source: std.Build.LazyPath, cldr_source: std.Build.LazyPath,) *std.Build.Module { if (host_collate_module) |m| return m;
const data_mod = hostData(b); const m = b.createModule(.{ .root_source_file = b.path("src/root.zig"), .target = b.graph.host, .optimize = .ReleaseSafe, .imports = &.{ .{ .name = "uucode", .module = b.dependency("uucode", .{ .target = b.graph.host, .fields = uucode_fields, }).module("uucode") }, .{ .name = "data", .module = data_mod }, }, }); // Both roots, because `--root=cldr` asks the generator to resolve rules // against CLDR's -- which is what CLDR wrote them against. `cldr_source` // is the stub when the build did not ask for the CLDR table, and the // generator then refuses `--root=cldr` by name rather than silently // resolving against the wrong one. m.addAnonymousImport("ducet", .{ .root_source_file = ducet_source, .target = b.graph.host, .imports = &.{.{ .name = "data", .module = data_mod }}, }); m.addAnonymousImport("cldr", .{ .root_source_file = cldr_source, .target = b.graph.host, .imports = &.{.{ .name = "data", .module = data_mod }}, }); // No tailorings: a rule's anchor is resolved against the untailored root, // so the generator must not see any tailoring, least of all the one it is // in the middle of writing. m.addAnonymousImport("locales", .{ .root_source_file = b.path("src/generated/no_locales.zig"), .target = b.graph.host, .imports = &.{.{ .name = "data", .module = data_mod }}, }); host_collate_module = m; return m;}var host_collate_module: ?*std.Build.Module = null;
const TableSource = struct { /// The `allkeys`-format file the table comes from. table: []const u8, /// What the generated executable is called, so that two tables do not /// share a build step. name: []const u8, /// Where to take section 10.1.3's siniform ranges from, for a table that /// does not carry its own `@implicitweights` lines. implicit_weights_from: ?[]const u8 = null, /// Where to take CLDR's Han order from -- the `[radical …]` lines of /// `FractionalUCA.txt`. Null for the DUCET, whose Han order is the /// code-point order section 10.1.3 computes. han_order_from: ?[]const u8 = null, /// Section 9.3.3's repertoire, as `-Drepertoire=` gave it. Empty means /// the whole of Unicode. repertoire: []const u8 = "",};
fn generateTable( b: *std.Build, uucode_fields: []const []const u8, check_step: *std.Build.Step, source: TableSource,) std.Build.LazyPath { // The generator runs on the build host and reads the same Unicode data // the library reads at run time, so that "this code point is // canonically decomposable and therefore unreachable after step 1" is // decided once, by one source, rather than twice. const host_uucode = b.dependency("uucode", .{ .target = b.graph.host, .fields = uucode_fields, }).module("uucode");
// A module's target is fixed when it is created, so the generator needs // its own `data` built for the host. The two never meet, so the fact // that they are different instances of the same file costs nothing. const host_data = b.createModule(.{ .root_source_file = b.path("src/data.zig"), .target = b.graph.host, });
const exe = b.addExecutable(.{ .name = b.fmt("gen-{s}", .{source.name}), .root_module = b.createModule(.{ .root_source_file = b.path("tools/gen_table.zig"), .target = b.graph.host, // The generator is run once per change to `data/`, and reads two // and a half megabytes of text to do it. A debug build of it // takes noticeably longer than the release build plus the time // to make it. .optimize = .ReleaseSafe, .imports = &.{ .{ .name = "uucode", .module = host_uucode }, .{ .name = "data", .module = host_data }, }, }), }); check_step.dependOn(&exe.step);
const run = b.addRunArtifact(exe); if (source.repertoire.len != 0) { run.addArg(b.fmt("--repertoire={s}", .{source.repertoire})); } run.addFileArg(b.path(source.table)); run.addFileArg(b.path("data/PropList-17.0.0.txt")); run.addFileArg(b.path("data/Blocks-17.0.0.txt")); const out = run.addOutputFileArg(b.fmt("{s}.zig", .{source.name})); if (source.implicit_weights_from) |path| run.addFileArg(b.path(path)); if (source.han_order_from) |path| run.addFileArg(b.path(path)); return out;}