The Unicode Collation Algorithm (UTS #10) and CLDR locale tailorings in Zig: sort text the way people expect rather than by code point.
zig-collate DESIGN.md
130 kB · 2,274 lines
Markdown
at main

zig-collate — design #

A Zig implementation of the Unicode Collation Algorithm, UTS #10, 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.

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.

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.

/// 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.

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 &<syllable><<*<homophones> 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:

// 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: &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<x maps x to two elements, a's and one primary-after e's, and x sorts between "ae" and "af" — which is what an expansion is. Getting this wrong is not subtle at scale: Burmese writes its independent vowels as tertiary variants of two-character sequences, &<1021><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 </collation>; pl.xml ends its collation element with </collation >, 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 <super> 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 &å<<<aa<<<Aa<<<AA and Maltese &[before 1]h<għ<<<gĦ<<<Għ<<<GĦ, both putting the mixed spellings between the two uniform ones. A sort key writes the case weight in front of the tertiary weight when caseFirst is on and writes the tertiary weight alone otherwise, so the field costs nothing until it is asked for.

ICU keeps its case bits in a field of their own, for what are evidently the same two reasons.

Section 5.1 is an algorithm, not a principle #

Where the bits come from, and what is done with them, was reasoned out from the shape of the data for a while. It did not need to be: LDML part 5 section 5.1 specifies both, and four separate defects came of not reading it. Each one was invisible at the settings CLDR's locales actually declare and showed up the moment -Doracle-mode= asked a hundred locales about a setting two of them use.

The root's case values are a named set of tertiary weights. "UPPER if x is in {08-0C, 0E, 11, 12, 1D}", and there is no MIXED in the root collation. The first five and the last are what UTS #10's Table 17 reads at a glance; 0x0E, 0x11 and 0x12 are not, and 0x11 and 0x12 are the halfwidth forms -- so the halfwidth voiced sound marks at U+FF9E and U+FF9F are uppercase, and under [caseFirst upper] they belong before the combining marks they are forms of. Ewe and Vietnamese each had two comparisons of six hundred thousand say so.

A tailored mapping's case bits are computed from its root elements. Not from the Unicode case properties of the target, which is a different question and gives different answers. The algorithm: N is the number of primary root collation elements of the target string and M the number of primary elements the tailoring maps it to; if N <= M the root's bits are copied one for one and any remaining tailored element is cleared; if N > 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:

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]ت<<<LRM>ة
&[before 2]<LRM>ي<LRM><<ی<<<LRM>ى

where <LRM> 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<ı<<<I and then &i<<<İ: the first moves I to be a tertiary variant of dotless ı, and the second needs room under i's primary — where I used to be. Reading the root found I still at i's primary with tertiary 0x08, shifted it to 0x09, and wrote that over the override the earlier rule had just made. It reads the tailoring's current answer now, so a code point an earlier rule has moved is somewhere else and is left alone.

That is a bug no test in this repository would have found. Swedish passes either way, the conformance suites do not exercise tailorings at all, and the Turkish test asserted the ordering of Turkish letters, which was right — what was wrong was capital I against a circled lowercase i, which nobody writes a test for and ICU knows about anyway.

The standing result, against ICU 78.3 over all 135 locales: all 101 that ICU can answer for agree with it on every pair, over 58,169,711 comparisons. Korean is 28,452,196 of those and Japanese 24,468,510, those two being the largest tailorings CLDR ships. Of the rest, 23 are locales CLDR gives no tailoring, ICU has no collation data at all for seven -- Church Slavonic among them -- and it knows four but carries no tailoring for them.

