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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
// Checks this library's collation against ICU, which is the reference// implementation of the CLDR collation algorithm and the thing every other// collation is checked against in turn.//// tools/oracle_dump.zig writes one comparison per line -- the locale, two// strings as hexadecimal code points, and the order this library puts them// in -- and this asks ICU the same question and reports every answer that// differs.//// There is no conformance suite for a tailoring. UTS #10 ships one for the// DUCET and CLDR ships one for its root, and both of those are already run// by `zig build test-conformance` and `test-conformance-cldr`; for the// per-locale tailorings there is nothing, which is why this exists.//// Three things are set so that the two are answering the same question// rather than nearly the same one://// Strength and alternate handling come from the dump's `#mode` line, and// are set on both sides. `tertiary` is tertiary strength with// non-ignorable handling, which is ICU's default for most locales but not// all, and a disagreement about a setting is not a disagreement about the// ordering. `primary`, `secondary` and `identical` are the other strengths// at the same handling, and `shifted` is quaternary strength with shifted// handling -- the path the conformance suites cover for the roots and// nothing covers for a tailoring.//// Normalization is on. This library always normalizes -- step 1 of the// algorithm is not optional here -- and ICU's FCD fast path is off by// default for most locales, so without this a string that is not already// in FCD form would be ordered by two different routes.//// Usage: oracle <path to the dump>
#include <unicode/coll.h>#include <unicode/tblcoll.h>#include <unicode/locid.h>#include <unicode/unistr.h>#include <unicode/uversion.h>
#include <cstdio>#include <cstdlib>#include <map>#include <memory>#include <string>#include <vector>
namespace {
// "0061 0308 " -> the string those code points spell.icu::UnicodeString parseHex(const std::string &field) { icu::UnicodeString out; std::size_t i = 0; while (i < field.size()) { while (i < field.size() && field[i] == ' ') i++; if (i >= field.size()) break; std::size_t end = i; while (end < field.size() && field[end] != ' ') end++; out.append(static_cast<UChar32>( std::strtoul(field.substr(i, end - i).c_str(), nullptr, 16))); i = end; } return out;}
std::string showHex(const std::string &field) { return field; }
const char *orderName(int32_t comparison) { if (comparison < 0) return "lt"; if (comparison > 0) return "gt"; return "eq";}
// What the dump's `#mode` line asked for, which both sides are set to.icu::Collator::ECollationStrength mode_strength = icu::Collator::TERTIARY;UColAttributeValue mode_alternate = UCOL_NON_IGNORABLE;// `UCOL_DEFAULT` leaves the locale's own, which is what every mode but the// three case ones wants: `[caseFirst]` and `[caseLevel]` are locale data on// both sides, so a collator for Danish puts uppercase first whether it is// asked to or not.UColAttributeValue mode_case_first = UCOL_DEFAULT;UColAttributeValue mode_case_level = UCOL_DEFAULT;
// Locales whose tailoring is empty, so this library had nothing to compare.std::vector<std::string> no_tailoring;// Locales ICU has no collation data for, so nothing was compared.std::vector<std::string> no_data;// Locales ICU knows but carries no tailoring for, likewise.std::vector<std::string> no_rules;
// One collator per locale, built once.icu::Collator *collatorFor(const std::string &locale, std::map<std::string, std::shared_ptr<icu::Collator>> &cache) { auto found = cache.find(locale); if (found != cache.end()) return found->second.get();
UErrorCode status = U_ZERO_ERROR; // CLDR spells a locale `de_AT`, which is what ICU wants too. icu::Locale asked(locale.c_str()); std::shared_ptr<icu::Collator> collator(icu::Collator::createInstance(asked, status)); if (U_FAILURE(status)) { std::fprintf(stderr, "icu: no collator for %s: %s\n", locale.c_str(), u_errorName(status)); cache[locale] = nullptr; return nullptr; }
// ICU falls back to the root for a locale it has no data for, silently // and successfully. Comparing against that is not comparing against a // tailoring -- it asks whether this library agrees with ICU's *root* // about a locale ICU has never heard of, and counts every place the // tailoring does its job as a difference. CLDR ships rules for a number // of locales ICU does not carry, so this is not a rare case: of 72 // locales it turned up six, and they accounted for well over half of the // differences in the first run that measured them. // // A fallback to a *different* locale is still a comparison: ICU maps `no` // to `nb`, which is Norwegian either way. Only a fallback all the way to // the root means there was nothing to ask. UErrorCode valid_status = U_ZERO_ERROR; icu::Locale got = collator->getLocale(ULOC_VALID_LOCALE, valid_status); if (U_SUCCESS(valid_status) && locale != "und" && std::string(got.getName()).empty()) { cache[locale] = nullptr; no_data.push_back(locale); return nullptr; }
// And the case a valid locale does not rule out: ICU knows the locale but // carries no tailoring for it, so the collator is the root under another // name. Asking for its rules is the only way to tell -- `ca` and `sa` are // both like this, and both looked like real disagreements until the rules // came back empty. CLDR ships tailorings ICU does not build. if (locale != "und") { icu::UnicodeString rules = static_cast<icu::RuleBasedCollator *>(collator.get())->getRules(); if (rules.isEmpty()) { cache[locale] = nullptr; no_rules.push_back(locale); return nullptr; } }
status = U_ZERO_ERROR; collator->setStrength(mode_strength); collator->setAttribute(UCOL_ALTERNATE_HANDLING, mode_alternate, status); collator->setAttribute(UCOL_CASE_FIRST, mode_case_first, status); collator->setAttribute(UCOL_CASE_LEVEL, mode_case_level, status); collator->setAttribute(UCOL_NORMALIZATION_MODE, UCOL_ON, status); if (U_FAILURE(status)) { std::fprintf(stderr, "icu: cannot set attributes for %s: %s\n", locale.c_str(), u_errorName(status)); cache[locale] = nullptr; return nullptr; }
cache[locale] = collator; return collator.get();}
struct Tally { long compared = 0; long differed = 0; long shown = 0;};
// How many differing comparisons to print per locale before summarizing.// Eight is enough to see that something is wrong and rarely enough to see// *what*: a finding is usually one rule shape repeated, and telling which// shape means seeing a spread of them. `ORACLE_SHOW=200` when diagnosing.long showLimit() { const char *asked = std::getenv("ORACLE_SHOW"); if (asked == nullptr) return 8; long n = std::strtol(asked, nullptr, 10); return n > 0 ? n : 8;}
} // namespace
int main(int argc, char **argv) { // `oracle --rules <locale>` prints the tailoring ICU actually loaded. // // Worth having as a first question rather than a last one. A // disagreement can mean this library read CLDR's rules wrongly, or it can // mean ICU is carrying a different version of them -- ICU 78 bundles a // CLDR release, and the files in `data/` and in the pinned CLDR archive // need not be that one. Comparing the two rule texts settles which // before anybody goes looking through weights. if (argc == 3 && std::string(argv[1]) == "--rules") { std::map<std::string, std::shared_ptr<icu::Collator>> cache; icu::Collator *collator = collatorFor(argv[2], cache); if (collator == nullptr) { std::printf("ICU has no collation data for %s\n", argv[2]); return 1; } icu::UnicodeString rules = static_cast<icu::RuleBasedCollator *>(collator)->getRules(); std::string utf8; rules.toUTF8String(utf8); std::printf("ICU %s rules for %s:\n%s\n", U_ICU_VERSION, argv[2], utf8.c_str()); return 0; }
if (argc != 2) { std::fprintf(stderr, "usage: oracle <dump> | oracle --rules <locale>\n"); return 2; } std::FILE *in = std::fopen(argv[1], "r"); if (in == nullptr) { std::fprintf(stderr, "cannot open %s\n", argv[1]); return 2; }
std::printf("ICU %s\n", U_ICU_VERSION);
std::map<std::string, std::shared_ptr<icu::Collator>> collators; std::map<std::string, Tally> tallies; std::vector<std::string> order; const long show_limit = showLimit();
char *line = nullptr; std::size_t capacity = 0; ssize_t length = 0; while ((length = getline(&line, &capacity, in)) > 0) { std::string text(line, static_cast<std::size_t>(length)); while (!text.empty() && (text.back() == '\n' || text.back() == '\r')) text.pop_back(); if (text.empty()) continue;
// The mode the dump was written in, which must arrive before the // first collator is built. if (text.compare(0, 6, "#mode\t") == 0) { std::string asked = text.substr(6); if (asked == "primary") { mode_strength = icu::Collator::PRIMARY; mode_alternate = UCOL_NON_IGNORABLE; } else if (asked == "secondary") { mode_strength = icu::Collator::SECONDARY; mode_alternate = UCOL_NON_IGNORABLE; } else if (asked == "tertiary") { mode_strength = icu::Collator::TERTIARY; mode_alternate = UCOL_NON_IGNORABLE; } else if (asked == "identical") { mode_strength = icu::Collator::IDENTICAL; mode_alternate = UCOL_NON_IGNORABLE; } else if (asked == "quaternary") { mode_strength = icu::Collator::QUATERNARY; mode_alternate = UCOL_NON_IGNORABLE; } else if (asked == "shifted") { mode_strength = icu::Collator::QUATERNARY; mode_alternate = UCOL_SHIFTED; } else if (asked == "case_level") { mode_strength = icu::Collator::TERTIARY; mode_alternate = UCOL_NON_IGNORABLE; mode_case_level = UCOL_ON; mode_case_first = UCOL_OFF; } else if (asked == "upper_first") { mode_strength = icu::Collator::TERTIARY; mode_alternate = UCOL_NON_IGNORABLE; mode_case_level = UCOL_OFF; mode_case_first = UCOL_UPPER_FIRST; } else if (asked == "lower_first") { mode_strength = icu::Collator::TERTIARY; mode_alternate = UCOL_NON_IGNORABLE; mode_case_level = UCOL_OFF; mode_case_first = UCOL_LOWER_FIRST; } else { std::fprintf(stderr, "unknown mode: %s\n", asked.c_str()); return 2; } if (!collators.empty()) { std::fprintf(stderr, "the mode line must come before any comparison\n"); return 2; } std::printf("mode: %s\n", asked.c_str()); continue; }
// The dump says so rather than leaving it to be inferred from a // suspiciously small corpus. if (text.compare(0, 7, "#empty\t") == 0) { no_tailoring.push_back(text.substr(7)); continue; }
std::size_t t1 = text.find('\t'); std::size_t t2 = text.find('\t', t1 + 1); std::size_t t3 = text.find('\t', t2 + 1); if (t1 == std::string::npos || t2 == std::string::npos || t3 == std::string::npos) { std::fprintf(stderr, "malformed line: %s\n", text.c_str()); return 2; } std::string locale = text.substr(0, t1); std::string a = text.substr(t1 + 1, t2 - t1 - 1); std::string b = text.substr(t2 + 1, t3 - t2 - 1); std::string ours = text.substr(t3 + 1);
icu::Collator *collator = collatorFor(locale, collators); if (collator == nullptr) continue;
if (tallies.find(locale) == tallies.end()) order.push_back(locale); Tally &tally = tallies[locale];
UErrorCode status = U_ZERO_ERROR; int32_t comparison = collator->compare(parseHex(a), parseHex(b), status); if (U_FAILURE(status)) { std::fprintf(stderr, "icu: compare failed: %s\n", u_errorName(status)); return 2; }
tally.compared++; const char *theirs = orderName(comparison); if (ours != theirs) { tally.differed++; if (tally.shown < show_limit) { tally.shown++; std::printf(" %-8s %-24s %-24s ours=%s icu=%s\n", locale.c_str(), showHex(a).c_str(), showHex(b).c_str(), ours.c_str(), theirs); } } } std::free(line); std::fclose(in);
if (!no_tailoring.empty()) { std::printf("\nCLDR gives these no tailoring, so this library had nothing to compare:\n "); for (const std::string &locale : no_tailoring) std::printf(" %s", locale.c_str()); std::printf("\n"); } if (!no_data.empty()) { std::printf("\nICU has no collation data for these, so they were not compared:\n "); for (const std::string &locale : no_data) std::printf(" %s", locale.c_str()); std::printf("\n"); } if (!no_rules.empty()) { std::printf("\nICU knows these but carries no tailoring for them, so likewise:\n "); for (const std::string &locale : no_rules) std::printf(" %s", locale.c_str()); std::printf("\n"); } std::printf("\n");
long total = 0; for (const std::string &locale : order) { const Tally &tally = tallies[locale]; total += tally.differed; if (tally.differed > tally.shown) { std::printf(" %-8s ... and %ld more\n", locale.c_str(), tally.differed - tally.shown); } std::printf("%-8s %7ld / %ld comparisons differ\n", locale.c_str(), tally.differed, tally.compared); } std::printf("%ld differences in total\n", total); return total == 0 ? 0 : 1;}