// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Writes down what this library makes of a set of comparisons, so that ICU //! can be asked the same ones. //! //! One record per line, tab separated: the locale, the two strings as //! hexadecimal code points, and the order this library puts them in. Shown //! here with the tabs drawn as bars, because a tab in a Zig comment is a //! compile error: //! //! und | 0061 0308 0062 | 0061 0062 | gt //! //! `tools/oracle.cpp` reads that and reports every line ICU disagrees with. //! Pairwise rather than a sorted list, because a disagreement about a pair //! names the two strings that caused it, where a difference between two //! orderings has to be worked back to one. //! //! ## What is compared //! //! `und` is the untailored root, and its corpus is a general one -- letters, //! accents, case, punctuation, digits, scripts that take derived weights, and //! section 10.1.6's Hangul shapes, which are there because how Hangul sorts //! is the root's answer and no tailoring's. It is the baseline, and it //! matters: ICU orders by the *CLDR* root, so running this against //! `collate.ducet` measures the distance between DUCET and CLDR rather than //! anything about this implementation. Against `collate.cldr_root` it should //! be close to zero, and whatever is left is a finding. //! //! Every locale the build was asked for is compared as well, and its corpus //! is built out of its own tailoring: the code points it overrides, the //! sequences it contracts, and the base letters those decompose to. Those are //! precisely the comparisons the tailoring exists to change, so they are the //! ones worth asking about. //! //! What that cannot reach is a sequence followed by something, since every //! entry is one code point or one of the tailoring's own sequences. That is //! the trailing weights problem of section 10.1.4, and it is why the Hangul //! shapes are written out rather than assembled from the corpus. //! //! ## The modes //! //! `--mode=tertiary` is the default and the one CI runs: tertiary strength, //! non-ignorable alternate handling, which is the question "does this library //! order letters the way ICU does". //! //! The others ask about a different path through `key.write`, and each is a //! run of its own rather than a pass in the same one because any of them //! writes a 615 MB file of comparisons and asks ICU thirty million questions. //! //! `--mode=shifted` is quaternary strength with shifted alternate handling, //! which moves a variable element's primary weight down to a fourth level. //! The conformance suites cover that for the two roots -- //! `CollationTest_SHIFTED_SHORT.txt` and its CLDR counterpart -- and nothing //! covers it for a tailoring, which is why the first run of it found two //! defects. //! //! `--mode=primary` and `--mode=secondary` truncate the key, which is what a //! caller asking to ignore accents or case gets. `--mode=identical` appends //! the NFD of the input behind the weights, and is the only mode that //! compares anything but weights. //! //! `--mode=case_level`, `--mode=upper_first` and `--mode=lower_first` force a //! case setting on both sides. Ordinarily each side takes those from the //! locale -- they are `[caseLevel]` and `[caseFirst]`, which are locale data //! for ICU as well -- and only three of CLDR's locales ask for either, one of //! which ICU has no data for at all. Forcing them asks about the case level //! and the case class across every locale instead of across two. //! //! There is no mode for `blanked` or `shift_trimmed`: ICU's //! `UCOL_ALTERNATE_HANDLING` takes only non-ignorable and shifted, so there //! is nothing to ask. const std = @import("std"); const Allocator = std.mem.Allocator; const collate = @import("collate"); /// Which root to compare. ICU's is CLDR's, so `cldr` is the like-for-like /// question and `ducet` measures the gap between the two roots. const Root = enum { ducet, cldr }; /// Which comparison to ask for. Both sides are set to the same thing rather /// than to their own defaults: ICU's default strength is tertiary and its /// default alternate handling is non-ignorable for most locales but not all, /// and a disagreement about the settings is not a disagreement about the /// collation. const Mode = enum { primary, secondary, tertiary, quaternary, identical, shifted, case_level, upper_first, lower_first, fn options(m: Mode) collate.Options { return switch (m) { .primary => .{ .strength = .primary, .alternate = .non_ignorable }, .secondary => .{ .strength = .secondary, .alternate = .non_ignorable }, .tertiary => .{ .strength = .tertiary, .alternate = .non_ignorable }, .quaternary => .{ .strength = .quaternary, .alternate = .non_ignorable }, .identical => .{ .strength = .identical, .alternate = .non_ignorable }, .shifted => .{ .strength = .quaternary, .alternate = .shifted }, .case_level => .{ .strength = .tertiary, .alternate = .non_ignorable, .case_level = true, }, .upper_first => .{ .strength = .tertiary, .alternate = .non_ignorable, .case_first = .upper_first, }, .lower_first => .{ .strength = .tertiary, .alternate = .non_ignorable, .case_first = .lower_first, }, }; } /// Whether the mode forces a setting that a tailoring would otherwise /// have its own say in. `[caseFirst]` and `[caseLevel]` are locale data /// on ICU's side too, so ordinarily both sides take the locale's; these /// three modes override both sides instead, which is how a setting only /// one or two locales ask for gets asked about across a hundred. fn forcesCase(m: Mode) bool { return switch (m) { .case_level, .upper_first, .lower_first => true, else => false, }; } }; pub fn main(init: std.process.Init.Minimal) !u8 { var gpa_state: std.heap.DebugAllocator(.{}) = .init; defer _ = gpa_state.deinit(); const gpa = gpa_state.allocator(); var threaded: std.Io.Threaded = .init(gpa, .{}); defer threaded.deinit(); const io = threaded.io(); var arena_state: std.heap.ArenaAllocator = .init(gpa); defer arena_state.deinit(); const arena = arena_state.allocator(); const args = try init.args.toSlice(arena); var which: Root = .cldr; var mode: Mode = .tertiary; var out_path: ?[]const u8 = null; for (args[1..]) |arg| { if (std.mem.eql(u8, arg, "--root=ducet")) { which = .ducet; } else if (std.mem.eql(u8, arg, "--root=cldr")) { which = .cldr; } else if (std.mem.startsWith(u8, arg, "--mode=")) { mode = std.meta.stringToEnum(Mode, arg["--mode=".len..]) orelse { std.debug.print("unknown mode {s}\n", .{arg["--mode=".len..]}); return error.UnknownArgument; }; } else if (!std.mem.startsWith(u8, arg, "-") and out_path == null) { out_path = arg; } else { std.debug.print( "usage: oracle_dump [--root=ducet|cldr] " ++ "[--mode=primary|secondary|tertiary|quaternary|identical|" ++ "shifted|case_level|upper_first|lower_first] [path]\n", .{}, ); return error.UnknownArgument; } } const table: collate.Table = switch (which) { .ducet => collate.ducet, .cldr => collate.cldr_root, }; if (table.stage1.len == 0) { std.debug.print( "that root was not compiled in; build with -Dembed-ducet or -Dembed-cldr\n", .{}, ); return error.NoTable; } // Written to a path when given one, and to stdout otherwise. The path is // what the build passes, and the reason is memory rather than tidiness: // Zig's build runner holds a captured stdout in memory until the step // finishes, and this dump is 1.1 GB with every locale in it -- which a // four-gigabyte runner cannot spare. The first run that included Japanese // failed with `SystemResources` trying to spawn the next step. var buffer: [64 * 1024]u8 = undefined; const file: std.Io.File = if (out_path) |path| try std.Io.Dir.cwd().createFile(io, path, .{}) else std.Io.File.stdout(); defer if (out_path != null) file.close(io); var out = file.writer(io, &buffer); const w = &out.interface; // The mode goes on its own line rather than into every record: ICU has to // be told the same thing, and one line at the top is cheaper than a fifth // column on twenty million of them. try w.print("#mode\t{t}\n", .{mode}); const settings = mode.options(); // The baseline: the root collation on its own. try dump(arena, w, "und", .{ .table = table, .options = settings }, &root_corpus); // And every tailoring this build has. const locales = collate.locales; inline for (@typeInfo(locales).@"struct".decls) |decl| { const field = @field(locales, decl.name); if (@TypeOf(field) != collate.Tailoring) continue; // A tailoring with nothing in it has nothing to compare, and saying // so is the point. `pl` was read as ruleless for a while by a // generator that could not find the `` CLDR writes with // spaces in it; the corpus was then the bare alphabet, ICU agreed // about all 325 pairs of it, and the run reported no differences for // Polish. An empty delta must be reported as an empty delta. if (field.overrides.len == 0 and field.contractions.len == 0 and field.reorder.len == 0 and comptime noSettings(field.settings)) { try w.print("#empty\t{s}\n", .{decl.name}); continue; } var corpus: std.ArrayList([]const u21) = .empty; try tailoringCorpus(arena, &corpus, &field, table); try dump(arena, w, decl.name, .{ .table = table.tailored(&field), // The tailoring's own `caseFirst` and `backwards` are applied, // because ICU takes those from its locale data as well and a // collator for Danish puts uppercase first whether it is asked to // or not. Its `alternate` is deliberately *not*: both sides are // forced to non-ignorable below, since ICU takes that from the // locale for a handful of them and a disagreement about the // setting is not a disagreement about the ordering. .options = if (mode.forcesCase()) // The mode has already said what the case settings are, and // ICU is told the same thing rather than reading them from // the locale, so the tailoring gets no say in these two. // `backwards` it still has, because nothing here overrides // that. settings.applying(.{ .backwards_secondary = field.settings.backwards_secondary, }) else settings.applying(.{ .case_first = field.settings.case_first, .backwards_secondary = field.settings.backwards_secondary, .case_level = field.settings.case_level, }), }, corpus.items); } try w.flush(); return 0; } /// Whether a tailoring's rules asked for no setting at all. /// /// Every field of `Settings` is an optional, and this walks them rather than /// naming them, so that a setting added later cannot be left out of the check /// -- which would make a tailoring that asks only for *that* setting look /// empty and go uncompared. fn noSettings(settings_of: collate.Settings) bool { inline for (@typeInfo(collate.Settings).@"struct".fields) |f| { if (@field(settings_of, f.name) != null) return false; } return true; } fn dump( arena: Allocator, w: *std.Io.Writer, locale: []const u8, collator: collate.Collator, corpus: []const []const u21, ) !void { var builder: collate.Builder = .empty; defer builder.deinit(arena); // Keys once, then every pair, which is what a sort would do. const keys = try arena.alloc([]u8, corpus.len); for (corpus, 0..) |s, i| { keys[i] = try builder.sortKeyAllocCodePoints(arena, collator, s); } for (corpus, 0..) |a, i| { for (corpus[i + 1 ..], i + 1..) |b, j| { try w.print("{s}\t", .{locale}); try writeHex(w, a); try w.writeByte('\t'); try writeHex(w, b); try w.print("\t{t}\n", .{collate.orderKeys(keys[i], keys[j])}); } } } fn writeHex(w: *std.Io.Writer, s: []const u21) !void { for (s) |cp| try w.print("{x:0>4} ", .{cp}); } /// The strings a tailoring actually has an opinion about, plus enough /// context to place them: every code point it overrides, every sequence it /// contracts, and the first code point of each of those, which is the base /// letter the rule hangs off. fn tailoringCorpus( arena: Allocator, out: *std.ArrayList([]const u21), tailoring: *const collate.Tailoring, root: collate.Table, ) !void { var seen: std.AutoHashMapUnmanaged(u64, void) = .empty; const add = struct { fn f( a: Allocator, list: *std.ArrayList([]const u21), set: *std.AutoHashMapUnmanaged(u64, void), s: []const u21, ) !void { if (s.len == 0) return; var h: u64 = 1469598103934665603; for (s) |cp| h = (h ^ cp) *% 1099511628211; if ((try set.getOrPut(a, h)).found_existing) return; try list.append(a, try a.dupe(u21, s)); } }.f; for (tailoring.overrides) |o| { try add(arena, out, &seen, &.{o.cp}); } for (tailoring.contractions) |c| { var buf: [collate.data.max_contraction]u21 = undefined; buf[0] = c.first; for (tailoring.restOf(c), 1..) |cp, i| buf[i] = cp; try add(arena, out, &seen, buf[0 .. 1 + c.rest_len]); // The base letter on its own, so that the tailored form has // something to be ordered against. try add(arena, out, &seen, buf[0..1]); } // `[suppressContractions [Ии]]` turns off root contractions, and the // corpus has to contain them or the setting is untested: the code point // itself, and every sequence the root contracts it into. Macedonian and // Serbian suppress и and И, which the root contracts with a following // combining breve, and without these their corpora were 2,346 comparisons // of the alphabet and the Cyrillic samples -- none of them the thing the // rule is about. for (tailoring.suppressed) |cp| { try add(arena, out, &seen, &.{cp}); for (root.contractionsFor(cp)) |c| { var buf: [collate.data.max_contraction]u21 = undefined; buf[0] = cp; for (root.restOf(c), 1..) |rest_cp, i| buf[i] = rest_cp; try add(arena, out, &seen, buf[0 .. 1 + c.rest_len]); } } // And the lower-case Latin alphabet, so that a letter moved to the end of // the alphabet has the whole alphabet to be at the end of. var letter: u21 = 'a'; while (letter <= 'z') : (letter += 1) try add(arena, out, &seen, &.{letter}); // A tailoring that reorders needs characters from the groups it moved, // and the groups it moved them past. Without these a reordering locale's // corpus is the Latin alphabet and nothing else -- `ru` tailors no // individual character at all, so its whole rule is `[reorder Cyrl]` and // a corpus of a-z tests none of it. The first run said 0 of 325 and meant // nothing. if (tailoring.reorder.len != 0) { for (script_samples) |cp| try add(arena, out, &seen, &.{cp}); } // A tailoring whose rules are nothing but settings has no material of its // own, and the alphabet alone tests none of it. `fr_CA` is the case: its // whole rule is `[backwards 2]`, and a corpus of a to z compared 325 pairs // of which not one has an accent in it. These are the words that setting // exists for, from section 3.8.1's own example, plus the cased pairs a // `caseFirst` has an opinion about. // // Any setting at all, rather than the two that obviously want them: a // locale whose only rule is a setting this list does not name would // otherwise be compared on material that cannot show it. if (!noSettings(tailoring.settings)) { for (accent_samples) |word| try add(arena, out, &seen, word); } } /// The rows of section 10.1.6's tables, as strings, for the root corpus. /// /// They belong to the root collation rather than to any tailoring, which was /// worth finding out: CLDR's Korean rules tailor no Hangul at all. Its /// `standard` collation is 2,212 `&<<*` chains that /// order *Hanja* by their Korean reading, and the conjoining jamo in `ko.xml` /// are all in its `search` and `searchjl` collations, which are for matching /// rather than sorting and are not compiled. So how Hangul sorts here is the /// root table's answer, and the root corpus is where these have to go. /// /// U+1100 is the leading consonant KIYEOK and U+1102 NIEUN; U+1161 is the /// vowel A and U+1165 EO; U+11A8 is the trailing consonant KIYEOK. `a` is a /// character from a script sorted before Hangul and U+4E00 one sorted after /// -- those two are what make the rows about what *follows* a syllable rather /// than about the syllable itself, which is the whole of the trailing weights /// problem. /// /// The precomposed forms are here beside the decomposed ones because they are /// canonically equivalent to them and so must sort equal: U+AC00 is the /// syllable GA and U+AC01 GAG. const hangul_shapes = [_][]const u21{ &.{ 0x1100, 0x1161 }, // L1 V1 &.{ 0x1100, 0x1161, 'a' }, // L1 V1 Xb &.{ 0x1100, 0x1161, 0x4E00 }, // L1 V1 Xa &.{ 0x1100, 0x1161, 0x11A8 }, // L1 V1 T1 &.{ 0x1100, 0x1161, 0x11A8, 'a' }, &.{ 0x1100, 0x1161, 0x11A8, 0x4E00 }, &.{ 0x1100, 0x1161, 0x1165 }, // L1 V1 V2, which only Old Korean has &.{ 0x1100, 0x1102, 0x1161 }, // L1 L2 V1, likewise &.{ 0x1100, 0x1161, 0x1102, 0x1161 }, // two syllables, L1 V1 L2 V2 &.{0xAC00}, // the same syllable precomposed &.{0xAC01}, &.{ 0xAC00, 'a' }, &.{ 0xAC00, 0x4E00 }, &.{ 0xAC00, 0xAC00 }, }; /// Words whose order depends on a secondary or tertiary setting: the four /// French spellings section 3.8.1 uses to show what a backwards secondary /// level does, and the same letters cased both ways. const accent_samples = [_][]const u21{ &.{ 'c', 'o', 't', 'e' }, &.{ 'c', 'o', 't', 0x00E9 }, // coté &.{ 'c', 0x00F4, 't', 'e' }, // côte &.{ 'c', 0x00F4, 't', 0x00E9 }, // côté &.{ 'C', 'o', 't', 'e' }, &.{ 'C', 'o', 't', 0x00E9 }, &.{ 'C', 0x00F4, 't', 'e' }, &.{ 'C', 0x00F4, 't', 0x00E9 }, &.{ 'C', 'O', 'T', 'E' }, &.{0x00E9}, &.{0x00C9}, &.{0x00E8}, &.{0x00C8}, &.{'e'}, &.{'E'}, }; /// One or two characters from each reordering group, so that moving a group /// shows up as a comparison that changed. The core groups are here too: /// `[reorder others digit]` moves digits past every letter, and nothing else /// in the corpus would notice. const script_samples = [_]u21{ ' ', '-', '!', '$', '0', '9', // space, punct, currency, digit '\u{00A4}', '\u{263A}', // currency sign, symbol 'a', 'z', '\u{03B1}', '\u{03C9}', // Greek '\u{0430}', '\u{044F}', // Cyrillic '\u{05D0}', '\u{05EA}', // Hebrew '\u{0627}', '\u{064A}', // Arabic '\u{0710}', // Syriac '\u{0905}', '\u{0939}', // Devanagari '\u{0985}', // Bengali '\u{0A05}', // Gurmukhi '\u{0B85}', // Tamil '\u{0C05}', // Telugu '\u{0D05}', // Malayalam '\u{0D85}', // Sinhala '\u{0E01}', '\u{0E2E}', // Thai '\u{0E81}', // Lao '\u{0F40}', // Tibetan '\u{1000}', // Myanmar '\u{10D0}', // Georgian '\u{0531}', // Armenian '\u{1200}', // Ethiopic '\u{13A0}', // Cherokee '\u{1780}', // Khmer '\u{1820}', // Mongolian '\u{3042}', '\u{30A2}', // Hiragana, Katakana '\u{4E00}', '\u{9FFF}', // Han '\u{AC00}', '\u{D7A3}', // Hangul '\u{A000}', // Yi }; /// A general corpus for the untailored root: the distinctions the algorithm /// is built to make, one of each. const root_corpus = [_][]const u21{ // Letters, case, accents -- the three weight levels. &.{'a'}, &.{'A'}, &.{ 'a', 0x0301 }, &.{'b'}, &.{'z'}, &.{ 'a', 0x0308 }, &.{ 'o', 0x0308 }, &.{ 'u', 0x0308 }, // Canonically equivalent spellings, which must compare equal. &.{0x00E4}, &.{ 'a', 0x0308 }, // Punctuation and digits, where the variable band lives. &.{'-'}, &.{'_'}, &.{' '}, &.{'!'}, &.{'0'}, &.{'1'}, &.{'9'}, // Words, so that prefixes and contractions get exercised. &.{ 'M', 0x00E4, 'r', 't', 'e', 'n', 's' }, &.{ 'M', 0x00F6, 'l', 'l', 'e', 'r' }, &.{ 'M', 'u', 'e', 'l', 'l', 'e', 'r' }, &.{ 'a', 'b', 'c' }, &.{ 'a', 'b', 'c', 'X' }, &.{ 'b', 'l', 'a', 'c', 'k', 'b', 'i', 'r', 'd' }, &.{ 'b', 'l', 'a', 'c', 'k', '-', 'b', 'i', 'r', 'd' }, // Derived weights: Han, Hangul, and a script with its own implicit range. &.{0x4E00}, &.{0x4E01}, &.{0xAC00}, &.{0xD7A3}, &.{0x3042}, &.{0x30A2}, // Greek and Cyrillic, which the two roots group differently. &.{0x03B1}, &.{0x0410}, } ++ hangul_shapes;