Getting there took some fifteen findings, and almost every one was a rule shape the generator had not had to handle rather than an arithmetic slip. Tamil's [before 1] on an anchor that an earlier rule had given a sub-weight, asking for a root primary weight beneath it. Adlam's two chains per letter, which a per-primary counter put in the wrong order and a shared position left case-blind. Burmese's independent vowels, which are tertiary variants of two-character sequences and so must map to two elements rather than one -- 101,098 comparisons of 543,403, the largest single finding of the project. Burmese again, for the two spellings of one syllable that share an anchor and an operator and must therefore displace one another. And Yiddish, which puts a [before 1] rule and an ordinary one in the same gap and settled that [before 1] takes the top of it. And Danish and Maltese, which asked for [caseFirst upper] and showed that emulating it by swapping Table 17's cased bands is not what it means -- the section above is that one. And Arabic, whose [before 2] chain inserts twice under the same anchor and needs the second insertion to move it again.

And three more found by asking the oracle a different question. The comparison had always been tertiary strength with non-ignorable alternate handling, which is what a tailoring is about; -Doracle-mode= asks the other four, and each is a different path through the sort key builder that the conformance suites cover for the two roots and nothing covered for a tailoring.

shifted -- quaternary strength with shifted alternate handling -- found two in key.write. A variable element that shifted handling had made completely ignorable still wrote a tertiary weight under [caseFirst upper], because the case weight folded into that weight is not zero even when the tertiary is; and the fourth level was writing a primary weight without the sub-weight that belongs behind it, so two Thai punctuation marks that a [before 1] rule had put at one primary with different sub-weights compared equal. Danish was 21 comparisons and Thai was one.

secondary found the third, in the generator, and it is the only finding so far that a truncated key shows: the ignorable-anchor fallback was being applied to tertiary relations as well as secondary ones. Yiddish's &פֿ<<<ף makes final pe a tertiary variant of pe with a rafe, and dropping the mark to bump pe's tertiary instead made final pe equal to bare pe at the secondary level, where ICU orders them. The fallback exists because the secondary space between two adjacent combining marks is full; the tertiary space inside one mark is not, so <<< keeps the mark and bumps its own tertiary weight now. At tertiary strength both orderings agree, which is why one comparison of 4,095 sat there unseen.

case_level, upper_first and lower_first force a case setting on both sides rather than reading it from the locale, and found four more: the case section above is all of them. They are the ones that make the case for asking a different question at all, because between them CLDR's locales declare [caseLevel] once and [caseFirst] twice, and one of those three is a locale ICU cannot be asked about -- so the case handling was being exercised by two locales out of a hundred until the mode existed.

primary and identical found nothing, which is worth saying: the first says the truncation is not where the Yiddish fault lay, and the second says the identical level -- three flat bytes per NFD code point, one higher than the code point -- orders the way ICU's does. quaternary, added with the fourth level itself, found nothing either and is the mode that says the fourth level a tailoring can write to and the one shifted synthesizes stay out of each other's way.

And two in Japanese, the last locale to compile. A contextual mapping's condition was checked where S2.1 matches contiguously and not where S2.1.1 grows a match across skipped non-starters, so every ゞ -- ゝ and U+3099, a non-starter -- took the second route and the first contextual mapping in the list whatever stood before it: 864,568 comparisons of 24,468,510. And the 6,355 kanji at &[last regular] landed in the reordering group of whatever script ends the regular space rather than in Han's, which put them after Hangul: 864,280 more. The two sections above are those.

Each of the sixteen was found by the oracle and by nothing else. The unit tests assert the ordering of the letters a locale's rules are about, which was right in every one of these cases; what was wrong was a capital against a circled lowercase, or one spelling of a Burmese syllable against another, and nobody writes those tests by hand.

The oracle detects the empty and absent cases rather than counting them, which matters more than it sounds. ICU answers a request for a locale it does not know with its root, silently and successfully; and a request for one it does know but has no rules for with the root under that name, which a valid-locale check does not catch. getRules() returning empty is the only way to tell the second apart, and between them the two cases accounted for 640 of the 952 differences in the first run that handled neither.

