Something went wrong. Try again.
A small configuration language for Zig: ZON with let, if and templates over a context, evaluated to a struct, always finishing.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! What the parser and the evaluator must do with a program nobody sensible//! wrote.//!//! A program is input -- a configuration file, edited by hand -- and the//! properties are the same for any of it. Parsing either succeeds or fails//! with a position inside the source; never a panic, a leak or a hang.//! Evaluating either succeeds within its limits or fails with one of its own//! errors and a message; and a string it produces is never longer than it was//! allowed to be. Formatting never changes what a program evaluates to,//! and formatting twice changes nothing.//!//! Each target is an ordinary test as well as a fuzz target: without `--fuzz`//! it runs the seeds beside it, so `zig build test` exercises the same//! properties on inputs that have already been interesting once.
const builtin = @import("builtin");const std = @import("std");const Allocator = std.mem.Allocator;const testing = std.testing;const Smith = std.testing.Smith;
const struthio = @import("struthio");
/// The allocator the targets run against.////// Under `zig build test` that is the testing allocator, which reports a leak/// as a failure. `tools/fuzz.zig` cannot name it -- it is not a test build --/// so it sets this to a checked allocator of its own instead.pub var backing: Allocator = if (builtin.is_test) testing.allocator else undefined;
const content_max = 4096;
const limits: struthio.Limits = .{ .max_depth = 32, .max_string = 4096, .max_list = 256, .max_steps = 100_000 };
/// Parse, and check that a failure says where, somewhere inside the source.fn fuzzParse(_: void, smith: *Smith) anyerror!void { var buf: [content_max]u8 = undefined; const src = buf[0..smith.slice(&buf)]; var d: struthio.Diagnostic = .{}; var program = struthio.Program.parse(backing, src, .{ .limits = limits }, &d) catch |err| switch (err) { error.OutOfMemory => return err, error.Syntax => return checkDiagnostic(src, &d), // Nothing here gives the parser a way to read a file, so no // `@include` can get as far as trying, and no filename to be wrong. error.Include => return error.IncludedWithoutAReader, error.InvalidFilename => return error.InvalidFilenameWithoutOne, }; program.deinit();}
const Context = struct { n: i32 = 7, f: f64 = 2.5, s: []const u8 = "a \"quoted\" ${string}", b: bool = true, none: ?u8 = null, some: ?[]const u8 = "x", xs: []const i64 = &.{ 3, 1, 2 }, names: []const []const u8 = &.{ "a", "b" }, level: enum { low, high } = .high, u: union(enum) { empty, full: struct { v: u8 = 1 } } = .{ .full = .{} }, m: struct { a: u8 = 1, b: struct { c: []const u8 = "deep" } = .{} } = .{}, big: u64 = std.math.maxInt(u64), alloc: Allocator = std.heap.page_allocator,};
/// What a fuzzed program is decoded into, besides `Value`: enough shapes/// that decoding gets exercised, with defaults for everything so that a/// program does not have to be a perfect match to get far.const Typed = struct { a: i32 = 0, b: ?[]const u8 = null, c: []const u16 = &.{}, d: enum { x, y } = .x, e: union(enum) { none, some: u8 } = .none, f: [2]bool = .{ false, false }, g: struct { h: f32 = 0 } = .{},};
/// Parse and evaluate against a fixed context, under small limits.fn fuzzEval(_: void, smith: *Smith) anyerror!void { var buf: [content_max]u8 = undefined; const src = buf[0..smith.slice(&buf)]; const typed = smith.value(bool);
var d: struthio.Diagnostic = .{}; var program = struthio.Program.parse(backing, src, .{ .limits = limits }, &d) catch |err| switch (err) { error.OutOfMemory => return err, error.Syntax => return, error.Include => return error.IncludedWithoutAReader, error.InvalidFilename => return error.InvalidFilenameWithoutOne, }; defer program.deinit();
const ctx: Context = .{}; if (typed) { const r = program.eval(Typed, backing, &ctx, &d) catch |err| return evalFailed(src, &d, err); r.deinit(); } else { const r = program.eval(struthio.Value, backing, &ctx, &d) catch |err| return evalFailed(src, &d, err); defer r.deinit(); if (r.value == .string and r.value.string.len > limits.max_string) return error.StringPastTheLimit; }}
/// Format, and check that formatting changed nothing that matters: a program/// that parses still parses, evaluates to the same thing or fails the same/// way, and formatting it again changes nothing at all. The outline, which/// parses the same way, is checked too: it accepts what formatting accepts,/// and every span lies within the source and within its parent, and every/// name within its span.fn fuzzFormat(_: void, smith: *Smith) anyerror!void { var buf: [content_max]u8 = undefined; const src = buf[0..smith.slice(&buf)];
var d: struthio.Diagnostic = .{}; const out = struthio.format(backing, src, .{}, &d) catch |err| switch (err) { error.OutOfMemory => return err, error.Syntax => { try checkDiagnostic(src, &d); // The formatter accepts more than the parser -- it checks no // names -- but nothing the parser accepts may be refused. var program = struthio.Program.parse(backing, src, .{}, &d) catch return; program.deinit(); return error.FormatterRefusedAProgram; }, }; defer backing.free(out);
const spans = try struthio.outline(backing, src, .{}, &d); defer backing.free(spans); for (spans, 0..) |span, i| { if (span.start > span.end or span.end > src.len) return error.SpanOutOfBounds; if (span.name) |n| if (n.start >= n.end or n.start < span.start or n.end > span.end) return error.NameOutsideItsSpan; const parent = span.parent orelse { if (i != 0) return error.SpanWithoutParent; continue; }; if (parent >= i) return error.SpanBeforeItsParent; const outer = spans[parent]; if (span.start < outer.start or span.end > outer.end) return error.SpanOutsideItsParent; }
const again = try struthio.format(backing, out, .{}, &d); defer backing.free(again); if (!std.mem.eql(u8, out, again)) return error.FormattingTwiceChangedIt;
const before = try outcome(src); defer backing.free(before); const after = try outcome(out); defer backing.free(after); if (!std.mem.eql(u8, before, after)) { std.debug.print("{s}\n=> {s}\nformatted:\n{s}\n=> {s}\n", .{ src, before, out, after }); return error.FormattingChangedTheResult; }}
/// What `src` comes to, as text: the value it evaluates to, written as ZON,/// or the name of the error it fails with and the message, without the/// position, which formatting may move. Text rather than `Value.eql` so that/// a NaN is the same as itself.fn outcome(src: []const u8) anyerror![]u8 { var d: struthio.Diagnostic = .{}; var program = struthio.Program.parse(backing, src, .{ .limits = limits }, &d) catch |err| switch (err) { error.OutOfMemory => return err, else => return std.fmt.allocPrint(backing, "{t}", .{err}), }; defer program.deinit(); const ctx: Context = .{}; const r = program.eval(struthio.Value, backing, &ctx, &d) catch |err| switch (err) { error.OutOfMemory => return err, else => return std.fmt.allocPrint(backing, "{t}: {s}", .{ err, d.message() }), }; defer r.deinit(); return std.fmt.allocPrint(backing, "{f}", .{r.value});}
fn evalFailed(src: []const u8, d: *const struthio.Diagnostic, err: struthio.EvalError) anyerror!void { switch (err) { error.OutOfMemory => return err, error.Eval, error.LimitExceeded => return checkDiagnostic(src, d), }}
fn checkDiagnostic(src: []const u8, d: *const struthio.Diagnostic) anyerror!void { const end = struthio.Diagnostic.Pos.of(src, src.len); if (d.pos.line < 1 or d.pos.line > end.line or d.pos.column < 1) return error.PositionOutsideSource; if (d.message().len == 0) return error.EmptyDiagnostic;}
const parse_seeds = [_][]const u8{ "", "1", ".{ .a = 1, .b = \"two\", .c = .three, .d = .{ 4, 5 }, .e = null, .f = 'x' }", "let a = 1; let b = a + 1; .{ .x = b }", "if (ctx.b) |x| x else if (false) 2 else 3", "\"a${ctx.s}b${\"c${1}\"}d\\${e}\"", "\\\\one ${ctx.n}\n\\\\two\n", "@join(@split(\"a,b\", \",\"), \"-\") ++ @lower(\"X\")", "-9223372036854775808 + 0x7fff_ffff * 1.5e3 / 2 % 3", "ctx.m.b.c[0] == 100 and !(ctx.n < 2) or ctx.none orelse 1 != 2", ".{ 1, if (true) 2, if (false) 3 else if (true) 4 }", ".{ .@\"if\" = inf, .b = -nan }", "switch (ctx.n) { 1...5, 9 => |v| v, -3 => 0, else => 1 }", ".{ .a = switch (ctx.level) { .low => 1 }, .b = switch (\"x\") { \"x\" => switch (2) { 2 => 3 } } }",};
const eval_seeds = [_][]const u8{ ".{ .a = ctx.n, .b = ctx.some, .c = ctx.xs, .d = .y, .e = .{ .some = 3 }, .f = .{ true, false }, .g = .{ .h = ctx.f } }", "\"${ctx.s}${ctx.n}${ctx.f}${ctx.level}\"", "ctx.u.full.v + ctx.xs[2] + @len(ctx.names) + @max(ctx.xs)", "ctx.u.empty", "ctx.big", "ctx.alloc.vtable", "ctx.m ++ .{ .z = 1 } ++ ctx.u", "let a = \"xxxxxxxx\"; let b = a ++ a; let c = b ++ b; let d = c ++ c; let e = d ++ d; let f = e ++ e; f ++ f", "let a = .{ 1, 1 }; let b = .{ a, a }; let c = .{ b, b }; let d = .{ c, c }; let e = .{ d, d }; let f = .{ e, e }; f == f", "@replace(ctx.s, \" \", \"________\")", "@int(\"12\") + @int(1e300)", "ctx.none.?", "if (ctx.some) |s| s ++ \"!\" else \"\"", "@contains(ctx.names, \"b\") and @startsWith(ctx.s, \"a\")", "switch (ctx.u) { .empty => 0, .full => |p| p.v }", "1 + if (ctx.b) switch (ctx.f) { 0...2 => 1 } else 2", "switch (ctx.some) { null => \"\", \"a\"...\"z\" => |s| s, else => ctx.none.? }",};
pub const Target = struct { name: []const u8, run: *const fn (input: []const u8) anyerror!void, corpus: []const []const u8, content_max: usize, slices: usize = 1,};
fn Driven(comptime one: fn (void, *Smith) anyerror!void) type { return struct { fn run(input: []const u8) anyerror!void { var smith: Smith = .{ .in = input }; return one({}, &smith); } };}
const format_seeds = [_][]const u8{ "// a comment\nlet a = 1; // one\n\n\nlet b = a +\n 2;\n.{ .x = b, .y = .{ 1, 2, }, // two\n}", ".{ .a = \\\\one ${ctx.n}\n\\\\two\n, .b = switch (ctx.n) { 1, 2, => 3, else => 4, } }", "0x1 .a",};
pub const all = [_]Target{ .{ .name = "parse", .run = Driven(fuzzParse).run, .corpus = &parse_seeds, .content_max = content_max }, .{ .name = "eval", .run = Driven(fuzzEval).run, .corpus = &(parse_seeds ++ eval_seeds), .content_max = content_max }, .{ .name = "format", .run = Driven(fuzzFormat).run, .corpus = &(parse_seeds ++ eval_seeds ++ format_seeds), .content_max = content_max },};
/// The seeds as `Smith` reads them: a four-byte length, the bytes, and then/// small numbers for whatever the target asks after.fn seedInput(gpa: Allocator, seed: []const u8, flag: u64) ![]u8 { var out: std.ArrayList(u8) = .empty; var len: [4]u8 = undefined; std.mem.writeInt(u32, &len, @intCast(seed.len), .little); try out.appendSlice(gpa, &len); try out.appendSlice(gpa, seed); var word: [8]u8 = undefined; std.mem.writeInt(u64, &word, flag, .little); try out.appendSlice(gpa, &word); return out.toOwnedSlice(gpa);}
test "every target survives every seed" { for (all) |target| { for (target.corpus) |seed| { for ([_]u64{ 0, 1 }) |flag| { const input = try seedInput(testing.allocator, seed, flag); defer testing.allocator.free(input); target.run(input) catch |err| { std.debug.print("{s} failed on {s}: {t}\n", .{ target.name, seed, err }); return err; }; } } }}
test "fuzz parse" { try testing.fuzz({}, fuzzParse, .{});}
test "fuzz eval" { try testing.fuzz({}, fuzzEval, .{});}
test "fuzz format" { try testing.fuzz({}, fuzzFormat, .{});}