Something went wrong. Try again.
The Unicode Collation Algorithm (UTS #10) and CLDR locale tailorings in Zig: sort text the way people expect rather than by code point.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Step 2 of the algorithm, UTS #10 section 7.2: turn an NFD string into an//! array of collation elements.//!//! This is the step with the table behind it and the step the subtle bugs//! live in, because the matching is not a simple longest-prefix walk. Two//! different matching methods run at each position, and the note at the end//! of section 7.2 is emphatic that they are different://!//! * S2.1 is contiguous and longest-match. It has to find a contraction//! `ABC` whether or not `AB` is also a contraction.//! * S2.1.1 to S2.1.3 are discontiguous. They grow a match one code point//! at a time across non-starters that get skipped, which means they can//! only find `ABC` by way of `AB`. Well-formedness condition WF5 is what//! guarantees `AB` is there to be found.//!//! The discontiguous half exists because of canonical equivalence rather//! than for its own sake. `<a, combining ring above>` and `<a, combining//! ring above, combining cedilla>` are not the same string, but the second//! normalizes to `<a, combining cedilla, combining ring above>`, which//! separates the `a` from the ring that a Danish contraction wants to pair//! it with. Without the lookahead that string would sort next to `a` instead//! of after `z`.
const std = @import("std");const Allocator = std.mem.Allocator;
const data = @import("data");const Element = data.Element;const Contraction = data.Contraction;const nfd = @import("nfd.zig");const Table = @import("table.zig").Table;
/// The most code points a partial match has to remember, which is the most a/// contraction may be. See `data.max_contraction`.const max_contraction = data.max_contraction;
/// Append the collation elements for `text` to `out`.////// `text` must already be in NFD -- step 1 -- and is taken **mutably**,/// because S2.1.3 says to "remove C" from the input when a discontiguous/// match consumes it. Removing it in place is what keeps the walk to a/// single pass; the alternative is a second buffer holding which positions/// have been eaten.pub fn append( out: *std.ArrayList(Element), gpa: Allocator, table: Table, text: []u21,) Allocator.Error!void { var len = text.len; var i: usize = 0; while (i < len) { var scratch: [1]Element = undefined;
// S2.1: the longest contiguous match at this point. const entry = table.entry(text[i]); var key: [max_contraction]u21 = undefined; key[0] = text[i]; var key_len: usize = 1; // How much of the front of the string this match covers. Only this // many code points are stepped over at the end, because anything a // discontiguous match ate has already been removed from the middle. var head_len: usize = 1; var elements: ?[]const Element = null;
if (entry.starts_contraction) { // The tailoring's list first, so that a locale can replace a // contraction the root already had, and each list sorted // longest-first so the first match in it is the longest, which // is what S2.1 asks for. for ([_]bool{ true, false }) |from_tailoring| { const list = if (from_tailoring) table.tailoredContractionsFor(text[i]) else table.rootContractionsFor(text[i]); for (list) |c| { const n = c.rest_len; if (i + 1 + n > len) continue; const rest = if (from_tailoring) table.tailoredRestOf(c) else table.restOf(c); if (!std.mem.eql(u21, text[i + 1 ..][0..n], rest)) continue; // A contextual mapping, section 3.3's `prefix|target`: // this one applies only after particular code points. // The prefix is a condition rather than part of the // match -- it has been weighed already and is not // consumed -- so it is checked here and changes nothing // about how much of the string this covers. // // Matched against the text as the walk left it, which is // what a discontiguous match's removal has already // accounted for. Sorted longest-prefix-first within a // target, so the most specific condition is tried first // and an unconditional mapping last. if (c.prefix_len != 0) { const prefix = if (from_tailoring) table.tailoredPrefixOf(c) else table.prefixOf(c); if (i < prefix.len) continue; if (!std.mem.eql(u21, text[i - prefix.len .. i], prefix)) continue; } elements = if (from_tailoring) table.elementsOfTailoredContraction(c) else table.elementsOfContraction(c); head_len = 1 + n; key_len = 1 + n; for (rest, 1..) |cp, k| key[k] = cp; break; } if (elements != null) break; } } if (elements == null and entry.len != 0) { elements = table.elementsOf(entry, &scratch); }
// S2.1.1 to S2.1.3: try to grow the match across skipped // non-starters. Only a code point that starts a contraction can // grow, so this costs nothing for the 99.8% of code points that // cannot. if (entry.starts_contraction) { // The greatest combining class among the code points between the // end of the match and the candidate. UTS10-D34: those are the // `B`s, and any one of them with ccc(B) >= ccc(C) puts C in a // blocking context. var blocking_ccc: u8 = 0; var j = i + head_len; while (j < len) { const ccc = nfd.combiningClass(text[j]); // "The search for such a match will terminate at the first // non-starter in a blocked context, or alternatively, at the // first starter encountered during the lookahead." if (ccc == 0 or ccc <= blocking_ccc) break;
if (key_len < max_contraction) { if (findContraction(table, text[0..i], key[0..key_len], text[j])) |found| { const c, const from_tailoring = found; elements = if (from_tailoring) table.elementsOfTailoredContraction(c) else table.elementsOfContraction(c); key[key_len] = text[j]; key_len += 1; // S2.1.3: remove C. The code points that were // skipped stay where they are and keep blocking, so // `blocking_ccc` is deliberately left alone -- it is // already the greatest class among them. std.mem.copyForwards(u21, text[j .. len - 1], text[j + 1 .. len]); len -= 1; continue; } } blocking_ccc = ccc; j += 1; } }
// S2.2: no match, so synthesize. S2.4: append. if (elements) |list| { try out.appendSlice(gpa, list); } else { try out.appendSlice(gpa, &table.implicit(text[i])); }
// S2.5. i += head_len; }}
/// The contraction for `matched ++ {next}`, if the table or its tailoring has/// one. The tailoring wins.////// `context` is the text before the match and is what a contextual mapping's/// own prefix is tested against -- the same condition the contiguous search/// applies, and it has to be applied here too: this is the second place a/// contraction can be chosen, and a conditional mapping that skipped the/// condition here would apply everywhere. Japanese is what noticed, with/// 864,568 disagreements of 24,468,510: ゞ is ゝ and U+3099, U+3099 is a/// non-starter, so *every* pair of them reached the discontiguous search and/// took the first contextual mapping in the list whatever stood before it.fn findContraction( table: Table, context: []const u21, matched: []const u21, next: u21,) ?struct { Contraction, bool } { const prefix = matched; for ([_]bool{ true, false }) |from_tailoring| { const list = if (from_tailoring) table.tailoredContractionsFor(prefix[0]) else table.rootContractionsFor(prefix[0]); for (list) |c| { if (c.rest_len != prefix.len) continue; const rest = if (from_tailoring) table.tailoredRestOf(c) else table.restOf(c); if (!std.mem.eql(u21, rest[0 .. prefix.len - 1], prefix[1..])) continue; if (rest[prefix.len - 1] != next) continue; if (c.prefix_len != 0) { const condition = if (from_tailoring) table.tailoredPrefixOf(c) else table.prefixOf(c); if (context.len < condition.len) continue; if (!std.mem.eql(u21, context[context.len - condition.len ..], condition)) continue; } return .{ c, from_tailoring }; } } return null;}
const testing = std.testing;const ducet = @import("table.zig").ducet;
fn collationElements(gpa: Allocator, cps: []const u21) !std.ArrayList(Element) { var text: std.ArrayList(u21) = .empty; defer text.deinit(gpa); try nfd.append(&text, gpa, cps);
var out: std.ArrayList(Element) = .empty; try append(&out, gpa, ducet, text.items); return out;}
/// Whether the DUCET table has an entry for each of these, which a build/// restricted by `-Drepertoire=` need not. A test that reads an element out/// of the table is about something that is not there otherwise.fn haveAll(cps: []const u21) bool { for (cps) |cp| { if (!ducet.inRepertoire(cp)) return false; if (ducet.entry(cp).len == 0) return false; } return true;}
test "the worked example in figure 1" { // Every character the figure names has to be in the table, which a build // restricted by `-Drepertoire=` need not have -- and without the // combining acute the accent takes an implicit weight and contributes a // primary difference rather than a secondary one, which is the whole // point of the figure. if (!haveAll(&.{ 'c', 'a', 0x0301, 'b' })) return error.SkipZigTest;
// "ca<combining acute>b" becomes // [.0706.0020.0002], [.06D9.0020.0002], [.0000.0021.0002], [.06EE.0020.0002] // The weights in the figure are from an older DUCET, so what is checked // here is the shape: four elements, and the accent contributing a // secondary difference with no primary weight of its own. var out = try collationElements(testing.allocator, &.{ 'c', 'a', 0x0301, 'b' }); defer out.deinit(testing.allocator);
try testing.expectEqual(@as(usize, 4), out.items.len); try testing.expect(out.items[0].isPrimary()); try testing.expect(out.items[1].isPrimary()); // The combining acute is a secondary collation element, UTS10-D10: no // primary weight, a secondary weight of its own. try testing.expect(!out.items[2].isPrimary()); try testing.expect(out.items[2].secondary != 0); try testing.expect(out.items[3].isPrimary());}
test "an unmatched code point gets two elements, not one" { // Section 10.1.2: every code point the table says nothing about maps to // a *pair*, so a Han ideograph contributes two primary weights. var out = try collationElements(testing.allocator, &.{0x4E00}); defer out.deinit(testing.allocator); try testing.expectEqual(@as(usize, 2), out.items.len); try testing.expectEqual(@as(u16, 0xFB40), out.items[0].primary); try testing.expectEqual(@as(u16, 0xCE00), out.items[1].primary);}
test "a contiguous contraction is one match" { // Taken out of the table rather than named, so that the test cannot go // stale when DUCET's contractions change. const c = for (ducet.contractions) |candidate| { if (candidate.rest_len == 1) break candidate; } else return error.SkipZigTest;
var out = try collationElements(testing.allocator, &.{ c.first, ducet.restOf(c)[0] }); defer out.deinit(testing.allocator);
// The pair weighs as the contraction says, not as its halves would // separately. if (!std.mem.eql(Element, ducet.elementsOfContraction(c), out.items)) { std.debug.print("contraction U+{X:0>4} U+{X:0>4}: table says {any}, got {any}\n", .{ c.first, ducet.restOf(c)[0], ducet.elementsOfContraction(c), out.items, }); return error.TestUnexpectedResult; }
// And it is a contraction rather than a redundant entry: the two code // points weighed apart are not the same sequence. For DUCET's first one, // U+004C U+00B7, the difference is in the second element -- the middle // dot's own [*0297.0020.0002] becomes [.0000.011F.0002], an ignorable // that contributes a secondary difference instead of a primary one. var apart: std.ArrayList(Element) = .empty; defer apart.deinit(testing.allocator); var first_half = try collationElements(testing.allocator, &.{c.first}); defer first_half.deinit(testing.allocator); var second_half = try collationElements(testing.allocator, &.{ducet.restOf(c)[0]}); defer second_half.deinit(testing.allocator); try apart.appendSlice(testing.allocator, first_half.items); try apart.appendSlice(testing.allocator, second_half.items); try testing.expect(!std.mem.eql(Element, out.items, apart.items));}
test "a discontiguous match still finds the contraction" { // The example section 7.2 gives. Take a two-code-point contraction whose // second half is a non-starter, put a *lower* combining class mark // between the two, and NFD will have reordered it to sit between them. // The contraction must still be found. const c = for (ducet.contractions) |candidate| { if (candidate.rest_len != 1) continue; const ccc = nfd.combiningClass(ducet.restOf(candidate)[0]); if (ccc == 0) continue; break candidate; } else return error.SkipZigTest;
const inner_ccc = nfd.combiningClass(ducet.restOf(c)[0]); // A non-starter with a strictly lower combining class, so that NFD sorts // it before the contraction's second half and splits the pair. const intruder: u21 = for ([_]u21{ 0x0316, 0x0323, 0x0334, 0x0591, 0x0301 }) |cp| { const ccc = nfd.combiningClass(cp); if (ccc != 0 and ccc < inner_ccc) break cp; } else return error.SkipZigTest;
var text: std.ArrayList(u21) = .empty; defer text.deinit(testing.allocator); try nfd.append(&text, testing.allocator, &.{ c.first, ducet.restOf(c)[0], intruder }); // NFD really did separate them, or the test is proving nothing. try testing.expectEqual(intruder, text.items[1]);
var out: std.ArrayList(Element) = .empty; defer out.deinit(testing.allocator); try append(&out, testing.allocator, ducet, text.items);
// The contraction's elements come first, then the intruder's. const contracted = ducet.elementsOfContraction(c); try testing.expect(out.items.len > contracted.len); try testing.expectEqualSlices(Element, contracted, out.items[0..contracted.len]);}
test "a starter blocks a discontiguous match" { // Section 3.5: "A sequence of characters which otherwise would result in // a contraction match can be made to sort as separate characters by // inserting, someplace within the sequence, a starter that maps to a // completely ignorable collation element." U+034F COMBINING GRAPHEME // JOINER is named there for exactly this. const c = if (ducet.contractions.len != 0) ducet.contractions[0] else return error.SkipZigTest; var with_cgj = try collationElements(testing.allocator, &.{ c.first, 0x034F, ducet.restOf(c)[0] }); defer with_cgj.deinit(testing.allocator);
var without = try collationElements(testing.allocator, &.{ c.first, ducet.restOf(c)[0] }); defer without.deinit(testing.allocator);
try testing.expect(with_cgj.items.len != without.items.len);}
test "hangul syllables weigh as their jamo" { var syllable = try collationElements(testing.allocator, &.{0xAC01}); defer syllable.deinit(testing.allocator);
var jamo = try collationElements(testing.allocator, &.{ 0x1100, 0x1161, 0x11A8 }); defer jamo.deinit(testing.allocator);
try testing.expectEqualSlices(Element, jamo.items, syllable.items);}
test "a contextual mapping applies only after its prefix" { // The elements the tailoring is built out of come from the table, so // they have to be in it. if (!haveAll(&.{ 'a', 'b', 'c' })) return error.SkipZigTest; // Section 3.3's `prefix|target`, built by hand because the one locale // that writes them does not compile yet. The shape is Japanese's: a // mark takes the weights of what comes before it, so that `aー` sorts // where `aa` does and `bー` does not. var scratch: [1]Element = undefined; const a = ducet.elementsOf(ducet.entry('a'), &scratch)[0]; const mark: u21 = 0x30FC; // KATAKANA-HIRAGANA PROLONGED SOUND MARK
const expansions = [_]Element{a}; const points = [_]u21{'a'}; // the prefix; the target has no rest const contractions = [_]Contraction{.{ .first = mark, .rest_index = 0, .rest_len = 0, .elements_index = 0, .elements_len = 1, .prefix_index = 0, .prefix_len = 1, }}; const tailoring: data.Tailoring = .{ .locale = "test", .root = "ducet", .overrides = &.{}, .contractions = &contractions, .contraction_points = &points, .expansions = &expansions, }; const table = ducet.tailored(&tailoring);
const weigh = struct { fn f(t: Table, cps: []const u21) !std.ArrayList(Element) { var text: std.ArrayList(u21) = .empty; defer text.deinit(testing.allocator); try nfd.append(&text, testing.allocator, cps); var out: std.ArrayList(Element) = .empty; try append(&out, testing.allocator, t, text.items); return out; } }.f;
// After the prefix: the mark weighs as a second `a`. var after = try weigh(table, &.{ 'a', mark }); defer after.deinit(testing.allocator); var doubled = try weigh(table, &.{ 'a', 'a' }); defer doubled.deinit(testing.allocator); try testing.expectEqualSlices(Element, doubled.items, after.items);
// After anything else: the mark weighs as itself, which is what the root // says, so the tailoring has changed nothing there. var elsewhere = try weigh(table, &.{ 'b', mark }); defer elsewhere.deinit(testing.allocator); var untailored = try weigh(ducet, &.{ 'b', mark }); defer untailored.deinit(testing.allocator); try testing.expectEqualSlices(Element, untailored.items, elsewhere.items);
// And at the start of a string there is no prefix to match, so likewise. var alone = try weigh(table, &.{mark}); defer alone.deinit(testing.allocator); var alone_untailored = try weigh(ducet, &.{mark}); defer alone_untailored.deinit(testing.allocator); try testing.expectEqualSlices(Element, alone_untailored.items, alone.items);}
test "a contextual mapping's condition holds on the discontiguous path too" { // The elements the tailoring is built out of come from the table, so // they have to be in it. if (!haveAll(&.{ 'a', 'b', 'c' })) return error.SkipZigTest; // The condition has to be checked in both places a contraction can be // chosen. S2.1 matches contiguously; S2.1.1 grows a match across skipped // non-starters, through `findContraction`, and a mapping whose target // *ends* in a non-starter is reached that way rather than by the first // search. // // Japanese is what found it, at 864,568 disagreements with ICU of // 24,468,510. ゞ is ゝ followed by U+3099, U+3099 is a non-starter, and // every pair of them therefore reached the second search -- which took // the first contextual mapping in the list whatever stood before it, so // a bare ゞ weighed as the kana of some rule's prefix. var scratch: [1]Element = undefined; const a = ducet.elementsOf(ducet.entry('a'), &scratch)[0]; const iteration: u21 = 0x309D; // HIRAGANA ITERATION MARK const voiced: u21 = 0x3099; // COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK try testing.expect(nfd.combiningClass(voiced) != 0);
const expansions = [_]Element{a}; // The target is the pair, and the condition is a single `a` before it. const points = [_]u21{ voiced, 'a' }; const contractions = [_]Contraction{.{ .first = iteration, .rest_index = 0, .rest_len = 1, .elements_index = 0, .elements_len = 1, .prefix_index = 1, .prefix_len = 1, }}; const tailoring: data.Tailoring = .{ .locale = "test", .root = "ducet", .overrides = &.{}, .contractions = &contractions, .contraction_points = &points, .expansions = &expansions, }; const table = ducet.tailored(&tailoring);
const weigh = struct { fn f(t: Table, cps: []const u21) !std.ArrayList(Element) { var text: std.ArrayList(u21) = .empty; defer text.deinit(testing.allocator); try nfd.append(&text, testing.allocator, cps); var out: std.ArrayList(Element) = .empty; try append(&out, testing.allocator, t, text.items); return out; } }.f;
// Without the condition met, the pair weighs as the root has it. var bare = try weigh(table, &.{ iteration, voiced }); defer bare.deinit(testing.allocator); var untailored = try weigh(ducet, &.{ iteration, voiced }); defer untailored.deinit(testing.allocator); try testing.expectEqualSlices(Element, untailored.items, bare.items);
// With it met, the mapping applies -- so the condition is being tested // rather than the whole mapping being unreachable. var after = try weigh(table, &.{ 'a', iteration, voiced }); defer after.deinit(testing.allocator); try testing.expectEqual(@as(usize, 2), after.items.len); try testing.expectEqual(a, after.items[1]);}