// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Fuzz targets: the properties a collation owes whatever its table says. //! //! These are reached from two places -- `zig build test`, which runs them on //! a handful of fixed inputs, and `tools/fuzz.zig`, which runs them on //! millions of generated ones. A target reached from both cannot name //! `std.testing.allocator`, which does not exist outside a test build, so //! the allocator arrives through `backing` instead: the test build points it //! at the testing allocator and the driver points it at a `DebugAllocator` //! it checks for leaks after every input. const std = @import("std"); const builtin = @import("builtin"); const Allocator = std.mem.Allocator; const Smith = std.testing.Smith; const collate = @import("collate"); pub var backing: Allocator = if (builtin.is_test) std.testing.allocator else undefined; /// How many inputs actually reached an assertion. /// /// A target that cannot make sense of its input has to give up, and a target /// that gives up on nearly everything is indistinguishable from one that is /// working -- both report millions of iterations and no findings. The driver /// prints this beside the iteration count so that the difference is visible /// rather than inferred. pub var asserted: usize = 0; /// The most code points a generated string holds. Carried in the target /// table because the driver has to write a length `Smith` will accept: a /// length larger than the buffer yields an *empty* slice rather than being /// reduced into range, so a driver that does not know the size tests the /// empty string several million times and says nothing about it. pub const max_length = 12; pub const Target = struct { name: []const u8, run: *const fn (smith: *Smith) anyerror!void, }; pub const targets: []const Target = &.{ .{ .name = "reflexive", .run = reflexive }, .{ .name = "antisymmetric", .run = antisymmetric }, .{ .name = "transitive", .run = transitive }, .{ .name = "builder-agrees", .run = builderAgrees }, .{ .name = "strength-refines", .run = strengthRefines }, .{ .name = "nfd-idempotent", .run = nfdIdempotent }, .{ .name = "canonically-equivalent", .run = canonicallyEquivalent }, .{ .name = "contractions-equivalent", .run = contractionsEquivalent }, .{ .name = "contractions-antisymmetric", .run = contractionsAntisymmetric }, .{ .name = "reordered-marks-agree", .run = reorderedMarksAgree }, .{ .name = "utf8-agrees", .run = utf8Agrees }, .{ .name = "expansions-fit", .run = expansionsFit }, .{ .name = "order-agrees", .run = orderAgrees }, .{ .name = "search-agrees", .run = searchAgrees }, .{ .name = "match-keys-agree", .run = matchKeysAgree }, .{ .name = "fuzzy-agrees", .run = fuzzyAgrees }, }; /// A generated string of code points. Every value a `u21` can hold, /// surrogates included, because those are what section 10.1.1 is about and /// what the conformance suite deliberately contains. fn string(smith: *Smith, buf: *[max_length]u21) []const u21 { const len = smith.valueRangeAtMost(u8, 0, max_length); for (buf[0..len]) |*cp| cp.* = smith.valueRangeAtMost(u21, 0, 0x10FFFF); return buf[0..len]; } /// Non-starters, one per distinct canonical combining class, found by /// scanning once on first use. /// /// Derived rather than written down. What makes a code point useful as an /// intruder is its combining class relative to a contraction's second half, /// and a hand-picked list would need re-checking every Unicode release. fn intruders() []const u21 { if (marks_len == 0) { var seen: [256]bool = @splat(false); var cp: u21 = 0; while (cp < 0x110000) : (cp += 1) { const ccc = collate.nfd.combiningClass(cp); if (ccc == 0 or seen[ccc]) continue; seen[ccc] = true; marks[marks_len] = cp; marks_len += 1; } } return marks[0..marks_len]; } var marks: [256]u21 = undefined; var marks_len: usize = 0; /// The contractions a discontiguous match is even possible for: the ones /// whose second code point is a non-starter, so that another mark can sort /// in between and split the pair. Nineteen of DUCET's 964. fn splittable() []const collate.data.Contraction { if (splittable_len == 0) { for (collate.ducet.contractions) |c| { if (c.rest_len == 0) continue; if (collate.nfd.combiningClass(collate.ducet.restOf(c)[0]) == 0) continue; if (splittable_len == splittable_table.len) break; splittable_table[splittable_len] = c; splittable_len += 1; } } return splittable_table[0..splittable_len]; } var splittable_table: [64]collate.data.Contraction = undefined; var splittable_len: usize = 0; /// A string built out of the table's own material, rather than out of /// uniform code points. /// /// This exists because uniform code points do not reach S2.1.1 to S2.1.3 at /// all. A discontiguous match needs one of nineteen specific starters, /// followed by a non-starter of strictly lower combining class, followed by /// the contraction's second half -- three particular values in that order. /// Drawn independently out of a million code points that is not a rare /// event, it is an absent one, and the trickiest code in the library would /// never be executed. fn tableString(smith: *Smith, buf: *[max_length]u21) []const u21 { const group = splittable(); if (group.len == 0) return buf[0..0]; const c = group[smith.index(group.len)]; const pool = intruders(); var len: usize = 0; buf[len] = c.first; len += 1; // Nought to three marks between the halves. Zero makes it a plain // contiguous match, which is worth generating too. const between = smith.valueRangeAtMost(u8, 0, 3); for (0..between) |_| { if (len == max_length) break; buf[len] = pool[smith.index(pool.len)]; len += 1; } for (collate.ducet.restOf(c)) |cp| { if (len == max_length) break; buf[len] = cp; len += 1; } // And a tail, so that what follows a contraction is exercised as well. const tail = smith.valueRangeAtMost(u8, 0, 3); for (0..tail) |_| { if (len == max_length) break; buf[len] = smith.valueRangeAtMost(u21, 0, 0x10FFFF); len += 1; } return buf[0..len]; } fn options(smith: *Smith) collate.Options { return .{ .strength = smith.value(collate.Strength), .alternate = smith.value(collate.Alternate), .backwards_secondary = smith.value(bool), }; } fn key(c: collate.Collator, text: []const u21) ![]u8 { return c.sortKeyAllocCodePoints(backing, text); } /// A string collates equal to itself, at every setting. fn reflexive(smith: *Smith) anyerror!void { var buf: [max_length]u21 = undefined; const c: collate.Collator = .{ .options = options(smith) }; const a = string(smith, &buf); asserted += 1; const one = try key(c, a); defer backing.free(one); const two = try key(c, a); defer backing.free(two); try std.testing.expectEqual(std.math.Order.eq, collate.orderKeys(one, two)); } /// Comparing the other way round gives the opposite answer. A comparison /// that is not antisymmetric makes `std.mem.sort` do undefined things, so /// this is the property a sort actually depends on. fn antisymmetric(smith: *Smith) anyerror!void { var buf_a: [max_length]u21 = undefined; var buf_b: [max_length]u21 = undefined; const c: collate.Collator = .{ .options = options(smith) }; const a = string(smith, &buf_a); const b = string(smith, &buf_b); asserted += 1; const ka = try key(c, a); defer backing.free(ka); const kb = try key(c, b); defer backing.free(kb); const forward = collate.orderKeys(ka, kb); const backward = collate.orderKeys(kb, ka); try std.testing.expectEqual(switch (forward) { .lt => std.math.Order.gt, .eq => std.math.Order.eq, .gt => std.math.Order.lt, }, backward); } fn transitive(smith: *Smith) anyerror!void { var buf_a: [max_length]u21 = undefined; var buf_b: [max_length]u21 = undefined; var buf_c: [max_length]u21 = undefined; const collator: collate.Collator = .{ .options = options(smith) }; const a = string(smith, &buf_a); const b = string(smith, &buf_b); const d = string(smith, &buf_c); asserted += 1; const ka = try key(collator, a); defer backing.free(ka); const kb = try key(collator, b); defer backing.free(kb); const kd = try key(collator, d); defer backing.free(kd); if (collate.orderKeys(ka, kb) != .gt and collate.orderKeys(kb, kd) != .gt) { try std.testing.expect(collate.orderKeys(ka, kd) != .gt); } } /// A reused builder and a fresh one give the same key. This is the property /// that makes the builder's scratch safe to keep between strings, and it is /// the one a stale `clearRetainingCapacity` would break. fn builderAgrees(smith: *Smith) anyerror!void { var buf_a: [max_length]u21 = undefined; var buf_b: [max_length]u21 = undefined; const c: collate.Collator = .{ .options = options(smith) }; const a = string(smith, &buf_a); const b = string(smith, &buf_b); asserted += 1; var builder: collate.Builder = .empty; defer builder.deinit(backing); // The warm-up runs a *different* string through a *different* collation, // so that anything the builder carries over -- a scratch array not // cleared, a variable-weighting pass left from another `Alternate` -- // has to show up in the key that follows. const other: collate.Collator = .{ .options = .{ .strength = .identical, .alternate = if (c.options.alternate == .shifted) .non_ignorable else .shifted, .backwards_secondary = !c.options.backwards_secondary, } }; const warm_up = try builder.sortKeyAllocCodePoints(backing, other, b); backing.free(warm_up); const reused = try builder.sortKeyAllocCodePoints(backing, c, a); defer backing.free(reused); const fresh = try key(c, a); defer backing.free(fresh); try std.testing.expectEqualSlices(u8, fresh, reused); } /// Each strength refines the one below it: two strings that differ at /// primary strength differ the same way at every greater strength. fn strengthRefines(smith: *Smith) anyerror!void { var buf_a: [max_length]u21 = undefined; var buf_b: [max_length]u21 = undefined; const alternate = smith.value(collate.Alternate); const a = string(smith, &buf_a); const b = string(smith, &buf_b); asserted += 1; var coarse: ?std.math.Order = null; for ([_]collate.Strength{ .primary, .secondary, .tertiary, .quaternary, .identical }) |strength| { const c: collate.Collator = .{ .options = .{ .strength = strength, .alternate = alternate }, }; const ka = try key(c, a); defer backing.free(ka); const kb = try key(c, b); defer backing.free(kb); const got = collate.orderKeys(ka, kb); if (coarse) |previous| { // A difference once found is never reversed, only refined -- // which is section 7.4 read the other way round. if (previous != .eq) try std.testing.expectEqual(previous, got); } coarse = got; } } fn nfdIdempotent(smith: *Smith) anyerror!void { var buf: [max_length]u21 = undefined; const a = string(smith, &buf); asserted += 1; var once: std.ArrayList(u21) = .empty; defer once.deinit(backing); try collate.nfd.append(&once, backing, a); var twice: std.ArrayList(u21) = .empty; defer twice.deinit(backing); try collate.nfd.append(&twice, backing, once.items); try std.testing.expectEqualSlices(u21, once.items, twice.items); } /// A string and its NFD collate equal at every strength, identical /// included. This is the guarantee step 1 exists to provide, and the one /// that a sort key is allowed to lose nothing else about. fn canonicallyEquivalent(smith: *Smith) anyerror!void { var buf: [max_length]u21 = undefined; const c: collate.Collator = .{ .options = options(smith) }; const a = string(smith, &buf); asserted += 1; var decomposed: std.ArrayList(u21) = .empty; defer decomposed.deinit(backing); try collate.nfd.append(&decomposed, backing, a); const original = try key(c, a); defer backing.free(original); const normalized = try key(c, decomposed.items); defer backing.free(normalized); try std.testing.expectEqualSlices(u8, original, normalized); } /// `canonicallyEquivalent`, on strings that actually contain contractions. fn contractionsEquivalent(smith: *Smith) anyerror!void { var buf: [max_length]u21 = undefined; const c: collate.Collator = .{ .options = options(smith) }; const a = tableString(smith, &buf); asserted += 1; var decomposed: std.ArrayList(u21) = .empty; defer decomposed.deinit(backing); try collate.nfd.append(&decomposed, backing, a); const original = try key(c, a); defer backing.free(original); const normalized = try key(c, decomposed.items); defer backing.free(normalized); try std.testing.expectEqualSlices(u8, original, normalized); } /// `antisymmetric`, likewise. fn contractionsAntisymmetric(smith: *Smith) anyerror!void { var buf_a: [max_length]u21 = undefined; var buf_b: [max_length]u21 = undefined; const c: collate.Collator = .{ .options = options(smith) }; const a = tableString(smith, &buf_a); const b = tableString(smith, &buf_b); asserted += 1; const ka = try key(c, a); defer backing.free(ka); const kb = try key(c, b); defer backing.free(kb); try std.testing.expectEqual(switch (collate.orderKeys(ka, kb)) { .lt => std.math.Order.gt, .eq => std.math.Order.eq, .gt => std.math.Order.lt, }, collate.orderKeys(kb, ka)); } /// Two non-starters of *different* combining class next to each other are /// canonically equivalent either way round, because NFD sorts them into the /// same order whichever way they were written. So swapping them must not /// change the key by a single byte. /// /// This is the sharpest test of step 2 there is. Swapping a mark is exactly /// what turns a contiguous contraction match into a discontiguous one, so /// the two strings reach the same answer down two different paths through /// S2.1 -- one through the longest-match branch, one through the lookahead /// that skips unblocked non-starters and removes what it consumed. Nothing /// else checks those against each other. /// /// Equal combining classes are excluded deliberately: two marks of the same /// class are *not* canonically equivalent when swapped, and a collation that /// treated them as such would be wrong in the other direction. fn reorderedMarksAgree(smith: *Smith) anyerror!void { const group = splittable(); const pool = intruders(); if (group.len == 0 or pool.len < 2) return; const c = group[smith.index(group.len)]; const first_mark = pool[smith.index(pool.len)]; const second_mark = pool[smith.index(pool.len)]; if (collate.nfd.combiningClass(first_mark) == collate.nfd.combiningClass(second_mark)) return; var forward: [max_length]u21 = undefined; var swapped: [max_length]u21 = undefined; var len: usize = 0; forward[len] = c.first; swapped[len] = c.first; len += 1; forward[len] = first_mark; swapped[len] = second_mark; len += 1; forward[len] = second_mark; swapped[len] = first_mark; len += 1; for (collate.ducet.restOf(c)) |cp| { forward[len] = cp; swapped[len] = cp; len += 1; } asserted += 1; const collator: collate.Collator = .{ .options = options(smith) }; const one = try key(collator, forward[0..len]); defer backing.free(one); const two = try key(collator, swapped[0..len]); defer backing.free(two); try std.testing.expectEqualSlices(u8, one, two); } /// The two entry points decode independently -- `nfd.append` walks code /// points, `nfd.appendUtf8` validates and walks bytes -- so the same text /// through both must give the same key. Nothing else compares them. /// Step 1 agrees with a straight reading of UAX #15 on strings built out of /// the code points that expand. /// /// Uniform random code points reach this badly: a Hangul syllable is one /// range of eleven thousand out of a million, and what is interesting here is /// a *mixture* -- something that decomposes to three code points, next to a /// mark that has to reorder, next to an inert one that takes the fast path. /// So the string is built out of those four kinds deliberately, which is the /// same reason the contraction targets build theirs out of the table's own /// material. /// /// Both entry points are checked, because the byte one has a path of its own /// for runs of ASCII, and both are checked against decomposing every code /// point and then sorting each run of non-starters. /// /// What this target does *not* do is find the bug that prompted it -- step 1 /// appending past a buffer reserved per input code point. That needs the /// capacity to be exactly full when an inert code point arrives, which takes /// a couple of hundred expanding code points in a row, and `max_length` here /// is twelve. A capacity boundary is arithmetic rather than luck, so it is /// covered by a deterministic test in `src/nfd.zig` instead: Hangul followed /// by ASCII at two hundred lengths. Worth writing down, because a fuzz target /// that looks like it covers something it cannot is worse than no target. fn expansionsFit(smith: *Smith) anyerror!void { const len = smith.valueRangeAtMost(u8, 1, max_length); var buf: [max_length]u21 = undefined; var bytes: std.ArrayList(u8) = .empty; defer bytes.deinit(backing); for (buf[0..len]) |*cp| { cp.* = switch (smith.valueRangeAtMost(u8, 0, 3)) { // A Hangul syllable, which decomposes to two jamo or three. 0 => smith.valueRangeAtMost(u21, 0xAC00, 0xD7A3), // A letter with two or three marks under it, from the range // where the deepest decompositions in the data live. 1 => smith.valueRangeAtMost(u21, 0x1E00, 0x1FFF), // A mark of its own, so that runs form and have to reorder. 2 => intruders()[smith.valueRangeAtMost(u8, 0, @intCast(intruders().len - 1))], // And an inert one, which is the code point that used to be // appended past the end. else => smith.valueRangeAtMost(u21, 'a', 'z'), }; var encoded: [4]u8 = undefined; const n = std.unicode.utf8Encode(cp.*, &encoded) catch unreachable; try bytes.appendSlice(backing, encoded[0..n]); } asserted += 1; // The reference: decompose each code point, then order the whole string. var reference: std.ArrayList(u21) = .empty; defer reference.deinit(backing); for (buf[0..len]) |cp| { var one: [collate.nfd.max_expansion]u21 = undefined; try reference.appendSlice(backing, collate.nfd.decompose(cp, &one)); } collate.nfd.canonicalOrder(reference.items); var from_cps: std.ArrayList(u21) = .empty; defer from_cps.deinit(backing); try collate.nfd.append(&from_cps, backing, buf[0..len]); try std.testing.expectEqualSlices(u21, reference.items, from_cps.items); var from_bytes: std.ArrayList(u21) = .empty; defer from_bytes.deinit(backing); try collate.nfd.appendUtf8(&from_bytes, backing, bytes.items); try std.testing.expectEqualSlices(u21, reference.items, from_bytes.items); } /// `Collator.order` gives what comparing two whole sort keys gives. /// /// It does not compare whole keys: it weighs both strings and then compares /// the levels one at a time, stopping at the first that decides, which is /// section 9.7's incremental comparison. Neither conformance suite covers /// that -- both compare keys -- and neither does the ICU oracle, which builds /// keys too. So this target is the only thing standing behind it. /// /// Both shapes of string are generated: one out of the table's own /// contractions, so that the levels are reached with expansions and /// discontiguous matches in them, and one uniform, and the options are /// generated too because every setting that changes a level's layout is a /// branch inside the level. fn orderAgrees(smith: *Smith) anyerror!void { var buf_a: [max_length]u21 = undefined; var buf_b: [max_length]u21 = undefined; const c: collate.Collator = .{ .options = options(smith) }; const a = if (smith.value(bool)) tableString(smith, &buf_a) else string(smith, &buf_a); const b = if (smith.value(bool)) tableString(smith, &buf_b) else string(smith, &buf_b); // `order` takes UTF-8, so a surrogate or an unpaired value has to go. var bytes_a: std.ArrayList(u8) = .empty; defer bytes_a.deinit(backing); var bytes_b: std.ArrayList(u8) = .empty; defer bytes_b.deinit(backing); var cps_a: std.ArrayList(u21) = .empty; defer cps_a.deinit(backing); var cps_b: std.ArrayList(u21) = .empty; defer cps_b.deinit(backing); for ([_][]const u21{ a, b }, [_]*std.ArrayList(u8){ &bytes_a, &bytes_b }, [_]*std.ArrayList(u21){ &cps_a, &cps_b }) |text, bytes, cps| { for (text) |cp| { var encoded: [4]u8 = undefined; const n = std.unicode.utf8Encode(cp, &encoded) catch continue; try bytes.appendSlice(backing, encoded[0..n]); try cps.append(backing, cp); } } asserted += 1; const incremental = try c.order(backing, bytes_a.items, bytes_b.items); const key_a = try key(c, cps_a.items); defer backing.free(key_a); const key_b = try key(c, cps_b.items); defer backing.free(key_b); const from_keys = collate.orderKeys(key_a, key_b); if (incremental != from_keys) { std.debug.print("order says {t}, keys say {t}, for {any} against {any} at {any}\n", .{ incremental, from_keys, cps_a.items, cps_b.items, c.options, }); return error.TestUnexpectedResult; } } fn utf8Agrees(smith: *Smith) anyerror!void { var buf: [max_length]u21 = undefined; const c: collate.Collator = .{ .options = options(smith) }; // Well-formed UTF-8 only, which means no surrogates and nothing above // U+10FFFF. The code point entry point accepts those and the byte one // refuses them, which is the documented difference rather than a // disagreement to fuzz for. const len = smith.valueRangeAtMost(u8, 0, max_length); var cps: usize = 0; var bytes: std.ArrayList(u8) = .empty; defer bytes.deinit(backing); for (0..len) |_| { const cp = smith.valueRangeAtMost(u21, 0, 0x10FFFF); if (cp >= 0xD800 and cp <= 0xDFFF) continue; var encoded: [4]u8 = undefined; const n = std.unicode.utf8Encode(cp, &encoded) catch continue; try bytes.appendSlice(backing, encoded[0..n]); buf[cps] = cp; cps += 1; } asserted += 1; const from_cps = try key(c, buf[0..cps]); defer backing.free(from_cps); const from_bytes = try c.sortKeyAlloc(backing, bytes.items); defer backing.free(from_bytes); try std.testing.expectEqualSlices(u8, from_cps, from_bytes); } /// What search strings are made of: few enough code points that a pattern /// often does occur in a target, and chosen for what makes search hard -- /// case and accents, punctuation that shifted handling makes ignorable, a /// combining mark that is a grapheme extender, the contraction for short i /// and the marks that can sit inside it, a Hangul syllable in jamo, both /// sharp s, and hiragana and katakana ka with the voicing mark. const search_alphabet = [_]u21{ 'a', 'b', 'A', 's', 'S', '-', ' ', 0x0301, 0x0327, 0x0438, 0x0306, 0x0328, 0x1100, 0x1161, 0x11A8, 0x00DF, 0x00E1, 0x0000, 0x1E9E, 0x304B, 0x30AB, 0x3099, }; fn searchString(smith: *Smith, buf: []u21) []const u21 { const len = smith.valueRangeAtMost(u8, 0, @intCast(buf.len)); for (buf[0..len]) |*cp| cp.* = search_alphabet[smith.index(search_alphabet.len)]; return buf[0..len]; } /// Search agrees with a brute-force reading of section 11's definitions. /// /// The reference is every pair of edges `(s, e)` the searcher allows at which /// the range, collated on its own, writes the pattern's sort key: DS2's /// matches. The first minimal match (DS4, DS6) is the one containing no other /// with the least start, and `find` must return it; `startsWith` and /// `endsWith` must say whether a match touches the start or the end; and a /// maximal match must be a match that contains the minimal one and cannot /// grow by an edge at either side. /// /// Both weigh a range in its target's context, as ADR 0002 has it, but the /// reference does it by weighing the whole target and slicing, where the /// searcher keeps its own edges and origins. /// /// An asymmetric match is decided by `asymmetricReference`, which searches /// every way of lining the two up rather than walking greedily as the /// searcher does. `sharp_s_tertiary` is checked at secondary strength and /// below, where it has to be the same as spelling ß and ẞ as `ss` and `SS`. fn searchAgrees(smith: *Smith) anyerror!void { var pattern_buf: [3]u21 = undefined; var target_buf: [max_length]u21 = undefined; const c: collate.Collator = .{ .options = .{ .strength = smith.value(collate.Strength), .alternate = smith.value(collate.Alternate), } }; const search_options: collate.SearchOptions = .{ .span = smith.value(collate.search_types.Span), .boundary = smith.value(collate.search_types.Boundary), // Not `value(bool)`, which the driver's small values answer `true` // about one time in twenty: odd out of sixteen is closer to one in // five. .asymmetric = smith.valueRangeAtMost(u8, 0, 15) % 2 == 1, .sharp_s_tertiary = smith.valueRangeAtMost(u8, 0, 15) % 2 == 1 and c.options.strength.levels() <= 2, }; const pattern = searchString(smith, &pattern_buf); const target = searchString(smith, &target_buf); const asymmetric = search_options.asymmetric and c.options.strength != .identical; var searcher = try collate.Searcher.initCodePoints(backing, c, pattern, search_options); defer searcher.deinit(); const edges = try backing.dupe(u32, try searcher.edgesCodePoints(target)); defer backing.free(edges); var spelled_buf: [2 * pattern_buf.len]u21 = undefined; const spelled = spellSharpS(search_options, pattern, &spelled_buf); const want = try key(c, spelled); defer backing.free(want); // The target weighed once, in place, and cut at the edges -- spelled // first when ß is, with each edge moved past the s it gained. A mark // after shifted punctuation weighs nothing in place and something on // its own, and with no boundaries an edge can fall between the two. var spelled_target_buf: [2 * max_length]u21 = undefined; const spelled_target = spellSharpS(search_options, target, &spelled_target_buf); var spelled_edges_buf: [max_length + 1]u32 = undefined; const spelled_edges = spelled_edges_buf[0..edges.len]; for (edges, spelled_edges) |e, *moved| { moved.* = e; if (!search_options.sharp_s_tertiary) continue; for (target[0..e]) |cp| { if (cp == 0x00DF or cp == 0x1E9E) moved.* += 1; } } var in_place = try InPlace.init(c, spelled_target, spelled_edges); defer in_place.deinit(); const pattern_elements = try weighedElements(c, spelled); defer backing.free(pattern_elements); // DS2's matches, as a table over pairs of edges. const n = edges.len; const matches = try backing.alloc(bool, n * n); defer backing.free(matches); for (0..n) |i| { for (0..n) |j| { matches[i * n + j] = false; if (j < i) continue; if (asymmetric) { const range = try in_place.weighing(i, j); defer backing.free(range); matches[i * n + j] = try asymmetricMatch(c, pattern_elements, range); continue; } const got = try in_place.key(i, j); defer backing.free(got); matches[i * n + j] = std.mem.eql(u8, got, want); } } // The first minimal match: no other match inside it, least start. var minimal: ?[2]usize = null; outer: for (0..n) |i| { for (i..n) |j| { if (!matches[i * n + j]) continue; var inside = false; for (i..j + 1) |ii| { for (ii..j + 1) |jj| { if ((ii != i or jj != j) and matches[ii * n + jj]) inside = true; } } if (inside) continue; minimal = .{ i, j }; break :outer; } } asserted += 1; const found = try searcher.findCodePoints(target, 0); // Everything needed to reproduce a finding, since the input file alone // says nothing a person can read. errdefer std.debug.print( "search-agrees: {t}/{t}/{t}/{t} asymmetric {} sharp s {} pattern {any} target {any} edges {any} minimal {any} found {any}\n", .{ c.options.strength, c.options.alternate, search_options.span, search_options.boundary, search_options.asymmetric, search_options.sharp_s_tertiary, pattern, target, edges, minimal, found }, ); // A pattern that weighs nothing matches as an empty range at the first // edge, whatever the span asked for: what `contains(x, "")` answers. const empty = try key(c, &.{}); defer backing.free(empty); if (std.mem.eql(u8, want, empty)) { const got = found orelse return error.SearchMissedAMatch; try std.testing.expectEqual(@as(usize, edges[0]), got.start); try std.testing.expectEqual(@as(usize, edges[0]), got.end); } else if (minimal == null) { try std.testing.expectEqual(@as(?collate.Match, null), found); } else { const m = minimal.?; const got = found orelse return error.SearchMissedAMatch; switch (search_options.span) { .minimal => { try std.testing.expectEqual(@as(usize, edges[m[0]]), got.start); try std.testing.expectEqual(@as(usize, edges[m[1]]), got.end); }, .maximal => { const i = std.mem.findScalar(u32, edges, @intCast(got.start)) orelse return error.NotAnEdge; const j = std.mem.findScalar(u32, edges, @intCast(got.end)) orelse return error.NotAnEdge; try std.testing.expect(matches[i * n + j]); try std.testing.expect(i <= m[0] and m[1] <= j); if (i > 0) try std.testing.expect(!matches[(i - 1) * n + j]); if (j + 1 < n) try std.testing.expect(!matches[i * n + j + 1]); }, } } var starts = false; var ends = false; for (0..n) |i| { for (i..n) |j| { if (!matches[i * n + j]) continue; if (i == 0) starts = true; if (j == n - 1) ends = true; } } try std.testing.expectEqual(starts, try searcher.startsWithCodePoints(target)); try std.testing.expectEqual(ends, try searcher.endsWithCodePoints(target)); // An exact match has no differences at the levels it compared, so the // ranking counts can only be about the levels it did not. if (found) |m| { if (!asymmetric and !search_options.sharp_s_tertiary) { const levels = c.options.strength.levels(); if (levels >= 2) try std.testing.expectEqual(@as(u32, 0), m.secondary_differences); if (levels >= 3) try std.testing.expectEqual(@as(u32, 0), m.tertiary_differences); } } } /// Match keys agree with the collation and with the searcher. /// /// Under the root table, which cannot split one set of weights between /// elements two ways -- a tailoring can, and DESIGN.md says how -- two /// strings have equal match keys exactly when they have equal sort keys, /// every key is a whole number of records, and a pattern the searcher finds /// in a target -- with no boundaries and none of the searcher's own options, /// which a key cannot express -- has its key in the target's. The converse /// is not a property: a key can be found where a character's own elements /// would have to be split, which no edge allows. fn matchKeysAgree(smith: *Smith) anyerror!void { var a_buf: [3]u21 = undefined; var b_buf: [max_length]u21 = undefined; const c: collate.Collator = .{ .options = .{ .strength = smith.value(collate.Strength), .alternate = smith.value(collate.Alternate), .case_level = smith.valueRangeAtMost(u8, 0, 15) % 2 == 1, .case_first = smith.value(collate.CaseFirst), } }; const a = searchString(smith, &a_buf); // Two strings drawn apart are seldom equal and seldom one inside the // other, so most of the time the second is made from the first: a copy // with some of its characters swapped for others, alone or with text on // either side. Zero is the driver's commonest answer to a small range, // so it is the plain copy, and a character is swapped only on a one. const b = switch (smith.valueRangeAtMost(u8, 0, 15) % 3) { 2 => searchString(smith, b_buf[0..smith.valueRangeAtMost(u8, 0, max_length)]), else => |shape| blk: { var len: usize = 0; const around = shape == 1; if (around) len += searchString(smith, b_buf[0..3]).len; for (a) |cp| { b_buf[len] = if (smith.valueRangeAtMost(u8, 0, 15) % 4 == 1) search_alphabet[smith.index(search_alphabet.len)] else cp; len += 1; } if (around) len += searchString(smith, b_buf[len..][0..3]).len; break :blk b_buf[0..len]; }, }; const a_key = try c.matchKeyAllocCodePoints(backing, a); defer backing.free(a_key); const b_key = try c.matchKeyAllocCodePoints(backing, b); defer backing.free(b_key); const a_sort = try key(c, a); defer backing.free(a_sort); const b_sort = try key(c, b); defer backing.free(b_sort); var searcher = try collate.Searcher.initCodePoints(backing, c, a, .{ .boundary = .none }); defer searcher.deinit(); const found = try searcher.findCodePoints(b, 0); const width = c.matchKeyWidth(); const at = c.findMatchKey(b_key, a_key); asserted += 1; errdefer std.debug.print( "match-keys-agree: {t}/{t} case level {} case first {t} a {any} b {any} keys {x} {x} found {any} at {any}\n", .{ c.options.strength, c.options.alternate, c.options.case_level, c.options.case_first, a, b, a_key, b_key, found, at }, ); try std.testing.expectEqual(@as(usize, 0), a_key.len % width); try std.testing.expectEqual(@as(usize, 0), b_key.len % width); try std.testing.expectEqual(std.mem.eql(u8, a_sort, b_sort), std.mem.eql(u8, a_key, b_key)); if (at) |offset| try std.testing.expectEqual(@as(usize, 0), offset % width); if (found != null) try std.testing.expect(at != null); } /// Fuzzy search agrees with a slow reading of what `max_edits` says. /// /// The reference cuts pattern and target at the edges the searcher allows, /// and finds the fewest edits between the pattern and each range of the /// target with the textbook table: a character left out of either side is /// an edit unless it weighs nothing, a substitution is one, and a run of /// characters on each side costs nothing where the two, collated on their /// own, write the same sort key -- or for asymmetric search, where /// `asymmetricReference` matches them. Then the candidates are every range /// within the limit that begins and ends with a character that weighs /// something, and the match must be among those overlapping the one that /// ends first, with the fewest edits of them. /// /// The reference does not count secondary and tertiary differences, so of /// the candidates with the fewest edits it cannot say which the ranking /// chooses -- those come before position -- only that the match is one of /// them. fn fuzzyAgrees(smith: *Smith) anyerror!void { var pattern_buf: [4]u21 = undefined; // Two either side of a pattern of four that can each become two. var target_buf: [12]u21 = undefined; const c: collate.Collator = .{ .options = .{ .strength = smith.value(collate.Strength), .alternate = smith.value(collate.Alternate), } }; const search_options: collate.SearchOptions = .{ .span = smith.value(collate.search_types.Span), .boundary = smith.value(collate.search_types.Boundary), .asymmetric = smith.valueRangeAtMost(u8, 0, 15) % 2 == 1, .max_edits = 1 + smith.valueRangeAtMost(u8, 0, 15) % 2, }; const asymmetric = search_options.asymmetric and c.options.strength != .identical; const pattern = searchString(smith, &pattern_buf); // Mostly the pattern again with a character or two changed and text // around it, since a target drawn on its own seldom has a candidate. A // change is a swap, a character left out or one put in, and zero, the // driver's commonest answer, keeps the character. const target = switch (smith.valueRangeAtMost(u8, 0, 15) % 3) { 2 => searchString(smith, &target_buf), else => blk: { var len: usize = searchString(smith, target_buf[0..2]).len; for (pattern) |cp| { switch (smith.valueRangeAtMost(u8, 0, 15) % 6) { 1 => target_buf[len] = search_alphabet[smith.index(search_alphabet.len)], 2 => continue, 3 => { target_buf[len] = cp; len += 1; target_buf[len] = search_alphabet[smith.index(search_alphabet.len)]; }, else => target_buf[len] = cp, } len += 1; } len += searchString(smith, target_buf[len..][0..@min(2, target_buf.len - len)]).len; break :blk target_buf[0..len]; }, }; var pattern_searcher = try collate.Searcher.initCodePoints(backing, c, &.{}, search_options); defer pattern_searcher.deinit(); const p_edges = try backing.dupe(u32, try pattern_searcher.edgesCodePoints(pattern)); defer backing.free(p_edges); var searcher = try collate.Searcher.initCodePoints(backing, c, pattern, search_options); defer searcher.deinit(); const t_edges = try backing.dupe(u32, try searcher.edgesCodePoints(target)); defer backing.free(t_edges); // Both strings weighed once, in place: a mark after shifted punctuation // weighs nothing there, where on its own it would weigh something. var pattern_in_place = try InPlace.init(c, pattern, p_edges); defer pattern_in_place.deinit(); var target_in_place = try InPlace.init(c, target, t_edges); defer target_in_place.deinit(); const m = p_edges.len - 1; const n = t_edges.len - 1; var p_weighs: [pattern_buf.len]bool = undefined; var weighing: usize = 0; for (0..m) |i| { p_weighs[i] = try pattern_in_place.weighs(i, i + 1); if (p_weighs[i]) weighing += 1; } var t_weighs: [target_buf.len]bool = undefined; for (0..n) |j| t_weighs[j] = try target_in_place.weighs(j, j + 1); // What the searcher caps the limit at; with no edits left it is an exact // search, which `search-agrees` checks. if (!try pattern_in_place.weighs(0, m)) return; const limit = @min(search_options.max_edits, weighing -| 1); if (limit == 0) return; // Whether pattern characters i..i_end match target characters j..j_end. const Runs = struct { c: collate.Collator, asymmetric: bool, pattern: *InPlace, target: *InPlace, fn match(r: @This(), i: usize, i_end: usize, j: usize, j_end: usize) !bool { if (r.asymmetric) { const p = try r.pattern.weighing(i, i_end); defer backing.free(p); const t = try r.target.weighing(j, j_end); defer backing.free(t); return asymmetricMatch(r.c, p, t); } const a = try r.pattern.key(i, i_end); defer backing.free(a); const b = try r.target.key(j, j_end); defer backing.free(b); return std.mem.eql(u8, a, b); } }; const runs: Runs = .{ .c = c, .asymmetric = asymmetric, .pattern = &pattern_in_place, .target = &target_in_place }; // The fewest edits from the pattern to target characters a..b, for // every a and b, by the table above. const inf = std.math.maxInt(u32); var distance: [target_buf.len + 1][target_buf.len + 1]u32 = undefined; for (0..n + 1) |a| { var table: [pattern_buf.len + 1][target_buf.len + 1]u32 = undefined; for (&table) |*row| @memset(row, inf); table[0][a] = 0; for (a..n + 1) |j| { for (0..m + 1) |i| { const here = table[i][j]; if (here == inf) continue; if (i < m) table[i + 1][j] = @min(table[i + 1][j], here + @intFromBool(p_weighs[i])); if (j < n) table[i][j + 1] = @min(table[i][j + 1], here + @intFromBool(t_weighs[j])); if (i < m and j < n) table[i + 1][j + 1] = @min(table[i + 1][j + 1], here + 1); for (i + 1..m + 1) |i_end| { for (j + 1..n + 1) |j_end| { if (try runs.match(i, i_end, j, j_end)) table[i_end][j_end] = @min(table[i_end][j_end], here); } } } } for (0..n + 1) |b| distance[a][b] = table[m][b]; } const Candidate = struct { start: usize, end: usize, edits: u32 }; var candidates: [target_buf.len * target_buf.len]Candidate = undefined; var count: usize = 0; for (0..n) |a| { if (!t_weighs[a]) continue; for (a + 1..n + 1) |b| { if (!t_weighs[b - 1] or distance[a][b] > limit) continue; candidates[count] = .{ .start = a, .end = b, .edits = distance[a][b] }; count += 1; } } asserted += 1; const found = try searcher.findCodePoints(target, 0); errdefer std.debug.print( "fuzzy-agrees: {t}/{t}/{t}/{t} asymmetric {} max edits {} pattern {any} target {any} pattern edges {any} target edges {any} candidates {any} found {any}\n", .{ c.options.strength, c.options.alternate, search_options.span, search_options.boundary, search_options.asymmetric, search_options.max_edits, pattern, target, p_edges, t_edges, candidates[0..count], found }, ); if (count == 0) return std.testing.expectEqual(@as(?collate.Match, null), found); const got = found orelse return error.SearchMissedAMatch; var ends_first = candidates[0]; for (candidates[1..count]) |x| { if (x.end < ends_first.end or (x.end == ends_first.end and x.start > ends_first.start)) ends_first = x; } var fewest: u32 = inf; for (candidates[0..count]) |x| { if (x.start >= ends_first.end or ends_first.start >= x.end) continue; fewest = @min(fewest, x.edits); } var start = std.mem.findScalar(u32, t_edges, @intCast(got.start)) orelse return error.NotAnEdge; var end = std.mem.findScalar(u32, t_edges, @intCast(got.end)) orelse return error.NotAnEdge; // A maximal match is a candidate with everything that weighs nothing // either side taken in, as far as it goes. if (search_options.span == .maximal) { if (start > 0) try std.testing.expect(t_weighs[start - 1]); if (end < n) try std.testing.expect(t_weighs[end]); while (start < end and !t_weighs[start]) start += 1; while (end > start and !t_weighs[end - 1]) end -= 1; } try std.testing.expect(start < ends_first.end and ends_first.start < end); try std.testing.expectEqual(fewest, got.edits); try std.testing.expectEqual(fewest, distance[start][end]); try std.testing.expect(t_weighs[start] and t_weighs[end - 1]); } /// A string weighed once, whole, and cut at a list of edges: what a piece of /// it weighs where it stands rather than cut out on its own. const InPlace = struct { c: collate.Collator, text: []const u21, edges: []const u32, weighted: []collate.sort_key.Weighted, /// The element boundary at each edge: how many elements the text up to /// the edge has, which at an edge the searcher allows is how many of /// the whole text's come before it. bounds: []usize, fn init(c: collate.Collator, text: []const u21, edges: []const u32) !InPlace { var builder: collate.Builder = .empty; defer builder.deinit(backing); const whole = try builder.sortKeyAllocCodePoints(backing, c, text); backing.free(whole); const weighted = try backing.dupe(collate.sort_key.Weighted, builder.weighted.items); errdefer backing.free(weighted); const bounds = try backing.alloc(usize, edges.len); errdefer backing.free(bounds); for (edges, bounds) |e, *b| { const prefix = try builder.sortKeyAllocCodePoints(backing, c, text[0..e]); backing.free(prefix); b.* = builder.weighted.items.len; } return .{ .c = c, .text = text, .edges = edges, .weighted = weighted, .bounds = bounds }; } fn deinit(x: *InPlace) void { backing.free(x.weighted); backing.free(x.bounds); } /// The sort key of the pieces `a..b` as they are weighed in place. fn key(x: *const InPlace, a: usize, b: usize) ![]u8 { var text: std.ArrayList(u21) = .empty; defer text.deinit(backing); if (x.c.options.strength == .identical) try collate.nfd.append(&text, backing, x.text[x.edges[a]..x.edges[b]]); var out: std.Io.Writer.Allocating = .init(backing); errdefer out.deinit(); try collate.sort_key.write(&out.writer, x.c.options, x.c.table.tailoring, x.weighted[x.bounds[a]..x.bounds[b]], text.items); return out.toOwnedSlice(); } fn weighs(x: *const InPlace, a: usize, b: usize) !bool { const k = try x.key(a, b); defer backing.free(k); const none = try collate.Collator.sortKeyAllocCodePoints(x.c, backing, &.{}); defer backing.free(none); return !std.mem.eql(u8, k, none); } /// The elements of pieces `a..b` that weigh something, in place. fn weighing(x: *const InPlace, a: usize, b: usize) ![]collate.sort_key.Weighted { const none = try collate.Collator.sortKeyAllocCodePoints(x.c, backing, &.{}); defer backing.free(none); var out: std.ArrayList(collate.sort_key.Weighted) = .empty; errdefer out.deinit(backing); for (x.weighted[x.bounds[a]..x.bounds[b]]) |w| { var one: std.Io.Writer.Allocating = .init(backing); defer one.deinit(); try collate.sort_key.write(&one.writer, x.c.options, x.c.table.tailoring, &.{w}, &.{}); if (std.mem.eql(u8, one.written(), none)) continue; try out.append(backing, w); } return out.toOwnedSlice(backing); } }; /// `text` with ß spelled `ss` and ẞ spelled `SS`, when `sharp_s_tertiary` /// is on. fn spellSharpS(search_options: collate.SearchOptions, text: []const u21, buf: []u21) []const u21 { if (!search_options.sharp_s_tertiary) return text; var len: usize = 0; for (text) |cp| { const pair: ?u21 = switch (cp) { 0x00DF => 's', 0x1E9E => 'S', else => null, }; buf[len] = pair orelse cp; len += 1; if (pair) |second| { buf[len] = second; len += 1; } } return buf[0..len]; } /// Section 11.2 read as a search over alignments: `range` matches `pattern` /// when the pattern's elements can be lined up, in order, with the range's, /// each against one it equals or is unmarked for at every level compared, /// with the range's elements that have no primary weight free to be left /// over where the pattern has a primary weight. Elements that weigh nothing /// at the strength are left out of both. fn asymmetricReference(c: collate.Collator, pattern: []const u21, range: []const u21) !bool { const p = try weighedElements(c, pattern); defer backing.free(p); const t = try weighedElements(c, range); defer backing.free(t); return asymmetricMatch(c, p, t); } /// `asymmetricReference` over elements already weighed, and without those /// that weigh nothing. fn asymmetricMatch(c: collate.Collator, p: []const collate.sort_key.Weighted, t: []const collate.sort_key.Weighted) !bool { if (p.len == 0) return t.len == 0; // reach[i * (t.len + 1) + j]: the first i of the pattern line up with // the first j of the range. const width = t.len + 1; const reach = try backing.alloc(bool, (p.len + 1) * width); defer backing.free(reach); @memset(reach, false); reach[0] = true; for (0..p.len + 1) |i| { for (0..t.len + 1) |j| { if (!reach[i * width + j]) continue; // A target accent can be left over only where the pattern // element it is set against -- the next, or the last once the // pattern is used up -- has a primary weight. const against = if (i < p.len) p[i] else p[p.len - 1]; if (j < t.len and t[j].element.primary == 0 and against.element.primary != 0) reach[i * width + j + 1] = true; if (i < p.len and j < t.len and unmarkedMatch(c.options, p[i], t[j])) reach[(i + 1) * width + j + 1] = true; } } return reach[p.len * width + t.len]; } /// A string's weighed elements, without those that weigh nothing at the /// collator's strength. fn weighedElements(c: collate.Collator, text: []const u21) ![]collate.sort_key.Weighted { var builder: collate.Builder = .empty; defer builder.deinit(backing); const k = try builder.sortKeyAllocCodePoints(backing, c, text); backing.free(k); const empty = try key(c, &.{}); defer backing.free(empty); var out: std.ArrayList(collate.sort_key.Weighted) = .empty; errdefer out.deinit(backing); for (builder.weighted.items) |w| { var one: std.Io.Writer.Allocating = .init(backing); defer one.deinit(); try collate.sort_key.write(&one.writer, c.options, c.table.tailoring, &.{w}, &.{}); if (std.mem.eql(u8, one.written(), empty)) continue; try out.append(backing, w); } return out.toOwnedSlice(backing); } /// Section 11.2's comparison of one pattern element with one target element, /// written from the section rather than from the searcher: the lowest weight /// at a level -- COMMON, a lowercase tertiary, a kana's normal form within /// its own syllabary -- matches anything there. fn unmarkedMatch(o: collate.Options, p: collate.sort_key.Weighted, t: collate.sort_key.Weighted) bool { const levels = o.strength.levels(); const a = p.element; const b = t.element; if (a.primary != b.primary or a.primary_sub != b.primary_sub) return false; if (levels >= 2 and a.secondary != b.secondary and a.secondary != 0x20) return false; if (levels >= 3 and a.tertiary != b.tertiary and !(a.secondary != b.secondary and caseOf(a) == caseOf(b))) { const unmarked = switch (a.tertiary) { 0x02 => true, 0x0E => b.tertiary == 0x0D, 0x11 => b.tertiary >= 0x0F and b.tertiary <= 0x13, else => false, }; if (!unmarked) return false; } if (levels >= 4 and (p.quaternary != t.quaternary or p.quaternary_sub != t.quaternary_sub)) return false; return true; } /// Section 5.1's case: a tertiary element counts as uppercase. fn caseOf(e: collate.data.Element) collate.data.Case { if (e.primary == 0 and e.secondary == 0) return .upper; return e.case; } test "every target runs on a handful of inputs" { // Enough to catch a target that does not compile or panics on the // trivial cases. `tools/fuzz.zig` is what actually searches. const seeds = [_][]const u8{ &.{}, &@as([64]u8, @splat(0)), &@as([64]u8, @splat(0xFF)), &@as([64]u8, @bitCast(@as([8][8]u8, @splat(.{ 1, 0, 0, 0, 0, 0, 0, 0 })))), }; for (targets) |target| { for (seeds) |seed| { var smith: Smith = .{ .in = seed }; target.run(&smith) catch |err| { std.debug.print("target {s} failed on a seed: {t}\n", .{ target.name, err }); return err; }; } } }