// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Turns the Unicode data files in `data/` into the Zig source of a //! collation element table. //! //! Either table: `allkeys.txt` is the Default Unicode Collation Element //! Table and `allkeys_CLDR.txt` is the CLDR root collation, and they are the //! same format, so the same generator reads both. The one thing the CLDR file //! lacks is the `@implicitweights` lines, which are UTS #10's //! parameterization of Table 16 rather than anything table-specific, so they //! are taken from whichever file was given as the implicit-weight source. //! //! Inputs, all of one Unicode version, which this checks: //! //! * `allkeys.txt` -- the table itself, UTS #10 section 12.1. //! * `PropList.txt` -- `Unified_Ideograph`, which section 10.1.3's //! Table 16 needs and which is in no other file. //! * `Blocks.txt` -- the two CJK blocks that split Table 16's "core" //! Han from the rest. //! //! This runs on the build host. See `build.zig`. //! //! It fails rather than guesses. The well-formedness conditions of section 5 //! that this library relies on for its representation are checked here, at //! the one moment there is a whole table in hand to check them against: if a //! future DUCET puts a non-variable collation element inside the variable //! primary weight range, or an expansion longer than `data.max_expansion`, //! the build stops here with a message rather than generating a table that //! quietly orders things wrongly. const std = @import("std"); const Allocator = std.mem.Allocator; const uucode = @import("uucode"); const data = @import("data"); const Element = data.Element; /// Whether a tertiary weight means an uppercase character. /// /// [UTS #35 part 5][ldml] section 5.1 gives the set outright, for exactly /// this purpose -- "for mappings in the root collation, the case value for /// each collation element is computed from the tertiary weight listed in /// allkeys_CLDR.txt ... UPPER if x is in {08-0C, 0E, 11, 12, 1D}" -- and adds /// that there is no MIXED value in the root collation. /// /// It is three weights wider than UTS #10's Table 17 reads at a glance. 0x08 /// through 0x0C are NONE, ``, ``, `` and `` with /// Uppercase and 0x1D is "``, ``, `` ... Uppercase", /// which is where this started; 0x0E, 0x11 and 0x12 are the ones it missed, /// and 0x11 and 0x12 are the halfwidth forms. Ewe and Vietnamese both /// noticed: the halfwidth voiced sound marks at U+FF9E and U+FF9F weigh /// 0x11, so under `[caseFirst upper]` they belong before the combining marks /// they are forms of, and were landing after them. /// /// [ldml]: https://www.unicode.org/reports/tr35/tr35-collation.html fn isUpper(tertiary: u16) bool { return switch (tertiary) { 0x08...0x0C, 0x0E, 0x11, 0x12, 0x1D => true, else => false, }; } const Entry = data.Entry; const Contraction = data.Contraction; const ImplicitRange = data.ImplicitRange; const code_point_count = 0x110000; const block_len = 256; const stage1_len = code_point_count / block_len; /// A stage-one entry pointing at no stage-two block, which must be what /// `Table.no_block` is: the library reads this value out of the array this /// tool writes. const no_block: u16 = 0xFFFF; pub fn main(init: std.process.Init.Minimal) !void { var gpa_state: std.heap.DebugAllocator(.{}) = .init; defer _ = gpa_state.deinit(); const gpa = gpa_state.allocator(); var threaded: std.Io.Threaded = .init(gpa, .{}); defer threaded.deinit(); const io = threaded.io(); var arena_state: std.heap.ArenaAllocator = .init(gpa); defer arena_state.deinit(); const arena = arena_state.allocator(); const all_args = try init.args.toSlice(arena); // `--repertoire=` is named rather than positional, because the positional // arguments already end in two optional files and a third optional thing // after them would be unreadable. var repertoire_names: []const u8 = ""; var positional: std.ArrayList([]const u8) = .empty; for (all_args) |arg| { const flag = "--repertoire="; if (std.mem.startsWith(u8, arg, flag)) { repertoire_names = arg[flag.len..]; } else { try positional.append(arena, arg); } } const args = positional.items; if (args.len != 5 and args.len != 6 and args.len != 7) { std.debug.print( "usage: gen_table [--repertoire=,...] " ++ " [implicitweights-source.txt [FractionalUCA.txt]]\n", .{}, ); return error.WrongNumberOfArguments; } const cwd: std.Io.Dir = .cwd(); const allkeys_text = try cwd.readFileAlloc(io, args[1], arena, .limited(16 << 20)); const proplist_text = try cwd.readFileAlloc(io, args[2], arena, .limited(4 << 20)); const blocks_text = try cwd.readFileAlloc(io, args[3], arena, .limited(4 << 20)); var table: Parsed = try .parse(arena, allkeys_text); // All three files must describe the same Unicode. A DUCET from one // version and an ideograph classification from another is a mismatch // that would show up as a handful of failures deep in the conformance // suite rather than as anything legible. const proplist_version = try headerVersion(proplist_text, "PropList"); const blocks_version = try headerVersion(blocks_text, "Blocks"); if (!std.mem.eql(u8, table.version, proplist_version) or !std.mem.eql(u8, table.version, blocks_version)) { std.debug.print( "data/ holds more than one Unicode version: allkeys {s}, PropList {s}, Blocks {s}\n", .{ table.version, proplist_version, blocks_version }, ); return error.VersionMismatch; } // Section 10.1.3's siniform ranges. `allkeys_CLDR.txt` carries no // `@implicitweights` lines of its own -- the rule is UTS #10's and not // the table's -- so they come from the file named for the purpose, which // for DUCET is the table itself. if (table.implicit_ranges.items.len == 0) { if (args.len < 6) { std.debug.print( "{s} has no @implicitweights lines; name a file to take them from\n", .{args[1]}, ); return error.NoImplicitWeights; } const source_text = try cwd.readFileAlloc(io, args[5], arena, .limited(16 << 20)); const source: Parsed = try .parse(arena, source_text); if (source.implicit_ranges.items.len == 0) { std.debug.print("{s} has no @implicitweights lines either\n", .{args[5]}); return error.NoImplicitWeights; } table.implicit_ranges = source.implicit_ranges; } try table.addIdeographRanges(arena, proplist_text, blocks_text); // CLDR's Han order, from the `[radical …]` lines of `FractionalUCA.txt`. // Only CLDR has one: the DUCET's order is the code-point order section // 10.1.3 computes, and its conformance suite tests exactly that. if (args.len == 7) { const fractional = try cwd.readFileAlloc(io, args[6], arena, .limited(32 << 20)); try table.addHanOrder(arena, fractional); if (table.han_order.items.len == 0) { std.debug.print("{s} has no [radical ...] lines\n", .{args[6]}); return error.NoHanOrder; } try table.reencodeHanPairs(arena); } // Section 9.3.3, reducing the repertoire: a code point outside it gets no // entry, which leaves it to be weighed from its code point value by // section 10.1.3 at run time -- "if characters are not fully supported by // an implementation, then their code points can be treated as if they // were unassigned". Nothing in the library needs to know: the lookup // already falls back to `Table.implicit` for a code point the table has // no mapping for. const named = try parseRepertoire(arena, blocks_text, repertoire_names); const repertoire = try closeUnderDecomposition(arena, named); if (repertoire.len != 0) try table.restrict(arena, repertoire); var built: Built = try .build(arena, &table); var source: std.Io.Writer.Allocating = .init(arena); defer source.deinit(); try built.emit(&source.writer, table.version, repertoire); try cwd.writeFile(io, .{ .sub_path = args[4], .data = source.written() }); } /// `allkeys.txt` as it is written, before anything is decided about how to /// store it. const Parsed = struct { version: []const u8, /// One code point to its collation elements. Canonically decomposable /// code points are dropped on the way in: step 1 of the algorithm has /// already replaced them by the time anything is looked up, so an entry /// for one could never be reached. singles: std.AutoHashMapUnmanaged(u21, []const Element), contractions: std.ArrayList(Contraction), contraction_points: std.ArrayList(u21), /// Every contraction's elements, kept beside the contraction until the /// expansion pool is laid out. contraction_elements: std.ArrayList([]const Element), implicit_ranges: std.ArrayList(ImplicitRange), /// CLDR's Han order, when a `FractionalUCA.txt` was named: see /// `data.HanRange`. han_order: std.ArrayList(data.HanRange) = .empty, /// The band of primary weights on collation elements that the table /// marked with a `*`, and every non-zero primary weight on one it did /// not. /// /// Well-formedness condition WF4 says no plain element's primary weight /// may fall between two variable ones, which is what makes /// `Table.isVariable` a range test rather than a stored flag. It is /// checked rather than assumed: see `checkVariableBand`. min_variable_primary: u16 = std.math.maxInt(u16), max_variable_primary: u16 = 0, plain_primaries: std.ArrayList(u16) = .empty, fn parse(arena: Allocator, text: []const u8) !Parsed { var self: Parsed = .{ .version = "", .singles = .empty, .contractions = .empty, .contraction_points = .empty, .contraction_elements = .empty, .implicit_ranges = .empty, }; // Leads already seen, so that the second Tangut range takes its base // from the first rather than from itself. `allkeys.txt` writes // Tangut as 17000..187FF and Tangut Supplement as 18D00..18D7F, both // with lead FB00, and Table 16 measures both from 0x17000. var bases: std.AutoHashMapUnmanaged(u16, u21) = .empty; var lines = std.mem.splitScalar(u8, text, '\n'); while (lines.next()) |raw| { const line = stripComment(raw); if (line.len == 0) continue; if (std.mem.startsWith(u8, line, "@version")) { self.version = std.mem.trim(u8, line["@version".len..], " \t\r"); continue; } if (std.mem.startsWith(u8, line, "@implicitweights")) { const body = std.mem.trim(u8, line["@implicitweights".len..], " \t\r"); const semi = std.mem.findScalar(u8, body, ';') orelse return error.BadImplicitWeights; const range = std.mem.trim(u8, body[0..semi], " \t"); const dots = std.mem.find(u8, range, "..") orelse return error.BadImplicitWeights; const first = try std.fmt.parseInt(u21, range[0..dots], 16); const last = try std.fmt.parseInt(u21, range[dots + 2 ..], 16); const lead = try std.fmt.parseInt(u16, std.mem.trim(u8, body[semi + 1 ..], " \t\r"), 16); const base = (try bases.getOrPutValue(arena, lead, first)).value_ptr.*; try self.implicit_ranges.append(arena, .{ .first = first, .last = last, .kind = .siniform, .lead = lead, .base = base, }); continue; } if (line[0] == '@') continue; const semi = std.mem.findScalar(u8, line, ';') orelse continue; var cps: std.ArrayList(u21) = .empty; var fields = std.mem.tokenizeAny(u8, line[0..semi], " \t"); while (fields.next()) |field| { try cps.append(arena, try std.fmt.parseInt(u21, field, 16)); } if (cps.items.len == 0) return error.BadEntry; var elements: std.ArrayList(Element) = .empty; var rest = line[semi + 1 ..]; while (std.mem.findScalar(u8, rest, '[')) |open| { const close = std.mem.findScalarPos(u8, rest, open, ']') orelse return error.BadEntry; const body = rest[open + 1 .. close]; rest = rest[close + 1 ..]; // The marker is the first character: `*` for a variable // collation element, `.` for any other. const variable = body[0] == '*'; var weights = std.mem.splitScalar(u8, body[1..], '.'); const primary = try std.fmt.parseInt(u16, weights.next() orelse return error.BadEntry, 16); const secondary = try std.fmt.parseInt(u16, weights.next() orelse return error.BadEntry, 16); const tertiary = try std.fmt.parseInt(u16, weights.next() orelse return error.BadEntry, 16); // A fourth field would mean a table with a fourth level, // which this library has nowhere to put: `Alternate.shifted` // computes level four rather than reading it. if (weights.next() != null) return error.FourthLevelInTable; if (variable) { self.min_variable_primary = @min(self.min_variable_primary, primary); self.max_variable_primary = @max(self.max_variable_primary, primary); } else if (primary != 0) { try self.plain_primaries.append(arena, primary); } try elements.append(arena, .{ .primary = primary, .secondary = @intCast(secondary), .tertiary = @intCast(tertiary), // Read from the tertiary weight here, where the table is // still exactly as Unicode published it. A tailoring can // shift a tertiary weight out of its band later, which is // why `Element` carries the answer rather than recomputing // it from the weight. A root element is one character, so // it is never the mixed case. .case = if (isUpper(tertiary)) .upper else .lower, }); } if (elements.items.len == 0) return error.BadEntry; if (elements.items.len > data.max_expansion) { std.debug.print( "an entry maps to {d} collation elements, more than data.max_expansion ({d})\n", .{ elements.items.len, data.max_expansion }, ); return error.ExpansionTooLong; } if (cps.items.len == 1) { const cp = cps.items[0]; // Unreachable after step 1, so not worth carrying: NFD has // already replaced it with its decomposition. if (uucode.get(.decomposition_type, cp) == .canonical) continue; try self.singles.put(arena, cp, elements.items); } else { if (cps.items.len > data.max_contraction) { std.debug.print( "a contraction is {d} code points long, more than " ++ "data.max_contraction ({d})\n", .{ cps.items.len, data.max_contraction }, ); return error.ContractionTooLong; } const rest_index: u32 = @intCast(self.contraction_points.items.len); try self.contraction_points.appendSlice(arena, cps.items[1..]); try self.contractions.append(arena, .{ .first = cps.items[0], .rest_index = rest_index, .rest_len = @intCast(cps.items.len - 1), .elements_index = 0, // filled in by `Built.build` .elements_len = @intCast(elements.items.len), }); try self.contraction_elements.append(arena, elements.items); } } if (self.version.len == 0) return error.NoVersion; try self.checkVariableBand(); return self; } /// WF4 in the form this library needs it: the variable collation /// elements occupy one contiguous band of primary weights, with no plain /// element's primary weight inside it. /// /// Elements *below* the band are fine and are not an oversight. Both /// roots put U+FFFE, the merge separator of section 1.6, at primary /// weight 0x0200 and do not mark it variable, deliberately, so that it /// sorts before everything including punctuation -- section 10.1.5 /// reserves that weight for it since UCA 18.0. fn checkVariableBand(self: *const Parsed) !void { if (self.max_variable_primary == 0) return; // no variable elements at all for (self.plain_primaries.items) |p| { if (p < self.min_variable_primary or p > self.max_variable_primary) continue; std.debug.print( "a non-variable collation element has primary weight {X:0>4}, inside the " ++ "variable band {X:0>4}..{X:0>4}. WF4 is broken and Table.isVariable " ++ "cannot be a range test.\n", .{ p, self.min_variable_primary, self.max_variable_primary }, ); return error.VariableWeightsInterleave; } } /// Table 16's Han rows, which no `@implicitweights` line covers. /// /// `Unified_Ideograph` comes from `PropList.txt`; the split between /// "core" Han and the rest is by block, and the two block ranges come /// from `Blocks.txt` rather than being written down here, because a /// block can grow. /// CLDR's Han order, out of `FractionalUCA.txt`'s `[radical …]` lines. /// /// Each line is `[radical =:]`, and /// the part after the colon is a run of code points and `a-b` ranges in /// order. The 214 lines are in radical order and the ideographs within /// each are in stroke order, so reading them start to finish and counting /// gives every ideograph's rank. `[radical end]` closes the section and /// has no colon. /// /// The ranges are recorded as they are written rather than merged: they /// are already maximal in the file, since a merge across two radicals /// would only be possible if the order agreed with the code point order /// there, and nothing downstream cares. fn addHanOrder(self: *Parsed, arena: Allocator, fractional_text: []const u8) !void { var rank: u21 = 0; var lines = std.mem.splitScalar(u8, fractional_text, '\n'); while (lines.next()) |raw| { const line = std.mem.trim(u8, raw, " \t\r"); if (!std.mem.startsWith(u8, line, "[radical ")) continue; const colon = std.mem.findScalar(u8, line, ':') orelse continue; const close = std.mem.findScalarLast(u8, line, ']') orelse return error.BadRadicalLine; if (close <= colon) return error.BadRadicalLine; const body = line[colon + 1 .. close]; var i: usize = 0; while (i < body.len) { const first_len = std.unicode.utf8ByteSequenceLength(body[i]) catch return error.BadRadicalLine; const first = std.unicode.utf8Decode(body[i..][0..first_len]) catch return error.BadRadicalLine; i += first_len; var last = first; if (i < body.len and body[i] == '-') { i += 1; if (i >= body.len) return error.BadRadicalLine; const last_len = std.unicode.utf8ByteSequenceLength(body[i]) catch return error.BadRadicalLine; last = std.unicode.utf8Decode(body[i..][0..last_len]) catch return error.BadRadicalLine; i += last_len; if (last < first) return error.BadRadicalLine; } try self.han_order.append(arena, .{ .first = first, .last = last, .base = rank, }); rank += @intCast(last - first + 1); } } // Searched by bisection at run time. std.mem.sort(data.HanRange, self.han_order.items, {}, struct { fn lessThan(_: void, a: data.HanRange, b: data.HanRange) bool { return a.first < b.first; } }.lessThan); } /// Where an ideograph sits in CLDR's order, or null if it is not listed. fn hanRank(self: *const Parsed, cp: u21) ?u21 { var lo: usize = 0; var hi: usize = self.han_order.items.len; while (lo < hi) { const mid = lo + (hi - lo) / 2; const r = self.han_order.items[mid]; if (cp < r.first) { hi = mid; } else if (cp > r.last) { lo = mid + 1; } else { return r.base + (cp - r.first); } } return null; } /// Rewrites the implicit-weight pairs the table writes out by hand so /// that they name an ideograph's *rank* in CLDR's order rather than its /// code point. /// /// `allkeys_CLDR.txt` has 1,466 entries of the shape /// `2F00 ; [.FB40.0020.0004][.CE00.0000.0000]`, which is KANGXI RADICAL /// ONE saying "sort like U+4E00, with a tertiary difference": the Kangxi /// radicals, the CJK radicals supplement, and the circled, parenthesised /// and squared ideographs. They are written in section 10.1.3's /// encoding -- a lead weight and a trailing weight computed from the code /// point -- so a table that has switched to CLDR's radical-stroke order /// for everything it computes must switch these too, or a radical and the /// ideograph it stands for end up in different places. fn reencodeHanPairs(self: *Parsed, arena: Allocator) !void { if (self.han_order.items.len == 0) return; var it = self.singles.iterator(); while (it.next()) |entry| { if (try self.reencoded(arena, entry.value_ptr.*)) |fixed| { entry.value_ptr.* = fixed; } } for (self.contraction_elements.items) |*els| { if (try self.reencoded(arena, els.*)) |fixed| els.* = fixed; } } /// One element list with its implicit pairs rewritten, or null if it has /// none. fn reencoded( self: *const Parsed, arena: Allocator, els: []const Element, ) !?[]const Element { var out: ?[]Element = null; var i: usize = 0; while (i + 1 < els.len) { const cp = hanPairCodePoint(els[i], els[i + 1]) orelse { i += 1; continue; }; const rank = self.hanRank(cp) orelse { i += 2; continue; }; if (out == null) out = try arena.dupe(Element, els); out.?[i].primary = @intCast(0xFB40 + (rank >> 15)); out.?[i + 1].primary = @intCast((rank & 0x7FFF) | 0x8000); i += 2; } return out; } /// Section 9.3.3: drop everything outside the repertoire. /// /// A single code point outside it loses its entry, and a contraction /// loses its if *any* of its code points is outside -- a contraction is /// one mapping over a sequence, so a sequence that is half supported is /// not supported. /// /// The variable band is left as the full table computed it. It is a range /// of primary weights rather than a set of code points, the entries that /// survive keep the weights they had, and so the band still classifies /// them correctly; narrowing it to what survived would be work for no /// difference. Implicit weights are untouched for the same reason -- they /// are computed from the code point and start above every weight in the /// table. fn restrict(self: *Parsed, arena: Allocator, repertoire: []const [2]u21) !void { const inside = struct { fn f(ranges: []const [2]u21, cp: u21) bool { for (ranges) |r| { if (cp >= r[0] and cp <= r[1]) return true; } return false; } }.f; var dropped_singles: usize = 0; var it = self.singles.iterator(); var doomed: std.ArrayList(u21) = .empty; defer doomed.deinit(arena); while (it.next()) |entry| { if (!inside(repertoire, entry.key_ptr.*)) try doomed.append(arena, entry.key_ptr.*); } for (doomed.items) |cp| { _ = self.singles.remove(cp); dropped_singles += 1; } var kept_contractions: std.ArrayList(Contraction) = .empty; var kept_elements: std.ArrayList([]const Element) = .empty; var dropped_contractions: usize = 0; for (self.contractions.items, self.contraction_elements.items) |c, elements| { var all_in = inside(repertoire, c.first); for (self.contraction_points.items[c.rest_index..][0..c.rest_len]) |cp| { if (!inside(repertoire, cp)) all_in = false; } if (!all_in) { dropped_contractions += 1; continue; } try kept_contractions.append(arena, c); try kept_elements.append(arena, elements); } self.contractions = kept_contractions; self.contraction_elements = kept_elements; std.debug.print( "repertoire: kept {d} code points and {d} contractions, dropped {d} and {d}\n", .{ self.singles.count(), self.contractions.items.len, dropped_singles, dropped_contractions, }, ); } fn addIdeographRanges( self: *Parsed, arena: Allocator, proplist_text: []const u8, blocks_text: []const u8, ) !void { const unified = try findBlock(blocks_text, "CJK Unified Ideographs"); const compatibility = try findBlock(blocks_text, "CJK Compatibility Ideographs"); var lines = std.mem.splitScalar(u8, proplist_text, '\n'); while (lines.next()) |raw| { const line = stripComment(raw); if (line.len == 0) continue; const semi = std.mem.findScalar(u8, line, ';') orelse continue; if (!std.mem.eql(u8, std.mem.trim(u8, line[semi + 1 ..], " \t\r"), "Unified_Ideograph")) continue; const range = std.mem.trim(u8, line[0..semi], " \t"); const first, const last = try parseRange(range); // A range is entirely inside one block or entirely outside both: // `Unified_Ideograph` is assigned blockwise, so no range needs // splitting. Checked rather than assumed. const in_core = inRange(first, unified) or inRange(first, compatibility); const last_in_core = inRange(last, unified) or inRange(last, compatibility); if (in_core != last_in_core) return error.IdeographRangeStraddlesBlock; try self.implicit_ranges.append(arena, .{ .first = first, .last = last, .kind = if (in_core) .core_han else .other_han, }); } } }; /// The table laid out the way it is stored. const Built = struct { min_variable_primary: u16, max_variable_primary: u16, stage1: [stage1_len]u16, stage2: std.ArrayList(u64), expansions: std.ArrayList(Element), contractions: std.ArrayList(Contraction), contraction_points: std.ArrayList(u21), implicit_ranges: []const ImplicitRange, han_order: []const data.HanRange, fn build(arena: Allocator, parsed: *Parsed) !Built { var self: Built = .{ .min_variable_primary = parsed.min_variable_primary, .max_variable_primary = parsed.max_variable_primary, .stage1 = @splat(no_block), .stage2 = .empty, .expansions = .empty, .contractions = .empty, .contraction_points = .empty, .implicit_ranges = parsed.implicit_ranges.items, .han_order = parsed.han_order.items, }; // Which code points begin a contraction, so that the entry can say // so and a lookup on any other code point never searches the list. var starters: std.AutoHashMapUnmanaged(u21, void) = .empty; for (parsed.contractions.items) |c| try starters.put(arena, c.first, {}); // Elements are pooled: two entries that map to the same sequence // share one run. Keyed by the bytes of the run, which is what makes // it worth doing -- the eighteen-element Arabic ligature is unique, // but plenty of shorter expansions repeat. var pool: std.StringHashMapUnmanaged(u32) = .empty; self.contraction_points = parsed.contraction_points; // Contractions first, so that their elements are in the pool before // the entries that share a run with them. for (parsed.contractions.items, parsed.contraction_elements.items) |c, elements| { var moved = c; moved.elements_index = try self.intern(arena, &pool, elements); try self.contractions.append(arena, moved); } std.mem.sort( Contraction, self.contractions.items, @as([]const u21, parsed.contraction_points.items), Contraction.lessThan, ); // Blocks are deduplicated by content, which pays: many blocks hold // nothing but runs of the same shape. var blocks: std.StringHashMapUnmanaged(u16) = .empty; var block: [block_len]u64 = undefined; var high: u21 = 0; while (high < stage1_len) : (high += 1) { var any = false; for (0..block_len) |low| { const cp: u21 = @intCast(high * block_len + low); const elements = parsed.singles.get(cp); const starts = starters.contains(cp); if (elements == null and !starts) { block[low] = @bitCast(Entry.none); continue; } any = true; const entry: Entry = if (elements) |list| switch (list.len) { 0 => unreachable, 1 => .{ .payload = @bitCast(list[0]), .len = 1, .starts_contraction = starts, }, else => .{ .payload = try self.intern(arena, &pool, list), .len = @intCast(list.len), .starts_contraction = starts, }, } else .{ // A code point with no mapping of its own that still // begins a contraction. Its own weights are derived, but // the contraction has to be tried first. .payload = 0, .len = 0, .starts_contraction = true, }; block[low] = @bitCast(entry); } if (!any) continue; const key = std.mem.sliceAsBytes(block[0..]); if (blocks.get(key)) |existing| { self.stage1[high] = existing; continue; } const index: u16 = @intCast(self.stage2.items.len / block_len); try self.stage2.appendSlice(arena, block[0..]); try blocks.put(arena, try arena.dupe(u8, key), index); self.stage1[high] = index; } return self; } /// Put a run of elements in the pool, returning where it starts. fn intern( self: *Built, arena: Allocator, pool: *std.StringHashMapUnmanaged(u32), elements: []const Element, ) !u32 { const key = std.mem.sliceAsBytes(elements); if (pool.get(key)) |index| return index; const index: u32 = @intCast(self.expansions.items.len); try self.expansions.appendSlice(arena, elements); try pool.put(arena, try arena.dupe(u8, key), index); return index; } fn emit( self: *const Built, w: *std.Io.Writer, version: []const u8, repertoire: []const [2]u21, ) !void { try w.print( \\// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie \\// SPDX-License-Identifier: MIT \\ \\//! A collation element table, generated from \\//! Unicode {s} by tools/gen_table.zig. Do not edit. \\ \\const data = @import("data"); \\ \\pub const unicode_version = "{s}"; \\ \\ , .{ version, version }); try w.print( \\/// The band of primary weights on variable collation elements. \\pub const min_variable_primary: u16 = 0x{X:0>4}; \\pub const max_variable_primary: u16 = 0x{X:0>4}; \\ \\ , .{ self.min_variable_primary, self.max_variable_primary }); // Only a restricted table declares one, and `Table.of` reads it // through `@hasDecl`, so an unrestricted table is byte for byte what // it was before this existed. if (repertoire.len != 0) { try w.writeAll( \\/// Section 9.3.3: the code point ranges this table covers. \\/// \\/// Everything outside them has no entry and is weighed from its \\/// code point by section 10.1.3, which orders it after every \\/// character that does have one. A table with this declared is a \\/// different collation from the full one, and conformant only \\/// over the repertoire it names. \\pub const repertoire = [_][2]u21{ \\ ); for (repertoire) |r| { try w.print(" .{{ 0x{X:0>4}, 0x{X:0>4} }},\n", .{ r[0], r[1] }); } try w.writeAll("};\n\n"); } // Only as far as the last block that has anything in it. `rootEntry` // already answers `Entry.none` for a code point whose block is past // the end of this array, so the tail of `no_block` entries is pure // cost -- and for a table restricted by `--repertoire=` it is nearly // the whole array: a Latin repertoire reaches U+206F, which is block // 0x20, so 33 entries say what 4,352 were saying. var used = self.stage1.len; while (used > 0 and self.stage1[used - 1] == no_block) used -= 1; try w.writeAll("pub const stage1 = [_]u16{"); for (self.stage1[0..used], 0..) |v, i| { if (i % 16 == 0) try w.writeAll("\n "); try w.print("0x{X:0>4},", .{v}); } try w.writeAll("\n};\n\n"); try w.writeAll("pub const stage2 = [_]u64{"); for (self.stage2.items, 0..) |v, i| { if (i % 8 == 0) try w.writeAll("\n "); try w.print("0x{X:0>16},", .{v}); } try w.writeAll("\n};\n\n"); try w.writeAll("pub const expansions = [_]data.Element{"); for (self.expansions.items, 0..) |e, i| { if (i % 4 == 0) try w.writeAll("\n "); try w.print( ".{{ .primary = 0x{X:0>4}, .secondary = 0x{X:0>3}, .tertiary = 0x{X:0>2}" ++ "{s} }},", .{ e.primary, @as(u16, e.secondary), @as(u16, e.tertiary), if (e.case == .upper) ", .case = .upper" else "", }, ); } try w.writeAll("\n};\n\n"); try w.writeAll("pub const contractions = [_]data.Contraction{"); for (self.contractions.items) |c| { try w.print( "\n .{{ .first = 0x{X:0>4}, .rest_index = {d}, .rest_len = {d}, " ++ ".elements_index = {d}, .elements_len = {d} }},", .{ c.first, c.rest_index, c.rest_len, c.elements_index, c.elements_len }, ); } try w.writeAll("\n};\n\n"); try w.writeAll("pub const contraction_points = [_]u21{"); for (self.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("pub const implicit_ranges = [_]data.ImplicitRange{"); for (self.implicit_ranges) |r| { try w.print( "\n .{{ .first = 0x{X:0>4}, .last = 0x{X:0>4}, .kind = .{t}, " ++ ".lead = 0x{X:0>4}, .base = 0x{X:0>4} }},", .{ r.first, r.last, r.kind, r.lead, r.base }, ); } try w.writeAll("\n};\n"); // Written as bare integers and bitcast in one go, because there are // 24,005 of them: a struct literal apiece is a megabyte of source, // an `@bitCast` apiece is 900 KB, and this is 400 KB. try w.print( "\npub const han_order: [{d}]data.HanRange = @bitCast(han_order_bits);\n" ++ "const han_order_bits = [_]u64{{", .{self.han_order.len}, ); for (self.han_order, 0..) |r, i| { if (i % 8 == 0) try w.writeAll("\n "); try w.print("0x{X},", .{@as(u64, @bitCast(r))}); } try w.writeAll("\n};\n"); } }; /// The ideograph an implicit-weight pair stands for, or null if the two /// elements are not such a pair. /// /// Section 10.1.3's encoding: a lead weight of 0xFB40 or 0xFB41 for the Han /// in the core blocks and 0xFB80 upwards for the rest, followed by an element /// whose primary weight is the low fifteen bits of the code point with the /// top bit set and whose other weights are zero. 0xFB86 is the highest lead /// Table 16 can give, for the Han from U+30000 up. The siniform leads, 0xFB00 /// to 0xFB05, are deliberately not here: Tangut, Nushu, Khitan, Jurchen and /// Seal are not Han and CLDR's radical order says nothing about them. fn hanPairCodePoint(lead: Element, trail: Element) ?u21 { if (trail.primary < 0x8000 or trail.secondary != 0 or trail.tertiary != 0) return null; const base: u21 = switch (lead.primary) { 0xFB40, 0xFB41 => 0xFB40, 0xFB80...0xFB86 => 0xFB80, else => return null, }; const high: u21 = @intCast(lead.primary - base); return (high << 15) | @as(u21, trail.primary & 0x7FFF); } fn stripComment(raw: []const u8) []const u8 { var line = raw; // Section 12.1: "A '#' or '%' and any following characters on a line are // comments." if (std.mem.findScalar(u8, line, '#')) |i| line = line[0..i]; if (std.mem.findScalar(u8, line, '%')) |i| line = line[0..i]; return std.mem.trim(u8, line, " \t\r"); } /// The version out of a UCD file's first line, which reads like /// `# PropList-18.0.0.txt`. fn headerVersion(text: []const u8, comptime name: []const u8) ![]const u8 { const prefix = "# " ++ name ++ "-"; const first = std.mem.sliceTo(text, '\n'); if (!std.mem.startsWith(u8, first, prefix)) return error.NoVersion; const rest = first[prefix.len..]; const dot_txt = std.mem.find(u8, rest, ".txt") orelse return error.NoVersion; return rest[0..dot_txt]; } fn parseRange(range: []const u8) !struct { u21, u21 } { if (std.mem.find(u8, range, "..")) |dots| { return .{ try std.fmt.parseInt(u21, range[0..dots], 16), try std.fmt.parseInt(u21, range[dots + 2 ..], 16), }; } const single = try std.fmt.parseInt(u21, range, 16); return .{ single, single }; } /// Section 9.3.3's repertoire, as the ranges named by `--repertoire=`. /// /// The names are `Blocks.txt` block names, which is the unit that makes the /// saving worth having: the scripts are too coarse, because `Common` alone is /// 9,123 code points scattered over dozens of blocks, so restricting to Latin /// by script still keeps 79 of the table's 188 stage-two blocks. Naming /// blocks instead -- `Basic Latin`, `Latin-1 Supplement`, `General /// Punctuation` -- keeps three. /// /// A range may also be written directly, as `0000..024F`, for a repertoire /// no block boundary describes. fn parseRepertoire( arena: Allocator, blocks_text: []const u8, names: []const u8, ) ![]const [2]u21 { var out: std.ArrayList([2]u21) = .empty; var it = std.mem.tokenizeScalar(u8, names, ','); while (it.next()) |raw| { const name = std.mem.trim(u8, raw, " \t"); if (name.len == 0) continue; const range = if (std.mem.indexOf(u8, name, "..") != null or (name.len != 0 and isHexOnly(name))) parseRange(name) catch { std.debug.print("--repertoire: cannot read the range {s}\n", .{name}); return error.BadRepertoire; } else findBlockNamed(blocks_text, name) catch { std.debug.print( "--repertoire: Blocks.txt has no block named {s}\n", .{name}, ); return error.BadRepertoire; }; try out.append(arena, .{ range[0], range[1] }); } std.mem.sort([2]u21, out.items, {}, struct { fn lt(_: void, a: [2]u21, b: [2]u21) bool { return a[0] < b[0]; } }.lt); return out.items; } /// The repertoire closed under canonical decomposition, which is what makes /// it usable rather than a trap. /// /// A canonically decomposable code point has no entry in the table at all -- /// step 1 has replaced it before anything is looked up -- so it sorts by /// whatever its decomposition weighs. If the decomposition falls outside the /// repertoire, that character gets section 10.1.3's implicit weights and /// sorts after the whole table, and the repertoire has silently failed to /// support a character it named. /// /// U+0374 GREEK NUMERAL SIGN is the one that found this: it is in the Greek /// and Coptic block and decomposes to U+02B9 MODIFIER LETTER PRIME, which is /// in Spacing Modifier Letters. A repertoire of Greek without that block put /// `0374 0062` after `0375 0021`, which the CLDR conformance file has the /// other way round -- one line out of order out of 7,294, and the only /// symptom. /// /// Hangul is the other case, and is arithmetic rather than tabulated: a /// syllable decomposes to jamo, so naming the syllables block pulls in the /// jamo blocks. fn closeUnderDecomposition(arena: Allocator, named: []const [2]u21) ![]const [2]u21 { if (named.len == 0) return named; const count = 0x110000; const set = try arena.alloc(bool, count); @memset(set, false); for (named) |r| { var cp = r[0]; while (cp <= r[1]) : (cp += 1) set[cp] = true; } // Repeated until nothing more is added, because a decomposition can // decompose again -- U+1E14 is E with macron and grave, whose mapping is // U+0112 and U+0300, and U+0112 maps on to U+0045 and U+0304. var added = true; while (added) { added = false; for (0..count) |i| { const cp: u21 = @intCast(i); if (!set[cp]) continue; if (cp >= 0xAC00 and cp <= 0xD7A3) { // Section 3.12's arithmetic decomposition, which no table // carries: the jamo it lands on. const index = cp - 0xAC00; for ([_]u21{ 0x1100 + index / (21 * 28), 0x1161 + (index % (21 * 28)) / 28, if (index % 28 == 0) 0 else 0x11A7 + index % 28, }) |jamo| { if (jamo != 0 and !set[jamo]) { set[jamo] = true; added = true; } } continue; } if (uucode.get(.decomposition_type, cp) != .canonical) continue; // `with` is how uucode hands back a mapping: the buffer is only // for the code point that maps to itself, which is one long. var mapping_buf: [1]u21 = undefined; const mapping = uucode.get(.decomposition_mapping, cp).with(&mapping_buf, cp); for (mapping) |part| { if (!set[part]) { set[part] = true; added = true; } } } } // Back to ranges, coalescing what is adjacent so the emitted list stays // readable. var out: std.ArrayList([2]u21) = .empty; var i: usize = 0; while (i < count) { if (!set[i]) { i += 1; continue; } const first: u21 = @intCast(i); while (i < count and set[i]) i += 1; try out.append(arena, .{ first, @intCast(i - 1) }); } return out.items; } fn isHexOnly(name: []const u8) bool { for (name) |ch| { if (!std.ascii.isHex(ch) and ch != '.') return false; } return true; } fn findBlockNamed(blocks_text: []const u8, name: []const u8) !struct { u21, u21 } { var lines = std.mem.splitScalar(u8, blocks_text, '\n'); while (lines.next()) |raw| { const line = stripComment(raw); if (line.len == 0) continue; const semi = std.mem.findScalar(u8, line, ';') orelse continue; const block = std.mem.trim(u8, line[semi + 1 ..], " \t\r"); if (!std.ascii.eqlIgnoreCase(block, name)) continue; return parseRange(std.mem.trim(u8, line[0..semi], " \t")); } return error.BlockNotFound; } fn findBlock(blocks_text: []const u8, comptime name: []const u8) !struct { u21, u21 } { var lines = std.mem.splitScalar(u8, blocks_text, '\n'); while (lines.next()) |raw| { const line = stripComment(raw); if (line.len == 0) continue; const semi = std.mem.findScalar(u8, line, ';') orelse continue; if (!std.mem.eql(u8, std.mem.trim(u8, line[semi + 1 ..], " \t\r"), name)) continue; return parseRange(std.mem.trim(u8, line[0..semi], " \t")); } return error.BlockNotFound; } fn inRange(cp: u21, range: struct { u21, u21 }) bool { return cp >= range[0] and cp <= range[1]; }