Catalan is the cautionary tale. Its six disagreements looked like a real finding, and I built an argument for one: the rule chain &L<ll<<<l·l<<<lL<<<... interleaves middle-dot forms with case forms, ICU's order grouped the plain forms before the dotted ones, and the two orderings differ in exactly six pairs -- which matched the six differences precisely, so I concluded ICU derives tertiary weights from case bits rather than from chain position. That was wrong. oracle --rules ca returns nothing: ICU has no Catalan tailoring, was ordering by the root, and the root groups the dotted forms after the plain ones for ordinary reasons. An inversion count that fits is not a mechanism.

There is no remaining disagreement. The last one to go was Arabic's, and it was the last locale to compile as well: the section on [before 2] above is that one. What is left is not a disagreement but an absence -- eleven locales ICU cannot be asked about, seven because it has no data for them and four because it knows them and carries no rules. Church Slavonic is in the first group and is the one worth naming, since it asks for five settings at once and nothing has compared it against another implementation.

The one approximation that remains is the ignorable-anchor fallback described near the top of this document, under Finnish's &D\u0335<<đ: ICU agrees with every one of the rules of that shape that CLDR actually writes, which is why it is a documented approximation rather than an open finding.

Reordering #

[reorder ...] is implemented, and the design is UTS #35 part 5's rather than inferred -- three attempts to derive the model from the data files failed, and the reason is that the specification says not to. Group boundaries are declared: FractionalUCA.txt carries 163 markers of the form FDD1 004C; [2A 02 02, 05, 05] # LATIN first primary, the group begins at the next real mapping after the marker, and that mapping's character sequence looked up in the root gives the 16-bit primary weight. Each group runs to the next one's start, so they partition the weight space contiguously by construction.

The rule's interpretation is the specification's four steps, and it is short enough to state: core codes not named go to the front in a fixed order, others goes at the end if absent, others expands to the unnamed groups in root order, and that is the ordering. Groups are then laid out from the low end of the span and each one's displacement recorded, so Russian's whole tailoring is four ranges.

Three exemptions are easy to miss and all three are handled: the TRAILING group, U+FFFE's field separator and every zero-primary element do not move. unassigned is dropped from the group list entirely -- its weights are computed by section 10.1.3 rather than tabulated, and its marker resolves through the root to U+FFFE's bottom weight, so leaving it in made it the base the whole layout was measured from and shifted every group by 512. The specification puts unassigned-implicit weights last within others; this does not, they move with whichever group ends the space, and no CLDR locale reorders that group so nothing exercises the difference.

And the fourth thing the specification is explicit about, which fell out for free: variability is decided before reordering. key.weigh completes before key.write touches a weight, so the variable band is read from the untailored primary and the reorder is applied after.

What is refused #

Nothing. All 135 of CLDR 49's locale files compile -- 112 tailorings plus 23 locales the root collation already answers for -- and every one of the 101 ICU can be asked about agrees with it on every pair, in all nine of the oracle's modes.

The generator still refuses by name rather than approximating, and the errors are worth keeping: OutOfSubWeights, OutOfSecondaryWeights, OutOfTertiaryWeights, OutOfQuaternaryWeights and OutOfRegularPrimaries when a rule asks for a weight there is no room for; UnsupportedContextualMapping for a contextual mapping wider than the pool it is stored in; UnsupportedResetPosition for a logical position that is not one of the four CLDR uses; ContractionTooLong, StarredCharacterNotInert, TooManyRelationOperators. A future CLDR release that asks for something new gets told which locale and which rule, rather than being compiled wrong.

Eleven groups of refusals have gone since this section was first written, and almost every one went by finding out what the rules meant rather than by adding a setting: [reorder …] was 45 locales; a secondary insertion that would move a root contraction was 11; [import …] was 6; [suppressContractions] was 3; the logical reset positions in the ignorable space were 3 between them; [caseLevel on] was 1; [strength N] was 1; [before 2] and [before 3] were 2; the directional marks CLDR wraps its Arabic operands in were 1; &[last secondary ignorable] was 1; and Japanese's three -- a quaternary relation, 627 contextual mappings and 6,355 kanji at &[last regular] -- were the last.

