// 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 }, }; /// 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); } 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{ &.{}, &(.{0} ** 64), &(.{0xFF} ** 64), &(.{ 1, 0, 0, 0, 0, 0, 0, 0 } ** 8), }; 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; }; } } }