// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Turns one CLDR locale's collation rules into the Zig source of a //! `Tailoring`: UTS #10 section 8, and the rule syntax of //! [UTS #35 part 5][ldml]. //! //! A tailoring is a delta over a root table, not a table of its own, and the //! weights of the elements it inserts come from `Element.primary_sub`. The //! point of doing this at build time rather than at run time is that the //! generator can see the whole root table at once, which is what makes a //! weight between two existing ones findable at all. //! //! ## What the rules say //! //! A rule file is a sequence of resets and relations: //! //! &Y<<ü<<<Ü ü sorts as a secondary variant of Y, Ü as a //! tertiary variant of ü //! &[before 1]i<ı ı gets a primary weight just below i's //! &t<<<þ/h þ sorts as a tertiary variant of t followed by h //! //! `&` resets the cursor to an anchor. Each following relation inserts its //! target immediately after the cursor at the given strength and becomes the //! new cursor: `<` primary, `<<` secondary, `<<<` tertiary, `=` identical. //! //! ## How the weights are chosen //! //! Two rules, and everything else follows from them. //! //! **The target maps to a sequence, not to one element.** The cursor is the //! whole collation element sequence of the reset position, or of the previous //! relation's target. A relation increments the last element of at least the //! operator's own strength, drops whatever followed it, and maps the target to //! what remains -- so `&ae " ++ "[--root=ducet|cldr] [--collation-dir=DIR]\n", .{}, ); return error.WrongNumberOfArguments; } const locale = args[1]; var collation_dir: ?[]const u8 = null; var dump_groups = false; for (args[5..]) |arg| { if (std.mem.eql(u8, arg, "--dump-groups")) { dump_groups = true; continue; } if (std.mem.startsWith(u8, arg, "--collation-dir=")) { collation_dir = arg["--collation-dir=".len..]; continue; } if (std.mem.eql(u8, arg, "--root=cldr")) { if (collate.cldr_root.stage1.len == 0) { std.debug.print( "--root=cldr needs the CLDR root table, which this build does not have\n", .{}, ); return error.NoCldrRoot; } root = collate.cldr_root; } else if (!std.mem.eql(u8, arg, "--root=ducet")) { std.debug.print("not an argument: {s}\n", .{arg}); return error.UnknownArgument; } } const cwd: std.Io.Dir = .cwd(); const xml = try cwd.readFileAlloc(io, args[2], arena, .limited(4 << 20)); const fractional = try cwd.readFileAlloc(io, args[3], arena, .limited(32 << 20)); const rules = extractRules(xml) orelse { // A locale with no `standard` tailoring at all is not an error: 23 of // CLDR's 135 are ordered by the root collation, German and French // among them. It gets an empty tailoring, which costs nothing and // keeps `collate.locales` uniform. var source: std.Io.Writer.Allocating = .init(arena); try emitEmpty(&source.writer, locale); try cwd.writeFile(io, .{ .sub_path = args[4], .data = source.written() }); return 0; }; var builder: Builder = .init(arena, locale); builder.groups = try reorderGroups(arena, fractional); // `--dump-groups` prints the reordering groups and stops, which is how // one finds out where a tailored primary weight lands. Nothing in the // build passes it. if (dump_groups) { for (builder.groups) |g| { std.debug.print("{s:<24} {s:<6} 0x{X:0>4}..0x{X:0>4}\n", .{ g.marker, g.code, g.first, g.last, }); } return 0; } builder.collation_dir = collation_dir; builder.io = io; builder.run(rules) catch |err| { std.debug.print( "{s}: {t} at rule offset {d}\n {s}\n", .{ locale, err, builder.offset, builder.context(rules) }, ); return err; }; var source: std.Io.Writer.Allocating = .init(arena); try builder.emit(&source.writer); try cwd.writeFile(io, .{ .sub_path = args[4], .data = source.written() }); return 0; } /// Which file an `[import …]` names, and which collation inside it. /// /// `es` is the `standard` collation of `es.xml`. `ja-u-co-private-kana` is the /// `private-kana` collation of `ja.xml`, the `-u-co-` being a BCP 47 /// extension naming a collation type. A subtag is written with a hyphen in an /// identifier and an underscore in a file name, so `sr-Latn` is /// `sr_Latn.xml`; and the root locale is spelled `und` but its file is /// `root.xml`. fn importTarget( arena: Allocator, value: []const u8, ) !struct { file_stem: []const u8, collation: []const u8 } { var id = value; var collation: []const u8 = "standard"; if (std.mem.find(u8, value, "-u-co-")) |at| { id = value[0..at]; collation = value[at + "-u-co-".len ..]; } if (id.len == 0) return error.MalformedImport; const file_stem = if (std.mem.eql(u8, id, "und") or std.mem.eql(u8, id, "root")) try arena.dupe(u8, "root") else try std.mem.replaceOwned(u8, arena, id, "-", "_"); return .{ .file_stem = file_stem, .collation = collation }; } /// The offset of the `` that closes the body, allowing for the /// spaces CLDR writes inside some of its tags. /// /// `pl.xml` ends its collation with ``, and a search for the /// literal tag does not find it. What made that worth a function of its own /// is how it failed: `extractRules` returned null, which means "this locale /// has no tailoring and is ordered by the root", so Polish generated /// cleanly, compiled, and ordered nothing. The oracle then compared the /// letters a to z, agreed with ICU about all 325 pairs of them, and reported /// no differences. fn findClose(body: []const u8) ?usize { var from: usize = 0; while (std.mem.findPos(u8, body, from, "') return at; from = at + 1; } return null; } /// The `standard` collation's rules out of a CLDR locale file. /// /// Targeted extraction rather than an XML parse. These files are machine /// generated and uniform, and the alternative is an XML parser in a library /// that has no other use for one. It is strict about the shape it expects, so /// a file that does not match yields null rather than something plausible. fn extractRules(xml: []const u8) ?[]const u8 { return extractRulesOfType(xml, "standard"); } /// The rules of one named collation out of a CLDR locale file. /// /// `standard` for a locale's own, and whatever `[import ja-u-co-private-kana]` /// asks for otherwise. fn extractRulesOfType(xml: []const u8, wanted: []const u8) ?[]const u8 { var rest = xml; while (std.mem.find(u8, rest, "') orelse return null; const tag = rest[0..tag_end]; const body_start = tag_end + 1; const body_end = findClose(rest[body_start..]) orelse return null; const body = rest[body_start..][0..body_end]; rest = rest[body_start + body_end ..]; var type_buf: [64]u8 = undefined; if (wanted.len + 8 > type_buf.len) return null; const needle = std.fmt.bufPrint(&type_buf, "type=\"{s}\"", .{wanted}) catch return null; if (std.mem.find(u8, tag, needle) == null) continue; const cr_open = std.mem.find(u8, body, "") orelse return null; const after = body[cr_open + "".len ..]; const cr_close = std.mem.find(u8, after, "") orelse return null; var rules = after[0..cr_close]; // The rules are wrapped in CDATA, because `<` is the primary // relation operator and would otherwise have to be escaped on nearly // every line. if (std.mem.find(u8, rules, "")) |close| rules = rules[0..close]; } return rules; } return null; } /// Turns rules into a delta. const Builder = struct { arena: Allocator, locale: []const u8, offset: usize = 0, /// Where the cursor is: the collation elements the next relation /// modifies, which are the reset position's or the previous relation's /// own. /// /// A sequence rather than one element, because that is what makes an /// expansion. Section 3.3's algorithm increments the last element of /// sufficient strength, drops whatever followed it, and maps the target /// to what remains -- so `&ae<102D><<<<1023>`, and U+1023 then weighed as a lone vowel sign /// instead of as the letter and the sign together. ICU disagreed with /// 101,098 of 543,403 comparisons. cursor: []const Element = &.{}, /// True while the cursor is still an element of the root table, where a /// secondary or tertiary weight may be taken already. cursor_is_root: bool = true, /// True while the cursor is a logical reset position rather than a /// character's elements: see `reset`. cursor_is_position: bool = false, /// The sub-weight the next primary insertion should take, when /// `[before 1]` named an anchor that already has one. Null otherwise. before: ?Before = null, /// What the rules asked for that is a collator setting rather than a /// weight: `[caseFirst upper]` and its two relatives. settings: data.Settings = .{}, /// Code points whose root contractions `[suppressContractions …]` turns /// off. Sorted and deduplicated on the way out. suppressed: std.ArrayList(u21) = .empty, /// Where CLDR's collation files are, for `[import …]`. Null when the /// build did not say, which makes an import a refusal rather than a /// silent omission. collation_dir: ?[]const u8 = null, /// For reading them. io: ?std.Io = null, /// How many imports deep, so that a cycle is an error rather than a /// stack overflow. import_depth: usize = 0, /// How many root elements had to be shifted to make room, for the /// comment at the top of the generated file: it is the one number that /// says how much a tailoring disturbed the table around it. moved: usize = 0, /// The reordering groups in root order, and the ranges a `[reorder]` /// moved. groups: []const Group = &.{}, reorder_ranges: std.ArrayList(data.ReorderRange) = .empty, overrides: std.ArrayList(data.Override) = .empty, contractions: std.ArrayList(Contraction) = .empty, contraction_points: std.ArrayList(u21) = .empty, expansions: std.ArrayList(Element) = .empty, /// Every distinct primary weight in the root table, sorted, so that /// `[before 1]` can find the one below its anchor. /// Every primary weight the root uses, sorted, for `primaryBelow`. primaries: []const u16 = &.{}, /// The next weight to hand out, for a chain anchored at /// `&[last regular]`. /// /// Null for every other anchor, where a primary insertion goes *between* /// two weights the root is using and so must subdivide one of them. /// Above the last regular weight there is nothing to insert between, so a /// chain there takes fresh weights instead -- and takes them in pairs, /// rolling the primary when the sub-weights under it run out, because a /// sort key compares (primary, sub) lexicographically and the pair is one /// weight in two halves. /// /// Japanese is the rule that needs it and the reason it rolls: 6,355 /// kanji in JIS order hang off that anchor, and there are 2,047 /// sub-weights under a primary. It stops below `implicit_tail_bit`, which /// leaves 3,132 primaries above the last regular one and so six million /// weights before anything has to be refused. free: ?FreeWeight = null, /// The code points holding each root primary weight, so that `makeRoom` /// looks instead of scanning. See `collectByPrimary`. by_primary: std.AutoHashMapUnmanaged(u16, []const u21) = .empty, /// Where each overridden code point is in `overrides`, so that /// overriding one again is a lookup rather than a walk. override_index: std.AutoHashMapUnmanaged(u21, usize) = .empty, fn init(arena: Allocator, locale: []const u8) Builder { return .{ .arena = arena, .locale = locale }; } /// What a `[before N]` reset asks the next relation to do: take the /// anchor's own weight at that level, which the relation frees by moving /// the anchor up, and then move on to the next weight for the relation /// after it. /// /// Or, for a `[before 2]` on a letter with the COMMON secondary, take a /// weight below COMMON and leave the anchor where it is: see the /// secondary branch of `increment`. const Before = struct { level: Strength, weight: u16, below_common: bool = false, }; /// The weight a `[before N]` reset left for a relation of this strength, /// or null if there was no such reset or it was about another level. fn beforeAt(b: *const Builder, level: Strength) ?u16 { const before = b.before orelse return null; return if (before.level == level) before.weight else null; } fn context(b: *const Builder, rules: []const u8) []const u8 { // Clamped, because the offset and the rules can come from different // files: an `[import]` processes another locale's rules against this // builder, and `fa_AF`'s own rules are twenty bytes long while the // failure was at offset 33 of Pashto's. `import` puts the offset back // before it re-raises, and this is what stands between a bad // diagnostic and a panic in the diagnostic. const start = @min(b.offset -| 20, rules.len); const end = @min(rules.len, b.offset + 20); return rules[start..end]; } fn run(b: *Builder, rules: []const u8) !void { b.primaries = try collectPrimaries(b.arena); b.by_primary = try collectByPrimary(b.arena); try b.process(rules); // Searched by bisection at run time, so sorted here -- and // deduplicated, since a set can name a code point twice. std.mem.sort(u21, b.suppressed.items, {}, std.sort.asc(u21)); var unique: usize = 0; for (b.suppressed.items) |cp| { if (unique != 0 and cp == b.suppressed.items[unique - 1]) continue; b.suppressed.items[unique] = cp; unique += 1; } b.suppressed.shrinkRetainingCapacity(unique); // Both lists are searched by binary search at run time. std.mem.sort(data.Override, b.overrides.items, {}, overrideLessThan); std.mem.sort( Contraction, b.contractions.items, @as([]const u21, b.contraction_points.items), Contraction.lessThan, ); } /// One rule set, start to finish. Separate from `run` because /// `[import hr]` is another rule set processed in the middle of this one, /// against the same builder and the same cursor. /// /// `anyerror` because that recursion is a cycle through `setting` and /// `import`, and three mutually recursive inferred error sets are a /// dependency loop the compiler refuses. fn process(b: *Builder, rules: []const u8) anyerror!void { var p: Parser = .{ .rules = rules }; while (true) { p.skipSpace(); b.offset = p.i; if (p.done()) break; switch (p.rules[p.i]) { '&' => { p.i += 1; try b.reset(&p); }, '<', '=' => { const strength = try p.strength(); // `*` on the operator abbreviates a run of single // characters into one relation each. if (p.eat("*")) { try b.starred(&p, strength); } else { try b.relation(&p, strength); } }, '[' => try b.setting(&p), else => return error.UnexpectedCharacter, } } } /// A `[...]` at the top level is a parametric setting rather than a /// rule. /// /// Two of them are no-ops here and are accepted as such. The rest change /// the ordering, or change settings this library does not have, and are /// refused *by name* -- "this locale wants [reorder Grek]" is a report, /// where "UnsupportedOption" is a shrug. fn setting(b: *Builder, p: *Parser) !void { // To the *matching* bracket, not the first one. A setting's argument // can be a UnicodeSet, which is written in brackets of its own: // Korean's rules open with `[optimize [가-각간…]]`, eleven thousand // Hangul syllables in one of them, and Macedonian and Serbian write // `[suppressContractions [Ии]]`. Stopping at the first `]` leaves a // stray one behind, which is what "UnexpectedCharacter at rule offset // 7104" meant for Korean. var depth: usize = 0; var close = p.i; while (close < p.rules.len) : (close += 1) { switch (p.rules[close]) { '[' => depth += 1, ']' => { depth -= 1; if (depth == 0) break; }, else => {}, } } else return error.MalformedSetting; const text = p.rules[p.i .. close + 1]; p.i = close + 1; // `[normalization on]` asks for what step 1 does unconditionally, and // `[normalization off]` is a performance hint that a conformant // implementation may decline -- section 9.5's fast path is exactly // what it is asking for and this library does not have it. Either way // the ordering is the same. if (std.mem.startsWith(u8, text, "[normalization")) return; // Purely a hint about which characters to make fast. if (std.mem.startsWith(u8, text, "[optimize")) return; if (std.mem.startsWith(u8, text, "[reorder")) return b.reorder(text); if (settingValue(text, "import")) |value| return b.import(value); if (settingValue(text, "suppressContractions")) |value| { return b.suppressContractions(value); } // The three that are a collator's business rather than a table's. // They are recorded on the tailoring and applied by // `key.Options.applying`, so what they change is how a sort key is // built and not what any character weighs. if (settingValue(text, "caseFirst")) |value| { b.settings.case_first = if (eqlIgnoreCase(value, "upper")) .upper_first else if (eqlIgnoreCase(value, "lower")) .lower_first else if (eqlIgnoreCase(value, "off")) .off else return error.UnknownCaseFirst; return; } if (settingValue(text, "backwards")) |value| { // Section 3.8.1 allows the setting at any level and says only the // second is of practical use; `Options` has a bool for that one. if (!std.mem.eql(u8, value, "2")) return error.UnsupportedBackwardsLevel; b.settings.backwards_secondary = true; return; } if (settingValue(text, "caseLevel")) |value| { b.settings.case_level = if (eqlIgnoreCase(value, "on")) true else if (eqlIgnoreCase(value, "off")) false else return error.UnknownCaseLevel; return; } if (settingValue(text, "strength")) |value| { // The default number of levels to compare. Only `ja`'s private // kana collation sets one, and it sets 3, which is the default // this library already has -- but it is recorded rather than // waved through, because a locale that asked for 1 would mean it. b.settings.strength = if (std.mem.eql(u8, value, "1")) .primary else if (std.mem.eql(u8, value, "2")) .secondary else if (std.mem.eql(u8, value, "3")) .tertiary else if (std.mem.eql(u8, value, "4")) .quaternary else if (eqlIgnoreCase(value, "I")) .identical else return error.UnknownStrength; return; } if (settingValue(text, "alternate")) |value| { b.settings.alternate = if (eqlIgnoreCase(value, "shifted")) .shifted else if (eqlIgnoreCase(value, "non-ignorable")) .non_ignorable else return error.UnknownAlternate; return; } std.debug.print("{s}: unimplemented setting {s}\n", .{ b.locale, text }); return error.UnsupportedSetting; } /// The value of a one-word setting: `[caseFirst upper]` yields `upper`, /// and anything not that setting yields null. fn settingValue(text: []const u8, name: []const u8) ?[]const u8 { if (!std.mem.startsWith(u8, text[1..], name)) return null; const rest = std.mem.trim(u8, text[1 + name.len .. text.len - 1], " \t"); if (rest.len == 0) return null; return rest; } /// `[suppressContractions [Ии]]`: the root's contractions beginning with /// any of these code points are not to be used. /// /// Macedonian and Serbian both ask for exactly that set. The root /// contracts и with a following combining breve into й and И with one into /// Й, and both languages want the breve ordered as a mark after the /// letter instead. It is the root's contractions the setting is about, so /// a tailoring's own are untouched. /// /// The argument is a UnicodeSet, and what is accepted here is the part of /// that syntax CLDR's standard collations use: a bracketed run of /// characters, escapes and `a-b` ranges. Anything else -- a property like /// `\p{Lu}`, a nested set, an intersection -- is refused by name rather /// than half-read, because a suppression that silently covered the wrong /// characters would be invisible. fn suppressContractions(b: *Builder, value: []const u8) !void { const trimmed = std.mem.trim(u8, value, " \t"); if (trimmed.len < 2 or trimmed[0] != '[' or trimmed[trimmed.len - 1] != ']') { std.debug.print( "{s}: [suppressContractions {s}] is not a bracketed set\n", .{ b.locale, value }, ); return error.UnsupportedSuppressionSet; } var p: Parser = .{ .rules = trimmed[1 .. trimmed.len - 1] }; var previous: ?u21 = null; while (!p.done()) { const c = p.rules[p.i]; switch (c) { '\\' => { const cp = try p.escape(); try b.suppressed.append(b.arena, cp); previous = cp; }, '-' => { p.i += 1; const start = previous orelse return error.UnsupportedSuppressionSet; if (p.done()) return error.UnsupportedSuppressionSet; const end = if (p.rules[p.i] == '\\') try p.escape() else try p.codePoint(); if (end < start) return error.UnsupportedSuppressionSet; var cp = start + 1; while (cp <= end) : (cp += 1) try b.suppressed.append(b.arena, cp); previous = end; }, '[', ']', '{', '}', '&', '^', '$', ':' => { std.debug.print( "{s}: [suppressContractions {s}] uses more of the set syntax " ++ "than this reads\n", .{ b.locale, value }, ); return error.UnsupportedSuppressionSet; }, ' ', '\t', '\r', '\n' => p.i += 1, else => { const cp = try p.codePoint(); try b.suppressed.append(b.arena, cp); previous = cp; }, } } if (b.suppressed.items.len == 0) return error.UnsupportedSuppressionSet; } /// `[import hr]`: another locale's rules, processed here. /// /// Six of CLDR's locales are written this way -- Galician imports /// Spanish, Bosnian and Latin Serbian import Croatian, Cyrillic Bosnian /// imports Serbian, Dari imports Pashto, and Japanese imports a private /// kana collation of its own. The identifier is a locale, optionally with /// a collation type after `-u-co-`, and it names a file in the same /// directory: `sr-Latn` is `sr_Latn.xml`, and `und` is `root.xml`. /// /// Processed in place, against this builder and this cursor, because that /// is what the rules mean: an import is the imported rules written out /// where the `[import]` stands. Whatever the imported rules ask for that /// this library cannot do is refused in the importing locale's name, which /// is why `fa_AF` and `bs_Cyrl` are still refused -- Pashto and Serbian /// are. fn import(b: *Builder, value: []const u8) !void { const dir = b.collation_dir orelse { std.debug.print( "{s}: [import {s}] needs the CLDR collation directory, which this " ++ "build did not pass\n", .{ b.locale, value }, ); return error.NoCollationDirectory; }; const io = b.io orelse return error.NoCollationDirectory; // An import chain that comes back to where it started would recurse // forever; CLDR has none, and this says so rather than finding out. if (b.import_depth == 8) { std.debug.print("{s}: [import {s}] is nested too deeply\n", .{ b.locale, value }); return error.ImportTooDeep; } const target = try importTarget(b.arena, value); const path = try std.fmt.allocPrint(b.arena, "{s}/{s}.xml", .{ dir, target.file_stem }); const wanted = target.collation; const xml = std.Io.Dir.cwd().readFileAlloc(io, path, b.arena, .limited(8 << 20)) catch { std.debug.print("{s}: [import {s}] names no file: {s}\n", .{ b.locale, value, path }); return error.ImportNotFound; }; const rules = extractRulesOfType(xml, wanted) orelse { std.debug.print( "{s}: [import {s}] names no `{s}` collation in {s}\n", .{ b.locale, value, wanted, path }, ); return error.ImportNotFound; }; // The offset in the diagnostics belongs to the outer rules, so it is // saved and put back: a failure inside an import should say where the // import was, not where it was in a file the reader is not looking at. const offset = b.offset; b.import_depth += 1; defer { b.import_depth -= 1; b.offset = offset; } try b.process(rules); } /// `[reorder Grek Latn digit]`: a permutation of the reordering groups. /// /// The interpretation is UTS #35 part 5's, in its own four steps. Any of /// the core codes not named is inserted at the front in the order `space /// punct symbol currency digit`; `others` is inserted at the end if /// absent; `others` expands to every group not named, in root order; and /// the list that results is the new order. So `[reorder Cyrl]` means /// space, punct, symbol, currency, digit, Cyrillic, then everything else /// where it already was. fn reorder(b: *Builder, text: []const u8) !void { if (b.groups.len == 0) return error.NoReorderGroups; const body = std.mem.trim(u8, text["[reorder".len .. text.len - 1], " \t"); var wanted: std.ArrayList([]const u8) = .empty; var it = std.mem.tokenizeAny(u8, body, " \t"); while (it.next()) |code| try wanted.append(b.arena, code); if (wanted.items.len == 0) return error.EmptyReorderList; // Step 3's `others`, located. `Zzzz` is its synonym. var others: ?usize = null; for (wanted.items, 0..) |code, i| { if (eqlIgnoreCase(code, "others") or eqlIgnoreCase(code, "Zzzz")) { if (others != null) return error.DuplicateReorderCode; others = i; } } // Steps 1, 2 and 3 together: the final order is the core codes that // were not named, then the codes named before `others`, then every // unnamed group in root order, then the codes named after it. var order: std.ArrayList(usize) = .empty; var placed = try b.arena.alloc(bool, b.groups.len); @memset(placed, false); const before = wanted.items[0 .. others orelse wanted.items.len]; const after = if (others) |i| wanted.items[i + 1 ..] else wanted.items[0..0]; for (core_codes) |core| { var named_anywhere = false; for (wanted.items) |code| { if (eqlIgnoreCase(code, core)) named_anywhere = true; } if (named_anywhere) continue; try b.appendGroups(&order, placed, core); } for (before) |code| try b.appendGroups(&order, placed, code); for (b.groups, 0..) |_, i| { if (placed[i]) continue; placed[i] = true; try order.append(b.arena, i); } for (after) |code| try b.appendGroups(&order, placed, code); // Every group is placed exactly once, so the permutation is total. if (order.items.len != b.groups.len) return error.IncompleteReorder; // Lay the groups out in the new order from the low end of the // reorderable span, and record how far each moved. var base: u32 = b.groups[0].first; for (order.items) |i| { const g = b.groups[i]; const width: u32 = @as(u32, g.last) - g.first + 1; const offset = @as(i32, @intCast(base)) - @as(i32, g.first); if (offset != 0) { try b.reorder_ranges.append(b.arena, .{ .first = g.first, .last = g.last, .offset = offset, }); } base += width; } if (base - 1 > trailing_primary) return error.ReorderOverflowsPrimarySpace; std.mem.sort(data.ReorderRange, b.reorder_ranges.items, {}, struct { fn lessThan(_: void, x: data.ReorderRange, y: data.ReorderRange) bool { return x.first < y.first; } }.lessThan); } /// Appends every group a reorder code names. More than one can match: /// some scripts always reorder together, Katakana with Hiragana among /// them, and a code that names a group already placed is an error the /// specification calls out. fn appendGroups( b: *Builder, order: *std.ArrayList(usize), placed: []bool, code: []const u8, ) !void { var found = false; for (b.groups, 0..) |g, i| { if (!g.named(code)) continue; if (placed[i]) return error.DuplicateReorderCode; placed[i] = true; try order.append(b.arena, i); found = true; } if (!found) { std.debug.print("{s}: no reordering group is called {s}\n", .{ b.locale, code }); return error.UnknownReorderCode; } } /// `&anchor`, or `&[before 1]anchor`. fn reset(b: *Builder, p: *Parser) !void { p.skipSpace(); // Every reset but one leaves a primary insertion needing to subdivide // an existing weight; `[last regular]` sets this again below. b.free = null; var before: ?Strength = null; if (p.eat("[before ")) { const level = p.rules[p.i]; p.i += 1; if (!p.eat("]")) return error.MalformedBefore; before = switch (level) { '1' => .primary, '2' => .secondary, '3' => .tertiary, else => return error.UnsupportedBeforeLevel, }; } // A logical reset position, section 3.3: `&[last tertiary ignorable]` // and its relatives name a boundary of the weight space rather than a // character. Only one of them appears in CLDR's standard collations, // and it is the one that needs no table of boundaries to answer: // "after the last tertiary ignorable" is after everything that weighs // nothing at all, so the position is the completely ignorable element // and a relation increments from zero. // // Urdu adds five tertiary variants there -- // `&[last tertiary ignorable]<<<\u0610<<<\u0611…`, the honorifics, // which sort after nothing and before every mark -- and Khmer maps two // code points onto it with `=`, which is how a rule says "ignore // these". if (p.rules[p.i] == '[') { const close = std.mem.findScalarPos(u8, p.rules, p.i, ']') orelse return error.MalformedResetPosition; const name = p.rules[p.i .. close + 1]; // The three positions in the ignorable space, which are the ones // CLDR's standard collations use and the ones that need no table // of boundary weights to answer. // // "After the last tertiary ignorable" is after everything that // weighs nothing at all, so it is the completely ignorable // element. "The first secondary ignorable" is the bottom of the // space above that -- primary and secondary zero, tertiary // non-zero -- and the CLDR root has no element there at all, so // the whole space is free. Church Slavonic puts its combining // marks in it, below every mark the root has. // // And "the last secondary ignorable" is the completely ignorable // element as well, which is not a fudge but what the definitions // come to over this root. A secondary ignorable is an element // whose primary and secondary weights are both zero (UTS10-D12), // which includes every completely ignorable element; the CLDR // root has nothing else in that space at all; and all the // completely ignorable elements are equal. So the last of them is // (0, 0, 0), the same answer as the tertiary position, and a // relation increments from zero. Arabic is the locale that asks, // and it hangs forty-three tertiary relations off it -- the // tashkil, which it makes tertiary differences rather than // secondary ones, and which are then the only elements in the // secondary-ignorable space. // And the one position outside that space: the top of the // regular primary weights, which is where a tailoring puts // characters that are to sort after every ordinary one. The root // says where it is -- the highest primary weight its mappings // use, below the TRAILING group -- so it is read off the table // rather than tabulated, like the other three. // // Japanese is the locale that asks, with 6,355 kanji in JIS // order after it. if (std.mem.eql(u8, name, "[last regular]")) { const last = b.lastRegularPrimary() orelse return error.NoRegularPrimaries; p.i = close + 1; if (before != null) return error.UnsupportedBeforeLogicalPosition; b.cursor = try b.arena.dupe(Element, &.{.{ .primary = last, .secondary = 0x20, .tertiary = 0x02, }}); b.cursor_is_root = true; b.cursor_is_position = true; b.before = null; const band = b.tailoringBand() orelse return error.NoRegularPrimaries; b.free = .{ .primary = band, .sub = 0 }; return; } const position: Element = if (std.mem.eql(u8, name, "[last tertiary ignorable]") or std.mem.eql(u8, name, "[last secondary ignorable]")) .{ .primary = 0, .secondary = 0, .tertiary = 0 } else if (std.mem.eql(u8, name, "[first secondary ignorable]")) .{ .primary = 0, .secondary = 0, .tertiary = 1 } else { std.debug.print( "{s}: unimplemented logical reset position {s}\n", .{ b.locale, name }, ); return error.UnsupportedResetPosition; }; p.i = close + 1; if (before != null) return error.UnsupportedBeforeLogicalPosition; b.cursor = try b.arena.dupe(Element, &.{position}); b.cursor_is_root = true; b.cursor_is_position = true; b.before = null; return; } var buf: [32]u21 = undefined; const anchor = try p.string(&buf); if (anchor.len == 0) return error.EmptyAnchor; // Resolved against the tailoring so far, not against the root. A // rule may anchor on something an earlier rule moved: Kurdish has // `&e<ê` and then `&ê<<é`, and after NFD those are `&e<<<0629>` -- teh marbuta as a secondary // variant *before* teh -- and Japanese's private kana collation // asks for `[before 3]` fifty-six times. if (level != .primary) { b.before = .{ .level = level, .weight = switch (level) { .secondary => at.secondary, .tertiary => at.tertiary, else => unreachable, }, .below_common = level == .secondary and at.primary != 0 and at.secondary == common_secondary, }; b.cursor = adjusted[0 .. k + 1]; b.cursor_is_root = true; return; } if (at.primary_sub != 0) { // The anchor is itself something an earlier rule inserted, so // "below it" is below a sub-weight rather than below a // primary. Tamil is the case: `&[before 1]க்ஷ<க்ஷ்` anchors on // the contraction க்ஷ that an earlier rule placed, and asking // `primaryBelow` for the root weight underneath it looks in // the wrong space entirely -- which put க்ஷ் on the wrong side // of ஹ, ICU's one disagreement with Tamil. // // Subs are handed out consecutively, so there is no room // below the anchor's either. `nextElement` makes it, one // insertion at a time, which is what lets a chain of them // work. b.before = .{ .level = .primary, .weight = at.primary_sub }; adjusted[k] = .{ .primary = at.primary, .primary_sub = at.primary_sub - 1, .secondary = 0x20, .tertiary = 0x02, }; } else { // Below the anchor *within its own primary weight*: sub-weight // zero, which `makeRoomSub` frees by moving the anchor and // everything else the root has at that primary up one. // // Staying inside the primary is what keeps the new letters in // the anchor's reordering group. Tibetan needs both at once: // `&[before 1]<0F40>` puts its marks before the first Tibetan // letter and `[reorder Tibt]` moves Tibetan ahead of Latin, so // taking the primary weight *below* the anchor's -- a weight // belonging to whatever precedes Tibetan -- left the marks // among the Latin letters, which was 5,470 of ICU's // disagreements. // // A `[before 1]` reset is always followed by a primary // relation, which section 3.3 requires, so the cursor itself // is only read by the relations after that one -- and those // read the element the first insertion produced. b.before = .{ .level = .primary, .weight = 0 }; } b.cursor = adjusted[0 .. k + 1]; // Not a root element any more, so the next relation is free to // choose whatever it likes below the primary level. b.cursor_is_root = false; } } /// One relation: `= raw.len) return error.MalformedStarredRange; const end = raw[i + 1]; if (end <= start) return error.MalformedStarredRange; var cp = start + 1; while (cp <= end) : (cp += 1) try b.starredOne(cp, strength); previous = end; previous_ended_range = true; i += 2; continue; } try b.starredOne(raw[i], strength); previous = raw[i]; previous_ended_range = false; i += 1; } } /// One character out of a starred relation. fn starredOne(b: *Builder, cp: u21, strength: Strength) !void { const target = try nfd(b.arena, &.{cp}); if (target.len != 1 or target[0] != cp) { std.debug.print( "{s}: U+{X:0>4} is not NFD-inert, so it cannot be written in a " ++ "starred relation\n", .{ b.locale, cp }, ); return error.StarredCharacterNotInert; } try b.apply(target, &.{}, strength, &.{}); } /// One relation, given its target: the half of `relation` that is not /// parsing, so that a starred relation can reach it once per character. /// /// `prefix` is section 3.3's contextual mapping, `prefix|target`: the /// code points that must come before the target for the mapping to /// apply. Empty for an ordinary relation, which is all but one locale's. fn apply( b: *Builder, target: []const u21, extra: []const u21, strength: Strength, prefix: []const u21, ) !void { const mapped = try b.nextElements(strength, caseOf(target)); // §3.3: "in all cases, even for `=`, the case bits are // recomputed". `caseOf` above answers a different question -- which // tertiary weight a *new* insertion starts at -- and the case bits of // the mapping are section 5.1's algorithm, which reads them off the // root. try applyCaseBits(b.arena, mapped, target); // The next relation in the chain modifies these, as though the rule // had been written as separate chains with a reset to this target -- // which is what §3.3 says a chain means. The extension below is not // part of it: those elements are copied into the mapping and then // forgotten. b.cursor = mapped; b.cursor_is_root = false; b.cursor_is_position = false; // `/h` means the target weighs as the new elements followed by the // elements of "h": section 8's expansion syntax. "h" weighs as the // tailoring has it so far, exactly as a reset's anchor does, and not // as the root has it. Hungarian is what says so: `&cs<< max_contraction) { std.debug.print( "{s}: a contraction is {d} code points long, more than " ++ "data.max_contraction ({d})\n", .{ b.locale, target.len, max_contraction }, ); return error.ContractionTooLong; } if (prefix.len > max_contraction) { std.debug.print( "{s}: a contextual mapping's prefix is {d} code points long, " ++ "more than data.max_contraction ({d})\n", .{ b.locale, prefix.len, max_contraction }, ); return error.ContextPrefixTooLong; } // A later rule about the same sequence *and* the same condition // replaces the earlier one rather than sitting in front of it, which // is what `override` does for a single code point. Japanese needs it: // its private kana collation is imported twice by `ja.xml`, so every // one of its 633 contextual mappings arrives a second time. const rest = target[1..]; for (b.contractions.items) |*c| { if (c.first != target[0] or c.rest_len != rest.len) continue; if (c.prefix_len != prefix.len) continue; const have = b.contraction_points.items[c.rest_index..][0..c.rest_len]; if (!std.mem.eql(u21, have, rest)) continue; const had = b.contraction_points.items[c.prefix_index..][0..c.prefix_len]; if (!std.mem.eql(u21, had, prefix)) continue; if (c.elements_len == elements.len) { @memcpy(b.expansions.items[c.elements_index..][0..elements.len], elements); } else { c.elements_index = @intCast(b.expansions.items.len); c.elements_len = @intCast(elements.len); try b.expansions.appendSlice(b.arena, elements); } return; } const index: u32 = @intCast(b.expansions.items.len); try b.expansions.appendSlice(b.arena, elements); const rest_index: u32 = @intCast(b.contraction_points.items.len); try b.contraction_points.appendSlice(b.arena, rest); const prefix_index: u32 = @intCast(b.contraction_points.items.len); try b.contraction_points.appendSlice(b.arena, prefix); try b.contractions.append(b.arena, .{ .first = target[0], .rest_index = rest_index, .rest_len = @intCast(rest.len), .elements_index = index, .elements_len = @intCast(elements.len), .prefix_index = prefix_index, .prefix_len = @intCast(prefix.len), }); } /// Whether the tailoring already maps this sequence unconditionally. /// /// A contextual mapping for the same sequence does not count: it applies /// only after its prefix, so the sequence still needs the mapping that /// applies the rest of the time. fn hasContraction(b: *const Builder, first: u21, rest: []const u21) bool { for (b.contractions.items) |c| { if (c.first != first or c.rest_len != rest.len or c.prefix_len != 0) continue; const have = b.contraction_points.items[c.rest_index..][0..c.rest_len]; if (std.mem.eql(u21, have, rest)) return true; } return false; } /// What the target maps to: the cursor's elements with the last one of /// sufficient strength incremented, and everything after it dropped. /// /// That is §3.3's algorithm verbatim. Which element is modified depends /// on the operator -- `<` finds the last one with a primary weight, `<<` /// the last with a primary or a secondary -- which is why the choice /// cannot be made once when the anchor is read. Finnish resets to /// `&D\u0335`, whose second element is the combining overlay's: a /// secondary element with no primary. A `<` after it modifies D's and /// drops the overlay's, so the new letter is a letter rather than /// something that weighs nothing at the first level; a `<<` after it /// would modify the overlay's and keep D's. fn nextElements(b: *Builder, strength: Strength, case: data.Case) ![]Element { // `=` maps the target to the cursor's elements untouched. if (strength == .identical) return b.arena.dupe(Element, b.cursor); // Nothing in the cursor is as strong as the operator. Section 3.3 // answers that case itself -- "reset the collation elements to a // single completely-ignorable CE" and increment that -- so the first // element is the base and the zero weights are what get incremented. // // Church Slavonic needs it twice over. `&[first secondary ignorable]` // is a position with only a tertiary weight, and the chain that // follows is `= \u0487 = \uA67C = \uA67E << \u0485 << …`: the `=` // relations map three code points onto the position, and then 46 `<<` // relations want secondary weights in a space where the root has // none. Each one lands below every mark the root has, which is what // UTN #41 section 5.1 asks for -- it is where those rules come from, // and it is in the README's references. // // A primary relation is the exception: a new primary weight just // above zero would be in the ignorable space, which is not what any // rule means by it. var k = lastAtStrength(b.cursor, strength) orelse switch (strength) { .secondary, .tertiary, .quaternary => 0, .primary, .identical => return error.AnchorIsIgnorable, }; // One deliberate departure. If the element the operator picked has no // primary weight of its own, the element with one before it is used // instead. // // Finnish is the case: `&D\u0335<<đ` anchors on D and U+0335 // COMBINING SHORT STROKE OVERLAY, whose element is secondary-only, so // §3.3 asks for a secondary weight one above the overlay's. This // library's secondary weights are dense integers, and every ignorable // in the root shares that space, so there is no room between the // overlay's weight and the next mark's: making it means moving every // combining mark in the table up one, and `makeRoom` refuses, because // a root contraction would have to move with them. // // What is used instead is a new secondary weight on D, which orders đ // after D, after `D\u0335`, and after D with any other mark -- where // ICU puts it after `D\u0335` and before D with the next mark. The // approximation shows up only in comparisons between the tailored // letter and its base letter carrying a *different* mark, which is // why ICU agrees with all four of Finnish's rules of this shape, and // with Lithuanian's and Kurdish's. if (strength == .secondary and b.cursor[k].primary == 0) { if (lastAtStrength(b.cursor[0..k], .primary)) |with_primary| k = with_primary; // With nothing in the anchor carrying a primary weight, the // insertion is *inside* the ignorable space -- a new secondary // weight among the combining marks, which is what Vietnamese's // `&<0300><<<0309><<<0303><<<0301><<<0323>` asks for. That works, // because `makeRoom` moves the root's marks out of the way, and it // only works because it runs for every relation in the chain // rather than the first: see `increment`. } const out = try b.arena.alloc(Element, k + 1); @memcpy(out[0..k], b.cursor[0..k]); // `k == 0` says the target maps to this element and nothing else, // which is what decides whether the weight has to be made room for. // See `increment`. out[k] = try b.increment(b.cursor[k], strength, case); return out; } /// One element, one step on at the given strength. fn increment(b: *Builder, cursor: Element, strength: Strength, case: data.Case) !Element { switch (strength) { .identical => unreachable, .primary => { // A chain anchored at `&[last regular]` takes whole primary // weights: there is nothing above the last regular one to // insert between, so the sub-weight machinery is neither // needed nor wide enough -- Japanese asks for 6,355 of these // and there are 2,047 sub-weights. if (b.free) |next| { if (next.primary >= data.implicit_primary_base) { std.debug.print( "{s}: a chain at [last regular] has reached 0x{X:0>4}, " ++ "where section 10.1.3's Han weights begin\n", .{ b.locale, data.implicit_primary_base }, ); return error.OutOfRegularPrimaries; } b.free = if (next.sub == max_sub) .{ .primary = next.primary + 1, .sub = 0 } else .{ .primary = next.primary, .sub = next.sub + 1 }; return .{ .primary = next.primary, .primary_sub = next.sub, .secondary = 0x20, .tertiary = if (case == .upper) 0x08 else 0x02, .case = case, }; } // `[before 1]` on a sub-weighted anchor: take the anchor's own // sub-weight by moving it, and everything above it, up one. // Each insertion in the chain does this again, so `a` lands // where the anchor was, `b` after `a`, and the anchor ends up // above both. if (b.beforeAt(.primary)) |wide| { const sub: @FieldType(Element, "primary_sub") = @intCast(wide); try b.makeRoomSub(cursor.primary, sub); b.before.?.weight = sub + 1; return .{ .primary = cursor.primary, .primary_sub = sub, .secondary = 0x20, .tertiary = if (case == .upper) 0x08 else 0x02, .case = case, }; } // One past the cursor's own sub-weight, with whatever is // already there moved up to make the position free. // // Both halves of that matter, and Adlam needs both. It // tailors each letter twice, once in each case, and a capital // and its small share a primary weight in the root: // // & (primary) // &<< (secondary) // & (primary) // &<< (secondary) // // This was a counter per primary weight, which gave the two // chains unrelated sub-weights in rule order, so the capital // chain came first and the case difference became a primary // one. A bare `cursor.primary_sub + 1` fixed that by landing // both chains on one position -- and then the small chain's // secondary variant outranked the capital chain's base, // because they were sharing the position rather than being // ordered within it. // // What ICU does is insert immediately after the anchor, which // pushes the earlier insertion further out: the second chain // takes the position and the first chain moves up one. So the // order is anchor, second chain, first chain, with each // chain's own variants alongside it -- and the reverse of rule // order is correct rather than accidental. if (cursor.primary_sub == max_sub) return error.OutOfSubWeights; const sub: @FieldType(Element, "primary_sub") = cursor.primary_sub + 1; try b.makeRoomSub(cursor.primary, sub); return .{ .primary = cursor.primary, .primary_sub = sub, .secondary = 0x20, .tertiary = if (case == .upper) 0x08 else 0x02, .case = case, }; }, .secondary => { // `[before 2]` on a letter whose secondary is COMMON: a weight // below COMMON, which no root element with a primary weight // has, so the letter keeps COMMON. Moving the letter up // instead, as below, orders the two just as well and makes // the variant the one with COMMON -- and section 11.2's // asymmetric search calls the lowest weight unmarked, so // Arabic's `&[before 2]ت<<ة` had teh marbuta finding teh and // not the other way round, and Chinese's pinyin rules // `&[before 2]a<<ā<<<Ā<<á…` would have had `ā` finding `a`. // ICU puts the variant below COMMON too. // // Each insertion in the chain goes immediately below the // letter, so the ones before it move down one to make room, // which keeps them in rule order beneath it. if (b.before) |before| if (before.level == .secondary and before.below_common) { try b.makeRoomBelowCommon(cursor.primary, cursor.primary_sub); return .{ .primary = cursor.primary, .primary_sub = cursor.primary_sub, .secondary = common_secondary - 1, .tertiary = if (case == .upper) 0x08 else 0x02, .case = case, }; }; // `[before 2]`: the anchor's own secondary weight, which // `makeRoom` frees by moving the anchor and everything at or // above it under the same primary up one. Each insertion in // the chain does it again, so the anchor ends up above them // all -- the same shape as `[before 1]` one level up. var taken = false; const next = if (b.beforeAt(.secondary)) |weight| blk: { taken = true; b.before.?.weight = weight + 1; break :blk @as(usize, weight); } else cursor.secondary + 1; if (next > max_secondary) return error.OutOfSecondaryWeights; const candidate: Element = .{ .primary = cursor.primary, .primary_sub = cursor.primary_sub, .secondary = @intCast(next), // The target's case, for the same reason a primary // insertion takes it: Adlam's vowels pair their rules // with `<<` rather than `=`, so the capital and small // doubled forms differ only by case and a hardcoded // lowercase tertiary made them equal. .tertiary = if (case == .upper) 0x08 else 0x02, .case = case, }; // A weight the `before` path chose is occupied by // definition -- it is the one the anchor has, or the one the // last insertion in the chain took -- so the room has to be // made whether or not `needsRoom` can see a reason. It // cannot: after the first insertion the cursor is the // tailoring's own element with sub-weight zero, which is // exactly the shape `needsRoom` answers "no" for. // // Arabic's P2 rule is the one that showed it: a `[before 2]` // on yeh with two secondary insertions under it, farsi yeh // and then alef maksura. The second insertion landed on the // weight the first had already pushed yeh to, and alef // maksura and yeh came out equal in 137 of ICU's 396,495 // comparisons. if (taken or b.needsRoom(candidate)) try b.makeRoom(candidate, .secondary); return candidate; }, .tertiary => { // `[before 3]`, the same thing one level further down. var taken = false; const next = if (b.beforeAt(.tertiary)) |weight| blk: { taken = true; b.before.?.weight = weight + 1; break :blk @as(usize, weight); } else cursor.tertiary + 1; if (next > max_tertiary) return error.OutOfTertiaryWeights; const candidate: Element = .{ .primary = cursor.primary, .primary_sub = cursor.primary_sub, .secondary = cursor.secondary, .tertiary = @intCast(next), // Section 3.3 ends with "in all cases, even for =, the // case bits are recomputed", and adds that an // implementation supporting neither `caseLevel` nor // `caseFirst` may skip it. This one supports `caseFirst`, // so it does not skip it. The weight itself stays one // above the cursor's, which is what the relation asked // for; the case travels beside it. // // Danish is what needs this. `&[before 1]Z<æ<<<Æ` makes Æ // a tertiary variant of æ, and with no case of its own Æ // sorted after æ under `[caseFirst upper]` rather than // before it, in 361 comparisons of 6,786. .case = case, }; // Room for a `before` weight whether or not `needsRoom` // can see a reason, as in the secondary branch above. if (taken or b.needsRoom(candidate)) try b.makeRoom(candidate, .tertiary); return candidate; }, .quaternary => { // `<<<<`. There is no `[before 4]` -- the specification's // `before` takes 1, 2 or 3 -- so this is always a step up // from the cursor. const next = cursor.quaternary + 1; if (next > max_quaternary) return error.OutOfQuaternaryWeights; const candidate: Element = .{ .primary = cursor.primary, .primary_sub = cursor.primary_sub, .secondary = cursor.secondary, .tertiary = cursor.tertiary, .quaternary = @intCast(next), .case = case, }; if (b.needsRoom(candidate)) try b.makeRoom(candidate, .quaternary); return candidate; }, } } /// Whether a weight has to be made room for before it is used. /// /// Three cases, and each of them is a bug that was found the hard way. /// /// **The cursor came straight from a reset.** Then the weight is one the /// root is using, and `&i<<<İ` is the example: İ goes immediately after i /// at tertiary strength, where the fullwidth i already is. /// /// **The insertion is among the ignorables.** There every relation of a /// chain needs room, not just the first, because the chain is competing /// with itself in a space it also shares with every mark in the root. /// Vietnamese's `&<0300><<<0309><<<0303><<<0301><<<0323>` places five /// combining marks one after another; making room only for the first put /// the other four on top of the root's breve and circumflex, and two of /// Vietnamese's tone marks came out equal. /// /// **The weight is in the tailoring's own sub-space.** No root element is /// there, but another insertion of the tailoring's can be, and Burmese /// relies on that: two spellings of one syllable share an anchor and an /// operator, so the second has to displace the first. /// /// What is *not* a case is the rest of a chain that is neither ignorable /// nor sub-weighted. Korean's `&<<*` chains insert /// after the last element of a decomposed syllable, so each lands in the /// space of a trailing jamo that hundreds of syllables share. Those /// insertions do not compete -- the jamo before them differ, so the first /// level separates them -- and making room would move all eleven thousand /// of them, which 511 secondary weights do not allow. fn needsRoom(b: *const Builder, candidate: Element) bool { return b.cursor_is_root or candidate.primary == 0 or candidate.primary_sub != 0; } /// Makes room for a weight the root table has already used, by moving /// what holds it. /// /// Reachable only when the cursor is a root element, which is the one /// case where the new element shares its higher levels with things that /// are already there. `&i<<<İ` is the example: İ must sort 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. There is no integer between 0x02 and 0x03. /// /// A run-time rule applier is stuck here, which is why ICU's weights are /// variable-length byte strings. A build-time generator is not: it can /// shift U+FF49 up to 0x04 and put İ at 0x03, because a shifted root /// element is just another entry in the delta. Everything at or above the /// wanted weight moves up one, which preserves their order among /// themselves and leaves the gap. fn makeRoom(b: *Builder, candidate: Element, level: Strength) !void { var moved: usize = 0; // Only the tailoring's own elements can be in a sub-weighted space, // so the root's code points and contractions are not worth looking at // for one. Its *overrides* always are: an override is the tailoring's // own element wherever it sits, and skipping those along with the root // moved Thai's `0E4D 0E32` contraction up a tertiary weight without // moving the U+0E33 override that sat above it, which made the two // equal where ICU orders them. const root_too = candidate.primary_sub == 0; // The root's code points at this primary weight, and the ones an // earlier rule has overridden -- which may have moved a code point // *into* this weight, where the root index would not have it. A code // point moved the other way is still in the index and is left alone, // because what is read below is where it is now. // Deduplicated, because a code point can be in both lists and one // shift per code point is the whole of what this does. Shifting twice // exhausts the tertiary level, which is what Swedish said when the // two lists were simply concatenated. var candidates: std.ArrayList(u21) = .empty; var seen: std.AutoHashMapUnmanaged(u21, void) = .empty; defer seen.deinit(b.arena); if (root_too) { for (b.by_primary.get(candidate.primary) orelse &.{}) |cp| { if ((try seen.getOrPut(b.arena, cp)).found_existing) continue; try candidates.append(b.arena, cp); } } for (b.overrides.items) |o| { if ((try seen.getOrPut(b.arena, o.cp)).found_existing) continue; try candidates.append(b.arena, o.cp); } for (candidates.items) |cp| { var scratch: [1]Element = undefined; // What this tailoring currently says, not what the root says. A // code point an earlier rule has already moved is somewhere else // now and must not be dragged back: Turkish is the case that // proves it. `&[before 1]i<ı<<<1031><102C><1000><1039><<<<1029><1000><1039> // &<1021><1031><102C><1000><1039><<<<1029><1031><102C><1000><1039> // // -- so the second insertion has to displace the first rather than // land on it. Without that the two spellings weighed the same and ICU // ordered them, the later rule first, in 60 comparisons. for (b.contractions.items) |c| { for (b.expansions.items[c.elements_index..][0..c.elements_len]) |*e| { if (!needsShift(e.*, candidate, level)) continue; e.* = try shiftOne(e.*, candidate, level); moved += 1; } } // A root contraction whose elements are in the way is replaced, // shifted, by one of the tailoring's own. Step 2 tries the // tailoring's contractions before the root's, so a replacement with // the same code points shadows the original -- which is the same // trick as overriding a code point, one level up. // // This used to be a refusal, and it was the largest one: eleven // locales, Persian and Thai and Vietnamese among them, all blocked by // Catalan's `L·` and its relatives sitting at a secondary weight // under L's primary. for (if (root_too) root.contractions else &[_]Contraction{}) |c| { const elements = root.elementsOfContraction(c); var affected = false; for (elements) |e| { if (needsShift(e, candidate, level)) affected = true; } if (!affected) continue; // Unless the tailoring already maps this sequence, in which case // its own copy is the one to move and the loop below does it. const rest = root.restOf(c); if (b.hasContraction(c.first, rest)) continue; var shifted: std.ArrayList(Element) = .empty; for (elements) |e| try shifted.append(b.arena, try shiftOne(e, candidate, level)); var target: std.ArrayList(u21) = .empty; try target.append(b.arena, c.first); try target.appendSlice(b.arena, rest); try b.contraction(target.items, shifted.items, &.{}); moved += 1; } b.moved += moved; } /// Moves everything at or above one sub-weight under a primary up by /// one, freeing that sub-weight. /// /// The sub-level counterpart of `makeRoom`, and the same reasoning: a /// build-time generator can shift what is in the way, where a run-time /// rule applier would have to find a value between two consecutive /// integers. Only the tailoring's own elements can be here at all -- a /// root element always has sub-weight zero -- so there is no table to /// scan and no root contraction to refuse over. fn makeRoomSub(b: *Builder, primary: u16, sub: u16) !void { if (sub == max_sub) return error.OutOfSubWeights; for (b.overrides.items) |o| { const elements = b.expansions.items[o.elements_index..][0..o.elements_len]; for (elements) |*e| { if (e.primary != primary or e.primary_sub < sub) continue; if (e.primary_sub == max_sub) return error.OutOfSubWeights; e.primary_sub += 1; b.moved += 1; } } for (b.contractions.items) |c| { const elements = b.expansions.items[c.elements_index..][0..c.elements_len]; for (elements) |*e| { if (e.primary != primary or e.primary_sub < sub) continue; if (e.primary_sub == max_sub) return error.OutOfSubWeights; e.primary_sub += 1; b.moved += 1; } } // Sub-weight zero is the root's, so freeing it means moving the root's // own mappings at this primary weight -- the letter a rule anchored on // and its compatibility forms -- into sub-weight one. `[before 1]` // needs that: see `reset`. // // Last, after the two loops above, for the reason `makeRoom` does the // same thing last. A replacement created here is the tailoring's own // from that moment on, and a loop that shifted it again in the call // that created it would move it twice. if (sub != 0) return; for (b.by_primary.get(primary) orelse &.{}) |cp| { // Unless the tailoring already overrides it, in which case the // loop above has moved it and moving it again would move it // twice. Maltese is what proves it: it has five `[before 1]` // rules, and U+1F18B -- the squared "IC" -- has an element at C's // primary and one at I's, so by the time the rule about i runs it // is already an override from the rule about c. Its I went to // sub-weight two where every other I went to one, and ICU // disagreed with 24 comparisons. if (b.override_index.contains(cp)) continue; var scratch: [1]Element = undefined; const elements = b.currentElements(cp, &scratch); if (elements.len == 0) continue; var affected = false; for (elements) |e| { if (e.primary == primary) affected = true; } if (!affected) continue; var shifted: std.ArrayList(Element) = .empty; for (elements) |e| { var out = e; if (out.primary == primary) { if (out.primary_sub == max_sub) return error.OutOfSubWeights; out.primary_sub += 1; } try shifted.append(b.arena, out); } try b.override(cp, shifted.items); b.moved += 1; } for (root.contractions) |c| { const elements = root.elementsOfContraction(c); var affected = false; for (elements) |e| { if (e.primary == primary) affected = true; } if (!affected) continue; const rest = root.restOf(c); if (b.hasContraction(c.first, rest)) continue; var shifted: std.ArrayList(Element) = .empty; for (elements) |e| { var out = e; if (out.primary == primary) out.primary_sub += 1; try shifted.append(b.arena, out); } var target: std.ArrayList(u21) = .empty; try target.append(b.arena, c.first); try target.appendSlice(b.arena, rest); try b.contraction(target.items, shifted.items, &.{}); b.moved += 1; } } /// Moves the tailoring's own elements below COMMON at one primary weight /// down a secondary weight, freeing the one immediately below COMMON. /// /// Only the tailoring's own elements can be there -- every root element /// with a primary weight has a secondary of COMMON or more -- so the /// root is not looked at. Weight zero would be no secondary weight at all, /// so 31 insertions under one letter is the limit; CLDR's most is four. fn makeRoomBelowCommon(b: *Builder, primary: u16, sub: u16) !void { for (b.overrides.items) |o| { try lowerBelowCommon(b.expansions.items[o.elements_index..][0..o.elements_len], primary, sub); } for (b.contractions.items) |c| { try lowerBelowCommon(b.expansions.items[c.elements_index..][0..c.elements_len], primary, sub); } } fn lowerBelowCommon(elements: []Element, primary: u16, sub: u16) !void { for (elements) |*e| { if (e.primary != primary or e.primary_sub != sub) continue; if (e.secondary == 0 or e.secondary >= common_secondary) continue; if (e.secondary == 1) return error.OutOfSecondaryWeights; e.secondary -= 1; } } /// One element moved up a level, if it is in the way at all. fn shiftOne(e: Element, candidate: Element, level: Strength) !Element { if (!needsShift(e, candidate, level)) return e; var out = e; switch (level) { .secondary => { if (out.secondary == max_secondary) return error.OutOfSecondaryWeights; out.secondary += 1; }, .tertiary => { if (out.tertiary == max_tertiary) return error.OutOfTertiaryWeights; out.tertiary += 1; }, .quaternary => { if (out.quaternary == max_quaternary) return error.OutOfQuaternaryWeights; out.quaternary += 1; }, else => unreachable, } return out; } /// Whether an element holds a weight that has to move out of the way. fn needsShift(e: Element, candidate: Element, level: Strength) bool { if (e.primary != candidate.primary) return false; if (e.primary_sub != candidate.primary_sub) return false; return switch (level) { .secondary => e.secondary >= candidate.secondary, .tertiary => e.secondary == candidate.secondary and e.tertiary >= candidate.tertiary, .quaternary => e.secondary == candidate.secondary and e.tertiary == candidate.tertiary and e.quaternary >= candidate.quaternary, else => false, }; } /// The tailoring as it stands, for resolving an anchor against what the /// rules have already done. /// /// Both lists are searched by bisection at lookup time, so both are /// sorted here; the builder keeps them in rule order until the end. A /// copy per anchor is cheap -- there is one anchor per `&`, and the /// largest rule set in CLDR has a few hundred. fn currentTailoring(b: *Builder) !data.Tailoring { const overrides = try b.arena.dupe(data.Override, b.overrides.items); std.mem.sort(data.Override, overrides, {}, overrideLessThan); const contractions = try b.arena.dupe(Contraction, b.contractions.items); std.mem.sort( Contraction, contractions, @as([]const u21, b.contraction_points.items), Contraction.lessThan, ); return .{ .locale = b.locale, .root = "", .overrides = overrides, .contractions = contractions, .contraction_points = b.contraction_points.items, .expansions = b.expansions.items, // Weights are chosen before any reordering is applied, so an // anchor must be resolved without it. .reorder = &.{}, }; } /// What this tailoring says one code point maps to at this moment: its /// own override if it has made one, and the root's answer otherwise. fn currentElements(b: *const Builder, cp: u21, scratch: *[1]Element) []const Element { for (b.overrides.items) |o| { if (o.cp != cp) continue; return b.expansions.items[o.elements_index..][0..o.elements_len]; } return root.elementsOf(root.entry(cp), scratch); } /// Records what one code point maps to, replacing any earlier record of /// it -- a later rule wins, and a shifted element may be shifted again. fn override(b: *Builder, cp: u21, elements: []const Element) !void { // An override that is only being moved is written over where it is. // // Both halves of this are about Korean, which shifts root elements // 159,974 times to make room for its 436 chains. Appending the new // elements to the pool each time left every superseded copy behind, // and the generated source came to 43 MB for a tailoring of 7,476 // code points; and finding the existing override by walking the list // is what made the run take minutes rather than seconds. if (b.override_index.get(cp)) |at| { const existing = &b.overrides.items[at]; if (existing.elements_len == elements.len) { @memcpy( b.expansions.items[existing.elements_index..][0..elements.len], elements, ); return; } existing.* = .{ .cp = cp, .elements_index = @intCast(b.expansions.items.len), .elements_len = @intCast(elements.len), .starts_contraction = false, }; try b.expansions.appendSlice(b.arena, elements); return; } const index: u32 = @intCast(b.expansions.items.len); try b.expansions.appendSlice(b.arena, elements); try b.override_index.put(b.arena, cp, b.overrides.items.len); try b.overrides.append(b.arena, .{ .cp = cp, .elements_index = index, .elements_len = @intCast(elements.len), .starts_contraction = false, }); } /// The highest sub-weight the tailoring has used under a primary weight, /// or zero if it has used none. /// /// Root elements always have sub-weight zero, so only the tailoring's own /// elements can answer this. fn highestSub(b: *Builder, primary: u16) u16 { var highest: u16 = 0; for (b.expansions.items) |e| { if (e.primary == primary and e.primary_sub > highest) highest = e.primary_sub; } return highest; } /// Where a chain at `&[last regular]` allocates from: the bottom of the /// Han group, which `reorderGroups` extends down to cover the weights /// between the siniform implicit leads and the Han ranks. /// /// Not `lastRegularPrimary() + 1`, which is the same place in CLDR's /// fractional space and a different one here: this library leaves a gap /// between the regular weights and the implicit ones, and a tailored /// weight in that gap would reorder with whatever script ends the regular /// space rather than with Han. See `reorderGroups`. fn tailoringBand(b: *const Builder) ?u16 { for (b.groups) |g| { if (g.last == trailing_primary - 1 and g.first < data.implicit_primary_base) { return g.first; } } return null; } /// The primary weight `&[last regular]` names: the highest one the root's /// own mappings use. /// /// Read off the table rather than declared, and the bound is /// `implicit_tail_bit`: above it lie the low halves of section 10.1.3's /// derived weight pairs, which the root's *expansions* do contain, and /// above those the TRAILING group's own -- U+FFFD and the merge separator /// weigh after every letter and are not regular either. What is left /// below is exactly the primary weights regular characters use, and the /// highest of them is what the rule names. In CLDR 49 it is 0x749E, /// U+14646 ANATOLIAN HIEROGLYPH A530. `FractionalUCA.txt` names a later /// character, U+3FC3F SMALL SEAL CHARACTER-3FC3F, because it gives the /// siniform scripts explicit weights where `allkeys_CLDR.txt` leaves them /// to section 10.1.3; either way the anchor is above every regular /// character this table holds, and ICU agrees about Japanese's kanji. fn lastRegularPrimary(b: *const Builder) ?u16 { var i = b.primaries.len; while (i > 0) { i -= 1; if (b.primaries[i] < data.implicit_tail_bit) return b.primaries[i]; } return null; } /// The root primary weight immediately below one, for `[before 1]`. fn primaryBelow(b: *const Builder, primary: u16) ?u16 { var lo: usize = 0; var hi: usize = b.primaries.len; while (lo < hi) { const mid = lo + (hi - lo) / 2; if (b.primaries[mid] < primary) lo = mid + 1 else hi = mid; } if (lo == 0) return null; return b.primaries[lo - 1]; } /// How many of the contractions apply only after a prefix, for the /// generated file's own summary. fn contextualCount(b: *const Builder) usize { var n: usize = 0; for (b.contractions.items) |c| { if (c.prefix_len != 0) n += 1; } return n; } fn emit(b: *const Builder, w: *std.Io.Writer) !void { try w.print( \\// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie \\// SPDX-License-Identifier: MIT \\ \\//! The CLDR collation tailoring for `{s}`, generated by \\//! tools/gen_tailoring.zig. Do not edit. \\//! \\//! {d} overridden code points, {d} added contractions, of which \\//! {d} apply only after a prefix. {d} of the overrides are root \\//! elements shifted to make room rather than characters the \\//! rules name. \\ \\const data = @import("data"); \\ \\pub const tailoring: data.Tailoring = .{{ \\ .locale = "{s}", \\ .root = "{s}", \\ .overrides = &overrides, \\ .contractions = &contractions, \\ .contraction_points = &contraction_points, \\ .expansions = &expansions, \\ .reorder = &reorder, \\ .settings = .{{{s}{s}{s}{s}{s} }}, \\ .suppressed = &suppressed, \\}}; \\ \\ , .{ b.locale, b.overrides.items.len, b.contractions.items.len, b.contextualCount(), b.moved, b.locale, rootName(), if (b.settings.case_level) |v| (if (v) " .case_level = true," else " .case_level = false,") else "", if (b.settings.strength) |v| switch (v) { .primary => " .strength = .primary,", .secondary => " .strength = .secondary,", .tertiary => " .strength = .tertiary,", .quaternary => " .strength = .quaternary,", .identical => " .strength = .identical,", } else "", if (b.settings.case_first) |v| switch (v) { .off => " .case_first = .off,", .upper_first => " .case_first = .upper_first,", .lower_first => " .case_first = .lower_first,", } else "", if (b.settings.backwards_secondary) |v| if (v) " .backwards_secondary = true," else " .backwards_secondary = false," else "", if (b.settings.alternate) |v| switch (v) { .non_ignorable => " .alternate = .non_ignorable,", .blanked => " .alternate = .blanked,", .shifted => " .alternate = .shifted,", } else "", }); try w.writeAll("const overrides = [_]data.Override{"); for (b.overrides.items) |o| { try w.print( "\n .{{ .cp = 0x{X:0>4}, .elements_index = {d}, .elements_len = {d}, " ++ ".starts_contraction = {} }},", .{ o.cp, o.elements_index, o.elements_len, o.starts_contraction }, ); } try w.writeAll("\n};\n\n"); try w.writeAll("const contractions = [_]data.Contraction{"); var prefix_buf: [64]u8 = undefined; for (b.contractions.items) |c| { // The condition is written only for the mappings that have one, // so that a generated file reads as the sequences the rules are // about. const prefix = if (c.prefix_len == 0) "" else std.fmt.bufPrint( &prefix_buf, ", .prefix_index = {d}, .prefix_len = {d}", .{ c.prefix_index, c.prefix_len }, ) catch unreachable; try w.print( "\n .{{ .first = 0x{X:0>4}, .rest_index = {d}, .rest_len = {d}, " ++ ".elements_index = {d}, .elements_len = {d}{s} }},", .{ c.first, c.rest_index, c.rest_len, c.elements_index, c.elements_len, prefix }, ); } try w.writeAll("\n};\n\n"); try w.writeAll("const contraction_points = [_]u21{"); for (b.contraction_points.items, 0..) |cp, i| { if (i % 12 == 0) try w.writeAll("\n "); try w.print("0x{X:0>4},", .{cp}); } try w.writeAll("\n};\n\n"); try w.writeAll("const reorder = [_]data.ReorderRange{"); for (b.reorder_ranges.items) |r| { try w.print( "\n .{{ .first = 0x{X:0>4}, .last = 0x{X:0>4}, .offset = {d} }},", .{ r.first, r.last, r.offset }, ); } try w.writeAll("\n};\n\n"); try w.writeAll("const suppressed = [_]u21{"); for (b.suppressed.items) |cp| try w.print("\n 0x{X:0>4},", .{cp}); try w.writeAll("\n};\n\n"); try w.writeAll("const expansions = [_]data.Element{"); var quaternary_buf: [24]u8 = undefined; for (b.expansions.items) |e| { // The two fields that are zero for all but a handful of elements // are written only when they are not, so that the generated // source reads as the weights the rules are about. const quaternary = if (e.quaternary == 0) "" else std.fmt.bufPrint( &quaternary_buf, ", .quaternary = 0x{X:0>1}", .{@as(u16, e.quaternary)}, ) catch unreachable; try w.print( "\n .{{ .primary = 0x{X:0>4}, .primary_sub = 0x{X:0>4}, " ++ ".secondary = 0x{X:0>3}, .tertiary = 0x{X:0>2}{s}{s} }},", .{ e.primary, e.primary_sub, @as(u16, e.secondary), @as(u16, e.tertiary), quaternary, switch (e.case) { .lower => "", .mixed => ", .case = .mixed", .upper => ", .case = .upper", }, }, ); } try w.writeAll("\n};\n"); } }; /// Which root the rules were resolved against, recorded in the generated /// module so that a mismatch is at least visible. fn rootName() []const u8 { return if (root.unicode_version.len != 0 and collate.cldr_root.stage1.len != 0 and root.stage1.ptr == collate.cldr_root.stage1.ptr) "cldr" else "ducet"; } fn emitEmpty(w: *std.Io.Writer, locale: []const u8) !void { try w.print( \\// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie \\// SPDX-License-Identifier: MIT \\ \\//! `{s}` has no `standard` collation tailoring in CLDR: it is ordered \\//! by the root collation. Generated by tools/gen_tailoring.zig. \\ \\const data = @import("data"); \\ \\pub const tailoring: data.Tailoring = .empty; \\ , .{locale}); } fn overrideLessThan(_: void, a: data.Override, b: data.Override) bool { return a.cp < b.cp; } /// A weight a chain at `&[last regular]` has yet to hand out. See /// `Builder.free`. const FreeWeight = struct { primary: u16, sub: @FieldType(Element, "primary_sub"), }; const Strength = enum { primary, secondary, tertiary, quaternary, identical }; const Parser = struct { rules: []const u8, i: usize = 0, fn done(p: *const Parser) bool { return p.i >= p.rules.len; } /// The directional marks CLDR writes around its operands for display. /// /// `ar.xml` is full of them: `\u200e&ءا\u200e<<\u200eآ\u200e` is one rule, /// and the LEFT-TO-RIGHT MARKs are there so that the file reads sensibly /// in an editor rather than because Arabic collation has anything to say /// about them. ICU skips them -- its own rule text for `ar` still has them /// in it, and `[before 2]ت<<‎ة` orders ة before ت, so the ة the rule is /// about is the bare letter -- and a parser that kept them would key a /// contraction on a two-code-point sequence no text contains. const lrm = "\u{200e}"; const rlm = "\u{200f}"; fn skipSpace(p: *Parser) void { while (p.i < p.rules.len) { if (std.mem.startsWith(u8, p.rules[p.i..], lrm) or std.mem.startsWith(u8, p.rules[p.i..], rlm)) { p.i += lrm.len; continue; } switch (p.rules[p.i]) { ' ', '\t', '\r', '\n' => p.i += 1, // A comment runs to the end of the line. '#' => while (p.i < p.rules.len and p.rules[p.i] != '\n') { p.i += 1; }, else => return, } } } fn eat(p: *Parser, literal: []const u8) bool { if (!std.mem.startsWith(u8, p.rules[p.i..], literal)) return false; p.i += literal.len; return true; } fn strength(p: *Parser) !Strength { if (p.eat("=")) return .identical; if (!p.eat("<")) return error.ExpectedRelation; if (!p.eat("<")) return .primary; if (!p.eat("<")) return .secondary; // `<<<<`, the quaternary relation. Japanese is the only collation // CLDR ships that writes one: its private kana collation has 116, // separating katakana from hiragana, which is a difference it does // not want at tertiary strength. A fifth `<` is not a relation at // all -- §3.3 has four. if (!p.eat("<")) return .tertiary; if (p.eat("<")) return error.TooManyRelationOperators; return .quaternary; } /// One `\uXXXX` and its relatives. /// /// CLDR writes some rules with these rather than with the characters /// themselves -- Finnish anchors on `&D\u0335`, U+0335 COMBINING SHORT /// STROKE OVERLAY -- and eleven locales' standard rules contain one. /// /// Reading them as literal text is not a small error. `D\u0335` becomes /// seven code points ending in the digit 5, so the anchor resolves to /// five's primary weight and every rule hanging off it lands in the /// digits. Finnish put six letters there, stacked on one primary in /// reverse rule order, and it compiled and tested clean: the ICU oracle /// is what noticed, at 202 disagreements out of 1,275. /// /// An escape this does not recognize is an error rather than a literal /// backslash, for the same reason. /// One code point of literal text, advancing past it. fn codePoint(p: *Parser) !u21 { if (p.done()) return error.UnexpectedEndOfRules; const n = std.unicode.utf8ByteSequenceLength(p.rules[p.i]) catch return error.InvalidUtf8; if (p.i + n > p.rules.len) return error.InvalidUtf8; const cp = std.unicode.utf8Decode(p.rules[p.i..][0..n]) catch return error.InvalidUtf8; p.i += n; return cp; } fn escape(p: *Parser) !u21 { std.debug.assert(p.rules[p.i] == '\\'); p.i += 1; if (p.i >= p.rules.len) return error.TrailingBackslash; const kind = p.rules[p.i]; const digits: usize = switch (kind) { 'u' => 4, 'U' => 8, 'x' => 2, // LDML also uses a backslash to make a syntax character literal. else => { const n = std.unicode.utf8ByteSequenceLength(kind) catch return error.InvalidUtf8; const cp = std.unicode.utf8Decode(p.rules[p.i..][0..n]) catch return error.InvalidUtf8; p.i += n; return cp; }, }; p.i += 1; if (p.i + digits > p.rules.len) return error.TruncatedEscape; const cp = std.fmt.parseInt(u21, p.rules[p.i..][0..digits], 16) catch return error.MalformedEscape; if (cp > 0x10FFFF) return error.EscapeOutOfRange; p.i += digits; return cp; } /// A rule operand: code points until the next operator, with `'...'` /// quoting a literal and `\uXXXX` naming one. fn string(p: *Parser, buf: []u21) ![]const u21 { p.skipSpace(); var len: usize = 0; while (p.i < p.rules.len) { // A directional mark inside an operand is display, not text: see // `lrm`. if (std.mem.startsWith(u8, p.rules[p.i..], lrm) or std.mem.startsWith(u8, p.rules[p.i..], rlm)) { p.i += lrm.len; continue; } const c = p.rules[p.i]; switch (c) { '&', '<', '=', '/', '|', '#', ' ', '\t', '\r', '\n' => break, '[', ']' => break, '\\' => { if (len == buf.len) return error.OperandTooLong; buf[len] = try p.escape(); len += 1; }, '\'' => { // A single quote opens a run in which syntax characters // are literal, and *two* of them are one apostrophe. // Uzbek needs the second rule: its digraphs are written // `o''`, `g''` -- o or g and an apostrophe -- as // typeable stand-ins for `oʻ` and `gʻ`. Read as an empty // quoted run, `o''` is just `o`, so the rule moved plain // g and o to the end of the alphabet and made G equal to // Gʻ. That was 86 of ICU's disagreements. if (p.i + 1 < p.rules.len and p.rules[p.i + 1] == '\'') { if (len == buf.len) return error.OperandTooLong; buf[len] = '\''; len += 1; p.i += 2; continue; } p.i += 1; while (p.i < p.rules.len) { if (p.rules[p.i] == '\'') { if (p.i + 1 < p.rules.len and p.rules[p.i + 1] == '\'') { if (len == buf.len) return error.OperandTooLong; buf[len] = '\''; len += 1; p.i += 2; continue; } p.i += 1; break; } // An escape inside a quoted run is still an escape. // CLDR writes a space as `'\u0020'`, quoted so that // it cannot end the operand and escaped so that it // can be written at all -- `en_US_POSIX` opens with // `<*'\u0020'-'/'`, the ASCII range from space to // slash, and `ja` writes three more. Read literally // that is a backslash, a u and four digits. if (p.rules[p.i] == '\\') { if (len == buf.len) return error.OperandTooLong; buf[len] = try p.escape(); len += 1; continue; } if (len == buf.len) return error.OperandTooLong; const n = std.unicode.utf8ByteSequenceLength(p.rules[p.i]) catch return error.InvalidUtf8; buf[len] = std.unicode.utf8Decode(p.rules[p.i..][0..n]) catch return error.InvalidUtf8; len += 1; p.i += n; } else return error.UnterminatedQuote; }, else => { if (len == buf.len) return error.OperandTooLong; const n = std.unicode.utf8ByteSequenceLength(c) catch return error.InvalidUtf8; buf[len] = std.unicode.utf8Decode(p.rules[p.i..][0..n]) catch return error.InvalidUtf8; len += 1; p.i += n; }, } } return buf[0..len]; } }; /// One reordering group: a contiguous stretch of primary weights, and the /// names a rule may call it by. const Group = struct { /// The marker's own name, `LATIN` or `PUNCTUATION`. marker: []const u8, /// The ISO 15924 code from the first mapping's comment, `Latn`. Empty /// when that mapping is Common or Inherited, which is the case for every /// core group. code: []const u8, first: u16, last: u16, /// Whether a rule's reorder code names this group. Rules use script /// codes (`Cyrl`) and the five lower-case core names (`digit`); the /// markers spell scripts out (`CYRILLIC`) and the core groups in capitals /// (`DIGIT`), so both are matched and case is ignored. fn named(g: Group, code: []const u8) bool { const wanted = alias(code); return eqlIgnoreCase(g.code, wanted) or eqlIgnoreCase(g.marker, wanted); } /// The code a group is actually declared under, for the scripts that /// share one. /// /// `FractionalUCA.txt` has no marker for Katakana, and section 4.7 says /// why: "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." So `[reorder Kana]`, which /// is what Japanese writes, names the group Hiragana is declared as -- /// and Katakana characters are always reordered with Hiragana, which the /// same section says in as many words. fn alias(code: []const u8) []const u8 { if (eqlIgnoreCase(code, "Kana") or eqlIgnoreCase(code, "Hrkt")) return "Hira"; if (eqlIgnoreCase(code, "Hans") or eqlIgnoreCase(code, "Hant")) return "Hani"; return code; } }; fn eqlIgnoreCase(a: []const u8, b: []const u8) bool { if (a.len != b.len or a.len == 0) return false; for (a, b) |x, y| { if (std.ascii.toLower(x) != std.ascii.toLower(y)) return false; } return true; } /// The reordering groups, in primary weight order. /// /// UTS #35 part 5 says how, and says not to infer it: `FractionalUCA.txt` /// declares each group with a line like /// /// FDD1 004C; [2A 02 02, 05, 05] # LATIN first primary starts new lead byte /// /// and the group begins at the *next real mapping* after that marker. Looking /// that mapping's character sequence up in the root table gives the primary /// weight. Each group then runs to the next one's start, so the groups /// partition the weight space contiguously by construction -- which is the /// thing no amount of grouping characters by script will reproduce, because a /// script's characters are spread across the punctuation, symbol, digit and /// letter groups and the common ones are apportioned among the core groups by /// general category. fn reorderGroups(arena: Allocator, fractional: []const u8) ![]const Group { var list: std.ArrayList(Group) = .empty; var pending_marker: ?[]const u8 = null; var lines = std.mem.splitScalar(u8, fractional, '\n'); while (lines.next()) |raw| { const line = std.mem.trim(u8, raw, " \t\r"); if (line.len == 0 or line[0] == '[' or line[0] == '#') continue; const semi = std.mem.findScalar(u8, line, ';') orelse continue; const chars = std.mem.trim(u8, line[0..semi], " \t"); if (std.mem.find(u8, line, "first primary")) |_| { // `# NAME first primary ...` const hash = std.mem.findScalar(u8, line, '#') orelse continue; var words = std.mem.tokenizeAny(u8, line[hash + 1 ..], " \t"); pending_marker = words.next() orelse continue; continue; } // The markers themselves are noncharacters and are not mappings. if (std.mem.startsWith(u8, chars, "FDD0") or std.mem.startsWith(u8, chars, "FDD1")) continue; const marker = pending_marker orelse continue; pending_marker = null; // Reserved ranges exist so that a fractional lead byte can be split. // Nothing maps into them and a `u16` has no lead bytes, so they are // left as part of the group before them. if (std.mem.startsWith(u8, marker, "REORDER_RESERVED")) continue; // `unassigned` is not a group that can be moved. Its weights are // computed by section 10.1.3 rather than tabulated, and its marker // resolves through the root to U+FFFE's 0x0001 -- the field separator // the specification exempts from reordering outright. Leaving it in // made it the lowest "group" and therefore the base the whole layout // was measured from, which shifted every other group by 512. // // The specification puts unassigned-implicit weights last within // `others`. This does not do that: they fall inside whichever group // ends the weight space, and move with it. No locale in CLDR reorders // that group, so nothing exercises the difference, but it is a // difference. if (eqlIgnoreCase(marker, "unassigned")) continue; var buf: [8]u21 = undefined; var n: usize = 0; var fields = std.mem.tokenizeAny(u8, chars, " "); while (fields.next()) |f| { if (n == buf.len) break; buf[n] = std.fmt.parseInt(u21, f, 16) catch break; n += 1; } if (n == 0) continue; const elements = elementsOf(arena, buf[0..n]) catch continue; if (elements.len == 0 or elements[0].primary == 0) continue; // The script code from the comment, when it is one. var code: []const u8 = ""; if (std.mem.findScalar(u8, line, '#')) |hash| { var words = std.mem.tokenizeAny(u8, line[hash + 1 ..], " \t"); if (words.next()) |w| { if (w.len == 4 and !std.mem.eql(u8, w, "Zyyy") and !std.mem.eql(u8, w, "Zinh")) { code = w; } } } try list.append(arena, .{ .marker = marker, .code = code, .first = elements[0].primary, .last = 0, // filled in below }); } // Order by start weight and close each range at the next one's start. std.mem.sort(Group, list.items, {}, struct { fn lessThan(_: void, a: Group, b: Group) bool { return a.first < b.first; } }.lessThan); // Drop anything that did not come out strictly increasing. The // implicit-weight groups are why: Tangut, Nushu and Khitan have no // mappings in the root at all, and `unassigned` resolves to U+FFFE's // 0x0001, which the specification exempts from reordering anyway. var kept: std.ArrayList(Group) = .empty; for (list.items) |g| { if (kept.items.len != 0 and g.first <= kept.items[kept.items.len - 1].first) continue; try kept.append(arena, g); } for (kept.items, 0..) |*g, i| { g.last = if (i + 1 < kept.items.len) kept.items[i + 1].first - 1 else trailing_primary - 1; } // The weights between the siniform implicit leads and the Han ranks // belong to the Han group, not to the group below them. // // This library lays the implicit weights out at fixed primaries -- // section 10.1.3's Table 16 order, Tangut and Nushu and Khitan at // `0xFB00` upwards and the Han ranks at `implicit_primary_base` -- which // leaves sixty primary weights unused between them. In CLDR's own // fractional space there is no gap at all: the implicit Han weights begin // immediately after the last regular one, so "after the last regular // weight" and "before the first Han weight" are the same place. A // tailoring that inserts there is inserting into Han, and Japanese proves // it: `&[last regular]<*` with 6,355 kanji, and `[reorder Latn Kana // Hani]` in the same locale, which ICU moves those kanji with. Left in // the group below, they sorted after Hangul instead -- 864,280 of // Japanese's 24,468,510 comparisons. for (kept.items, 0..) |*g, i| { if (g.first != data.implicit_primary_base or i == 0) continue; const below = &kept.items[i - 1]; if (below.first < 0xFB00) break; below.last = below.first; g.first = below.first + 1; break; } return kept.items; } /// The TRAILING group's primary weight, which is not reordered and so bounds /// the reorderable span. const trailing_primary: u16 = 0xFFFD; /// The core groups, in the order step 1 inserts them. const core_codes = [_][]const u8{ "space", "punctuation", "symbol", "currency", "digit" }; /// Step 1 on its own, so that a rule's operands are in the form the lookups /// will be. fn nfd(arena: Allocator, text: []const u21) ![]const u21 { var out: std.ArrayList(u21) = .empty; try collate.nfd.append(&out, arena, text); return out.items; } /// [UTS #35 part 5][ldml] section 5.1's case bits for a tailored mapping, /// written into `mapped` in place. /// /// The bits are *not* a reading of the target's Unicode case properties. /// They are read off the target's **root** collation elements, and the /// specification gives an algorithm for it because the two do not agree: /// /// * N is the number of primary root collation elements of the target /// string, M the number of primary elements the tailoring maps it to. If /// N <= M the root's case bits are copied across one for one and any /// remaining tailored element is cleared; if N > M the first M-1 are /// copied and the last tailored element takes the *combination* of the /// root elements M-1 onwards -- uppercase if all of them are, lowercase /// if none is, and mixed otherwise. /// * A secondary element's bits are cleared, a tertiary element's are set /// to uppercase -- which is what keeps such an element above every /// primary and secondary one at the case level, UCA well-formedness /// condition 2 -- and a completely ignorable element's are cleared. /// /// Three locales are what showed that the properties are the wrong source. /// Croatian writes `&D any_upper = true, .lower, .mixed => any_else = true, }; mapped[primaries.items[m - 1]].case = if (any_upper and any_else) .mixed else if (any_upper) .upper else .lower; } } // The weaker elements are not a matter of judgement. for (mapped) |*e| { if (e.primary != 0) continue; e.case = if (e.secondary != 0) .lower else if (e.tertiary != 0) .upper else .lower; } } /// Which tertiary weight a new insertion starts at, by whether the target /// looks uppercase. /// /// This is not section 5.1's case bits -- `applyCaseBits` is -- but the /// choice between Table 17's 0x02 and 0x08 for an element the tailoring is /// creating from nothing. Adlam is what needs it: its vowels pair their rules /// with `<<` rather than `=`, so the capital and small doubled forms differ /// only by this, and a hardcoded 0x02 made them equal. fn caseOf(target: []const u21) data.Case { var any_upper = false; var any_lower = false; for (target) |cp| switch (uucode.get(.general_category, cp)) { .letter_uppercase, .letter_titlecase => any_upper = true, .letter_lowercase => any_lower = true, else => {}, }; if (any_upper and any_lower) return .mixed; if (any_upper) return .upper; return .lower; } /// The index of the last element whose own strength is at least `strength`: /// for `<` the last with a primary weight, for `<<` the last with a primary /// or a secondary, for `<<<` the last that is not completely ignorable. /// /// Null when the sequence has nothing that strong in it at all. fn lastAtStrength(elements: []const Element, strength: Strength) ?usize { var i = elements.len; while (i > 0) { i -= 1; const e = elements[i]; const strong_enough = switch (strength) { .primary => e.primary != 0, .secondary => e.primary != 0 or e.secondary != 0, // A quaternary weight is a refinement of a tertiary one rather // than a level with ignorables of its own, so the same test // serves: the last element that weighs anything at all. .tertiary, .quaternary, .identical => e.primary != 0 or e.secondary != 0 or e.tertiary != 0, }; if (strong_enough) return i; } return null; } fn elementsOfTable(arena: Allocator, t: collate.Table, text: []const u21) ![]const Element { var builder: collate.Builder = .empty; defer builder.deinit(arena); const elements = try builder.collationElements(arena, .{ .table = t }, text); return arena.dupe(Element, elements); } /// The untailored root's elements, for the places that want the root /// specifically. fn elementsOf(arena: Allocator, text: []const u21) ![]const Element { return elementsOfTable(arena, root, text); } /// Every code point whose root elements use a given primary weight. /// /// `makeRoom` needs the code points that hold a weight at or above the one it /// is freeing, and they all share that weight's primary. Without this it /// walked all 1,114,112 code points per call, which is tolerable for a /// locale with a dozen rules and not for Korean: its 436 chains each begin at /// a root element, so each one pays for a full scan, and the generator ran /// for tens of minutes. The buckets are small -- a primary weight belongs to /// a letter and its compatibility forms -- so the same work becomes a lookup. fn collectPrimaries(arena: Allocator) ![]const u16 { var seen: std.AutoHashMapUnmanaged(u16, void) = .empty; defer seen.deinit(arena); var cp: u21 = 0; while (cp < 0x110000) : (cp += 1) { var scratch: [1]Element = undefined; for (root.elementsOf(root.entry(cp), &scratch)) |e| { if (e.primary != 0) try seen.put(arena, e.primary, {}); } } for (root.expansions) |e| { if (e.primary != 0) try seen.put(arena, e.primary, {}); } var list: std.ArrayList(u16) = .empty; var it = seen.keyIterator(); while (it.next()) |k| try list.append(arena, k.*); std.mem.sort(u16, list.items, {}, std.sort.asc(u16)); return list.items; } fn collectByPrimary(arena: Allocator) !std.AutoHashMapUnmanaged(u16, []const u21) { var lists: std.AutoHashMapUnmanaged(u16, std.ArrayList(u21)) = .empty; defer lists.deinit(arena); var cp: u21 = 0; while (cp < 0x110000) : (cp += 1) { var scratch: [1]Element = undefined; for (root.elementsOf(root.entry(cp), &scratch)) |e| { const entry = try lists.getOrPut(arena, e.primary); if (!entry.found_existing) entry.value_ptr.* = .empty; // One code point can hold the same primary twice, in an // expansion; once in the bucket is enough. if (entry.value_ptr.items.len != 0 and entry.value_ptr.items[entry.value_ptr.items.len - 1] == cp) continue; try entry.value_ptr.append(arena, cp); } } var out: std.AutoHashMapUnmanaged(u16, []const u21) = .empty; var it = lists.iterator(); while (it.next()) |entry| { try out.put(arena, entry.key_ptr.*, entry.value_ptr.items); } return out; } const testing = std.testing; /// Every one of these is a rule shape that CLDR actually uses and that this /// parser once read wrongly, silently, producing a tailoring that compiled /// and ordered nothing correctly. The ICU oracle found all three; these are /// here so that it does not have to again. fn expectOperand(expected: []const u21, rules: []const u8) !void { var p: Parser = .{ .rules = rules }; var buf: [32]u21 = undefined; try testing.expectEqualSlices(u21, expected, try p.string(&buf)); } test "a \\uXXXX escape is one code point, not six characters" { // Finnish anchors on `&D̵`. Read as text that is D and then five // ASCII characters ending in the digit 5, so the anchor resolved to // five's primary weight and six Finnish letters landed among the digits. try expectOperand(&.{ 'D', 0x0335 }, "D\\u0335"); try expectOperand(&.{0x0300}, "\\u0300"); try expectOperand(&.{ 0x1F600, 'x' }, "\\U0001F600x"); try expectOperand(&.{0x41}, "\\x41"); } test "an escape that is not understood is an error, not a backslash" { var p: Parser = .{ .rules = "\\uZZZZ" }; var buf: [32]u21 = undefined; try testing.expectError(error.MalformedEscape, p.string(&buf)); var truncated: Parser = .{ .rules = "\\u03" }; try testing.expectError(error.TruncatedEscape, truncated.string(&buf)); var trailing: Parser = .{ .rules = "a\\" }; try testing.expectError(error.TrailingBackslash, trailing.string(&buf)); } test "two quotes are one apostrophe" { // Uzbek writes its digraphs `o''` and `g''` -- a letter and an // apostrophe -- as typeable stand-ins for `oʻ` and `gʻ`. Read as an // empty quoted run, `o''` is just `o`, and the rule then moved plain g // and o to the end of the alphabet. try expectOperand(&.{ 'o', '\'' }, "o''"); try expectOperand(&.{'\''}, "''"); try expectOperand(&.{ 'a', '\'', 'b' }, "a''b"); } test "a quoted run makes syntax characters literal" { try expectOperand(&.{ '<', '<' }, "'<<'"); try expectOperand(&.{ 'a', '&', 'b' }, "a'&'b"); // And a doubled quote inside a run is still one apostrophe. try expectOperand(&.{ 'a', '\'', 'b' }, "'a''b'"); var unterminated: Parser = .{ .rules = "'abc" }; var buf: [32]u21 = undefined; try testing.expectError(error.UnterminatedQuote, unterminated.string(&buf)); } test "an operand stops at the next operator" { try expectOperand(&.{'a'}, "a