//! 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()); }