[strength N] is the one worth a sentence on its own: it is the default number of levels to compare, which is an Options field, so the tailoring records it in Settings like caseFirst and the other three. ja asks for 3, which is the default this library already has, and it is recorded rather than waved through because a locale that asked for 1 would mean it.

The one thing to say about cu: ICU has no Church Slavonic collation data at all, so the oracle cannot check it. It compiles, and [caseLevel on], [caseFirst upper], [backwards 2], [reorder Cyrl] and [suppressContractions] -- all five of which it asks for at once -- are covered by unit tests and by the other locales that use them, but nothing has compared Church Slavonic against another implementation.

Searching #

UTS #10 section 11 defines search by collation, and src/search.zig is that. The decisions behind its shape are in GLOSSARY.md's vocabulary and in docs/adr/; what follows is how it is built and what building it found.

A match is sort-key equality of the target's own elements. A candidate range is accepted when key.write over its elements produces the pattern's key byte for byte -- the same writer Collator uses, so case level, case first, backwards secondary, tailored sub-weights and compression are all the collation's own rather than a second implementation of them. The elements are the target's, weighed in place, not the range's weighed on its own. The two differ only where something reaches across a match edge -- a contraction, a contextual mapping, shifted handling's "ignorables after a variable" -- and the edges are chosen so that nothing does; docs/adr/0002 records why this reading and not the literal one.

Edges are clean cuts. Step 1 can reorder marks and step 2 can build one element from code points that are not adjacent, so a gap between two code points need not be a gap between elements. nfd.appendTracked and elements.appendTracked carry, for every element, the lowest and highest index of the caller's code points it came from -- a range rather than a point because a discontiguous contraction takes a code point from further on and leaves the marks it skipped to be weighed after it, inside its range. A boundary between elements is a cut when the highest origin before it is below the lowest after it. Both functions are siblings of the hot-path ones rather than flags on them: elements.append and appendTracked share one body through a comptime parameter, and NFD's tracked version is its own short loop, so a sort key pays nothing for search.

whole_character then keeps only the cuts on grapheme cluster boundaries, from uucode's UAX #29 implementation. Its data is a second uucode table (fields_1), not more fields in the first: step 1 reads whole rows of the first table, and widening them would tax every sort key. The second table is 4,352 two-byte stage-one entries and 56,832 one-byte rows, about 64 KiB, linked only into a program that searches.

The walk is by primary weight. Every match contains the pattern's non-zero primary weights in order, so a candidate starting at a cut is abandoned at the first primary that disagrees, and only one whose primaries are complete has its key written. A pattern with no primary weight -- a lone accent at secondary strength -- walks until the next primary in the target, which bounds it just as well.

Spans are trimming and growing over elements that weigh nothing. An element that writes nothing to a key at the strength searched at can be added to or removed from a range without changing its key, so the minimal match is the found one trimmed of such elements back to the nearest cut, and the maximal is it grown over them. Whether an element weighs nothing is asked of key.write too, by writing it alone and comparing with the empty key. At identical strength nothing weighs nothing, since every code point is part of the key.

ICU is the oracle, and it disagrees in four ways that are conventions. zig build oracle-search asks icu::StringSearch the same questions over the collation oracle's corpora, 536,953 searches at primary, secondary and tertiary strength and under shifted handling, and they agree on every match. What it sets aside, with a count each:

  • A pattern that weighs nothing matches everywhere here, as an empty range, and nowhere in ICU.
  • ICU ends a match inside a grapheme cluster when that does not split a combining sequence -- the L and V of a jamo-spelled Hangul syllable.
  • ICU ends a match between two elements of one contraction: L inside the CLDR root's L·, whose second element is a secondary-only weight for the middle dot.
  • ICU's search and ICU's collator disagree. Under shifted handling the search treats every element without a primary weight as ignorable, where UCA, and ICU's own collator, zero only those that follow a variable element. The oracle tells these apart by asking ICU's collator whether the match ICU's search found, or the one this library found, equals the pattern.

The edges this library allows are written into the dump so that the contraction case is decided mechanically, from the same cuts the search used.

