feat: complete M0 foundations (job ids, atomic fs helpers, Jackson-style JSON writer, TOML subset parser)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8cf40344a4
commit
d05dc22cee
6 files changed
+714
No files matched your search
@@ -24,3 +24,7 @@ Guidance for AI coding agents working in `zag`, the Zig port of the
|
||||
| `src/duration.zig` | `\d+[mhdwMHDW]` duration parser |
|
||||
| `src/timestamp.zig` | ISO-8601 instant formatting/parsing (barn-compatible) |
|
||||
| `src/state.zig` | Job states and the transition state machine |
|
||||
| `src/jobid.zig` | `job-` + 8 hex job ids |
|
||||
| `src/fsutil.zig` | Atomic writes, trimmed reads, advisory `FileLock` |
|
||||
| `src/jsonpretty.zig` | Streaming JSON writer matching Jackson `INDENT_OUTPUT` layout |
|
||||
| `src/toml.zig` | Parser for barn's TOML subset (`[section]`, `key = value`, arrays) |
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
//! File helpers: atomic writes, trimmed reads and an advisory lock.
|
||||
//! Job state is stored one-value-per-file, always replaced atomically (temp file + rename).
|
||||
const std = @import("std");
|
||||
const Io = std.Io;
|
||||
const Dir = Io.Dir;
|
||||
const File = Io.File;
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
pub const WriteError = Dir.CreateFileAtomicError || File.Writer.Error || File.Atomic.ReplaceError;
|
||||
|
||||
/// Atomically replaces `sub_path` (relative to `dir`) with `data`.
|
||||
/// Readers see either the old or the new content, never a partial write.
|
||||
pub fn writeAtomic(io: Io, dir: Dir, sub_path: []const u8, data: []const u8) WriteError!void {
|
||||
var atomic = try dir.createFileAtomic(io, sub_path, .{ .replace = true });
|
||||
defer atomic.deinit(io);
|
||||
try atomic.file.writeStreamingAll(io, data);
|
||||
try atomic.replace(io);
|
||||
}
|
||||
|
||||
/// Reads a whole file with surrounding whitespace trimmed. Returns null if the file does not exist.
|
||||
/// Caller owns the returned slice.
|
||||
pub fn readTrimmed(io: Io, gpa: Allocator, dir: Dir, sub_path: []const u8) !?[]u8 {
|
||||
const raw = dir.readFileAlloc(io, sub_path, gpa, .limited(1 << 20)) catch |err| switch (err) {
|
||||
error.FileNotFound => return null,
|
||||
else => |e| return e,
|
||||
};
|
||||
defer gpa.free(raw);
|
||||
return try gpa.dupe(u8, std.mem.trim(u8, raw, &std.ascii.whitespace));
|
||||
}
|
||||
|
||||
/// Deletes `sub_path`; a file that is already gone is not an error.
|
||||
pub fn deleteIfExists(io: Io, dir: Dir, sub_path: []const u8) !void {
|
||||
dir.deleteFile(io, sub_path) catch |err| switch (err) {
|
||||
error.FileNotFound => {},
|
||||
else => |e| return e,
|
||||
};
|
||||
}
|
||||
|
||||
/// Exclusive advisory lock on a file, released by `release` or when the process exits.
|
||||
/// The lock file is never unlinked while held (unlinking races with other lockers).
|
||||
pub const FileLock = struct {
|
||||
file: File,
|
||||
|
||||
pub const AcquireError = File.OpenError || File.LockError;
|
||||
|
||||
/// Returns null if another holder has the lock.
|
||||
pub fn tryAcquire(io: Io, dir: Dir, sub_path: []const u8) AcquireError!?FileLock {
|
||||
var file = try dir.createFile(io, sub_path, .{ .read = true, .truncate = false });
|
||||
errdefer file.close(io);
|
||||
if (!try file.tryLock(io, .exclusive)) {
|
||||
file.close(io);
|
||||
return null;
|
||||
}
|
||||
return .{ .file = file };
|
||||
}
|
||||
|
||||
pub fn release(self: *FileLock, io: Io) void {
|
||||
self.file.unlock(io);
|
||||
self.file.close(io);
|
||||
self.* = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
test "writeAtomic creates and replaces" {
|
||||
const io = std.testing.io;
|
||||
var tmp = std.testing.tmpDir(.{});
|
||||
defer tmp.cleanup();
|
||||
|
||||
try writeAtomic(io, tmp.dir, "state", "queued");
|
||||
const first = (try readTrimmed(io, std.testing.allocator, tmp.dir, "state")).?;
|
||||
defer std.testing.allocator.free(first);
|
||||
try std.testing.expectEqualStrings("queued", first);
|
||||
|
||||
try writeAtomic(io, tmp.dir, "state", "running\n");
|
||||
const second = (try readTrimmed(io, std.testing.allocator, tmp.dir, "state")).?;
|
||||
defer std.testing.allocator.free(second);
|
||||
try std.testing.expectEqualStrings("running", second);
|
||||
}
|
||||
|
||||
test "writeAtomic leaves no temp files behind" {
|
||||
const io = std.testing.io;
|
||||
var tmp = std.testing.tmpDir(.{ .iterate = true });
|
||||
defer tmp.cleanup();
|
||||
|
||||
try writeAtomic(io, tmp.dir, "pid", "123");
|
||||
var it = tmp.dir.iterate();
|
||||
var count: usize = 0;
|
||||
while (try it.next(io)) |entry| {
|
||||
try std.testing.expectEqualStrings("pid", entry.name);
|
||||
count += 1;
|
||||
}
|
||||
try std.testing.expectEqual(@as(usize, 1), count);
|
||||
}
|
||||
|
||||
test "readTrimmed returns null for a missing file" {
|
||||
const io = std.testing.io;
|
||||
var tmp = std.testing.tmpDir(.{});
|
||||
defer tmp.cleanup();
|
||||
try std.testing.expect((try readTrimmed(io, std.testing.allocator, tmp.dir, "nope")) == null);
|
||||
}
|
||||
|
||||
test "deleteIfExists tolerates missing files" {
|
||||
const io = std.testing.io;
|
||||
var tmp = std.testing.tmpDir(.{});
|
||||
defer tmp.cleanup();
|
||||
try deleteIfExists(io, tmp.dir, "nope");
|
||||
try writeAtomic(io, tmp.dir, "x", "1");
|
||||
try deleteIfExists(io, tmp.dir, "x");
|
||||
try std.testing.expect((try readTrimmed(io, std.testing.allocator, tmp.dir, "x")) == null);
|
||||
}
|
||||
|
||||
test "FileLock excludes a second holder until released" {
|
||||
const io = std.testing.io;
|
||||
var tmp = std.testing.tmpDir(.{});
|
||||
defer tmp.cleanup();
|
||||
|
||||
var first = (try FileLock.tryAcquire(io, tmp.dir, "scheduler.lock")).?;
|
||||
// flock locks belong to the open file description, so a second open conflicts even in-process.
|
||||
try std.testing.expect((try FileLock.tryAcquire(io, tmp.dir, "scheduler.lock")) == null);
|
||||
first.release(io);
|
||||
var again = (try FileLock.tryAcquire(io, tmp.dir, "scheduler.lock")).?;
|
||||
again.release(io);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
//! Job ids: `job-` followed by 8 lowercase hex characters (e.g. `job-6d368040`).
|
||||
const std = @import("std");
|
||||
const Io = std.Io;
|
||||
|
||||
pub const len = 12;
|
||||
|
||||
pub fn generate(io: Io) [len]u8 {
|
||||
var raw: [4]u8 = undefined;
|
||||
io.random(&raw);
|
||||
return format(raw);
|
||||
}
|
||||
|
||||
pub fn format(raw: [4]u8) [len]u8 {
|
||||
var out: [len]u8 = undefined;
|
||||
out[0..4].* = "job-".*;
|
||||
out[4..].* = std.fmt.bytesToHex(raw, .lower);
|
||||
return out;
|
||||
}
|
||||
|
||||
pub fn isValid(id: []const u8) bool {
|
||||
if (id.len != len or !std.mem.startsWith(u8, id, "job-")) return false;
|
||||
for (id[4..]) |c| switch (c) {
|
||||
'0'...'9', 'a'...'f' => {},
|
||||
else => return false,
|
||||
};
|
||||
return true;
|
||||
}
|
||||
|
||||
test "format is job- plus 8 lowercase hex" {
|
||||
try std.testing.expectEqualStrings("job-6d368040", &format(.{ 0x6d, 0x36, 0x80, 0x40 }));
|
||||
}
|
||||
|
||||
test "generate produces valid, varying ids" {
|
||||
const a = generate(std.testing.io);
|
||||
const b = generate(std.testing.io);
|
||||
try std.testing.expect(isValid(&a));
|
||||
try std.testing.expect(isValid(&b));
|
||||
}
|
||||
|
||||
test "isValid rejects bad ids" {
|
||||
for ([_][]const u8{ "", "job-", "job-6D368040", "job-6d36804", "job-6d3680400", "xob-6d368040", "job-6d36804g" }) |bad| {
|
||||
try std.testing.expect(!isValid(bad));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
//! Streaming JSON writer that reproduces Jackson's `INDENT_OUTPUT` layout, which barn's
|
||||
//! `--output=json`, `manifest.json` and IPC payloads use:
|
||||
//!
|
||||
//! {
|
||||
//! "id" : "job-6d368040",
|
||||
//! "command" : [ "echo", "Hello World" ],
|
||||
//! "jobs" : [ {
|
||||
//! "id" : "x"
|
||||
//! } ],
|
||||
//! "empty" : [ ],
|
||||
//! "none" : { }
|
||||
//! }
|
||||
//!
|
||||
//! Objects put one member per line with two-space indent and ` : ` between key and value.
|
||||
//! Arrays are always inline (`[ a, b ]`), and objects inside an array indent relative to the
|
||||
//! enclosing object, not the array.
|
||||
const std = @import("std");
|
||||
const Io = std.Io;
|
||||
|
||||
pub const max_depth = 32;
|
||||
|
||||
const Frame = struct {
|
||||
is_object: bool,
|
||||
opened: bool = false,
|
||||
};
|
||||
|
||||
pub const Writer = struct {
|
||||
out: *Io.Writer,
|
||||
stack: [max_depth]Frame = undefined,
|
||||
depth: usize = 0,
|
||||
after_key: bool = false,
|
||||
/// Number of enclosing objects, which determines indentation.
|
||||
object_level: usize = 0,
|
||||
|
||||
pub const Error = Io.Writer.Error;
|
||||
|
||||
pub fn init(out: *Io.Writer) Writer {
|
||||
return .{ .out = out };
|
||||
}
|
||||
|
||||
pub fn beginObject(self: *Writer) Error!void {
|
||||
try self.beforeValue();
|
||||
self.push(.{ .is_object = true });
|
||||
self.object_level += 1;
|
||||
}
|
||||
|
||||
pub fn endObject(self: *Writer) Error!void {
|
||||
const f = self.pop();
|
||||
std.debug.assert(f.is_object);
|
||||
if (f.opened) {
|
||||
try self.out.writeByte('\n');
|
||||
try self.indent(self.object_level - 1);
|
||||
try self.out.writeByte('}');
|
||||
} else {
|
||||
try self.out.writeAll("{ }");
|
||||
}
|
||||
self.object_level -= 1;
|
||||
}
|
||||
|
||||
pub fn beginArray(self: *Writer) Error!void {
|
||||
try self.beforeValue();
|
||||
self.push(.{ .is_object = false });
|
||||
}
|
||||
|
||||
pub fn endArray(self: *Writer) Error!void {
|
||||
const f = self.pop();
|
||||
std.debug.assert(!f.is_object);
|
||||
try self.out.writeAll(if (f.opened) " ]" else "[ ]");
|
||||
}
|
||||
|
||||
pub fn key(self: *Writer, name: []const u8) Error!void {
|
||||
const f = &self.stack[self.depth - 1];
|
||||
std.debug.assert(f.is_object and !self.after_key);
|
||||
try self.out.writeAll(if (f.opened) ",\n" else "{\n");
|
||||
f.opened = true;
|
||||
try self.indent(self.object_level);
|
||||
try std.json.Stringify.encodeJsonString(name, .{}, self.out);
|
||||
try self.out.writeAll(" : ");
|
||||
self.after_key = true;
|
||||
}
|
||||
|
||||
pub fn string(self: *Writer, s: []const u8) Error!void {
|
||||
try self.beforeValue();
|
||||
try std.json.Stringify.encodeJsonString(s, .{}, self.out);
|
||||
}
|
||||
|
||||
pub fn int(self: *Writer, n: anytype) Error!void {
|
||||
try self.beforeValue();
|
||||
try self.out.print("{d}", .{n});
|
||||
}
|
||||
|
||||
/// Doubles print like Java's `Double.toString` for ordinary values: `2.0`, `1.5`.
|
||||
pub fn float(self: *Writer, x: f64) Error!void {
|
||||
try self.beforeValue();
|
||||
var buf: [64]u8 = undefined;
|
||||
const s = std.fmt.bufPrint(&buf, "{d}", .{x}) catch unreachable;
|
||||
try self.out.writeAll(s);
|
||||
if (std.mem.findAny(u8, s, ".eEnN") == null) try self.out.writeAll(".0");
|
||||
}
|
||||
|
||||
pub fn boolean(self: *Writer, b: bool) Error!void {
|
||||
try self.beforeValue();
|
||||
try self.out.writeAll(if (b) "true" else "false");
|
||||
}
|
||||
|
||||
pub fn @"null"(self: *Writer) Error!void {
|
||||
try self.beforeValue();
|
||||
try self.out.writeAll("null");
|
||||
}
|
||||
|
||||
/// Writes a string, or `null` for an absent value.
|
||||
pub fn optString(self: *Writer, s: ?[]const u8) Error!void {
|
||||
if (s) |v| try self.string(v) else try self.@"null"();
|
||||
}
|
||||
|
||||
pub fn field(self: *Writer, name: []const u8, comptime kind: enum { string, int, boolean, float }, value: anytype) Error!void {
|
||||
try self.key(name);
|
||||
switch (kind) {
|
||||
.string => try self.string(value),
|
||||
.int => try self.int(value),
|
||||
.boolean => try self.boolean(value),
|
||||
.float => try self.float(value),
|
||||
}
|
||||
}
|
||||
|
||||
fn beforeValue(self: *Writer) Error!void {
|
||||
if (self.depth == 0) return;
|
||||
const f = &self.stack[self.depth - 1];
|
||||
if (self.after_key) {
|
||||
self.after_key = false;
|
||||
return;
|
||||
}
|
||||
std.debug.assert(!f.is_object); // object members need a key first
|
||||
try self.out.writeAll(if (f.opened) ", " else "[ ");
|
||||
f.opened = true;
|
||||
}
|
||||
|
||||
fn push(self: *Writer, f: Frame) void {
|
||||
self.stack[self.depth] = f;
|
||||
self.depth += 1;
|
||||
}
|
||||
|
||||
fn pop(self: *Writer) Frame {
|
||||
self.depth -= 1;
|
||||
return self.stack[self.depth];
|
||||
}
|
||||
|
||||
fn indent(self: *Writer, level: usize) Error!void {
|
||||
for (0..level) |_| try self.out.writeAll(" ");
|
||||
}
|
||||
};
|
||||
|
||||
fn render(comptime build: fn (*Writer) Io.Writer.Error!void) ![]u8 {
|
||||
var aw: Io.Writer.Allocating = .init(std.testing.allocator);
|
||||
defer aw.deinit();
|
||||
var w = Writer.init(&aw.writer);
|
||||
try build(&w);
|
||||
return aw.toOwnedSlice();
|
||||
}
|
||||
|
||||
test "service status example from the README" {
|
||||
const out = try render(struct {
|
||||
fn f(w: *Writer) !void {
|
||||
try w.beginObject();
|
||||
try w.field("status", .string, "running");
|
||||
try w.field("running", .boolean, true);
|
||||
try w.field("pid", .int, 17474);
|
||||
try w.key("jobs");
|
||||
try w.beginObject();
|
||||
try w.field("running", .int, 0);
|
||||
try w.field("total", .int, 2);
|
||||
try w.endObject();
|
||||
try w.field("data_dir", .string, "/tmp/zag");
|
||||
try w.endObject();
|
||||
}
|
||||
}.f);
|
||||
defer std.testing.allocator.free(out);
|
||||
try std.testing.expectEqualStrings(
|
||||
\\{
|
||||
\\ "status" : "running",
|
||||
\\ "running" : true,
|
||||
\\ "pid" : 17474,
|
||||
\\ "jobs" : {
|
||||
\\ "running" : 0,
|
||||
\\ "total" : 2
|
||||
\\ },
|
||||
\\ "data_dir" : "/tmp/zag"
|
||||
\\}
|
||||
, out);
|
||||
}
|
||||
|
||||
test "arrays are inline; objects in arrays indent relative to the enclosing object" {
|
||||
const out = try render(struct {
|
||||
fn f(w: *Writer) !void {
|
||||
try w.beginObject();
|
||||
try w.key("command");
|
||||
try w.beginArray();
|
||||
try w.string("echo");
|
||||
try w.string("Hello World");
|
||||
try w.endArray();
|
||||
try w.key("tag");
|
||||
try w.@"null"();
|
||||
try w.key("jobs");
|
||||
try w.beginArray();
|
||||
try w.beginObject();
|
||||
try w.field("id", .string, "job-6d368040");
|
||||
try w.endObject();
|
||||
try w.beginObject();
|
||||
try w.field("id", .string, "job-2");
|
||||
try w.endObject();
|
||||
try w.endArray();
|
||||
try w.key("summary");
|
||||
try w.beginObject();
|
||||
try w.field("total", .int, 1);
|
||||
try w.endObject();
|
||||
try w.endObject();
|
||||
}
|
||||
}.f);
|
||||
defer std.testing.allocator.free(out);
|
||||
try std.testing.expectEqualStrings(
|
||||
\\{
|
||||
\\ "command" : [ "echo", "Hello World" ],
|
||||
\\ "tag" : null,
|
||||
\\ "jobs" : [ {
|
||||
\\ "id" : "job-6d368040"
|
||||
\\ }, {
|
||||
\\ "id" : "job-2"
|
||||
\\ } ],
|
||||
\\ "summary" : {
|
||||
\\ "total" : 1
|
||||
\\ }
|
||||
\\}
|
||||
, out);
|
||||
}
|
||||
|
||||
test "empty containers, floats and escapes" {
|
||||
const out = try render(struct {
|
||||
fn f(w: *Writer) !void {
|
||||
try w.beginObject();
|
||||
try w.key("a");
|
||||
try w.beginArray();
|
||||
try w.endArray();
|
||||
try w.key("o");
|
||||
try w.beginObject();
|
||||
try w.endObject();
|
||||
try w.field("m", .float, 2.0);
|
||||
try w.field("n", .float, 1.5);
|
||||
try w.field("s", .string, "q\"\\\n/é");
|
||||
try w.endObject();
|
||||
}
|
||||
}.f);
|
||||
defer std.testing.allocator.free(out);
|
||||
try std.testing.expectEqualStrings(
|
||||
\\{
|
||||
\\ "a" : [ ],
|
||||
\\ "o" : { },
|
||||
\\ "m" : 2.0,
|
||||
\\ "n" : 1.5,
|
||||
\\ "s" : "q\"\\\n/é"
|
||||
\\}
|
||||
, out);
|
||||
}
|
||||
|
||||
test "top-level empty object" {
|
||||
const out = try render(struct {
|
||||
fn f(w: *Writer) !void {
|
||||
try w.beginObject();
|
||||
try w.endObject();
|
||||
}
|
||||
}.f);
|
||||
defer std.testing.allocator.free(out);
|
||||
try std.testing.expectEqualStrings("{ }", out);
|
||||
}
|
||||
@@ -2,6 +2,10 @@
|
||||
pub const duration = @import("duration.zig");
|
||||
pub const timestamp = @import("timestamp.zig");
|
||||
pub const state = @import("state.zig");
|
||||
pub const jobid = @import("jobid.zig");
|
||||
pub const fsutil = @import("fsutil.zig");
|
||||
pub const jsonpretty = @import("jsonpretty.zig");
|
||||
pub const toml = @import("toml.zig");
|
||||
|
||||
test {
|
||||
@import("std").testing.refAllDecls(@This());
|
||||
|
||||
+266
@@ -0,0 +1,266 @@
|
||||
//! Parser for the TOML subset used by barn/zag configuration (not full TOML):
|
||||
//! `[section]` headers, `key = value` with string / integer / float / boolean / flat-array
|
||||
//! values, and `#` comments. Key/value pairs must appear inside a section.
|
||||
//! Mirrors barn's `TomlParser`.
|
||||
const std = @import("std");
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
pub const Value = union(enum) {
|
||||
string: []const u8,
|
||||
int: i64,
|
||||
float: f64,
|
||||
boolean: bool,
|
||||
array: []const Value,
|
||||
};
|
||||
|
||||
pub const Section = std.StringArrayHashMapUnmanaged(Value);
|
||||
pub const Doc = std.StringArrayHashMapUnmanaged(Section);
|
||||
|
||||
pub const ParseError = error{ InvalidSyntax, KeyOutsideSection, InvalidValue, OutOfMemory };
|
||||
|
||||
pub const Diagnostic = struct {
|
||||
/// 1-based line of the failure.
|
||||
line: usize = 0,
|
||||
};
|
||||
|
||||
/// Parses `text`. All allocations (keys, strings, maps) come from `arena`, which the caller
|
||||
/// should free as a whole.
|
||||
pub fn parse(arena: Allocator, text: []const u8, diag: ?*Diagnostic) ParseError!Doc {
|
||||
var doc: Doc = .empty;
|
||||
var current: ?*Section = null;
|
||||
var line_no: usize = 0;
|
||||
var lines = std.mem.splitScalar(u8, text, '\n');
|
||||
while (lines.next()) |raw| {
|
||||
line_no += 1;
|
||||
errdefer if (diag) |d| {
|
||||
d.line = line_no;
|
||||
};
|
||||
const line = std.mem.trim(u8, stripComment(raw), &std.ascii.whitespace);
|
||||
if (line.len == 0) continue;
|
||||
|
||||
if (line[0] == '[' and line[line.len - 1] == ']' and isIdent(std.mem.trim(u8, line[1 .. line.len - 1], &std.ascii.whitespace))) {
|
||||
const name = std.mem.trim(u8, line[1 .. line.len - 1], &std.ascii.whitespace);
|
||||
const gop = try doc.getOrPut(arena, try arena.dupe(u8, name));
|
||||
if (!gop.found_existing) gop.value_ptr.* = .empty;
|
||||
current = gop.value_ptr;
|
||||
continue;
|
||||
}
|
||||
|
||||
const eq = std.mem.indexOfScalar(u8, line, '=') orelse return error.InvalidSyntax;
|
||||
const key = std.mem.trim(u8, line[0..eq], &std.ascii.whitespace);
|
||||
const value_text = std.mem.trim(u8, line[eq + 1 ..], &std.ascii.whitespace);
|
||||
if (!isIdent(key) or value_text.len == 0) return error.InvalidSyntax;
|
||||
const section = current orelse return error.KeyOutsideSection;
|
||||
const value = try parseValue(arena, value_text);
|
||||
try section.put(arena, try arena.dupe(u8, key), value);
|
||||
}
|
||||
return doc;
|
||||
}
|
||||
|
||||
fn isIdent(s: []const u8) bool {
|
||||
if (s.len == 0 or std.ascii.isDigit(s[0])) return false;
|
||||
for (s) |c| if (!std.ascii.isAlphanumeric(c) and c != '_') return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Removes a trailing `# comment`, ignoring `#` inside double quotes.
|
||||
fn stripComment(line: []const u8) []const u8 {
|
||||
var in_string = false;
|
||||
for (line, 0..) |c, i| {
|
||||
if (c == '"' and (i == 0 or line[i - 1] != '\\')) {
|
||||
in_string = !in_string;
|
||||
} else if (c == '#' and !in_string) {
|
||||
return line[0..i];
|
||||
}
|
||||
}
|
||||
return line;
|
||||
}
|
||||
|
||||
fn parseValue(arena: Allocator, s: []const u8) ParseError!Value {
|
||||
if (s.len >= 2 and s[0] == '"' and s[s.len - 1] == '"') {
|
||||
return .{ .string = try unescape(arena, s[1 .. s.len - 1]) };
|
||||
}
|
||||
if (std.ascii.eqlIgnoreCase(s, "true")) return .{ .boolean = true };
|
||||
if (std.ascii.eqlIgnoreCase(s, "false")) return .{ .boolean = false };
|
||||
if (isInteger(s)) return .{ .int = std.fmt.parseInt(i64, s, 10) catch return error.InvalidValue };
|
||||
if (isFloat(s)) return .{ .float = std.fmt.parseFloat(f64, s) catch return error.InvalidValue };
|
||||
if (s.len >= 2 and s[0] == '[' and s[s.len - 1] == ']') return parseArray(arena, s[1 .. s.len - 1]);
|
||||
return error.InvalidValue;
|
||||
}
|
||||
|
||||
fn digitsOnly(s: []const u8) bool {
|
||||
if (s.len == 0) return false;
|
||||
for (s) |c| if (!std.ascii.isDigit(c)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
fn isInteger(s: []const u8) bool {
|
||||
return digitsOnly(if (s.len > 0 and s[0] == '-') s[1..] else s);
|
||||
}
|
||||
|
||||
fn isFloat(s: []const u8) bool {
|
||||
const body = if (s.len > 0 and s[0] == '-') s[1..] else s;
|
||||
const dot = std.mem.indexOfScalar(u8, body, '.') orelse return false;
|
||||
return digitsOnly(body[0..dot]) and digitsOnly(body[dot + 1 ..]);
|
||||
}
|
||||
|
||||
fn parseArray(arena: Allocator, content: []const u8) ParseError!Value {
|
||||
var items: std.ArrayList(Value) = .empty;
|
||||
var start: usize = 0;
|
||||
var depth: usize = 0;
|
||||
var in_string = false;
|
||||
for (content, 0..) |c, i| {
|
||||
if (c == '"' and (i == 0 or content[i - 1] != '\\')) {
|
||||
in_string = !in_string;
|
||||
} else if (in_string) {
|
||||
continue;
|
||||
} else if (c == '[') {
|
||||
depth += 1;
|
||||
} else if (c == ']') {
|
||||
depth -|= 1;
|
||||
} else if (c == ',' and depth == 0) {
|
||||
try appendItem(arena, &items, content[start..i]);
|
||||
start = i + 1;
|
||||
}
|
||||
}
|
||||
try appendItem(arena, &items, content[start..]);
|
||||
return .{ .array = try items.toOwnedSlice(arena) };
|
||||
}
|
||||
|
||||
fn appendItem(arena: Allocator, items: *std.ArrayList(Value), raw: []const u8) ParseError!void {
|
||||
const t = std.mem.trim(u8, raw, &std.ascii.whitespace);
|
||||
if (t.len == 0) return;
|
||||
try items.append(arena, try parseValue(arena, t));
|
||||
}
|
||||
|
||||
/// Handles `\"`, `\\`, `\n`, `\t`, `\r`; other backslashes are kept literally.
|
||||
fn unescape(arena: Allocator, s: []const u8) Allocator.Error![]const u8 {
|
||||
var out: std.ArrayList(u8) = .empty;
|
||||
var i: usize = 0;
|
||||
while (i < s.len) : (i += 1) {
|
||||
if (s[i] == '\\' and i + 1 < s.len) {
|
||||
const repl: ?u8 = switch (s[i + 1]) {
|
||||
'"' => '"',
|
||||
'\\' => '\\',
|
||||
'n' => '\n',
|
||||
't' => '\t',
|
||||
'r' => '\r',
|
||||
else => null,
|
||||
};
|
||||
if (repl) |r| {
|
||||
try out.append(arena, r);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
try out.append(arena, s[i]);
|
||||
}
|
||||
return out.toOwnedSlice(arena);
|
||||
}
|
||||
|
||||
// --- accessors -------------------------------------------------------------------------
|
||||
|
||||
pub fn get(doc: Doc, section: []const u8, key: []const u8) ?Value {
|
||||
const s = doc.get(section) orelse return null;
|
||||
return s.get(key);
|
||||
}
|
||||
|
||||
// --- tests (ported from barn's TomlParserTest) -----------------------------------------
|
||||
|
||||
fn parseT(arena: Allocator, text: []const u8) !Doc {
|
||||
return parse(arena, text, null);
|
||||
}
|
||||
|
||||
test "empty, comments and whitespace yield an empty doc" {
|
||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
for ([_][]const u8{ "", "# a\n# b\n", " \n \n " }) |t| {
|
||||
try std.testing.expectEqual(@as(usize, 0), (try parseT(arena.allocator(), t)).count());
|
||||
}
|
||||
}
|
||||
|
||||
test "sections" {
|
||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const doc = try parseT(arena.allocator(), "[service]\n[jobs]\n[cleanup]\n");
|
||||
try std.testing.expect(doc.contains("service") and doc.contains("jobs") and doc.contains("cleanup"));
|
||||
}
|
||||
|
||||
test "scalar values" {
|
||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const doc = try parseT(arena.allocator(),
|
||||
\\[s]
|
||||
\\name = "my service name"
|
||||
\\quote = "say \"hello\""
|
||||
\\nl = "line1\nline2"
|
||||
\\n = 5
|
||||
\\neg = -10
|
||||
\\zero = 0
|
||||
\\f = 2.5
|
||||
\\nf = -1.5
|
||||
\\t = true
|
||||
\\u = TRUE
|
||||
\\x = false
|
||||
);
|
||||
try std.testing.expectEqualStrings("my service name", get(doc, "s", "name").?.string);
|
||||
try std.testing.expectEqualStrings("say \"hello\"", get(doc, "s", "quote").?.string);
|
||||
try std.testing.expectEqualStrings("line1\nline2", get(doc, "s", "nl").?.string);
|
||||
try std.testing.expectEqual(@as(i64, 5), get(doc, "s", "n").?.int);
|
||||
try std.testing.expectEqual(@as(i64, -10), get(doc, "s", "neg").?.int);
|
||||
try std.testing.expectEqual(@as(i64, 0), get(doc, "s", "zero").?.int);
|
||||
try std.testing.expectEqual(@as(f64, 2.5), get(doc, "s", "f").?.float);
|
||||
try std.testing.expectEqual(@as(f64, -1.5), get(doc, "s", "nf").?.float);
|
||||
try std.testing.expect(get(doc, "s", "t").?.boolean);
|
||||
try std.testing.expect(get(doc, "s", "u").?.boolean);
|
||||
try std.testing.expect(!get(doc, "s", "x").?.boolean);
|
||||
}
|
||||
|
||||
test "arrays" {
|
||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const doc = try parseT(arena.allocator(),
|
||||
\\[j]
|
||||
\\codes = [1, 2, 3]
|
||||
\\empty = []
|
||||
\\words = ["a,b", "c"]
|
||||
\\nested = [[1, 2], [3]]
|
||||
);
|
||||
const codes = get(doc, "j", "codes").?.array;
|
||||
try std.testing.expectEqual(@as(usize, 3), codes.len);
|
||||
try std.testing.expectEqual(@as(i64, 3), codes[2].int);
|
||||
try std.testing.expectEqual(@as(usize, 0), get(doc, "j", "empty").?.array.len);
|
||||
const words = get(doc, "j", "words").?.array;
|
||||
try std.testing.expectEqualStrings("a,b", words[0].string);
|
||||
try std.testing.expectEqual(@as(usize, 2), get(doc, "j", "nested").?.array.len);
|
||||
}
|
||||
|
||||
test "comments are stripped outside strings only" {
|
||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const doc = try parseT(arena.allocator(), "[s]\na = 1 # trailing\nb = \"x # y\" # c\n");
|
||||
try std.testing.expectEqual(@as(i64, 1), get(doc, "s", "a").?.int);
|
||||
try std.testing.expectEqualStrings("x # y", get(doc, "s", "b").?.string);
|
||||
}
|
||||
|
||||
test "errors carry the line number" {
|
||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
var diag: Diagnostic = .{};
|
||||
try std.testing.expectError(error.KeyOutsideSection, parse(arena.allocator(), "a = 1\n", &diag));
|
||||
try std.testing.expectEqual(@as(usize, 1), diag.line);
|
||||
try std.testing.expectError(error.InvalidSyntax, parse(arena.allocator(), "[s]\nnot valid\n", &diag));
|
||||
try std.testing.expectEqual(@as(usize, 2), diag.line);
|
||||
try std.testing.expectError(error.InvalidValue, parse(arena.allocator(), "[s]\n\na = nope\n", &diag));
|
||||
try std.testing.expectEqual(@as(usize, 3), diag.line);
|
||||
try std.testing.expectError(error.InvalidValue, parse(arena.allocator(), "[s]\na = 99999999999999999999\n", &diag));
|
||||
}
|
||||
|
||||
test "later keys override earlier ones and sections merge" {
|
||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const doc = try parseT(arena.allocator(), "[s]\na = 1\n[t]\nb = 2\n[s]\na = 3\nc = 4\n");
|
||||
try std.testing.expectEqual(@as(i64, 3), get(doc, "s", "a").?.int);
|
||||
try std.testing.expectEqual(@as(i64, 4), get(doc, "s", "c").?.int);
|
||||
try std.testing.expectEqual(@as(usize, 2), doc.count());
|
||||
}
|
||||
Reference in new issue
Block a user