// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! What the compiler and the evaluator must do with input nobody wrote. //! //! An expression is the part of a stylesheet, a query or a config file that //! most often comes from somewhere else, so the property is the usual weak //! one: **return, do not crash**. An error is a fine answer and so is a value; //! a panic, a leak or a stack overflow is a failure in whatever embedded this //! rather than in the expression that caused it. //! //! Compiling and evaluating are separate targets because they fail in separate //! ways. A compiler is a parser and breaks on shapes; an evaluator breaks on //! what the shapes mean once there is a document under them. const std = @import("std"); const builtin = @import("builtin"); const Allocator = std.mem.Allocator; const zxpath = @import("zxpath"); const ztree = @import("ztree"); 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, seeds: []const []const u8, }; pub const targets = [_]Target{ .{ .name = "compile", .run = fuzzCompile, .seeds = &expression_seeds }, .{ .name = "evaluate", .run = fuzzEvaluate, .seeds = &expression_seeds }, }; fn fuzzCompile(input: []const u8) anyerror!void { var compiled = zxpath.Compiled.init(backing, input, .none) catch return; defer compiled.deinit(); } /// Compiles and then runs the expression against a small document, which is /// the only way to reach the axes, the predicates and the core library at all. fn fuzzEvaluate(input: []const u8) anyerror!void { var compiled = zxpath.Compiled.init(backing, input, .none) catch return; defer compiled.deinit(); const doc = try ztree.parse(backing, sample, .{}); defer doc.destroy(); var ev: zxpath.Evaluator(error{}) = .init(backing); const v = ev.eval(compiled.expr, .{ .node = doc.ref(doc.root) }) catch return; defer v.deinit(backing); // Every value must convert to every other type without complaint: that is // what XPath promises, and a conversion is where an evaluator that built // something malformed finally trips. const s = try v.toString(backing); defer backing.free(s); _ = try v.toNumber(backing); _ = v.toBoolean(); } const sample = \\ \\ Alpha10 \\ Beta25 \\ \\ ; const expression_seeds = [_][]const u8{ "", ".", "/", "//", "*", "@*", "@id", "node()", "text()", "comment()", "processing-instruction()", "processing-instruction('pi')", "//book", "//book[1]", "//book[@lang='en']", "//book[price>20]", "//book[last()]", "//book/../book", "//title|//price", "(//title)[1]", "count(//book)", "sum(//price)", "string(//title)", "concat('a','b','c')", "substring('12345',2,3)", "substring('12345',1.5,2.6)", "normalize-space(' a b ')", "translate('abc','ab','AB')", "starts-with('abc','a')", "contains('abc','b')", "substring-before('a/b','/')", "substring-after('a/b','/')", "string-length('héllo')", "boolean(//book)", "not(//none)", "true()", "false()", "lang('en')", "number('42')", "floor(-2.5)", "ceiling(-2.5)", "round(-1.5)", "1 div 0", "0 div 0", "1 + 2 * 3 - 4 div 5 mod 6", "- - -1", "//price = 10", "//price != 10", "//price < 20", "a and b or c", "$undefined", "unknown-function()", "ancestor::node()", "descendant::*", "following::*", "preceding::*", "following-sibling::*", "preceding-sibling::*", "namespace::*", "self::node()", "parent::node()", "ancestor-or-self::*", "descendant-or-self::*", "div div div", "mod mod mod", "a[a[a[a]]]", "((((1))))", "'unterminated", "concat(", "bogus-axis::a", ":", "::", "id('b1')", "local-name()", "namespace-uri()", "name(//*[1])", // A filter over something that is not a node-set. These are a type error, // and the point is that raising it frees the operand exactly once: an // `errdefer` beside the explicit free made `'x'[1]` a double free. "'x'[1]", "1[1]", "true()[1]", "concat('a','b')[1]", "(1)[1]", "'x'[1][2]", // A string literal that is not valid UTF-8. Nothing forbids one, and the // character-counting functions used to step past the end of it. "substring('abcd\xf0', 1, 9)", "string-length('abcd\xf0')", "translate('abcd\xf0', '\xf0', 'x')", }; const testing = std.testing; // Replays every seed of every target, which is what makes the corpus a // regression suite rather than a pile of inputs only the fuzzer ever reads. test "the seed corpus still passes every target" { for (targets) |target| { for (target.seeds) |seed| { target.run(seed) catch |err| { std.debug.print("target {s} failed on seed: {s}\n", .{ target.name, seed }); return err; }; } } } /// `Smith` reads a four-byte little-endian length before the bytes, so a /// corpus entry has to carry one. Without it every seed decodes to the empty /// string and the run tests nothing at all. fn fuzzOne(comptime index: usize) fn (void, *std.testing.Smith) anyerror!void { return struct { fn run(_: void, smith: *std.testing.Smith) anyerror!void { var buf: [16 * 1024]u8 = undefined; const len = smith.slice(&buf); return targets[index].run(buf[0..len]); } }.run; } inline fn smithCorpus(comptime seeds: []const []const u8) []const []const u8 { comptime { var out: [seeds.len][]const u8 = undefined; for (seeds, &out) |seed, *slot| { var length: [4]u8 = undefined; std.mem.writeInt(u32, &length, @intCast(seed.len), .little); slot.* = length ++ seed; } const frozen = out; return &frozen; } } test "fuzz compile" { try std.testing.fuzz({}, fuzzOne(0), .{ .corpus = comptime smithCorpus(&expression_seeds) }); } test "fuzz evaluate" { try std.testing.fuzz({}, fuzzOne(1), .{ .corpus = comptime smithCorpus(&expression_seeds) }); }