It found a sorting bug on its first run. Hungarian's &cs<<<ccs/cs resolved the /cs extension against the root, which has no cs, so ccs weighed as cs, c, s where LDML and ICU have cs, cs. ICU's search then found ccs in CSCs where this library did not. The collation oracle had passed Hungarian all along, because telling cs c s from cs cs needs a pair like ccs against cscz, which its corpus did not contain. Extensions now resolve against the tailoring as built so far, as a reset's anchor does.

And a brute-force reference. The search-agrees fuzz target reads section 11 over the permitted edges -- every range whose sort key equals the pattern's is a match, and the first one containing no other is the first minimal match -- and checks find, startsWith, endsWith and the maximal span against it, over a short alphabet chosen so that patterns do occur in targets. A range's key is written from the whole target's elements, weighed once and sliced at the edges, which is ADR 0002's in-place reading done without the searcher's machinery. It wrote each range's key from the range collated on its own until fuzzy matching showed where the two readings part: see "The reference had to weigh in place" below.

It is an element comparison, not a key. A key cannot say "this weight matches anything", so an asymmetric match is decided by walking the pattern's elements against the range's, level by level up to the strength: equal weights match, and so does a pattern weight that is unmarked at its level -- COMMON at the secondary, 0x02 at the tertiary. The primary walk that finds candidates is the same as for an exact search, since primaries are never waived.

Kana are unmarked within their own syllabary. Section 11.2 names 0x0E and 0x11 as unmarked, the normal hiragana and katakana, and its own table has けんこ find げんご but not ケンコ at tertiary strength. So 0x0E matches the small hiragana 0x0D and 0x11 the katakana forms 0x0F through 0x13, and neither matches the other.

An extra accent is passed over a character at a time. The first version let any target element without a primary weight be skipped, which made é find ệ́. The oracle's first run disagreed 15,000 times, and almost every one was this: ICU skips such an element only when the pattern element it is set against has a primary weight. That is section 11.2's own wording read a character at a time -- a marked character "will only match a character in the target that is marked in the same way" -- and it is what the walk does now. It also removes the walk's only choice, so taking each element greedily is exact, and the fuzz target checks that against a search over every alignment.

A tailoring's own letter is compared by case at the tertiary level. Lithuanian's &A<<ą<<<Ą makes Ą one element whose tertiary weight, 3, is a step along that rule's chain; in the root 3 would be a compatibility form and uppercase would be 0x08. So pattern A did not find Ą. When the secondary weights differ -- which, for a match, means the pattern's was COMMON and the target carries its accent in the element itself -- the tertiary comparison falls back to the case bits.

"Unmarked" is the literal lowest weight, which is why the tailoring generator puts a variant ordered before its letter below COMMON. &[before 2]ت<<ة once moved teh up to 0x21 to make room, which left teh marbuta with COMMON and made ة find ت rather than the other way round. The section on [before 2] above has the change.

The ß option drops one element. The DUCET writes ß as two s weights with [.0000.011F.0004] between them, and that element is the whole of its secondary difference from ss. With sharp_s_tertiary the target's and the pattern's elements lose any element without a primary weight that came from ß or ẞ alone -- origins say which -- before variable weighting, so what is left differs from ss only by its tertiary 0x04.

Ranking #

Every match carries its secondary and tertiary differences from the pattern, whatever the strength. A match has the pattern's primary weights in order, so the two line up primary by primary; paired elements differ at a level when their weights there do. The accents between primaries are paired first where their secondary weights agree, then what is left on each side in order as substitutions, and an accent with nothing to pair is one difference at its highest level -- so è for é is one difference, not a removal and an addition. Match.closeness is section 11.2.1's order: edits, then secondary, then tertiary.

Fuzzy matching #

max_edits is the edit-distance layer that grilling question 6 put on top of section 11.2.1, which has edits at the head of its ranking and says no more about them. An edit is a character, and the characters are the pieces between one cut and the next: grapheme clusters by default, so æ is one edit and not three elements' worth, and a contraction is one too.

