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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883// 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.//// And a comparison ICU cannot answer is set aside rather than counted. When// ICU is on an older Unicode than the dump -- the dump's `#unicode` line says// which it was built from -- a character added since is unassigned to ICU,// weighed after everything else by section 10.1.3, and every comparison it// takes part in disagrees for that reason alone. ICU 78 against Unicode 18.0.0// made 91,741 such differences and no others. So a pair holding a code point// ICU says was never assigned is skipped and counted, and only while ICU is// behind; once it catches up nothing is skipped. That costs the code points// unassigned in both versions too, which ICU could have answered, and it is// the price of not having to carry a second copy of the UCD here.//// A dump that begins `#search` asks about search instead: each record is// the locale, a comparison (`primary`, `secondary`, `tertiary` or// `shifted`), a pattern, a target, where this library found the pattern in// the target as two code point offsets or `-`, and the offsets where it would// let a match begin or end. ICU's// `StringSearch` is asked for its first match and the two answers are// compared.//// Four differences of convention are set aside rather than counted, each// with a tally of its own, because each is a choice the two make differently// rather than a disagreement about the collation://// A pattern that weighs nothing at the strength asked for -- a lone accent// at primary strength -- matches everywhere here, as an empty range, which// is what `contains(x, "")` conventionally answers. ICU matches it nowhere.//// ICU will end a match inside a grapheme cluster, as long as it does not// split a combining sequence: the L and V of a Hangul syllable spelled in// jamo, say. Whole-character boundaries do not allow that.//// ICU will end a match between two collation elements that one// contraction produced -- `L` inside the CLDR root's `L·`, for instance --// where this library never splits what the collation weighed as one.//// ICU's search and ICU's collation do not always agree, and when they do// not, the collation is the one that passes UCA's conformance suite. The// case that comes up most is shifted handling: the search treats every element// without a primary weight as ignorable, where UCA, and ICU's collator,// make only those that follow a variable element so. So when ICU's search// matches text its own collator says differs from the pattern, or finds// nothing where its collator calls this library's match equal to the// pattern, the two ICU answers are at odds and the comparison says nothing// about this one.//// Usage: oracle <path to the dump>
#include <unicode/coleitr.h>#include <unicode/coll.h>#include <unicode/tblcoll.h>#include <unicode/brkiter.h>#include <unicode/locid.h>#include <unicode/stsearch.h>#include <unicode/uchar.h>#include <unicode/unistr.h>#include <unicode/uversion.h>
#include <cstdio>#include <cstdlib>#include <map>#include <memory>#include <set>#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;
// Whether ICU's Unicode is older than the one the dump was written from,// from the dump's `#unicode` line. Only then are comparisons set aside.bool icu_behind = false;
// "18.0.0" against ICU's own version, field by field.bool olderThan(const UVersionInfo icu, const std::string &dump) { UVersionInfo theirs; u_versionFromString(theirs, dump.c_str()); for (int i = 0; i < U_MAX_VERSION_LENGTH; i++) { if (icu[i] != theirs[i]) return icu[i] < theirs[i]; } return false;}
// Whether every code point in `s` is one ICU knows. `u_charAge` is 0.0.0.0// only for a code point never assigned -- a noncharacter, a surrogate and a// private-use code point all have an age -- so this asks exactly "was this// assigned in the Unicode ICU carries".bool knownToIcu(const icu::UnicodeString &s) { for (int32_t i = 0; i < s.length(); i = s.moveIndex32(i, 1)) { UVersionInfo age; u_charAge(s.char32At(i), age); if (age[0] == 0 && age[1] == 0 && age[2] == 0 && age[3] == 0) return false; } return true;}
// 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; long unknown = 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;}
// The collator settings a search comparison names.bool searchSettings(const std::string &comparison) { mode_case_first = UCOL_DEFAULT; mode_case_level = UCOL_DEFAULT; mode_alternate = UCOL_NON_IGNORABLE; if (comparison == "primary") { mode_strength = icu::Collator::PRIMARY; } else if (comparison == "secondary" || comparison == "secondary-asymmetric") { mode_strength = icu::Collator::SECONDARY; } else if (comparison == "tertiary" || comparison == "tertiary-asymmetric") { mode_strength = icu::Collator::TERTIARY; } else if (comparison == "shifted") { mode_strength = icu::Collator::QUATERNARY; mode_alternate = UCOL_SHIFTED; } else { return false; } return true;}
// Whether ICU's own grapheme cluster segmentation puts a boundary at UTF-16// offset `at` of `s`.bool graphemeBoundary(const icu::UnicodeString &s, int32_t at) { static std::unique_ptr<icu::BreakIterator> characters; if (!characters) { UErrorCode status = U_ZERO_ERROR; characters.reset(icu::BreakIterator::createCharacterInstance(icu::Locale::getRoot(), status)); if (U_FAILURE(status)) return true; } characters->setText(s); return characters->isBoundary(at);}
// Whether ICU's collator weighs code point offset `at` of `s` with no// primary weight and something at a lower level: what ICU's asymmetric// search lets a match pass over.bool primaryIgnorable(icu::Collator *collator, const icu::UnicodeString &s, int32_t at) { int32_t from = s.moveIndex32(0, at); icu::UnicodeString one(s.char32At(from)); std::unique_ptr<icu::CollationElementIterator> elements( static_cast<icu::RuleBasedCollator *>(collator)->createCollationElementIterator(one)); UErrorCode status = U_ZERO_ERROR; bool weighs = false; for (int32_t order = elements->next(status); U_SUCCESS(status) && order != icu::CollationElementIterator::NULLORDER; order = elements->next(status)) { if (icu::CollationElementIterator::primaryOrder(order) != 0) return false; if (icu::CollationElementIterator::secondaryOrder(order) != 0 || icu::CollationElementIterator::tertiaryOrder(order) != 0) weighs = true; } return weighs;}
// The collation elements ICU gives `s`, as 32-bit orders, without ignorable// ones and, unless asked, without continuations -- the second halves of// weights too long for one 32-bit order.std::vector<int32_t> icuElements(icu::Collator *collator, const icu::UnicodeString &s, bool continuations = false) { std::vector<int32_t> out; std::unique_ptr<icu::CollationElementIterator> elements( static_cast<icu::RuleBasedCollator *>(collator)->createCollationElementIterator(s)); UErrorCode status = U_ZERO_ERROR; for (int32_t order = elements->next(status); U_SUCCESS(status) && order != icu::CollationElementIterator::NULLORDER; order = elements->next(status)) { // Not `isIgnorable`, which means primary-ignorable and would drop // every accent. if (order == 0) continue; if ((order & 0xC0) == 0xC0 && !continuations) continue; out.push_back(order); } return out;}
// `unmarkedSignature` in tools/oracle_dump.zig, from ICU's elements: COMMON// is 05 at both levels there, and the case bits are the top two of the// tertiary byte. A continuation carrying the rest of a long secondary weight// counts as an element of its own, because that is how ICU's asymmetric// comparison reads it: Korean hanja end in one whose byte is 05, which it// takes for COMMON.std::string icuUnmarked(icu::Collator *collator, const icu::UnicodeString &s) { std::string out; for (int32_t order : icuElements(collator, s, true)) { bool continuation = (order & 0xC0) == 0xC0; if (icu::CollationElementIterator::primaryOrder(order) == 0 && !(continuation && icu::CollationElementIterator::secondaryOrder(order) != 0)) continue; out += icu::CollationElementIterator::secondaryOrder(order) == 0x05 ? '1' : '0'; } std::vector<int32_t> elements = icuElements(collator, s); out += '/'; for (int32_t order : elements) { out += (icu::CollationElementIterator::tertiaryOrder(order) & 0x3F) == 0x05 && (order & 0xC0) == 0 ? '1' : '0'; } return out;}
// What ICU's `StringSearch` said about one search.struct IcuMatch { // Refused to search at all, as it does for an empty pattern. bool refused = false; // The match as code point offsets in the form the dump writes them, or // `-` for none. std::string answer; // Whether the match starts or ends inside a grapheme cluster, which this // library's `whole_character` boundary never allows. ICU's search // checks only that a match does not split a combining sequence, so it // will match the L and V of a Hangul L V T syllable spelled in jamo; that // is a different convention rather than a disagreement about weights. bool splits_grapheme = false;};
// Where ICU's `StringSearch` first finds `pattern` in `target`.IcuMatch icuSearch(icu::Collator *collator, const icu::UnicodeString &pattern, const icu::UnicodeString &target, bool asymmetric) { IcuMatch out; UErrorCode status = U_ZERO_ERROR; icu::StringSearch search(pattern, target, static_cast<icu::RuleBasedCollator *>(collator), nullptr, status); if (asymmetric && U_SUCCESS(status)) { search.setAttribute(USEARCH_ELEMENT_COMPARISON, USEARCH_PATTERN_BASE_WEIGHT_IS_WILDCARD, status); } int32_t at = U_SUCCESS(status) ? search.first(status) : USEARCH_DONE; if (U_FAILURE(status)) { out.refused = true; return out; } if (at == USEARCH_DONE) { out.answer = "-"; return out; } int32_t length = search.getMatchedLength(); out.splits_grapheme = !graphemeBoundary(target, at) || !graphemeBoundary(target, at + length); int32_t start = target.countChar32(0, at); int32_t end = start + target.countChar32(at, length); out.answer = std::to_string(start) + " " + std::to_string(end); return out;}
} // 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; // For search, one cache per comparison, since each sets the collator // differently and ICU reads the settings when a search is made. std::map<std::string, std::map<std::string, std::shared_ptr<icu::Collator>>> search_collators; bool searching = false; long icu_refused = 0; long icu_split = 0; long empty_pattern = 0; long icu_inside_unit = 0; long icu_at_odds = 0; long asymmetric_span = 0; long asymmetric_tertiary = 0; long asymmetric_absorbs = 0; long asymmetric_followed = 0; long asymmetric_unmarked = 0; 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; }
if (text.compare(0, 9, "#unicode\t") == 0) { std::string version = text.substr(9); UVersionInfo ours; u_getUnicodeVersion(ours); icu_behind = olderThan(ours, version); char icu_version[U_MAX_VERSION_STRING_LENGTH]; u_versionToString(ours, icu_version); std::printf("Unicode: %s here, %s in ICU\n", version.c_str(), icu_version); continue; }
if (text == "#search") { searching = true; std::printf("mode: search\n"); 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; }
if (searching) { std::size_t f1 = text.find('\t'); std::size_t f2 = text.find('\t', f1 + 1); std::size_t f3 = text.find('\t', f2 + 1); std::size_t f4 = text.find('\t', f3 + 1); std::size_t f5 = text.find('\t', f4 + 1); if (f1 == std::string::npos || f2 == std::string::npos || f3 == std::string::npos || f4 == std::string::npos || f5 == std::string::npos) { std::fprintf(stderr, "malformed line: %s\n", text.c_str()); return 2; } std::string locale = text.substr(0, f1); std::string comparison = text.substr(f1 + 1, f2 - f1 - 1); std::string a = text.substr(f2 + 1, f3 - f2 - 1); std::string b = text.substr(f3 + 1, f4 - f3 - 1); std::string ours = text.substr(f4 + 1, f5 - f4 - 1); // The edges, and for an asymmetric search two more fields: this // library's maximal match and its asymmetric match at secondary // strength. std::size_t f6 = text.find('\t', f5 + 1); std::string edges = " " + text.substr(f5 + 1, f6 == std::string::npos ? std::string::npos : f6 - f5 - 1) + " "; std::string ours_maximal, ours_secondary, ours_unbounded, ours_unmarked; if (f6 != std::string::npos) { std::size_t f7 = text.find('\t', f6 + 1); std::size_t f8 = text.find('\t', f7 + 1); std::size_t f9 = text.find('\t', f8 + 1); ours_maximal = text.substr(f6 + 1, f7 - f6 - 1); ours_secondary = text.substr(f7 + 1, f8 - f7 - 1); ours_unbounded = text.substr(f8 + 1, f9 - f8 - 1); ours_unmarked = text.substr(f9 + 1); }
if (!searchSettings(comparison)) { std::fprintf(stderr, "unknown comparison: %s\n", comparison.c_str()); return 2; } icu::Collator *collator = collatorFor(locale, search_collators[comparison]); if (collator == nullptr) continue;
std::string label = locale + " " + comparison; if (tallies.find(label) == tallies.end()) order.push_back(label); Tally &tally = tallies[label];
icu::UnicodeString pattern = parseHex(a); icu::UnicodeString target = parseHex(b); if (icu_behind && !(knownToIcu(pattern) && knownToIcu(target))) { tally.unknown++; continue; } const bool asymmetric = comparison.find("-asymmetric") != std::string::npos; IcuMatch icu_match = icuSearch(collator, pattern, target, asymmetric); if (icu_match.refused) { icu_refused++; continue; } const std::string &theirs = icu_match.answer; if (ours != theirs) { if (icu_match.splits_grapheme) { icu_split++; continue; } int ours_start = -1, ours_end = -1; std::sscanf(ours.c_str(), "%d %d", &ours_start, &ours_end); if (theirs == "-" && ours_start >= 0 && ours_start == ours_end) { empty_pattern++; continue; } int theirs_start = -1, theirs_end = -1; std::sscanf(theirs.c_str(), "%d %d", &theirs_start, &theirs_end); if (theirs_start >= 0 && (edges.find(" " + std::to_string(theirs_start) + " ") == std::string::npos || edges.find(" " + std::to_string(theirs_end) + " ") == std::string::npos)) { icu_inside_unit++; continue; } // The match each side found, as a string, judged by ICU's // collator against the pattern. auto substring = [&](int start, int end) { int32_t from = target.moveIndex32(0, start); int32_t to = target.moveIndex32(0, end); return icu::UnicodeString(target, from, to - from); }; auto collatorSaysEqual = [&](const icu::UnicodeString &candidate) { UErrorCode compare_status = U_ZERO_ERROR; return collator->compare(pattern, candidate, compare_status) == UCOL_EQUAL; }; // Not for an asymmetric search, whose matches are not // equal to the pattern by the collator's lights: that is // what asymmetric means. It has two conventions of its own. if (asymmetric) { // ICU's match takes in accents before or after it that // the pattern has nothing for, which the minimal match // leaves out and the maximal one takes in: both are // matches, and ICU's lies between them. int max_start = -1, max_end = -1; std::sscanf(ours_maximal.c_str(), "%d %d", &max_start, &max_end); if (theirs_start >= 0 && ours_start >= 0 && max_start >= 0 && max_start <= theirs_start && theirs_start <= ours_start && ours_end <= theirs_end && theirs_end <= max_end) { asymmetric_span++; continue; } // ICU's match goes on over characters with no primary // weight before or after it -- after it, each one taken // because it lines up with the pattern's last element // or follows an element with a primary weight. Here a // pattern that ends in an accent, or in the variant // marker the DUCET spells a compatibility form with, // matches only a character marked the same way, so the // marks after it make the character a different one, // and a mark before it is a cluster of its own that the // minimal match leaves out. Without boundaries this // library's match is ICU's less those characters. int un_start = -1, un_end = -1; std::sscanf(ours_unbounded.c_str(), "%d %d", &un_start, &un_end); if (theirs_start >= 0 && un_start >= theirs_start && un_end <= theirs_end) { bool passed_over = true; for (int k = theirs_start; k < un_start; k++) { if (!primaryIgnorable(collator, target, k)) passed_over = false; } for (int k = un_end; k < theirs_end; k++) { if (!primaryIgnorable(collator, target, k)) passed_over = false; } if (passed_over) { asymmetric_absorbs++; continue; } } // ICU's match took in more characters with no primary // weight, each weighing exactly what the pattern's last // character does: ICU lets a repeat of the pattern's // last accent line up with it again. Here a character // marked twice is not one marked once. if (theirs_start >= 0) { int32_t pattern_chars = pattern.countChar32(); icu::UnicodeString last(pattern.char32At(pattern.moveIndex32(pattern.length(), -1))); std::vector<int32_t> last_elements = icuElements(collator, last); bool repeats = theirs_end - theirs_start > pattern_chars && primaryIgnorable(collator, last, 0); for (int k = theirs_start + pattern_chars - 1; repeats && k < theirs_end; k++) { icu::UnicodeString one(target.char32At(target.moveIndex32(0, k))); if (icuElements(collator, one) != last_elements) repeats = false; } if (repeats) { asymmetric_absorbs++; continue; } } // ICU refuses a match when the character after it has no // primary weight and does not line up with the pattern's // last element, even when that character is a grapheme // cluster of its own; here the match ends at the // cluster boundary and what follows is not part of it. if (ours_start >= 0 && ours_end < target.countChar32() && graphemeBoundary(target, target.moveIndex32(0, ours_end)) && primaryIgnorable(collator, target, ours_end)) { asymmetric_followed++; continue; } // ICU and this library take different weights of the // pattern to be unmarked. ICU's encoding of the CLDR // root makes some compatibility variants COMMON, and a // kana's normal form is unmarked here and not in ICU. if (!ours_unmarked.empty() && ours_unmarked != icuUnmarked(collator, pattern)) { asymmetric_unmarked++; continue; } // ICU and this library agree once tertiary weights are // set aside, and differ about which of them are // unmarked: ICU's encoding of the CLDR root makes some of // its compatibility variants unmarked, a tailoring's // chain positions are its own, and ICU does not let a // normal kana find its small form. if (comparison == "tertiary-asymmetric") { searchSettings("secondary-asymmetric"); icu::Collator *at_secondary = collatorFor(locale, search_collators["secondary-asymmetric"]); searchSettings(comparison); if (at_secondary != nullptr && icuSearch(at_secondary, pattern, target, true).answer == ours_secondary) { asymmetric_tertiary++; continue; } } } else if ((theirs_start >= 0 && !collatorSaysEqual(substring(theirs_start, theirs_end))) || (theirs == "-" && ours_start >= 0 && collatorSaysEqual(substring(ours_start, ours_end)))) { icu_at_odds++; continue; } } tally.compared++; if (ours != theirs) { tally.differed++; if (tally.shown < show_limit) { tally.shown++; std::printf(" %-8s %-9s %-20s %-36s ours=%s icu=%s\n", locale.c_str(), comparison.c_str(), a.c_str(), b.c_str(), ours.c_str(), theirs.c_str()); } } 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];
icu::UnicodeString first = parseHex(a); icu::UnicodeString second = parseHex(b); if (icu_behind && !(knownToIcu(first) && knownToIcu(second))) { tally.unknown++; continue; }
UErrorCode status = U_ZERO_ERROR; int32_t comparison = collator->compare(first, second, 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"); } // A search run builds a collator per comparison, so the same locale can // be listed once for each; say each once. if (!no_data.empty()) { std::printf("\nICU has no collation data for these, so they were not compared:\n "); std::set<std::string> said; for (const std::string &locale : no_data) { if (said.insert(locale).second) 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 "); std::set<std::string> said; for (const std::string &locale : no_rules) { if (said.insert(locale).second) std::printf(" %s", locale.c_str()); } std::printf("\n"); } if (icu_split > 0) { std::printf("\nICU matched inside a grapheme cluster %ld times, which whole-character " "boundaries do not allow\n", icu_split); } if (empty_pattern > 0) { std::printf("\nA pattern weighing nothing matched here as an empty range and not in " "ICU %ld times\n", empty_pattern); } if (icu_inside_unit > 0) { std::printf("\nICU ended a match inside what this collation weighs as one %ld times\n", icu_inside_unit); } if (icu_at_odds > 0) { std::printf("\nICU's search and ICU's collator disagreed about the match %ld times\n", icu_at_odds); } if (asymmetric_span > 0) { std::printf("\nICU's asymmetric match took in accents beside it that the minimal match " "leaves out %ld times\n", asymmetric_span); } if (asymmetric_absorbs > 0) { std::printf("\nICU's asymmetric match took in characters with no primary weight " "that a match here leaves out or cannot reach %ld times\n", asymmetric_absorbs); } if (asymmetric_followed > 0) { std::printf("\nICU refused an asymmetric match followed by a character with no " "primary weight in a cluster of its own %ld times\n", asymmetric_followed); } if (asymmetric_unmarked > 0) { std::printf("\nICU and this library took different weights of the pattern to be " "unmarked %ld times\n", asymmetric_unmarked); } if (asymmetric_tertiary > 0) { std::printf("\nICU's asymmetric search and this library differed only about which " "tertiary weights are unmarked %ld times\n", asymmetric_tertiary); } if (icu_refused > 0) { std::printf("\nICU refused to search %ld times (an empty or ignorable pattern)\n", icu_refused); } std::printf("\n");
long total = 0; long unknown = 0; for (const std::string &locale : order) { const Tally &tally = tallies[locale]; total += tally.differed; unknown += tally.unknown; 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); } if (unknown > 0) { std::printf("%ld comparisons set aside: they hold a character this ICU's Unicode " "does not have\n", unknown); } std::printf("%ld differences in total\n", total); return total == 0 ? 0 : 1;}