// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Step 2 of the algorithm, UTS #10 section 7.2: turn an NFD string into an //! array of collation elements. //! //! This is the step with the table behind it and the step the subtle bugs //! live in, because the matching is not a simple longest-prefix walk. Two //! different matching methods run at each position, and the note at the end //! of section 7.2 is emphatic that they are different: //! //! * S2.1 is contiguous and longest-match. It has to find a contraction //! `ABC` whether or not `AB` is also a contraction. //! * S2.1.1 to S2.1.3 are discontiguous. They grow a match one code point //! at a time across non-starters that get skipped, which means they can //! only find `ABC` by way of `AB`. Well-formedness condition WF5 is what //! guarantees `AB` is there to be found. //! //! The discontiguous half exists because of canonical equivalence rather //! than for its own sake. `` and `` are not the same string, but the second //! normalizes to ``, which //! separates the `a` from the ring that a Danish contraction wants to pair //! it with. Without the lookahead that string would sort next to `a` instead //! of after `z`. const std = @import("std"); const Allocator = std.mem.Allocator; const data = @import("data"); const Element = data.Element; const Contraction = data.Contraction; const nfd = @import("nfd.zig"); const Table = @import("table.zig").Table; /// The most code points a partial match has to remember, which is the most a /// contraction may be. See `data.max_contraction`. const max_contraction = data.max_contraction; /// Append the collation elements for `text` to `out`. /// /// `text` must already be in NFD -- step 1 -- and is taken **mutably**, /// because S2.1.3 says to "remove C" from the input when a discontiguous /// match consumes it. Removing it in place is what keeps the walk to a /// single pass; the alternative is a second buffer holding which positions /// have been eaten. pub fn append( out: *std.ArrayList(Element), gpa: Allocator, table: Table, text: []u21, ) Allocator.Error!void { return appendImpl(false, out, undefined, gpa, table, text, undefined); } test append { const gpa = std.testing.allocator; var out: std.ArrayList(Element) = .empty; defer out.deinit(gpa); // и and a combining breve are short i, й: two code points, and one // contraction weighing them as a letter of its own. var text = [_]u21{ 0x0438, 0x0306 }; try append(&out, gpa, ducet, &text); try std.testing.expectEqual(@as(usize, 1), out.items.len); // A letter after и, not и with an accent. var scratch: [1]Element = undefined; const i = ducet.elementsOf(ducet.entry(0x0438), &scratch)[0]; try std.testing.expect(out.items[0].primary > i.primary); } /// Which code points of the caller's text a collation element came from, as /// the lowest and highest of their indices. /// /// Usually one code point, or several adjacent ones for a contraction. A /// discontiguous contraction (S2.1.1 to S2.1.3) is the case that makes this a /// range rather than a list: it takes a code point from further on and leaves /// the marks it skipped to be weighed after it, so the skipped marks' origins /// fall *inside* the contraction's range. Search uses that to refuse a match /// edge that would separate them. pub const Origin = struct { first: u32, last: u32 }; /// `append`, also recording each element's `Origin`. /// /// `origins` holds, for each code point of `text`, its index in the caller's /// text -- what `nfd.appendTracked` produces -- and is edited alongside /// `text` when a discontiguous match removes a code point. pub fn appendTracked( out: *std.ArrayList(Element), out_origins: *std.ArrayList(Origin), gpa: Allocator, table: Table, text: []u21, origins: []u32, ) Allocator.Error!void { std.debug.assert(text.len == origins.len); return appendImpl(true, out, out_origins, gpa, table, text, origins); } test appendTracked { const gpa = std.testing.allocator; var out: std.ArrayList(Element) = .empty; defer out.deinit(gpa); var out_origins: std.ArrayList(Origin) = .empty; defer out_origins.deinit(gpa); // `x`, then the contraction й from code points 1 and 2. var text = [_]u21{ 'x', 0x0438, 0x0306 }; var origins = [_]u32{ 0, 1, 2 }; try appendTracked(&out, &out_origins, gpa, ducet, &text, &origins); try std.testing.expectEqualSlices(Origin, &.{ .{ .first = 0, .last = 0 }, .{ .first = 1, .last = 2 }, }, out_origins.items); } fn appendImpl( comptime tracked: bool, out: *std.ArrayList(Element), out_origins: if (tracked) *std.ArrayList(Origin) else void, gpa: Allocator, table: Table, text: []u21, origins: if (tracked) []u32 else void, ) Allocator.Error!void { var len = text.len; var i: usize = 0; while (i < len) { var scratch: [1]Element = undefined; // The code points this match consumes, so far: the one at `i`, and // whatever the searches below add. var origin: Origin = if (tracked) .{ .first = origins[i], .last = origins[i] } else undefined; // S2.1: the longest contiguous match at this point. const entry = table.entry(text[i]); var key: [max_contraction]u21 = undefined; key[0] = text[i]; var key_len: usize = 1; // How much of the front of the string this match covers. Only this // many code points are stepped over at the end, because anything a // discontiguous match ate has already been removed from the middle. var head_len: usize = 1; var elements: ?[]const Element = null; if (entry.starts_contraction) { // The tailoring's list first, so that a locale can replace a // contraction the root already had, and each list sorted // longest-first so the first match in it is the longest, which // is what S2.1 asks for. for ([_]bool{ true, false }) |from_tailoring| { const list = if (from_tailoring) table.tailoredContractionsFor(text[i]) else table.rootContractionsFor(text[i]); for (list) |c| { const n = c.rest_len; if (i + 1 + n > len) continue; const rest = if (from_tailoring) table.tailoredRestOf(c) else table.restOf(c); if (!std.mem.eql(u21, text[i + 1 ..][0..n], rest)) continue; // A contextual mapping, section 3.3's `prefix|target`: // this one applies only after particular code points. // The prefix is a condition rather than part of the // match -- it has been weighed already and is not // consumed -- so it is checked here and changes nothing // about how much of the string this covers. // // Matched against the text as the walk left it, which is // what a discontiguous match's removal has already // accounted for. Sorted longest-prefix-first within a // target, so the most specific condition is tried first // and an unconditional mapping last. if (c.prefix_len != 0) { const prefix = if (from_tailoring) table.tailoredPrefixOf(c) else table.prefixOf(c); if (i < prefix.len) continue; if (!std.mem.eql(u21, text[i - prefix.len .. i], prefix)) continue; } elements = if (from_tailoring) table.elementsOfTailoredContraction(c) else table.elementsOfContraction(c); head_len = 1 + n; key_len = 1 + n; for (rest, 1..) |cp, k| key[k] = cp; break; } if (elements != null) break; } } if (elements == null and entry.len != 0) { elements = table.elementsOf(entry, &scratch); } // S2.1.1 to S2.1.3: try to grow the match across skipped // non-starters. Only a code point that starts a contraction can // grow, so this costs nothing for the 99.8% of code points that // cannot. if (entry.starts_contraction) { // The greatest combining class among the code points between the // end of the match and the candidate. UTS10-D34: those are the // `B`s, and any one of them with ccc(B) >= ccc(C) puts C in a // blocking context. var blocking_ccc: u8 = 0; var j = i + head_len; while (j < len) { const ccc = nfd.combiningClass(text[j]); // "The search for such a match will terminate at the first // non-starter in a blocked context, or alternatively, at the // first starter encountered during the lookahead." if (ccc == 0 or ccc <= blocking_ccc) break; if (key_len < max_contraction) { if (findContraction(table, text[0..i], key[0..key_len], text[j])) |found| { const c, const from_tailoring = found; elements = if (from_tailoring) table.elementsOfTailoredContraction(c) else table.elementsOfContraction(c); key[key_len] = text[j]; key_len += 1; // S2.1.3: remove C. The code points that were // skipped stay where they are and keep blocking, so // `blocking_ccc` is deliberately left alone -- it is // already the greatest class among them. std.mem.copyForwards(u21, text[j .. len - 1], text[j + 1 .. len]); if (tracked) { origin.first = @min(origin.first, origins[j]); origin.last = @max(origin.last, origins[j]); std.mem.copyForwards(u32, origins[j .. len - 1], origins[j + 1 .. len]); } len -= 1; continue; } } blocking_ccc = ccc; j += 1; } } // S2.2: no match, so synthesize. S2.4: append. const before = out.items.len; if (elements) |list| { try out.appendSlice(gpa, list); } else { try out.appendSlice(gpa, &table.implicit(text[i])); } if (tracked) { for (origins[i..][0..head_len]) |o| { origin.first = @min(origin.first, o); origin.last = @max(origin.last, o); } try out_origins.appendNTimes(gpa, origin, out.items.len - before); } // S2.5. i += head_len; } } /// The contraction for `matched ++ {next}`, if the table or its tailoring has /// one. The tailoring wins. /// /// `context` is the text before the match and is what a contextual mapping's /// own prefix is tested against -- the same condition the contiguous search /// applies, and it has to be applied here too: this is the second place a /// contraction can be chosen, and a conditional mapping that skipped the /// condition here would apply everywhere. Japanese is what noticed, with /// 864,568 disagreements of 24,468,510: ゞ is ゝ and U+3099, U+3099 is a /// non-starter, so *every* pair of them reached the discontiguous search and /// took the first contextual mapping in the list whatever stood before it. fn findContraction( table: Table, context: []const u21, matched: []const u21, next: u21, ) ?struct { Contraction, bool } { const prefix = matched; for ([_]bool{ true, false }) |from_tailoring| { const list = if (from_tailoring) table.tailoredContractionsFor(prefix[0]) else table.rootContractionsFor(prefix[0]); for (list) |c| { if (c.rest_len != prefix.len) continue; const rest = if (from_tailoring) table.tailoredRestOf(c) else table.restOf(c); if (!std.mem.eql(u21, rest[0 .. prefix.len - 1], prefix[1..])) continue; if (rest[prefix.len - 1] != next) continue; if (c.prefix_len != 0) { const condition = if (from_tailoring) table.tailoredPrefixOf(c) else table.prefixOf(c); if (context.len < condition.len) continue; if (!std.mem.eql(u21, context[context.len - condition.len ..], condition)) continue; } return .{ c, from_tailoring }; } } return null; } const testing = std.testing; const ducet = @import("table.zig").ducet; fn collationElements(gpa: Allocator, cps: []const u21) !std.ArrayList(Element) { var text: std.ArrayList(u21) = .empty; defer text.deinit(gpa); try nfd.append(&text, gpa, cps); var out: std.ArrayList(Element) = .empty; try append(&out, gpa, ducet, text.items); return out; } /// Whether the DUCET table has an entry for each of these, which a build /// restricted by `-Drepertoire=` need not. A test that reads an element out /// of the table is about something that is not there otherwise. fn haveAll(cps: []const u21) bool { for (cps) |cp| { if (!ducet.inRepertoire(cp)) return false; if (ducet.entry(cp).len == 0) return false; } return true; } test "the worked example in figure 1" { // Every character the figure names has to be in the table, which a build // restricted by `-Drepertoire=` need not have -- and without the // combining acute the accent takes an implicit weight and contributes a // primary difference rather than a secondary one, which is the whole // point of the figure. if (!haveAll(&.{ 'c', 'a', 0x0301, 'b' })) return error.SkipZigTest; // "cab" becomes // [.0706.0020.0002], [.06D9.0020.0002], [.0000.0021.0002], [.06EE.0020.0002] // The weights in the figure are from an older DUCET, so what is checked // here is the shape: four elements, and the accent contributing a // secondary difference with no primary weight of its own. var out = try collationElements(testing.allocator, &.{ 'c', 'a', 0x0301, 'b' }); defer out.deinit(testing.allocator); try testing.expectEqual(@as(usize, 4), out.items.len); try testing.expect(out.items[0].isPrimary()); try testing.expect(out.items[1].isPrimary()); // The combining acute is a secondary collation element, UTS10-D10: no // primary weight, a secondary weight of its own. try testing.expect(!out.items[2].isPrimary()); try testing.expect(out.items[2].secondary != 0); try testing.expect(out.items[3].isPrimary()); } test "an unmatched code point gets two elements, not one" { // Section 10.1.2: every code point the table says nothing about maps to // a *pair*, so a Han ideograph contributes two primary weights. var out = try collationElements(testing.allocator, &.{0x4E00}); defer out.deinit(testing.allocator); try testing.expectEqual(@as(usize, 2), out.items.len); try testing.expectEqual(@as(u16, 0xFB40), out.items[0].primary); try testing.expectEqual(@as(u16, 0xCE00), out.items[1].primary); } test "a contiguous contraction is one match" { // Taken out of the table rather than named, so that the test cannot go // stale when DUCET's contractions change. const c = for (ducet.contractions) |candidate| { if (candidate.rest_len == 1) break candidate; } else return error.SkipZigTest; var out = try collationElements(testing.allocator, &.{ c.first, ducet.restOf(c)[0] }); defer out.deinit(testing.allocator); // The pair weighs as the contraction says, not as its halves would // separately. if (!std.mem.eql(Element, ducet.elementsOfContraction(c), out.items)) { std.debug.print("contraction U+{X:0>4} U+{X:0>4}: table says {any}, got {any}\n", .{ c.first, ducet.restOf(c)[0], ducet.elementsOfContraction(c), out.items, }); return error.TestUnexpectedResult; } // And it is a contraction rather than a redundant entry: the two code // points weighed apart are not the same sequence. For DUCET's first one, // U+004C U+00B7, the difference is in the second element -- the middle // dot's own [*0297.0020.0002] becomes [.0000.011F.0002], an ignorable // that contributes a secondary difference instead of a primary one. var apart: std.ArrayList(Element) = .empty; defer apart.deinit(testing.allocator); var first_half = try collationElements(testing.allocator, &.{c.first}); defer first_half.deinit(testing.allocator); var second_half = try collationElements(testing.allocator, &.{ducet.restOf(c)[0]}); defer second_half.deinit(testing.allocator); try apart.appendSlice(testing.allocator, first_half.items); try apart.appendSlice(testing.allocator, second_half.items); try testing.expect(!std.mem.eql(Element, out.items, apart.items)); } test "a discontiguous match still finds the contraction" { // The example section 7.2 gives. Take a two-code-point contraction whose // second half is a non-starter, put a *lower* combining class mark // between the two, and NFD will have reordered it to sit between them. // The contraction must still be found. const c = for (ducet.contractions) |candidate| { if (candidate.rest_len != 1) continue; const ccc = nfd.combiningClass(ducet.restOf(candidate)[0]); if (ccc == 0) continue; break candidate; } else return error.SkipZigTest; const inner_ccc = nfd.combiningClass(ducet.restOf(c)[0]); // A non-starter with a strictly lower combining class, so that NFD sorts // it before the contraction's second half and splits the pair. const intruder: u21 = for ([_]u21{ 0x0316, 0x0323, 0x0334, 0x0591, 0x0301 }) |cp| { const ccc = nfd.combiningClass(cp); if (ccc != 0 and ccc < inner_ccc) break cp; } else return error.SkipZigTest; var text: std.ArrayList(u21) = .empty; defer text.deinit(testing.allocator); try nfd.append(&text, testing.allocator, &.{ c.first, ducet.restOf(c)[0], intruder }); // NFD really did separate them, or the test is proving nothing. try testing.expectEqual(intruder, text.items[1]); var out: std.ArrayList(Element) = .empty; defer out.deinit(testing.allocator); try append(&out, testing.allocator, ducet, text.items); // The contraction's elements come first, then the intruder's. const contracted = ducet.elementsOfContraction(c); try testing.expect(out.items.len > contracted.len); try testing.expectEqualSlices(Element, contracted, out.items[0..contracted.len]); } test "a starter blocks a discontiguous match" { // Section 3.5: "A sequence of characters which otherwise would result in // a contraction match can be made to sort as separate characters by // inserting, someplace within the sequence, a starter that maps to a // completely ignorable collation element." U+034F COMBINING GRAPHEME // JOINER is named there for exactly this. const c = if (ducet.contractions.len != 0) ducet.contractions[0] else return error.SkipZigTest; var with_cgj = try collationElements(testing.allocator, &.{ c.first, 0x034F, ducet.restOf(c)[0] }); defer with_cgj.deinit(testing.allocator); var without = try collationElements(testing.allocator, &.{ c.first, ducet.restOf(c)[0] }); defer without.deinit(testing.allocator); try testing.expect(with_cgj.items.len != without.items.len); } test "hangul syllables weigh as their jamo" { var syllable = try collationElements(testing.allocator, &.{0xAC01}); defer syllable.deinit(testing.allocator); var jamo = try collationElements(testing.allocator, &.{ 0x1100, 0x1161, 0x11A8 }); defer jamo.deinit(testing.allocator); try testing.expectEqualSlices(Element, jamo.items, syllable.items); } test "a contextual mapping applies only after its prefix" { // The elements the tailoring is built out of come from the table, so // they have to be in it. if (!haveAll(&.{ 'a', 'b', 'c' })) return error.SkipZigTest; // Section 3.3's `prefix|target`, built by hand because the one locale // that writes them does not compile yet. The shape is Japanese's: a // mark takes the weights of what comes before it, so that `aー` sorts // where `aa` does and `bー` does not. var scratch: [1]Element = undefined; const a = ducet.elementsOf(ducet.entry('a'), &scratch)[0]; const mark: u21 = 0x30FC; // KATAKANA-HIRAGANA PROLONGED SOUND MARK const expansions = [_]Element{a}; const points = [_]u21{'a'}; // the prefix; the target has no rest const contractions = [_]Contraction{.{ .first = mark, .rest_index = 0, .rest_len = 0, .elements_index = 0, .elements_len = 1, .prefix_index = 0, .prefix_len = 1, }}; const tailoring: data.Tailoring = .{ .locale = "test", .root = "ducet", .overrides = &.{}, .contractions = &contractions, .contraction_points = &points, .expansions = &expansions, }; const table = ducet.tailored(&tailoring); const weigh = struct { fn f(t: Table, cps: []const u21) !std.ArrayList(Element) { var text: std.ArrayList(u21) = .empty; defer text.deinit(testing.allocator); try nfd.append(&text, testing.allocator, cps); var out: std.ArrayList(Element) = .empty; try append(&out, testing.allocator, t, text.items); return out; } }.f; // After the prefix: the mark weighs as a second `a`. var after = try weigh(table, &.{ 'a', mark }); defer after.deinit(testing.allocator); var doubled = try weigh(table, &.{ 'a', 'a' }); defer doubled.deinit(testing.allocator); try testing.expectEqualSlices(Element, doubled.items, after.items); // After anything else: the mark weighs as itself, which is what the root // says, so the tailoring has changed nothing there. var elsewhere = try weigh(table, &.{ 'b', mark }); defer elsewhere.deinit(testing.allocator); var untailored = try weigh(ducet, &.{ 'b', mark }); defer untailored.deinit(testing.allocator); try testing.expectEqualSlices(Element, untailored.items, elsewhere.items); // And at the start of a string there is no prefix to match, so likewise. var alone = try weigh(table, &.{mark}); defer alone.deinit(testing.allocator); var alone_untailored = try weigh(ducet, &.{mark}); defer alone_untailored.deinit(testing.allocator); try testing.expectEqualSlices(Element, alone_untailored.items, alone.items); } test "a contextual mapping's condition holds on the discontiguous path too" { // The elements the tailoring is built out of come from the table, so // they have to be in it. if (!haveAll(&.{ 'a', 'b', 'c' })) return error.SkipZigTest; // The condition has to be checked in both places a contraction can be // chosen. S2.1 matches contiguously; S2.1.1 grows a match across skipped // non-starters, through `findContraction`, and a mapping whose target // *ends* in a non-starter is reached that way rather than by the first // search. // // Japanese is what found it, at 864,568 disagreements with ICU of // 24,468,510. ゞ is ゝ followed by U+3099, U+3099 is a non-starter, and // every pair of them therefore reached the second search -- which took // the first contextual mapping in the list whatever stood before it, so // a bare ゞ weighed as the kana of some rule's prefix. var scratch: [1]Element = undefined; const a = ducet.elementsOf(ducet.entry('a'), &scratch)[0]; const iteration: u21 = 0x309D; // HIRAGANA ITERATION MARK const voiced: u21 = 0x3099; // COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK try testing.expect(nfd.combiningClass(voiced) != 0); const expansions = [_]Element{a}; // The target is the pair, and the condition is a single `a` before it. const points = [_]u21{ voiced, 'a' }; const contractions = [_]Contraction{.{ .first = iteration, .rest_index = 0, .rest_len = 1, .elements_index = 0, .elements_len = 1, .prefix_index = 1, .prefix_len = 1, }}; const tailoring: data.Tailoring = .{ .locale = "test", .root = "ducet", .overrides = &.{}, .contractions = &contractions, .contraction_points = &points, .expansions = &expansions, }; const table = ducet.tailored(&tailoring); const weigh = struct { fn f(t: Table, cps: []const u21) !std.ArrayList(Element) { var text: std.ArrayList(u21) = .empty; defer text.deinit(testing.allocator); try nfd.append(&text, testing.allocator, cps); var out: std.ArrayList(Element) = .empty; try append(&out, testing.allocator, t, text.items); return out; } }.f; // Without the condition met, the pair weighs as the root has it. var bare = try weigh(table, &.{ iteration, voiced }); defer bare.deinit(testing.allocator); var untailored = try weigh(ducet, &.{ iteration, voiced }); defer untailored.deinit(testing.allocator); try testing.expectEqualSlices(Element, untailored.items, bare.items); // With it met, the mapping applies -- so the condition is being tested // rather than the whole mapping being unreachable. var after = try weigh(table, &.{ 'a', iteration, voiced }); defer after.deinit(testing.allocator); try testing.expectEqual(@as(usize, 2), after.items.len); try testing.expectEqual(a, after.items[1]); } test "tracked elements are the same elements, with where each came from" { if (!haveAll(&.{ 0x0438, 0x0306, 0x0328, 'a' })) return error.SkipZigTest; const gpa = testing.allocator; // и, ogonek, breve: the ogonek (class 202) does not block the breve // (230), so S2.1.1 to S2.1.3 reach past it and form the contraction for // short i out of code points 0 and 2. The ogonek is weighed after it, and // its origin lies inside the contraction's range. const input = [_]u21{ 'a', 0x0438, 0x0328, 0x0306 }; var text: std.ArrayList(u21) = .empty; defer text.deinit(gpa); var origins: std.ArrayList(u32) = .empty; defer origins.deinit(gpa); try nfd.appendTracked(&text, &origins, gpa, &input); var tracked: std.ArrayList(Element) = .empty; defer tracked.deinit(gpa); var element_origins: std.ArrayList(Origin) = .empty; defer element_origins.deinit(gpa); try appendTracked(&tracked, &element_origins, gpa, ducet, text.items, origins.items); var plain = try collationElements(gpa, &input); defer plain.deinit(gpa); try testing.expectEqualSlices(Element, plain.items, tracked.items); try testing.expectEqual(@as(usize, 3), tracked.items.len); try testing.expectEqual(Origin{ .first = 0, .last = 0 }, element_origins.items[0]); try testing.expectEqual(Origin{ .first = 1, .last = 3 }, element_origins.items[1]); try testing.expectEqual(Origin{ .first = 2, .last = 2 }, element_origins.items[2]); }