The search is the textbook table for approximate matching, a column of the pattern's cuts for each of the target's from every start, with one step that the textbook does not need. Characters do not line up one to one under a collation -- æ is a and e at primary strength, ß is two s with sharp_s_tertiary -- so a step from one pair of cuts to any later pair costs no edits when the two runs between them match, compared whole the way an exact match is. That is what makes no edits mean an exact match: an exact match is one such run. Only runs with the same primary weights are tried, so the step costs a walk along the pattern's primaries rather than every pair. Each step carries secondary and tertiary differences as well as edits, so the table finds the cheapest alignment in Match.closeness order, and those are the counts a fuzzy match reports. Characters that weigh nothing are free to insert or delete, as they are free to pass over in an exact match.

Choosing among candidates is grilling question 23: every candidate starting at or after from is found until one has ended -- nothing starting later can overlap it -- and of those overlapping the one that ends first, the match is the one with the fewest edits, then differences, then the leftmost and the shortest. A candidate has to begin and end with a character that weighs something, which is the minimal span; a maximal one is then grown over what weighs nothing, as an exact match is.

A match keeps one of the pattern's characters. Without that, a pattern of two characters with two edits matches every pair of characters in the target, and with three it matches the empty range everywhere; so the limit is at most one below the number of the pattern's characters that weigh something, and a one-character pattern is searched for exactly.

The reference had to weigh in place. The fuzzy-agrees fuzz target's first reference cut the strings at their edges and collated each piece on its own, and disagreed with the searcher about a cedilla after a hyphen under shifted handling: section 4 makes a mark after a variable element ignorable, so in place it weighs nothing and alone it does not. That is a context reaching across an edge, which ADR 0002 said no edge allows, and it reaches across match edges too: with boundary = .none the edge between the hyphen and the cedilla is one, and ̧a is not found in -̧a here though the range, collated on its own, is the pattern. With grapheme boundaries the mark is in the hyphen's cluster and there is no edge between them. In place is the reading ADR 0002 chose, so the search stands and the ADR says so now; search-agrees had only missed it because its patterns rarely begin with a mark. Both references now weigh each string once and slice it.

Finding the first start by bisection rather than by walking was the other change: an iterator asks once a match, and walking from the start made iterating over a long text quadratic -- the exact search's too.

What the asymmetric oracle found #

273,933 asymmetric searches agree with ICU. What is counted apart, each decided from ICU's own answers, boundaries and collation elements:

  • ICU's span takes in accents around the match (345): between this library's minimal and maximal match.
  • ICU goes on over characters with no primary weight (1,518): ICU, once the pattern is used up, keeps taking each following element that lines up with the pattern's last element, so a pattern ending in an accent, or in the DUCET's variant marker for a compatibility form, takes the marks after it, and a repeated accent matches again. The check is that this library's match without boundaries is ICU's less those characters, or that every one of them weighs what the pattern's last character does.
  • ICU refuses a match followed by a character with no primary weight (554), even when that character is a grapheme cluster of its own.
  • The two take different weights of the pattern to be unmarked (126), shown by computing the pattern's signature on both sides: Korean hanja, whose secondary weights continue into a second 32-bit element whose byte 05 ICU's comparison reads as COMMON; kana; and some of the CLDR root's compatibility variants, which ICU encodes with a COMMON tertiary.
  • They differ only at the tertiary level (7): this library's secondary-strength answer is ICU's.

One lesson from building those checks: ICU's CollationElementIterator::isIgnorable means primary-ignorable. The first signature check used it to drop ignorable elements, dropped every accent with them, and so would have counted a real disagreement over any pattern with an accent as a difference of convention. Here the corrected check sets aside nearly the same cases, but that was something to measure, not to assume.

Match keys #

