// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie
// SPDX-License-Identifier: MIT
//! What the tree builder and the serializer must do with input nobody wrote.
//!
//! The weak property is the usual one -- **return, do not crash**. An error is
//! a fine answer and so is a tree; a panic, an out-of-bounds index, a leak or
//! a stack overflow is a failure in whatever embedded this library rather than
//! in the document that caused it.
//!
//! The strong one is the interesting one: **whatever parsed must serialize to
//! something that parses again**. A tree is not much use if writing it out
//! produces a document nobody can read, and the two halves are easy to drift
//! apart because nothing else compares them. That property is what found the
//! bug behind zxml's name validation -- `<:/>` parsed as an element whose name
//! was a single colon, and serialized to `<>`.
//!
//! `backing` is how a target gets an allocator in both worlds:
//! `std.testing.allocator` does not exist outside a test build, so the
//! standalone driver in `tools/fuzz.zig` points this at a `DebugAllocator` it
//! checks for leaks after every input.
const std = @import("std");
const builtin = @import("builtin");
const Allocator = std.mem.Allocator;
const ztree = @import("ztree");
/// The allocator every target uses. A test build gets the testing allocator,
/// which fails the test on a leak; the standalone driver sets this to one it
/// owns.
pub var backing: Allocator = if (builtin.is_test) std.testing.allocator else undefined;
pub const Target = struct {
name: []const u8,
run: *const fn (input: []const u8) anyerror!void,
/// Inputs that have broken something, or that reach a part of the target
/// random bytes never would.
seeds: []const []const u8,
};
pub const targets = [_]Target{
.{ .name = "document", .run = fuzzDocument, .seeds = &document_seeds },
.{ .name = "indent", .run = fuzzIndent, .seeds = &document_seeds },
.{ .name = "html", .run = fuzzHtml, .seeds = &html_seeds },
.{ .name = "strip", .run = fuzzStrip, .seeds = &document_seeds },
.{ .name = "validate", .run = fuzzValidate, .seeds = &dtd_seeds },
};
/// Parse, serialize, and parse what came out.
fn fuzzDocument(input: []const u8) anyerror!void {
return roundTrip(input, .{}, .{});
}
/// The same, indented. Indenting inserts text into the document, so it is the
/// one output setting that can change what a reparse sees.
fn fuzzIndent(input: []const u8) anyerror!void {
return roundTrip(input, .{}, .{ .indent = true });
}
/// Whitespace stripping on the way in, which removes nodes from a tree that
/// has already been built.
fn fuzzStrip(input: []const u8) anyerror!void {
return roundTrip(input, .{ .whitespace = .strip }, .{});
}
/// The HTML output method, which is not XML and so is checked only for not
/// crashing: `
` is deliberately not well-formed XML.
fn fuzzHtml(input: []const u8) anyerror!void {
const doc = ztree.parse(backing, input, .{}) catch return;
defer doc.destroy();
const out = try ztree.serialize.toOwnedSlice(backing, doc, .{ .method = .html });
defer backing.free(out);
}
/// Read the document type, throw the source away, then reach a verdict.
///
/// Freeing the source before validating is the property worth having here.
/// The declarations are copied into the document's arena precisely so that a
/// tree outlives the text it came from, and a validator that reached back into
/// that text would read freed memory -- which is the kind of bug that surfaces
/// in six months rather than in the test that introduced it.
fn fuzzValidate(input: []const u8) anyerror!void {
const source = try backing.dupe(u8, input);
const doc = ztree.parse(backing, source, .{ .dtd = true }) catch {
backing.free(source);
return;
};
defer doc.destroy();
backing.free(source);
const report = ztree.validate.run(backing, doc) catch return;
defer report.deinit(backing);
for (report.problems) |problem| {
// A problem nobody can act on is not a problem that was found.
if (problem.detail.len == 0) return error.EmptyDetail;
if (problem.node >= doc.nodes.items.len) return error.ProblemOutOfRange;
}
}
fn roundTrip(
input: []const u8,
parse_options: ztree.ParseOptions,
output: ztree.serialize.Output,
) anyerror!void {
const doc = ztree.parse(backing, input, parse_options) catch return;
defer doc.destroy();
const out = try ztree.serialize.toOwnedSlice(backing, doc, output);
defer backing.free(out);
const again = ztree.parse(backing, out, parse_options) catch |err| {
std.debug.print("serialized output did not parse again: {t}\n{s}\n", .{ err, out });
return error.RoundTripFailed;
};
defer again.destroy();
}
const document_seeds = [_][]const u8{
"",
"",
"text",
"",
"",
"",
"",
"&<>"'",
"AA",
"]]>",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"]]>",
"\r\n",
" ",
"&undefined;",
// Names a namespace cannot read. zxml rejects these now; the seeds stay
// because they are what the round-trip property was added to catch.
"<:/>",
"",
"<:/>",
// Mixed content, which indenting must not reflow.
"onetwothree",
"",
"not xml at all",
};
/// Documents with a document type, since random bytes never form one and the
/// declarations are otherwise never reached.
const dtd_seeds = [_][]const u8{
"]>",
"]>",
"]>xy",
"]>",
"]>",
"]>",
"]>",
"]>&e;",
"]>",
"\">%p;]>",
// An external subset, which is named and never read, so no verdict is
// reached at all.
"",
// Every kind of invalid: wrong root, undeclared element, unsatisfied
// model, duplicate ID, dangling reference.
"]>",
"]>",
"]>",
"]>",
// Declarations that do not parse, and a document type with nothing in it.
"",
"",
"",
"",
"",
};
const html_seeds = [_][]const u8{
"hi
",
"T
",
"",
"",
"",
"
",
"",
"