# zig-collate — design A Zig implementation of the Unicode Collation Algorithm, [UTS #10][uca], for callers that need to order human-readable text rather than code points. It exists because a collation is wrong in the same way in every project that reimplements one, and because sorting by code point puts `Mueller` before `Märtens` — `u` is U+0075 and `ä` is U+00E4 — which is not a localization nicety but a plain defect. Written against UTS #10 revision 55 (UCA 18.0.0) and Zig 0.17.0. **Status: implemented, and it passes.** The conformance suite of section 12.2 runs clean — 212,066 cases with `non_ignorable` variable weighting and 212,066 with `shifted`, at identical strength, with none of the ill-formed lines filtered out. The CLDR root collation passes CLDR's own suite too, 210,186 cases in each. What follows is the design as built; the places where building it changed the plan are marked. [uca]: https://www.unicode.org/reports/tr10/ ## What the algorithm actually asks for UTS #10 §7 is four steps, and each one has a different cost and a different amount of data behind it. **Step 1, normalize (§7.1, S1.1).** Convert the input to NFD. `uucode` does not do this — it exposes `canonical_combining_class`, `decomposition_type` and `decomposition_mapping`, which is the *data* NFD runs on and not NFD itself, and it has no normalization API at all. So this library implements NFD: - Recursive canonical decomposition, filtered to `decomposition_type == .canonical` so that compatibility mappings are left alone. Measured against Unicode 18.0.0: 2,081 canonically decomposable code points, recursion depth at most 3, and a single code point expands to at most **4** code points (U+1F82 GREEK SMALL LETTER ALPHA WITH PSILI AND VARIA AND YPOGEGRAMMENI → U+03B1 U+0313 U+0300 U+0345). A fixed `[4]u21` per code point is therefore enough, with no allocation in the decomposition step itself. - Hangul syllables U+AC00..U+D7A3 arithmetically, to two or three jamo. These are not in `UnicodeData.txt` and no table lookup will find them. - Canonical ordering: a stable sort of each run of non-starters by `canonical_combining_class`. Maximum CCC in the data is 240; the runs are short, so insertion sort is the right one. §9.5 describes skipping normalization for text already in FCD form. Part of that is done and the rest is not: see [What step 1 costs](#what-step-1-costs). **Step 2, produce collation elements (§7.2, S2.1–S2.5).** Walk the NFD string, at each point taking the longest contiguous match in the table, then attempting to extend it discontiguously across unblocked non-starters (S2.1.1–S2.1.3). Unmatched code points get implicit weights (§10.1.3). This is the step with the table behind it and the step where the subtle bugs live. **Step 3, form sort keys (§7.3, S3.1–S3.10).** Append every non-zero weight of level 1, a separator, every non-zero weight of level 2, and so on. The result is a byte string. **Step 4, compare (§7.4).** `memcmp`. That is the whole point of step 3: once each string has a key, ordering *n* strings costs *n* key constructions and `n log n` byte comparisons, not `n log n` collations. ## What is in DUCET Numbers below are counted from `allkeys-17.0.0.txt`, not remembered, because several of them decide a representation. | | | |---|---| | Entries | 39,749 | | Single code point | 38,785 | | Contractions | 964 — 956 of length 2, 8 of length 3 | | Longest contraction | 3 code points | | Distinct contraction-initial code points | **77** | | Entries mapping to exactly one collation element | 34,876 | | Longest expansion | 18 collation elements (U+FDFA ARABIC LIGATURE SALLALLAHOU ALAYHE WASALLAM) | | Levels per collation element | 3, uniformly | | L1 range | 0x0000..0xFFFD, 29,587 distinct | | L2 range | 0x0000..0x0127, 265 distinct | | L3 range | 0x0000..0x001E, 29 distinct | | `@implicitweights` lines | 6 (Tangut, Tangut Components, Tangut Supplement, Tangut Components Supplement, Nushu, Khitan Small Script) | Four of those numbers shape the code: **A collation element fits in 32 bits.** L1 needs 16 bits, L2 needs 9 (0x0127 = 295), L3 needs 5 (0x1E = 30). That is 30 bits, so a `packed struct(u32)` holds one with two bits spare — no `u64`, no struct-of-arrays needed to keep the table small. **Variability is a comparison, not a stored bit.** The variable collation elements have primary weights 0x0201 through 0x221F, and the lowest non-zero primary weight above them on a non-variable one is 0x2220. Below them is only U+FFFE at 0x0200, which section 10.1.5 reserves for it since UCA 18.0 and which is never variable. Well-formedness condition WF4 forbids interleaving and the data honors it, so `isVariable(ce) = 0x0201 <= ce.primary <= 0x221F` is exact and the `*` marker in `allkeys.txt` need not be carried into the generated table. The threshold is generated as a constant so that it tracks the data rather than being typed in. **Contractions want a side table, not a trie.** 964 of them, over only 77 distinct first code points, none longer than three code points. A bit on the single-code-point entry saying "this code point may start a contraction", plus a small sorted array of continuations, is smaller and faster than a general trie and much easier to read. WF5 guarantees that a three-code-point contraction ending in a non-starter has its two-code-point prefix in the table, which is what makes incremental extension in S2.1.2 able to find it. **2,081 single-code-point entries are unreachable.** They are the canonically decomposable code points, which S1.1 has already removed by the time step 2 looks anything up. They are dropped from the generated table. (Keeping them is what the rest of §9.5 would need — the canonical closure — and what "What step 1 costs" below weighs up.) One wrinkle worth recording: U+337F SQUARE ERA NAME MEIJI maps to `[.FB40.0020.001C][.E82A.0000.0000]`, a collation element with a non-zero primary and a zero secondary. That breaks WF1 as stated, and is the documented large-weight-value exception of §9.2 — the second half of an implicit-weight pair, written out by hand. The table representation must not assume WF1. ## The generated table ``` ducet.zig (generated into the cache, never committed) ├── unicode_version "18.0.0" ├── max_variable_primary 0x221F ├── stage1: [0x1100]u16 code point >> 8 -> stage2 block, or 0xFFFF ├── stage2: [48128]u64 188 blocks of 256, deduplicated by content ├── expansions: [_]Element every run of more or fewer than one element ├── contractions: [_]Contraction sorted by (first, length desc, rest) └── implicit_ranges: [_]ImplicitRange Table 16, as ranges ``` `isVariable` lives on `Table`, not on `Element`. Whether an element is variable depends on the threshold the table was generated with, and UTS #10 defines "variable collation element" relative to a table, so putting it on the element would have meant either a global or a lie. ```zig /// One collation element, UTS10-D2. Three weights and two fields a tailoring /// needs: forty-eight bits, of which DUCET alone would fill thirty. pub const Element = packed struct(u48) { primary: u16, /// Where this element sits *between* two root primary weights, for one a /// tailoring inserted. Eleven bits, and the most any CLDR tailoring /// reaches is 265. primary_sub: u11 = 0, secondary: u9, /// Six bits rather than DUCET's five, because Arabic hangs forty-three /// tertiary relations off one anchor. tertiary: u6, /// The fourth level, for the one collation that writes `<<<<`. Zero /// everywhere else. quaternary: u4 = 0, /// Section 5.1's case bits, which are not a reading of the tertiary /// weight once a tailoring is involved. case: Case = .lower, }; /// What one code point maps to. pub const Entry = packed struct(u64) { /// The element itself when `len == 1`, an index into `expansions` when /// `len > 1`, meaningless when `len == 0`. payload: u48, /// Zero means the table says nothing and §10.1 derives the weights. len: u8, /// 77 code points in DUCET have this set. Everything else never touches /// the contraction list at all. starts_contraction: bool, /// The payload indexes a *tailoring's* expansions rather than the root /// table's. Never set by a generated root table. tailored: bool = false, _reserved: u6 = 0, }; ``` **`stage2` is emitted as `u64` rather than as `Entry`.** It is the one big array — 188 blocks of 256 — and a hexadecimal literal apiece is about a third of the generated source that a struct literal apiece would be. The cast back happens on the way out of `Table.entry`, where it is free. `expansions` is small enough (a few thousand) to stay typed, which matters because slices of it are handed out. That the generated file carries typed arrays at all is why `src/data.zig` is a *module* rather than a file of the library: Zig types are nominal, so the generator and the code reading what it generated have to import the same declarations, and a file reached twice would be two types. The generator gets its own instance of that module built for the host, which never meets the library's. A two-stage table rather than uucode's more elaborate packing because the key space here is dense in the low planes and nearly empty above them, and because the generator has to stay readable — it is the file that gets re-checked whenever Unicode moves. ## Public API The core works on `[]const u21` and UTF-8 is a layer on top. Two reasons: the conformance suite's test cases are sequences of hexadecimal code points, including lone surrogates that well-formed UTF-8 cannot carry, and callers that have already decoded should not re-encode to call this. ```zig const collate = @import("collate"); /// §7.4 and §3.7: how many levels a comparison looks at. `identical` adds /// S3.10, the NFD of the original string, which is what the conformance /// suite compares at. pub const Strength = enum { primary, secondary, tertiary, quaternary, identical }; /// §4. Note the default: UCA says `shifted`, LDML says `non_ignorable` /// (§8.1), and the conformance suite ships a file for each. pub const Alternate = enum { non_ignorable, blanked, shifted }; pub const Options = struct { strength: Strength = .tertiary, alternate: Alternate = .shifted, /// §3.8.1. French dictionary ordering scans level 2 backwards. Only /// level 2 has a practical use, so this is a bool and not a level mask. backwards_secondary: bool = false, }; /// A collation: a table plus the parametric settings applied to it. Holds no /// allocation and is cheap to copy, so sharing one between threads is fine. pub const Collator = struct { table: Table = ducet, options: Options = .{}, pub fn sortKeyAlloc(c: Collator, gpa: Allocator, text: []const u8) Error![]u8; pub fn sortKeyAllocCodePoints(c: Collator, gpa: Allocator, text: []const u21) Allocator.Error![]u8; pub fn order(c: Collator, gpa: Allocator, a: []const u8, b: []const u8) Error!std.math.Order; /// For finding rather than sorting: see "Match keys" under Searching. pub fn matchKeyAlloc(c: Collator, gpa: Allocator, text: []const u8) Error![]u8; pub fn matchKeyAllocCodePoints(c: Collator, gpa: Allocator, text: []const u21) Allocator.Error![]u8; pub fn matchKeyWidth(c: Collator) usize; pub fn findMatchKey(c: Collator, target_key: []const u8, pattern_key: []const u8) ?usize; }; /// Step 4, for `std.mem.sort` once the keys exist. pub fn orderKeys(a: []const u8, b: []const u8) std.math.Order; /// Reusable scratch, for the case this library exists to serve: a key for /// every node in a node-set, at every sort level. One per thread. pub const Builder = struct { /// The NFD of the string in hand. Mutable, because S2.1.3 says to remove /// a code point from the input when a discontiguous match eats it. text: std.ArrayList(u21), elements: std.ArrayList(Element), weighted: std.ArrayList(Weighted), pub const empty: Builder; pub fn deinit(b: *Builder, gpa: Allocator) void; /// Levels cannot be streamed independently — every primary weight in the /// string precedes the first secondary weight — so the element array is /// buffered here whatever the caller does with the bytes. pub fn writeSortKey(b: *Builder, gpa: Allocator, w: *std.Io.Writer, c: Collator, text: []const u21) !void; pub fn writeSortKeyUtf8(b: *Builder, gpa: Allocator, w: *std.Io.Writer, c: Collator, text: []const u8) !void; pub fn sortKeyAlloc(b: *Builder, gpa: Allocator, c: Collator, text: []const u8) Error![]u8; pub fn sortKeyAllocCodePoints(b: *Builder, gpa: Allocator, c: Collator, text: []const u21) Allocator.Error![]u8; /// And the same four for match keys. pub fn writeMatchKey(b: *Builder, gpa: Allocator, w: *std.Io.Writer, c: Collator, text: []const u21) !void; pub fn writeMatchKeyUtf8(b: *Builder, gpa: Allocator, w: *std.Io.Writer, c: Collator, text: []const u8) !void; pub fn matchKeyAlloc(b: *Builder, gpa: Allocator, c: Collator, text: []const u8) Error![]u8; pub fn matchKeyAllocCodePoints(b: *Builder, gpa: Allocator, c: Collator, text: []const u21) Allocator.Error![]u8; /// For a caller that wants to look at the elements rather than a key. pub fn collationElements(b: *Builder, gpa: Allocator, c: Collator, text: []const u21) Allocator.Error![]const Element; }; ``` There are **three** scratch arrays rather than the two the first sketch had. Variable weighting turned out to want a pass of its own: it is stateful left to right — "any sequence of ignorable collation elements that immediately follows the variable collation element is also affected" — and each level of the sort key is a separate walk over the elements, so doing it inside the per-level walk would have recomputed it three or four times and, worse, would have made the levels disagree with each other under `backwards_secondary`, which walks one level in the other direction. Keeping the element array exactly what the table says is also what makes `collationElements` worth exposing and the step-2 tests worth reading. `Collator.sortKeyAlloc` and `Collator.order` make a temporary `Builder`; a caller sorting a list should hoist one. ### What step 1 costs `zig build bench` is here because a performance change needs a number in front of it. It times the whole of `writeSortKeyUtf8` per corpus, then step 1 alone, then the bare UTF-8 decode into the `[]u21` that step 2 walks -- which happens whether or not anything is normalized, since S2.1.3 removes a code point a discontiguous match consumed and so the buffer has to be the collator's own. The difference between the second and the third is what §9.5 could save. The first run said step 1 was **40% of key construction and nearly the same share for every corpus** -- ASCII, Han and Vietnamese alike -- of which about 17 points was that unavoidable decode. A cost that does not vary with the script is not decomposing anything: it is the two property lookups step 1 does per code point, `decomposition_type` in `decompose` and `canonical_combining_class` in `canonicalOrder`. So the cheap part of §9.5 is not FCD at all. It is three things that between them stop step 1 asking the property tables anything it can work out for itself: **A bound below which nothing decomposes or reorders.** U+00C0 LATIN CAPITAL LETTER A WITH GRAVE is the first canonical decomposition there is and U+0300 COMBINING GRAVE ACCENT the first non-zero combining class, so a code point below the lower of the two is its own NFD and cannot move. `nfd.inert_below` is that bound, asserted against the data by a test rather than trusted. **One table row instead of two lookups.** `uucode.get` walks its stage tables per *field*, and the four fields this build asks for share one table -- so asking whether a code point decomposes and then what its combining class is walks the same three stages twice. `getAll` returns the row, and both answers come out of it. **Canonical ordering one code point at a time.** With the class already in hand there is no reason to make a second pass over the string to find it: appending each code point and inserting it back over any mark of a higher class is the same insertion sort with the same stability, so `canonicalOrder` as a pass is gone from the hot path. It is still there, still tested, and now also tested *against* the incremental version -- over every assigned code point in three shapes, because an equivalence is the kind of claim a sweep can settle. **And a run of ASCII bytes copied in one go.** Which is worth 7% on its own, and is also what makes the copy sound: see the bug below. | corpus | before | after | |---|---|---| | ascii | 278 ns | **185 ns** | | latin-nfc | 305 ns | **236 ns** | | latin-nfd | 318 ns | **225 ns** | | vietnamese | 400 ns | **334 ns** | | han | 158 ns | **142 ns** | | japanese | 245 ns | **232 ns** | | hangul | 277 ns | 273 ns | Step 1 is 8% of a sort key for a string of ASCII now, against 44% before. **The bug this turned up is worth more than the speed.** The first version of the inert fast path appended with `appendAssumeCapacity` against a reserve of one slot per input code point -- and a code point that decomposes takes more than one, so a Hangul syllable followed by an ASCII letter could append past the reserve. In a test build that is an assertion failure; in ReleaseFast the assertion is gone and it is a write past the end of the buffer. It was found by arithmetic rather than by a test, while reading the code for something else, and there is a test for it now: Hangul then ASCII at two hundred lengths, which is how the capacities are made to line up. Two other things were measured and rejected, which is the other half of what a benchmark is for. Skipping the reordering *pass* by asking whether anything had a combining class costs a lookup per code point to answer, which is dearer than the pass it avoids -- 5% dearer on Han and Hangul, which reorder nothing either way. And the first benchmark reported 21 microseconds a string with step 1 at 0.3%, which was a number about `DebugAllocator`: a key per string through `sortKeyAlloc` is an allocation per string, so the benchmark writes into a buffer it keeps instead. ### What the entry points allocated `zig build bench` times `Collator.order` as well, because that is the convenient way to compare two strings and therefore the one that ends up inside a sort comparator. It was allocating **five times per comparison**: a `Builder` per call, whose three buffers are an allocation each, and then a key apiece. Against an arena that measured 604 ns a pair where writing the keys into buffers the caller keeps measured 399; against the checking allocator the benchmark itself uses, it measured **30 microseconds**. So the three allocating entry points take their scratch off the stack, through `std.heap.stackFallback`, and `order` writes both keys there too. Nothing is allocated for a string of about forty code points or fewer, and the allocator is reached only past that -- which is what would have happened for every string before. | entry point | before | after | |---|---|---| | `order`, checking allocator | 30,240 ns | **428 ns** | | `order`, arena | 604 ns | **422 ns** | | keys into caller's buffers, one `Builder` | 399 ns | 375 ns | The two `order` rows converging is the point: the call no longer depends on what allocator is behind it. What is left between it and the buffered row is the `Builder` itself, which a caller sorting a list should hoist anyway, and the API documentation says so. The `order` numbers in that table are what the allocation fix left; the section below took them further. ### Comparing a level at a time, which section 9.7 asks for With the allocations gone, what was left in `order` was work done to answer a question that had already been settled. Both strings were weighed, both whole keys were written, and then the keys were compared -- when almost every comparison of two different strings is decided by the primary level, and the secondary, tertiary and case bytes behind it are written only to be skipped. Section 9.7 says to compare incrementally instead, and names the two halves separately. The cheaper half is the one taken here: weigh both strings in full, then write and compare **one level at a time**, stopping at the first level that decides. Step 3 is the part that becomes conditional, and step 3 is 28% to 39% of building a key -- 73 ns of ascii's 190, 83 of `latin-nfc`'s 239, 53 of han's 145 -- so for two strings that differ in their first letter, most of it is never done. The other half, weighing incrementally as well, is not taken. It would mean producing collation elements a few at a time from each string and comparing primaries as they appear, which is a real saving for long strings with an early difference -- but a contraction, an expansion or a discontiguous match can all reach backwards or forwards across the point the weighing stopped, so a partial weighing has to be able to resume and to revise. Weighing is also the cheaper half to repeat: it is the other 61% to 72% of a key, but it is a linear walk over text that is already in cache, where writing a level is a second pass over the elements with a branch per element for every setting that changes the layout. `writeLevel` in `src/key.zig` is the function that made this possible, and factoring it out is most of the change. `write` had been one pass with the level loop inside it; it is now a loop that calls `writeLevel` per level, which means the whole-key path and the incremental path write each level through the same code rather than through two implementations that have to agree. The identical level and the case level came out as `writeIdenticalLevel` and `writeCaseLevelPublic` for the same reason. | corpus | whole keys, then compare | a level at a time | |---|---|---| | ascii | 376 ns | **319 ns** | | `latin-nfc` | 477 ns | **398 ns** | | `latin-nfd` | 452 ns | **354 ns** | | vietnamese | 726 ns | **552 ns** | | hangul | 526 ns | **443 ns** | | han | 287 ns | **267 ns** | | japanese | 450 ns | **367 ns** | `order` is now faster than writing two whole keys and comparing them, which is the thing that had not been true before: it was 428 ns against the buffered route's 375, and the advice for anyone comparing strings was to build keys themselves. It is the other way round now, and for sorting a list keys still win for a different reason -- a key is built once and compared *n* log *n* times. Han gains least, at 7%, because a Han primary is four bytes where a Latin one is two: the level that decides is a bigger share of the key, so there is less behind it to skip. **What stands behind it.** Nothing else covers this path. Both conformance suites compare sort keys, the ICU oracle builds sort keys, and so every check the library had went through `write` and not through `order`. So the guard is a fuzz target of its own, `order-agrees`: it generates two strings -- one shape drawn from the table's own contractions so that expansions and discontiguous matches land inside the levels, one uniform -- and a random set of options, and asserts that `order` gives exactly what comparing two whole keys gives. Every setting that changes a level's layout is a branch inside `writeLevel`, which is why the options are generated rather than fixed. There is also a unit test in `src/key.zig` that asserts the levels written one at a time are byte-for-byte the whole key, over 480 combinations of settings. ### FCD proper, measured and declined The other half of §9.5 is skipping normalization for text that is merely *FCD* rather than NFD -- text like `Märtens` with the umlaut composed. It was costed rather than built, and the costing says no. **What it would take.** The table must map composed characters, which is the "canonical closure": the 2,081 entries the generator drops, plus a closure override in every *tailoring* for each composed character whose decomposition that tailoring changes the weights of. The input must be tested for FCD, which needs the leading and trailing combining class of each code point -- a table of its own, since those are properties of a code point's decomposition rather than of the code point. And the specification names a trap: a contraction that crosses a sequence boundary has to fall back to a full NFD, so the fast path must know when it cannot be taken. **What it would win.** `latin-nfc` and `latin-nfd` in the benchmark are the same twenty words in the two forms, and FCD input would be handled the way NFD input already is -- so the gap between those rows is the ceiling. It is 239 ns against 233 ns: **2.5%**, which is inside the benchmark's own noise. Composed kana would gain more, perhaps a tenth, because a voiced kana decomposes where a Latin letter with one mark barely does; ASCII, Han, Hangul and any text already in NFD would gain nothing at all, since they do not decompose in the first place. That is a poor trade for a new table, a closure in every tailoring, a second path through step 1 and a fallback rule -- and the earlier guess in this document that it was "worth about another 20%" was wrong. It came from reading step 1's share in an isolated loop, where the string is cache-hot and the share overstates what the same work costs inside a whole key. **And the closure cannot be taken from the data.** `allkeys_CLDR.txt` does carry mappings for composed characters, and 1,066 of the 2,081 agree exactly with what their decomposition weighs here; thirteen more differ only by completely ignorable elements the composed form omits, which a sort key discards anyway. The remaining **1,002 are CJK compatibility ideographs whose mappings are computed from the code point** -- U+F967 is `[.FB40.0020.0002][.CE0D.0000.0000]`, which is §10.1.3's formula applied to U+4E0D -- and this library weighs Han by CLDR's radical-stroke *rank* instead, because `allkeys_CLDR.txt` has no Han mappings and CLDR orders the URO by radical. Keeping those entries would make a compatibility ideograph disagree with its own decomposition: a closure that breaks canonical equivalence rather than preserving it. They would have to be computed through this library's own table, which is doable and is one more thing to get right. One more negative result from the same session, for whoever picks this up: carrying each decomposition's combining classes alongside its code points, so that the classes come out of the rows the decomposition was read from, is *slower* -- 9% on Hangul and 4% on Vietnamese. The second table walk is cheaper than the memory traffic of carrying the answer. ### Sort key encoding Every weight is a big-endian `u16`, every level separated by `0x00 0x00`. Zero weights are skipped (§7.3, S3.5), so the separator is below every weight that can appear and the prefix property of §7.3's note holds: `abc` < `abcX`. On top of that sits one compression: **§9.1.4's run-length compression** of the levels that repeat themselves. §9.4's zero-byte avoidance is not needed at all: a key is a Zig slice, not a C string. ### Run-length compression, which halves a key Sort keys repeat below the first level. 0x0020 is **94.6%** of the root tables' non-zero secondary weights and 0x0002 is **80.0%** of their tertiaries — and the non-zero weights are the only ones a key writes, since S3.5 skips the rest. A string of unaccented lowercase Latin letters has nothing else at either level, so its secondary and tertiary levels are one weight repeated as many times as the string is long. §9.1.4 replaces each maximal run of that most common weight — COMMON — with one synthetic weight standing for the run's length. The trick is where the synthetic weights come from and which end they are taken from. The real weights are moved out of the middle of the `u16` space: a weight at or below COMMON keeps its value, and one above COMMON is lifted to the top of the space, which leaves a gap of about 65,000 values between the two bands. A run is then written as one value out of that gap, and **which end of the gap decides the order**: * followed by a weight below COMMON, or by nothing at all, the run becomes `COMMON + length`, so a longer run sorts *higher* — right, because it is more of a weight that is higher than what follows it; * followed by a weight above COMMON, it becomes `MAXBOTTOM - length`, so a longer run sorts *lower*, which is the same statement read the other way. A run too long for one synthetic weight becomes a sequence of them. That needs 32,735 identical secondary weights in a row, which no corpus reaches, so the test reaches it deliberately: it encodes runs either side of that boundary both ways and requires every pair to compare the same compressed as uncompressed, which is exactly what §9.1.4 claims for itself. | corpus | key bytes before | after | |---|---|---| | ascii | 40.3 | **22.1** | | `latin-nfc` | 44.2 | **26.3** | | `latin-nfd` | 44.2 | **26.3** | | vietnamese | 54.6 | **35.2** | | hangul | 50.8 | **23.6** | | han | 20.0 | **16.0** | | japanese | 32.8 | **28.9** | **It costs nothing in time**, once the three functions that do it are `inline`. Without that it was 18% on step 3 and 3% on a whole key — a branch and a call per weight, against the handful of writes it saves — and with it ASCII writes its key in 70 ns where it took 68 to 73 uncompressed, which is inside the noise. The win is bytes: a sorted list of keys is half the size it was, and `order` and the buffered comparison are unchanged. The same mechanism covers §5.1's **case level**, whose weights are the three case classes and where a string of lowercase letters is one long run. ### The fourth level, where COMMON is at the top The fourth level is compressed too, and it needed the technique turned upside down. Under `shifted` every element that is not variable gets `max_quaternary` there — 0xFFFF — so COMMON is not a weight with room above it, it is the **largest weight the level can hold**. §9.1.4 opens its gap by lifting the weights above COMMON to the top of the space, and here there are none to lift. So the gap is taken from *below* COMMON instead. Everything else on that level is a variable primary weight, and those sit in one low band — 0x0201..0x04E0 in both root tables, kept contiguous by well-formedness condition WF4 — which leaves 0x8000..0xFFFE for synthetic weights with COMMON above all of them. `[reorder]` can move primary weights about, so that band is not fixed by the table alone; across all 135 tailorings CLDR ships none moves it at all, the highest reordered variable primary being 0x04E0, exactly where it started. The bound is set at 0x7FFF regardless and **asserted**, because relying on that measurement would be relying on data rather than on a guarantee, and a weight above the bound would misorder silently rather than fail. A test walks the whole variable band of every tailoring built. **A tailored collation writes that level as pairs**, the weight and its sub-weight, and the pair is the unit a run is made of. That is the part worth reading twice, because a pair *above* COMMON exists: a `<<<<` relation gives an element `(max_quaternary, q)` with `q` above zero, which is above `(max_quaternary, 0)` while beginning with the same weight. Japanese is the locale that has them. It works out because the band a run belongs in can still be decided from the following weight alone: a pair above COMMON begins with COMMON's own weight, which is not *below* COMMON, which selects the high band — and a variable element's pair begins with its primary weight, which is below COMMON and selects the low band. The synthetic weights sit below COMMON, so they are below every such pair and above every variable primary, which is what both cases need. There was once a `shift_trimmed` here too, §4's `shifted` with the fourth level's trailing maximum weights dropped. UCA 18.0 removed Shift-Trimmed from §4, and it went from here with it: nothing but its own test exercised it -- the conformance files are `shifted` and `non_ignorable`, ICU has no mode for it, and no CLDR locale asks for it -- and §4 had only ever called it a POSIX emulation, "otherwise not recommended". | corpus | quaternary key before | after | of which level 4 | |---|---|---|---| | ascii | 36.2 | **26.1** | 14.1 → 4.0 | | `latin-nfc` | 42.4 | **30.3** | 16.1 → 4.0 | | vietnamese | 57.4 | **43.0** | 22.2 → 7.8 | | hangul | 41.2 | **27.6** | 17.6 → 4.0 | | han | 26.0 | **20.0** | 10.0 → 4.0 | | japanese | 41.7 | **32.9** | 12.8 → 4.0 | Four bytes is the floor: two for the level separator and two for the one synthetic weight a whole level of maximum weights comes to. None of this shows at the default strength, where the fourth level is not written at all — it is what a key costs to a caller who asks for `quaternary` or `identical`, which is what the conformance runner asks for on all 872,037 of its cases. ### §9.3.3, reducing the repertoire `-Drepertoire=` generates a table covering only the Unicode blocks it names. Everything else loses its entry and is weighed from its own code point by §10.1.3, exactly as an unassigned character is — which is what §9.3.3 sanctions: "if characters are not fully supported by an implementation, then their code points can be treated as if they were unassigned". **Nothing in the library changed.** The lookup already falls back to `Table.implicit` for a code point it has no mapping for, and that computes from the code point value. So the whole feature is a filter in the generator plus a declaration of what survived. | repertoire | table | `stage1` | |---|---|---| | the whole of Unicode | 501.8 KiB | 3,586 | | `Basic Latin` | **2.0 KiB** | 1 | | `Cyrillic` | 4.1 KiB | 5 | | `Greek and Coptic` | 6.1 KiB | 4 | | the five Latin blocks a European application wants | 9.9 KiB | 33 | | those plus Greek and Cyrillic | 14.1 KiB | 33 | **Blocks and not scripts**, which was a measurement rather than a preference. Restricting by script sounds right and does not pay: `Common` alone is 9,123 code points scattered over dozens of blocks, so a Latin-by-script repertoire still keeps 79 of the table's 188 stage-two blocks — 158 KiB of the 376. Naming blocks keeps three. A range can also be given directly, as `0000..024F`, for a repertoire no block boundary describes. **The repertoire is closed under canonical decomposition**, and that was the bug. A canonically decomposable code point has no entry in *any* of these tables — step 1 has replaced it before anything is looked up — so it sorts by whatever its decomposition weighs. If the decomposition falls outside the repertoire, a character the repertoire *names* silently takes implicit weights and sorts after the whole table. U+0374 GREEK NUMERAL SIGN found it. It is in Greek and Coptic and decomposes to U+02B9 MODIFIER LETTER PRIME, which is in Spacing Modifier Letters, so a repertoire of Greek without that block put `0374 0062` after `0375 0021` — one line out of order in 7,294, and no other symptom. The generator closes the repertoire over decomposition now, repeatedly, because a decomposition can decompose again; Hangul is included arithmetically, since a syllable's decomposition is in no table. The closure is visible in what the generated table declares: ask for `Greek and Coptic` and the ranges come back as `003B..003B 00A8..00A8 00B7..00B7 02B9..02B9 0301..0301 0308..0308 0370..03FF`. **What checks it.** `zig build test-conformance -Drepertoire=…` runs the conformance files against the restricted table, skipping the lines that reach outside the repertoire — and that is a strong check rather than a weakened one, because the file is one totally ordered list, so every subsequence of it is ordered too and the lines that remain must come out exactly as they do under the full table. Restricting is supposed to leave them alone. The five-block Latin table answers 6,755 of the DUCET's 212,066 cases with none out of order; the Latin-Greek-Cyrillic CLDR table answers 10,841 with none. The skipping is decided on each line's *NFD*, not on the line as written, since that is what gets looked up — which is worth 2,000 more cases than the naive test, and is the same insight the closure bug turned on. There is also a test asserting the closure directly, and `Table.hasEntries` for the unit tests that read weights straight out of the table, which skip when a restricted build has not got them. **A tailoring is resolved against the unrestricted root**, and is not filtered. Two reasons, one of principle and one that stopped a build. The principle: a tailoring's weights are relative to root weights, and the entries a restriction leaves behind keep the weights they had, so the deltas are the same either way — and a tailoring that names a character the repertoire does not carries its own weights for it, which is the tailoring saying it supports that character. The build: a restricted root has no script *groups* left to resolve `[reorder Latn Kana Hani]` against, so `-Dlocales=ja` with a Latin repertoire failed with `UnknownReorderCode` until the generator was given the full table to read. When a restriction is asked for, the full table is generated a second time for the generator alone. **`stage1` stops at the last block that has anything in it**, which is where most of the saving above came from in the end. It was a fixed 4,352 `u16` indexing every 256-code-point block in Unicode — 8.5 KiB, and for a restricted table nearly all of it entries saying "no block". A Latin repertoire reaches U+206F, which is block 0x20, so 33 entries say what 4,352 were saying, and `Basic Latin` needs exactly one. Nothing in the library had to change for that: `rootEntry` already answers `Entry.none` for a code point whose block is past the end of the array, which is the same answer a `no_block` entry gives. It is worth 1.5 KiB on the full table too, which reaches block 0xE01 — the variation selectors at U+E0100 — and so stops 766 entries short of the top. That leaves `stage2` as the floor, at 2 KiB for a single block, which is the one thing a table for one block genuinely needs. ### Hangul and the trailing weights problem §10.1.6 describes four tailored methods — simple, data, terminator, interleaving — for the problem §10.1.4 raises: a Hangul syllable written as conjoining jamo has a different length depending on whether it has a trailing consonant, so `L V` and `L V T` are two and three weights, and what follows the syllable lands where the `T` would have been. None of the four is implemented here. What follows is what was measured instead, because the honest reason is not "later" but "CLDR does not do it either". **Syllables are decomposed, as S1.1 requires**, so U+AC00 is weighed as U+1100 U+1161 and the problem is reachable. The root table's jamo weights are contiguous and in code point order: | | primary weights | |---|---| | `a` … `z` | 0x23EC … 0x26EE | | L, the leading consonants | 0x4771 … 0x47ED | | V, the vowels | 0x47EF … 0x4835 | | T, the trailing consonants | 0x484D … 0x48A4 | | Hiragana あ | 0x48D6 | | Han | derived, from 0xFB40 | §10.1.6's methods all turn on making `T` outrank every other script, so that `L1V1T1` sorts above `L1V1Xa` for any following character Xa. CLDR's root does not: Hiragana and Han sit above T. So the anomaly is present, and this is what this library orders — with the shapes named as §10.1.6 names them, and `가` for `L1V1` and `각` for `L1V1T1`: ``` L1L2V1 < 가 < 가a < 가가 < L1V1V2 < 각 < 각a < 각一 < 가一 ``` `가一` last is the problem in one line: a syllable followed by a Han ideograph outranks the same syllable with a trailing consonant, where Korean dictionary order compares syllable by syllable and would put `가一` before `각`. `L1L2V1` first is the same problem from the other end — the data method would make `L1L2` a contraction, and without one the second leading consonant is compared against a vowel and wins. **ICU gives the same order**, which is what settles it. Those shapes are in the oracle's root corpus now — the precomposed forms beside the decomposed ones, each syllable alone and followed by a character from a script below Hangul and one above — and all 1,035 comparisons agree in every mode. So the anomaly is CLDR's answer rather than this implementation's, and applying any of §10.1.6's methods would make this library disagree with ICU and with CLDR on Korean text. That is a decision for whoever wants a Korean tailoring beyond CLDR's, not a defect to fix. It is worth saying where CLDR's Korean rules *do* go, since the answer was a surprise: `ko.xml`'s `standard` collation is 2,212 `&<<*` chains that order **Hanja by their Korean reading**, and tailors no Hangul at all. The conjoining jamo in that file are all in its `search` and `searchjl` collations, which are for matching rather than sorting and are not compiled here. Korean's 28,452,196 oracle comparisons are therefore about ideographs, and before these shapes were added nothing in this project compared a jamo sequence against what followed it. ### The rest of §9.1, and why the data settles most of it The one thing §9.1.4 says that is not done here is picking COMMON by measurement. The values are the specification's own — 0x0020, 0x0002, 0xFFFF — and the case level's is whichever class an uncased letter falls in. A tailoring could in principle make some other weight the commonest at a level, and would then compress worse rather than wrongly. * **§9.1.1, dropping the level separators.** The condition is that all L3 weights be below all L2 weights, and for the root collations it holds: 0x02..0x1E against 0x20..0x0127. For a *tailored* collation it does not. A tailoring's tertiary weights are chain positions rather than cases, and Arabic's tashkil run to 43, above the lowest secondary weight there is — so the technique would apply to the untailored collations and not to the tailored ones, which is worth less than it looks and is two encodings to keep right instead of one. * **§9.1.2, the levels in eight bits.** The tertiary level fits: 28 distinct non-zero weights, and 255 at the widest once `caseFirst` folds the case class in. The secondary level **cannot**, and no reassignment makes it: the root tables use 264 distinct non-zero secondary weights filling 0x20..0x0127 without a gap, and 264 values plus room for synthetic weights do not fit in 255. Narrowing the tertiary level alone was measured, after run-length compression had already taken most of that level away, and it was worth **two more bytes a key** — 22.1 to 20.1 on ASCII. That is not worth a second set of rules about how wide a retained separator has to be. * **§9.1.3, comparing as machine words.** The comparison is `std.mem.order`, which already goes a word at a time where the alignment lets it. A key is therefore comparable only with another key from the same collation built by the same version of this library. Nothing ever promised otherwise, and a stored key is not a stable identifier. A tailored collation writes **two** weights per element at the levels that hold a primary weight: the primary and the sub-weight it was inserted with, the pair being one weight in two halves. That is level one, and it is also level *four*, because what `shifted` alternate handling moves down to the fourth level is a primary weight and carries its sub-weight with it. An untailored key writes neither, so it is byte for byte what it was before sub-weights existed -- which is the encoding both conformance suites pass on. At `identical` strength the NFD of the input is appended as **three big-endian bytes per code point**, not as UTF-8. UTF-8 would order the same way, but it cannot encode a surrogate, and §12.2's files deliberately contain lines that hold one — that is the point of them. Three flat bytes have an answer for every value a `u21` can hold and still order by code point. Each code point is written one higher than itself, which still fits at U+10FFFF, so that U+FFFE can be written as zero; see below. ### Ill-formed input §10.1.1 offers two approaches. This library takes the second: a surrogate code point reaching the `[]const u21` entry point is weighted as an unassigned code point by §10.1.3, which is what lets the conformance files be run without filtering out the lines containing surrogates. The UTF-8 entry point instead returns `error.InvalidUtf8`, since a UTF-8 slice that holds one is a bug in the caller rather than an ordering question. ### U+FFFE, since UCA 18.0 UCA 18.0 made U+FFFE a real field separator rather than just a low weight. §10.1.5 reserves primary weight 0x0200 for it, below the variable band and never variable, and asks for two things of the sort key so that `a + U+FFFE + b` sorts as the merged keys of `a` and `b` would: - **A backwards level is backwards within each field** (S3.6). The elements are split at U+FFFE's, the fields are taken forwards and reversed one at a time, and the separator's own weight goes between them. A reversal of the whole level lets an accent at the end of the second field outrank one at the end of the first. - **The identical level gives U+FFFE "a minimal, unique weight"** (S3.10). §12.2's suite is what said so: eight lines, all of the shape `l` U+FFFE U+1D165 `f` before `l` U+0001 U+FFFE `f`, where both ignorables vanish from the first three levels and the identical level then has to put U+FFFE below U+0001. Writing it as zero and every other code point one higher does that. The backwards level has only the elements to go on, so `key.weigh` marks U+FFFE's element as it passes, by asking the table: it is the one element with a non-zero primary weight below the variable band, in both roots. CLDR has had U+FFFE at the bottom since long before UCA 18.0 and moved it from 0x0001 to 0x0200 in CLDR 49 to match. §10.1.5 also notes the cheaper reading -- common rather than unique low weights for U+FFFE at levels two and three, and no special handling but the backwards one -- and this is that reading. In both roots COMMON (0x0020, and 0x0002 at level three) is already the lowest weight any element puts at those levels, so nothing in them sorts between a field and its separator. ## What this looks like from zxsl `Transformer.sortNodes` already computes one key per node per sort level up front and compares with `std.mem.order(u8, ka.text, kb.text)`. The change is confined to how `Key.text` is produced: ```zig // was: keys[...] = .{ .text = text, ... }; keys[i * specs.items.len + level] = .{ .text = try builder.sortKeyAlloc(t.gpa, collator, text), .num = if (spec.numeric) value.stringToNumber(text) else 0, }; ``` The comparison line does not change, the stability rule does not change, and the numeric path does not change. `xsl:sort lang=` stays unimplemented until tailorings exist; `case-order` stays out of scope, at parity with libxslt, which marks its own argument `ATTRIBUTE_UNUSED`. ## The CLDR root collation CLDR publishes its root as `common/uca/allkeys_CLDR.txt`, in the same format as `allkeys.txt`, so it is a second table out of the same generator rather than a second code path. What CLDR changes before any language is considered: scripts are regrouped and the variable band narrows from 0x0201..0x221F to 0x0201..0x04E4 — symbols are variable in DUCET and not in CLDR. Both put U+FFFE, the sentinel for sort key merging, at 0x0200; CLDR added it first, and DUCET has had it since UCA 18.0. It is what ICU orders by. Two things had to be settled to make it work, and CLDR's own conformance suite is what settled them: - **The variable band**, above. - **The implicit weights.** `allkeys_CLDR.txt` carries no `@implicitweights` lines at all. Those parameterize §10.1.3's siniform rows for Tangut, Nushu and Khitan Small Script, and neither table gives those scripts explicit entries — so without the lines they would fall through to the unassigned formula and sort wrongly. The rule is UTS #10's rather than any one table's, and `FractionalUCA.txt` shows CLDR deriving the same `[.FB40.0020.0004][.CE00.0000.0000]` pairs for Han, so the generator takes the lines from whichever file is named as the source — for DUCET, itself. 210,186 cases apiece passing is the evidence that this is right. It is behind `-Dembed-cldr`, off by default, and the reason is the tests rather than the table. CLDR's conformance files are distributed only inside the CLDR repository, whose release tarball is 66 MB and unpacks to 409 MB. That is a lazy dependency and an ordinary build neither fetches nor unpacks it, but a default that did would be rude. The dependency will pay for itself when the per-locale tailorings arrive, since their rules are 135 more files in the same archive. ## Per-locale tailorings The rules are CLDR's, in the syntax of [UTS #35 part 5][ldml]: `&Y<<ü<<<Ü` makes ü a secondary variant of Y and Ü a tertiary variant of ü; `&[before 1]i<ı` gives ı a primary weight just below i's; `&t<<<þ/h` makes þ weigh as a tertiary variant of t followed by h. `tools/gen_tailoring.zig` parses them and emits a `Tailoring`. ### Two rules, and everything else follows The generator does two things, and the whole of §3.3 is in them. **A relation maps its target to a sequence, not to an element.** The cursor is the entire collation element sequence of the reset position, or of the previous relation's target. A relation increments the last element that is at least as strong as the operator, drops whatever followed it, and maps the target to what remains. So `&ae<102D><<<<1023>`, and while the generator emitted one element per target U+1023 weighed as a lone vowel sign instead of as the letter and the sign together. ICU disagreed with 101,098 of 543,403 comparisons. **A relation takes the position immediately after the cursor, and moves whatever is already there up one.** At primary strength that position is the next `primary_sub` under the cursor's primary weight. At secondary or tertiary strength it may be a weight the root already uses — `&i<<<İ` asks for İ immediately after i at tertiary strength, i has tertiary `0x02`, and U+FF49 FULLWIDTH LATIN SMALL LETTER I already holds `0x03` under the same primary and secondary, with no integer between them. That second half is the wall ICU's variable-length fractional weights exist to get over, because ICU applies rules at run time to a table it cannot renumber. A generator can: it shifts U+FF49 up to `0x04` and puts İ at `0x03`, since a shifted root element is just another entry in the delta. `makeRoom` does that — everything at or above the wanted weight moves up one, preserving their order among themselves and leaving the gap. Moving rather than counting is also what orders two chains that hang off the same anchor, and CLDR has rules whose entire meaning is that. Adlam tailors each letter twice, once per case, and a capital and its small share a primary weight in the root, so both chains ask for the same position and the second must push the first out. Burmese spells one syllable two ways and gives both spellings the same anchor and the same operator, so the second spelling must displace the first rather than land on it. A per-primary counter gets the first of those wrong; landing both on one position gets the second wrong; displacing is the only thing that gets both right, and it is what ICU does. `[before 1]` is the exception that proves the rule is about position rather than about order of arrival. It is pinned to the *anchor*, so it takes the top of the gap below it and displaces nothing — the previous primary weight is only how that space is addressed. Yiddish puts both `&<05E9><<05E9><05C2>` and `&[before 1]<05EA><<05EA><05BC>` in the gap between shin and tav, and the one pinned to tav belongs above the one inserted after shin. A root *contraction* whose elements have to move is handled by replacing it: a copy with the same code points and shifted weights goes in the tailoring's own list, which step 2 tries before the root's, so the copy shadows the original. That used to be a refusal and was eleven locales. One limit is left, and it is an approximation rather than a refusal. When the element an operator selects is an ignorable — `&D\u0335<<đ` selects the combining overlay's, which has no primary weight — the element with a primary before it is used instead, because this library's secondary weights are dense integers that every ignorable in the root shares, so making room between two adjacent ones would move every combining mark in the table and every root contraction that weighs one. That approximation orders đ after D with *any* mark where ICU puts it after `D\u0335` and before the next mark; it shows up only in comparisons between the tailored letter and its base carrying a different mark, and ICU agrees with all four of Finnish's rules of that shape, and with Lithuanian's and Kurdish's. ### Three things the data did not do as expected **CLDR's rule files are not consistently normalized.** `tr.xml` writes ç decomposed, as `c` and a combining cedilla; `sv.xml` writes å composed, as U+00E5. This is not a detail: step 1 of the algorithm normalizes its input, so a rule keyed on the composed form is keyed on something no lookup will ever see. Swedish generated cleanly, passed its own build, and changed no ordering at all — å was an override on U+00E5 that NFD had already dissolved into `a` and a combining ring before anything was looked up. The generator normalizes its operands now, which also decides override-versus-contraction correctly: after NFD, most accented targets *are* sequences. **CLDR does not close its tags uniformly, and a strict reader silently believed a locale had no rules.** `extractRules` searched for the literal ``; `pl.xml` ends its collation element with ``, so the search failed, the function returned null — which means "this locale has no tailoring and is ordered by the root" — and Polish generated cleanly, compiled, and ordered nothing. What makes this worth recording is how the oracle reported it: the corpus is built from the tailoring's own material, an empty tailoring contributes none, so the comparison was the bare alphabet a to z, ICU agreed about all 325 pairs of it, and the run said Polish had no differences. Seven locales were in that state. The close tag is matched allowing for spaces now, and the oracle reports an empty tailoring as an empty tailoring rather than comparing whatever is left. **A tailoring's overrides and its contractions are independent.** The overlay first took `Entry.starts_contraction` from the override when there was one, which loses any contraction starting at that code point. Swedish trips it exactly: `a` is shifted by `makeRoom` *and* is the first code point of the contraction that å became, so the override masked the contraction and the ordering the rule existed to fix disappeared. The flag is now the union of both lists and is set after the override rather than as part of it. Both of these produced a tailoring that built, loaded, and did nothing, which is the failure mode to fear here: there is no conformance suite for a tailoring, so a test that asserts a real expected ordering is the only thing standing between "generated successfully" and "correct". ### Settings are not table data Three of the parametric settings a locale can ask for -- `caseFirst`, `backwards` and `alternate` -- change how a sort key is *built* rather than what any character weighs. They live on `Tailoring.settings` as three optionals, where null means the rules said nothing, and `Options.applying` takes them up. Applied on request rather than automatically, because the locale's opinion and the caller's are different things: `xsl:sort case-order=` has an opinion about case and has to be able to win. That is the whole of what Danish, Maltese and Canadian French were refused for. `caseFirst` then turned out to need more than a setting. It was implemented by swapping Table 17's two cased bands of tertiary weights over, which is exact for the DUCET -- the band *is* the case there -- and wrong twice over once a tailoring is involved. The first way is that the bands are interleaved with weights in neither of them. 0x14 is `` and 0x1D is its uppercase counterpart, with nine other assignments between them, so no swap of pairs can put every uppercase form before every lowercase one. Danish asks for exactly that, and 330 of its 6,786 comparisons said so. The second is that a tailoring shifts root tertiary weights to make room, and one shift takes 0x0C to 0x0D, which is small hiragana and not uppercase anything. Danish shifts weights under the primary of H, and SCRIPT CAPITAL H then read as lowercase. So the case is a field of `Element` now, in the two bits the struct had spare. It takes three values, not two, because section 3.3 of LDML part 5 says a target of more than one letter can be mixed case and CLDR writes rules that depend on it: Danish orders `&å<< M the first M-1 are copied and the last takes the *combination* of root elements M-1 onwards, which is uppercase if all of them are, lowercase if none is, and mixed otherwise. Then a secondary element's bits are cleared, a tertiary element's are set to uppercase, and a completely ignorable one's are cleared. Three locales show why the properties are the wrong source. Croatian maps the single code points U+01C4 and U+01C5 onto `DŽ` and `Dž`; both are general category Lt, so the properties call both uppercase, where the root elements say one is two uppercase elements and the other an uppercase and a lowercase one -- mixed. Breton's `c'h` spellings are *all* mixed, C'H included, because the apostrophe between the letters is a primary root element with no case at all, so "all of them uppercase" is false. Hausa's `'Y` is mixed for the same reason. **With a case level the tertiary weight is unmodified.** The table of modified collation elements writes `p.s.t -> p.s.c.t`: the case weight goes on a level of its own and `t` stays `t`. Folding the cased band onto the uncased one as well looks harmless -- for a root element it even gives the same ordering -- but a tailoring's tertiary weights are chain positions, not cases, and nine of Arabic's forty-three tashkil land in 0x08..0x0C and were being moved down by six. **And the case level ignores what the table says to ignore**: every secondary ignorable at any strength, because `0.0.T` becomes `0.0.0.T`, and every primary ignorable at primary strength, because `0.S.t` becomes `0.0` -- which is what makes "ignore accents but not case" ignore them. Giving each of Arabic's tashkil a case weight made a string of two marks differ from a string of one at a level above the one the rules are about. One more line of the same section is worth writing down because it reads like an exception and is not: a tertiary element's case weight is the constant 3, whatever its case bits and whatever `caseFirst` asks for. UCA well-formedness condition 2 wants such an element above every primary and secondary one at that level, its tertiary weight is already above theirs, and a computed case weight of 1 under `[caseFirst upper]` would undo it. ### The abbreviated relation syntax `<*`, `<<*`, `<<<*` and `=*` each expand a run of single characters into one relation apiece, and a `-` between two of them means the code points in between as well, so `&a<*bcd-gp-s` is eleven relations. Two locales are written almost entirely in it: Korean uses `<<*` 436 times, once per syllable with its homophones after it, and `en_US_POSIX` writes the whole of printable ASCII as five ranges. LDML part 5 requires each character to be NFD-inert, and the generator checks that rather than assuming it, because a character that decomposed would quietly become a contraction of two elements instead of the letter the rule is about. What the parser did before is worth recording, because it is the same failure as every other one in this file: `<*` read as a primary relation whose target begins with an asterisk, so a whole run became one long contraction. That is why `en_US_POSIX` was refused for having a 27-code-point contraction and the real reason was this. No locale that compiled used the syntax, so nothing was silently mis-ordered -- but `fa`, `ps` and `ja` would have hit it the moment their other refusals were lifted. Korean needed two other things fixed to be reachable at all. **A setting's argument can be brackets of its own.** `[optimize [가-각간…]]` holds eleven thousand Hangul syllables, and the scanner stopped at the first `]`, leaving a stray one that became "UnexpectedCharacter at rule offset 7104". Macedonian and Serbian write `[suppressContractions [Ии]]` and were being *named* wrongly in their refusal for the same reason. **`makeRoom` walked all 1,114,112 code points per call.** That is fine for a locale with a dozen rules and not for one with 436 chains, each of which begins at a root element and so pays for a scan: the generator ran for tens of minutes. The code points it needs all share the candidate weight's primary, so the root table is indexed by primary weight once and the scan becomes a lookup; a hash from code point to override index replaced a linear walk at the same time. Korean generates in about two seconds now. And **an override that is only being moved is written over in place.** Korean shifts root elements 159,974 times, and appending the new elements to the pool on each shift left every superseded copy behind: 43 MB of generated Zig for a tailoring of 7,476 code points, which is now 2.4 MB. ### `[import …]` Six locales are written as another locale's rules plus a few of their own, and an import is exactly that: the imported rules processed where the `[import]` stands, against the same builder and the same cursor. The generator is handed CLDR's collation directory as well as the one file it was asked about, and the identifier names a file in it -- `sr-Latn` is `sr_Latn.xml`, `und` is `root.xml`, and `ja-u-co-private-kana` is the `private-kana` collation inside `ja.xml` rather than its `standard` one. Galician imports Spanish, Bosnian and Latin Serbian import Croatian, and all three now compile and agree with ICU -- and the oracle says so in a way worth noticing: `bs` and `sr_Latn` compare exactly the 5,253 pairs `hr` does, and `gl` the 406 that `es` does, because the corpus is built from the tailoring's own material and theirs is now Croatian's and Spanish's. The other three are still refused, and for the right reason: Dari imports Pashto, which would move a root contraction; Cyrillic Bosnian imports Serbian, which wants `[suppressContractions]`; and Japanese imports a kana collation that sets `[strength 3]`. A refusal naming what the *imported* rules ask for is the honest outcome, and it needed one fix to read that way -- the diagnostic slices the rule text around the offset where the failure was, and after an import those two come from different files. `fa_AF`'s own rules are twenty bytes long and the failure was at offset 33 of Pashto's, which panicked in the error path. The offset is restored on the way out of an import now, so the message points at the `[import]`, and the slice is clamped as well. ### Two settings that turned out to be small **`[suppressContractions [Ии]]`** turns off the root's contractions beginning with the code points in a set, and Macedonian, Serbian and Cyrillic Bosnian all want the same one: the root contracts и with a following combining breve into й, and they want the breve ordered as a mark after the letter. The tailoring carries the set as `Tailoring.suppressed`, sorted, and step 2 asks `Table.rootContractionsFor`, which answers with nothing for a suppressed code point. The tailoring's *own* contractions are untouched, which is what the setting says. The set is a UnicodeSet, and what the parser accepts is the part of that syntax CLDR's standard collations use -- characters, escapes and `a-b` ranges inside brackets. A property, a nested set or an intersection is refused by name rather than half-read, because a suppression that quietly covered the wrong characters would be invisible. It also needed the oracle's corpus widened, and that is the more interesting half. The corpus is built from what a tailoring *says*, and a suppression says nothing -- it takes something away. Macedonian's first clean run compared 2,346 pairs of the alphabet and the Cyrillic samples, not one of which contained a breve. The corpus now includes every suppressed code point and every root contraction beginning with one, which is 3,240 pairs for Macedonian, and the run means something. **`&[last tertiary ignorable]`** is a logical reset position, section 3.3's table of named boundaries in the weight space. Urdu adds five honorifics after it and Khmer maps two code points onto it with `=`, and they are the only two of CLDR's standard collations to use any of them. It needs no table of boundaries to answer: "after the last tertiary ignorable" is after everything that weighs nothing at all, so the cursor is the completely ignorable element and a relation increments from zero -- which is also, word for word, what the spec says to do with an anchor that has no element of the operator's strength. ### `[before 1]` inside the anchor's primary weight The last locale to disagree with ICU was `bo`, by 5,436 comparisons of 423,660, every one a Tibetan mark against a letter of some other script. Its rules do two things at once: `&[before 1]<0F40>` puts the marks before the first Tibetan letter, and `[reorder Tibt]` moves Tibetan ahead of Latin. `[before 1]` took the primary weight *below* the anchor's -- 0x37FC, where KA is 0x37FD -- and that weight belongs to whatever group comes before Tibetan, so the reordering moved Tibetan and left the marks among the Latin letters. So `[before 1]` takes the anchor's own primary weight now, with sub-weight zero, and `makeRoomSub` frees that by moving the root's mappings at that primary up one sub -- the letter the rule anchored on, its compatibility forms, and any root contraction that begins with one of them. The new letters are then inside the anchor's reordering group, which is the whole point. Two attempts at it broke something else first, and both were the same mistake: a weight moved twice. **A replacement must not be shifted by the call that creates it.** The root mappings are walked *after* the tailoring's own, because a replacement created for a root contraction is the tailoring's own from that moment, and a pass that shifted it again would move it two sub-weights instead of one. `makeRoom` had learned this a few commits earlier, on Burmese, and `makeRoomSub` had to learn it too. **A code point the tailoring already overrides must be skipped.** The pass over the tailoring's own elements has already moved it, and the root walk reads the current state, so it would move it again. Maltese is the case that proves it: five `[before 1]` rules, and U+1F18B -- the squared "IC" -- has an element at C's primary and one at I's. By the time the rule about i runs, 1F18B is already an override from the rule about c, and its I went to sub-weight two where every other I went to one. ICU disagreed with 24 comparisons, all of them a compatibility form containing I against that square. With those two right, every locale that compiles agrees with ICU on every pair it can be asked about. ### `[before 2]` and `[before 3]` The same idea, one and two levels down, and the reason they are worth a note is that they are *not* a new mechanism. `before` is a level and a weight rather than a flag: ```zig const Before = struct { level: Strength, weight: u16, below_common: bool = false }; ``` `[before 1]` takes the anchor's primary and sub-weight zero; `[before 2]` takes the anchor's own *secondary* weight, and `[before 3]` its tertiary, and in each case `makeRoom` moves the anchor up to free the weight the rule is asking for. Taking the anchor's own weight rather than the one below it is what the Tibetan section above is about, and it matters at every level for the same reason: a weight below the anchor's may belong to something else entirely. `ar` is the only locale asking for `[before 2]` and `ja` for `[before 3]`, so `[before 3]` is not exercised by the oracle -- `ja` is still refused for its quaternary relation. `[before 2]` is, by Arabic's 396,495 comparisons, and it found the one thing this shape gets wrong on its own. **A weight the `before` path chose must be freed whether or not `needsRoom` says so.** Arabic's P2 rule is a `[before 2]` with *two* secondary insertions under it -- farsi yeh, then alef maksura, both below yeh -- and the second one landed on the weight the first had already pushed yeh to. `needsRoom` is right to say no: it answers for a cursor that is the tailoring's own element with sub-weight zero, which is the shape that ordinarily needs nothing moved. But a `before` weight is occupied by definition -- it is the anchor's own, or the one the last insertion in the chain took -- so the room has to be made regardless. Without it alef maksura and yeh came out equal in 137 of ICU's comparisons. `[before 1]` never showed this because its own path calls `makeRoomSub` unconditionally; the two lower levels went through `needsRoom` and had to learn the same thing. **Below COMMON, when the anchor is an unaccented letter.** Moving the anchor up orders the variant below it just as well, and it is what this did for both of Arabic's rules until asymmetric search arrived. That gave teh 0x21 and teh marbuta COMMON, and section 11.2 calls the lowest weight unmarked, so `ة` found `ت` and `ت` did not find `ة`: backwards, and not what ICU does. ICU gives the variant a weight below COMMON and leaves the letter alone. So a `[before 2]` whose anchor has a primary weight and the COMMON secondary does that too. The root has nothing with a primary weight below COMMON, so 0x01 to 0x1F under any primary are free for the tailoring's own elements. Each insertion of the chain takes 0x1F, immediately below the letter, and the ones before it move down one -- the same shape as moving the anchor up, mirrored, and the reason the chain stays in rule order. Both of Arabic's rules go this way now, which leaves the shifting path above, and its lesson about `needsRoom`, for a `[before 2]` on an anchor that already has an accent. No locale CLDR ships writes one. Chinese's pinyin collations write `&[before 2]a<<ā<<<Ā<<á…` for every vowel and would want this most, but only a locale's `standard` collation is compiled, and Chinese has none. ### Five bits moved out of the sub-weight `Element` is forty-eight bits and was exactly full: a sixteen-bit primary, a sixteen-bit sub-weight, nine bits of secondary, five of tertiary and two of case. Arabic's tashkil chain is forty-three tertiary relations deep and five bits reach 31, so something had to give. What gave was the sub-weight, which is eleven bits now -- one to the tertiary level and, later, four to the quaternary weight the section after next is about. The measurement is the argument: over all 135 tailorings CLDR 49 ships, the largest sub-weight any of them reaches is 265 -- Burmese's, which inserts 255 consecutive primaries after one anchor -- so even the eleven bits it has now are seven times the headroom the data asks for, while the tertiary level was a factor of 1.4 short. The secondary level was not a candidate: nine bits reach 511 and the root already uses 295. (Japanese's 6,355-long chain is not a counterexample -- it rolls into fresh primaries rather than subdividing one, which is what the section on `&[last regular]` is about.) Two things had to follow. The generator's ceilings are read off the fields with `@FieldType` rather than written as `maxInt(u5)` and friends, so that a rule which does not fit is still refused by name when a field changes width. And `key.caseWeight`, which puts the case weight in front of the tertiary weight for `caseFirst`, multiplies by the size of the tertiary field rather than by a constant 0x20 -- with a six-bit field and the old stride, class 1 weight 0x21 and class 2 weight 0x01 both came to 0x41 and two different cases weighed the same. ### A contextual mapping is a contraction with a condition `prefix|target`, section 3.3: the rule applies to the target only when the prefix comes before it. Japanese writes 633 of them in the private kana collation it imports, giving an iteration mark or the prolonged sound mark the weights of the kana it follows, and it is the only collation CLDR 49 ships that writes any. (`ko.xml` has five as well, in its `searchjl` collation, which is not the one the generator reads, so Korean compiles without them.) The first design was a list of its own -- a `Context` type keyed on the pair, a `has_context` bit in `Entry`, a lookup in step 2 beside the contraction search. Measuring the data is what replaced it: in NFD both halves are one or two code points, because `が` is か followed by U+3099, so a contextual mapping is a mapping for a *sequence* with a condition attached. Which is to say it is a contraction with a condition, and `Contraction` carries a `prefix` now, empty for every mapping that is not conditional and so for every one in a root table. Everything S2.1 already does then serves it unchanged: the longest-match search, the discontiguous growth of section 7.2, and `Entry.starts_contraction`, which keeps the whole mechanism off the path of the 1,114,048 code points that start nothing. The prefix is a condition rather than part of the match -- it has been weighed as itself already and is not consumed -- so checking it neither consumes text nor changes how much of the string the match covers. The sort puts the longest prefix first within a target, so the most specific condition is tried first and an unconditional mapping last; and the generator replaces a mapping for the same sequence *and* the same condition rather than stacking a second one in front of it, which Japanese needs because `ja.xml` imports the private kana collation twice. What is not implemented is a discontiguous *prefix* match -- the prefix is compared against the code points immediately before the target, as the walk left them. No CLDR rule needs otherwise, and the alternative reading is not obviously right: the prefix is context rather than content. ### The fourth level, which a tailoring can write to after all UTS #10 says a fourth level exists in the algorithm (UTS10-D7) and never in a table, and for the DUCET that is exactly right: `Alternate.shifted` computes the level from the primary weight of a variable element when the key is built. A *tailoring* can put a weight there, and one does. `<<<<` is a relation at that level, Japanese writes 116 of them to separate katakana from hiragana, and the reason it wants the fourth level rather than the third is that it does not want the distinction at tertiary strength. So `Element` has a four-bit `quaternary`, zero for everything in a root table and for all but a handful of elements in a tailored one. Four bits because every one of Japanese's chains is one step deep; the weight came out of `primary_sub`, which is eleven bits now against a measured maximum of 265, and a rule that wanted more is refused by name rather than wrapping. **The two uses share the level, and the key keeps them apart with a pair.** Exactly as level one writes a primary weight and its sub-weight, level four writes a high half and a low half for a tailored collation: the high half is the element's own primary weight when shifting moved one down, and otherwise `max_quaternary`, a marker above every weight shifting can produce; the low half is the element's quaternary weight, or the shifted primary's sub-weight when it was shifting that wrote the high half. That ordering is ICU's rather than a reading of the specification, which does not contemplate both uses at once. Asking it settled the question in one run: for Japanese under shifted handling, a hyphen followed by katakana sorts *before* hiragana followed by a hyphen, which puts every shifted primary weight below the marker. **The level is written under `non_ignorable` handling too.** A `<<<<` difference is not conditional on how punctuation is handled, and ICU answers identically in its quaternary and shifted modes, so `weigh` produces the fourth level for both. For an untailored collation that makes the level one repeated weight, which cannot change an ordering: two strings that are equal at the first three levels have the same number of elements contributing to each of those levels -- a primary element contributes at the first, a primary ignorable at the second, a secondary ignorable at the third -- so they have the same number of elements here. Both conformance suites, which compare at identical strength, are unchanged by it. What it costs is two bytes an element in a key built at quaternary strength or above, and nothing at all at the default strength, where the level is not written. ### 6,355 kanji at the top of the regular space `&[last regular]<*` and the JIS-ordered kanji after it is Japanese's own rule rather than the private kana collation's, and it was the last thing CLDR asked for that this could not do. Two questions, and ICU had to answer the second. **Where the chain's weights come from.** A primary insertion ordinarily subdivides the weight it goes under, because DUCET's primaries are consecutive and leave nothing between two of them; at the top of the regular space there is nothing to insert *between*, so a chain there takes fresh weights. It takes them as (primary, sub-weight) pairs, rolling the primary when the 2,047 sub-weights under one run out, because that pair is what a sort key compares lexicographically at the first level and 6,355 does not fit in 2,047. **Which reordering group they belong to**, which is the part that cannot be reasoned out from the rule text. Japanese also asks for `[reorder Latn Kana Hani]`, and ICU sorts those kanji where Han sorts: after the kana, before the untailored ideographs, with Hangul after all of them. This library lays section 10.1.3's derived weights out at fixed primaries -- Table 16's order, the siniform leads at 0xFB00 and the Han ranks at `implicit_primary_base` -- which leaves sixty primary weights unused between them. CLDR's fractional space has no such gap: the implicit Han weights begin immediately after the last regular weight, so "after the last regular weight" and "before the first Han weight" are the same place there, and a tailoring inserting at one is inserting at the other. So the band is allocated from the bottom of the Han group, and `reorderGroups` extends that group's declared range down to cover it. Allocated instead just above the last regular weight -- which is what the rule appears to say, and what the first attempt did -- the kanji fell inside whichever script ends the regular space, which is Anatolian Hieroglyphs, and sorted after Hangul. It was 864,280 of Japanese's 24,468,510 comparisons, and the only thing that could have said so is ICU. ### The directional marks around Arabic rules `ar.xml` writes its rules with the operands wrapped in U+200E LEFT-TO-RIGHT MARK, which is what makes them readable in a left-to-right editor: ``` &[before 2]ت<<ة &[before 2]ي<<ی<<ى ``` where `` stands for the mark itself, which is invisible where it actually appears. Read literally, the second rule says something about the two-character sequence LRM + yeh. It does not: the mark is punctuation around the rule, in the same class as the whitespace CLDR also puts between operands, and the letter the rule is about is bare. ICU's own `getRules` hands the marks back unchanged and orders ة before ت, which is only possible if it reads the rule the same way. So `skipSpace` skips U+200E and U+200F, and `string()` stops collecting at one, and nothing else in the generator has to know. ### Script codes that are not distinct scripts `[reorder …]` names groups by script code, and three of the codes CLDR uses are not groups of their own. LDML part 5 says why, in one line that saves a table: "There are no mappings for Hrkt, Hans, or Hant because they are not fully distinct scripts; they share primary weights with other scripts: Hrkt=Hira=Kana & Hans=Hant=Hani." `FractionalUCA.txt` agrees, declaring the kana group as HIRAGANA and the Han group as HAN and neither of the others at all. `Group.alias` is that line: `Kana` and `Hrkt` resolve to `Hira`, `Hans` and `Hant` to `Hani`. `ja` asks for `[reorder Kana]`, which was a refusal reason of its own until the spec was read. ### Han in CLDR's order The other difference that was left is not left: **CLDR orders Han by radical and stroke count, and this library now does too.** Section 10.1.3's implicit weights are computed from the code point, which is what the DUCET describes and what this did everywhere. CLDR's root orders the Unified Repertoire by radical and stroke instead, and declares that order in `FractionalUCA.txt` -- 214 lines of the form `[radical 87=⽖爫:爫-爯…]`, each listing one radical's ideographs in sequence. What `allkeys_CLDR.txt` has to say about Han is *nothing*: it carries no Han mappings at all, so a table built from it alone keeps the implicit order and there is nothing in that file to suggest otherwise. Probing ICU with hand-written pairs is what found it. `und 7fff 8000`, `und 722b 722c` and `und 4e00 9fef` all agree, so it was not the lead-byte boundary or the implicit formula's arithmetic; `und 9fef 9ffe` said `ours=lt icu=gt`, and U+9FFE belongs to an early radical where U+9FEF belongs to a late one. Six locales differed by 34 comparisons each because of it -- every one a CJK radical against an ideograph -- and any comparison of two ideographs could have. The order is kept as `Table.han_order`: the ranges those lines describe, each with the rank of its first ideograph, and an implicit weight computed from the rank rather than the code point. 24,005 ranges cover 101,997 ideographs, which is every Han code point CLDR classifies; the compatibility ideographs are not among them because NFD has replaced them before anything is looked up. They are emitted as bare integers and bitcast in one go, which is 400 KB of generated source where a struct literal apiece would be a megabyte, and 192 KB of table. Two things about it were not obvious. **The radicals are written out by hand, in the old encoding.** `allkeys_CLDR.txt` has 1,466 entries of the shape `2F00 ; [.FB40.0020.0004][.CE00.0000.0000]` -- KANGXI RADICAL ONE saying "sort like U+4E00, with a tertiary difference" in section 10.1.3's code-point encoding. The Kangxi radicals, the CJK radicals supplement, and the circled, parenthesised and squared ideographs are all like that. A table that has switched to ranks for everything it *computes* has to switch these too, or a radical and the ideograph it stands for part company: that is what the six locales were still reporting after the first attempt. **The ranks need four lead weights, and there is room.** 101,997 ranks is 0xFB40 to 0xFB43, where section 10.1.3 uses 0xFB40 and 0xFB41 for the core Han blocks and 0xFB80 upwards for the rest. So an ideograph CLDR has not classified -- one newer than the release, of which there are none today -- takes 0xFB80 and sorts after every ideograph that is classified, rather than among them. The DUCET table keeps section 10.1.3's order, because that is what the DUCET *is* and what its conformance suite tests. CLDR's own suite barely tests Han: 45 of its 210,186 lines contain a unified ideograph, and between them they use nine: U+4E00 to U+4E05, which radical 1 happens to order the same way as the code points, and three from the extension blocks. Both suites pass unchanged. **Tibetan's `[before 1]` lands outside the group it reorders.** `bo` differs by 5,470 comparisons of 423,660, all of them a Tibetan mark against a letter of some other script. Its rules do two things at once: `&[before 1]<0F40>` puts the marks before the first Tibetan letter, and `[reorder Tibt]` moves Tibetan ahead of Latin. `[before 1]` takes the primary weight *below* the anchor's -- 0x37FC, where KA is 0x37FD -- and that weight belongs to whatever group comes before Tibetan, so the reordering leaves the marks behind among the Latin letters. The fix looks obvious and is not: take the anchor's *own* primary with a sub-weight below it, which keeps the marks in the Tibetan group. Doing that means moving the anchor up a sub-weight, and then a contraction that begins with the anchor compares wrongly against the anchor alone -- Tibetan's own `&<0F40><0F62><<0F40><0F62><0F90>`, Turkish's fullwidth i, and Tamil's க்ஷ all said so, in one to three comparisons each. It wants an answer that keeps both, and until there is one the 5,470 stand. ### What ICU says `zig build oracle` is the acceptance test for the tailorings, because nothing else is: CLDR ships no conformance data for them. It dumps every pairwise comparison over a corpus built from each tailoring's own material and asks `icu::Collator` the same questions. The two must be on the same Unicode for the answers to mean anything, and they are not always. ICU 78 is Unicode 17.0.0 and CLDR 48; this is Unicode 18.0.0 and CLDR 49. To ICU a character added in 18.0.0 is unassigned and sorts after everything, and the first run after the move found 91,741 differences, every one of which held such a character and none of which held anything else. So the dump records the Unicode version its tables were built from, and while ICU's is older the oracle sets aside any pair holding a code point whose `u_charAge` is 0.0.0.0 -- one ICU says was never assigned -- and prints how many: 180,002 of about 56 million. Once ICU catches up nothing is set aside. It earned itself on the first run. Turkish disagreed with ICU on 21 comparisons, every one of them capital I against some lowercase-i variant — ℹ, ⅈ, ⅰ, ⓘ, i, the mathematical i's. The cause was `makeRoom` reading the *root* table when deciding what to shift. Turkish's rules are `&[before 1]i<ı<</uca/`, and that copy is immutable: `Public/17.0.0/uca/CollationTest.zip` is byte for byte the zip `latest/` served a year ago. `latest/` moved to UCA 18.0.0 on 2026-08-26, the pinned hash stopped matching, and the build could not fetch the conformance suite at all until the dependency was pointed at the numbered copy. Two lessons, and the second is the one worth keeping: a directory listing that does not contain what you want is evidence about that listing and not about the archive. Options, following zig-datetime's shape: - `-Dembed-ducet` (default true). Off, the table is empty, every code point takes §10.1's derived weights, and the ordering collapses to roughly code point order — useful only to a caller that will supply a `Table` of its own and would rather not compile a 48,128-entry one it will never read. - `-Drepertoire=…` — §9.3.3, restricting the generated tables to named Unicode blocks, or to ranges written directly as `0000..024F`. It applies to both roots, since a build embedding one of them wants the same repertoire from either. "§9.3.3, reducing the repertoire" above has what it costs and what it is checked against. It was listed here as `-Dducet-repertoire=` before it existed; naming DUCET in it was wrong, the CLDR root wants it just as much. ### What the generator refuses The representation rests on properties of the data, so the generator checks them at the one moment a whole table is in hand, and stops the build rather than emitting something subtly wrong: - **WF4, in the form this library needs it.** The highest variable primary weight must be below the lowest non-variable one, or `Table.isVariable` cannot be a single comparison. - An expansion longer than `data.max_expansion` (18). - A contraction longer than `Contraction.rest` holds (3 code points). - A collation element with a fourth weight, which the table has nowhere to put. - The three data files naming different Unicode versions. - A `Unified_Ideograph` range straddling a CJK block boundary, which would mean Table 16's core/other split needed splitting ranges rather than classifying them. ## Testing **The conformance suite is the acceptance criterion, and it passes.** `CollationTest.zip` (4.95 MB, a lazy dependency — this one *is* an archive, so Zig will fetch it) holds four files; the `_SHORT` variants are 2.3 and 2.5 MB and carry 212,066 cases apiece. §12.2 gives the procedure: each line must order at or after the one before it, at identical strength. `CollationTest_NON_IGNORABLE_SHORT.txt` and `CollationTest_SHIFTED_SHORT.txt` between them pin both `Alternate` values that matter. Both run clean, with none of the lines containing surrogates filtered out — §12.2 permits filtering them, and this implementation does not need to, because §10.1.1's second approach weights a surrogate as a reserved code point. It is an executable rather than a `zig build test` binary, because a Zig test binary takes no arguments and the suite's path is a lazy dependency that only resolves at make time. Being a program also means it can report every out-of-order line rather than stopping at the first, which is what made it usable while the implementation was still wrong. Alongside it, `zig build test` — because a conformance failure 100,000 lines in is not a diagnosis: - The case from the issue: `Märtens` < `Möller` < `Mueller`, which the root collation gets right with no tailoring, because ä, ö and ü take the same primary weights as a, o and u. - Worked examples from the specification wherever it gives one. Figure 3's four levels; §4.1's Table 12, both the `non_ignorable` and the `shifted` column, ten strings apiece; §10.1.3's `[.FB40.0020.0002][.CE00.0000.0000]` for U+4E00; §3.5's note that U+034F COMBINING GRAPHEME JOINER breaks a contraction, tested against a contraction taken out of the table rather than named; NFD's deepest case, U+1F82 through three levels to four code points. - Weights checked against `data/allkeys-18.0.0.txt` rather than against the specification's examples. §12.1 says outright that the values in it "may not match the actual values in the current data file", and they do not — `A` is `[.2485.0020.0008]` in DUCET 18.0.0 and `[.06D9.0020.0008]` in the specification's illustration. Three tests failed on that before the data was consulted. - `Blanked` is deliberately *not* tested against Table 12. It leaves four of those ten strings equal at every level it looks at, so their order in the table is the sort's stability rather than the collation's answer. `zig build fuzz` is a loop of this project's own, of the shape merle65 and zig-ftp use, over the properties a collation owes whatever its table says: comparison reflexive, antisymmetric and transitive; a reused `Builder` agreeing with a fresh one even after a different string under a different collation; each strength refining the one below it; NFD idempotent; a string and its own NFD producing byte-identical keys; and the code point and UTF-8 entry points, which decode independently, agreeing. **The structure lives in the targets, not in the generator**, and that is the whole lesson of building this. A driver emitting uniform code points cannot reach S2.1.1 to S2.1.3 at all: only 19 of DUCET's 964 contractions have a non-starter as their second code point, which is what makes a discontiguous match possible, and reaching one also wants an intruding mark of strictly lower combining class between the halves. Three particular values in a particular order is not a rare event when drawn independently out of a million code points, it is an absent one — so the trickiest code in the library was getting no coverage whatever while the run reported no findings. Five of the thirteen targets now build their strings out of the table's own material and spend their randomness on which contraction and which marks. `order-agrees` draws half its strings that way and half uniformly, because what it is checking is a level's layout rather than a match, and it wants both the contractions that make the levels interesting and the spread that a contraction table does not have. The best of them is `reordered-marks-agree`, because it is the only thing that checks the two halves of S2.1 against *each other*. Two non-starters of different combining class are canonically equivalent either way round, since NFD sorts them identically however they were written; so swapping them must not change the key by a byte. But swapping a mark is exactly what turns a contiguous contraction match into a discontiguous one, so the two strings arrive at the same answer down two different code paths — one through the longest-match branch, one through the lookahead that skips unblocked non-starters and removes what it consumed. **The driver counts how many inputs reached an assertion** and prints it beside each total, because a target that gives up on its input is indistinguishable from one that works: both report millions of iterations and nothing found. That count earned itself immediately. `std.testing.Smith` answers a value outside the range a target asked for with that range's *minimum* rather than reducing it into range, so a generator whose distribution is too wide picks the first entry of every table every time — `reordered-marks-agree` was drawing the same mark twice on nearly half its inputs, and `Strength` was `.primary` on nine in ten. Two narrower buckets fixed both, and the count is how either was visible at all. This is a driver of its own rather than `zig build test --fuzz`. It was written when Zig 0.16.0 could not build a test executable in fuzz mode; Zig 0.17 can, with coverage feedback when LLVM compiles the test binary, but the targets have not been moved onto it. ## Deliberately later Everything that used to be on this list has been done or costed and declined, and the sections above say which and how. What is left: - **A contextual mapping wider than two code points on either side**, and a discontiguous match of a mapping's *prefix*. Neither is asked for by CLDR 49 -- every one of Japanese's 627 is one or two code points each side, and the prefix is compared against the code points immediately before the target -- and the second is not obviously right even in principle, since a prefix is context rather than content. - **The rest of §9.5, avoiding normalization** -- costed and declined rather than pending. "FCD proper, measured and declined" above has the numbers: the ceiling is 2.5% on composed Latin text, and the price is a canonical closure in the root table and in every tailoring, a table of leading and trailing combining classes, and a fallback rule. It would want revisiting for a workload of composed kana, where the ceiling is nearer a tenth. - **§10.1.6 Hangul** -- measured and declined rather than pending. "Hangul and the trailing weights problem" above has the order this library produces for that section's own shapes, the root table's jamo weights that explain it, and the reason applying any of the four methods would mean disagreeing with ICU and with CLDR. It was cited here as §10.1.5 for a while, which is *Reserved Weights*; Hangul Collation is §10.1.6. [ldml]: https://www.unicode.org/reports/tr35/tr35-collation.html