Collator.matchKeyAlloc writes one fixed-width record per weighted element that weighs something at the strength's levels: the primary, and the sub-weight in a tailored table; the secondary; the case, when case_level is on; the tertiary, with caseFirst folded in as the sort key folds it; and the fourth level and its sub-weight. Two bytes each, zeros written, so every record is matchKeyWidth bytes, and findMatchKey accepts only an offset that is a whole number of them. At identical strength the record is the NFD code point, because equal NFD is the whole of identical-strength equality. ADR 0001 is why keys rather than section 11.1's readable folding.

Records are not levels, and that is the one place a key can disagree with the collation. A sort key -- and the Searcher, which compares written keys -- reads each level as a sequence of its own, so two strings are equal when every level's sequence is, however their elements share those weights out. Records keep each element's weights together, so they are equal only when the elements are. Equal records always mean equal levels; the reverse needs the way weights are split between elements to be recoverable from the levels, and for both root tables it is:

  • every element with a primary weight has COMMON as its secondary, and no element without one has COMMON, so the secondary level alone says where each accent sits among the letters;
  • no element weighs only at the tertiary level;
  • an element with a primary weight and no secondary -- the second half of an implicit Han weight -- only ever directly follows an implicit lead weight, which nothing else has; and
  • under shifted, a variable element's fourth-level weight is below the max_quaternary every other element there gets, so the fourth level marks where the variable elements were.

A tailoring can break the first two. Arabic puts its tashkil where they weigh only at the tertiary level, at chain positions that coincide with letters' tertiary weights: high hamza and dammatan, in either order, are equal under the collation and ICU alike, and their keys differ. The match-keys-agree fuzz target checks the equivalence over the DUCET; a test pins the Arabic case.

A key also cannot see edges. It does not record which elements came from which character, so a key can occur where the Searcher would put a match edge inside a character -- a in æ at primary strength, where æ expands to an a and an e. The fuzz target found twelve such inputs in 200,000, all of that shape. A key hit is a candidate; a match is a key hit, except under the tailorings above.

Build wiring #

allkeys.txt is committed, in data/, alongside PropList.txt and Blocks.txt. This is the one place the plan changed outright, and it is worth saying why at length, because it is not the shape zig-datetime uses and it looks like carelessness otherwise.

Zig's package manager will not fetch it. zig fetch on https://www.unicode.org/Public/17.0.0/uca/allkeys.txt answers

error: unrecognized 'Content-Type' header: 'text/plain; charset=utf-8'

and Unicode publishes the DUCET only as a plain text file. There is no archive of it: Public/zipped/latest/UCD.zip does not contain it (checked — 74 files, no allkeys), CollationTest.zip holds only the tests, and allkeys.txt.gz is a 404 beside either copy of it. The one git repository carrying a versioned copy is unicode-org/unicodetools, whose tarball is 618 MB for a 2.3 MB file. Committing it is 2.3 MB of text that git stores in about 390 KB, refreshed by tools/update-ducet.sh — which is the same relationship zig-datetime has with tools/update-tzdata.sh, one step further along.

Two more files came with that decision, and they buy exactness rather than convenience. §10.1.3's Table 16 needs Unified_Ideograph, which lives in PropList.txt and in no other UCD file — uucode does not ship it and has no property for it. Splitting Table 16's "core" Han from the rest is by block, and block ranges have grown before, so the two CJK block boundaries come out of Blocks.txt rather than being written into the generator. Without them the Han rows of Table 16 would have to be approximated.

Three files also means three chances to be inconsistent, so the generator checks that they agree — each names its own Unicode version on its first line — and fails the build if they do not.

The version problem from the first sketch is half fixed. uucode ships Unicode 18.0.0 and so does data/, and step 1 reading uucode's UCD and step 2 reading data/ must be the same release; uucode exposes no version constant to assert against, so that half stays a comment and a line in the update script.

The other half was an immutable URL, and there is one — it is just not where it looks like it should be. Public/UCA/ has numbered directories that stop at 16.0.0, which reads as "17.0.0 was never archived", and the conclusion drawn from that was to fetch from Public/UCA/latest/. A release's UCA data is also published in the UCD tree, at Public/<version>/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.