//! The configuration tree (M1-YAML-005, M1-YAML-006, M1-YAML-007). //! //! Turns the event stream from events.zig into a small tree of mappings, //! sequences and scalars. Scalars carry their style, because M1-YAML-005 //! resolves plain ones by the YAML 1.2 Core Schema but quoted and block ones //! always as strings. //! //! Shape validation lives in schema.zig; this file only builds and resolves. const std = @import("std"); const diag = @import("../diag.zig"); const events = @import("events.zig"); pub const Error = error{ InvalidYaml, InvalidConfig, OutOfMemory }; /// A plain scalar resolved by the YAML 1.2 Core Schema (M1-YAML-005). pub const Resolved = union(enum) { boolean: bool, float: f64, integer: i64, null, string: []const u8, }; pub const Scalar = struct { mark: events.Mark, style: events.ScalarStyle, text: []const u8, /// M1-YAML-005. Only plain scalars are resolved; quoted and block scalars /// are strings whatever they spell, so "true" is not a boolean. pub fn resolved(self: Scalar) Resolved { return switch (self.style) { .plain => resolvePlain(self.text), .quoted => .{ .string = self.text }, }; } }; pub const Entry = struct { key: []const u8, key_mark: events.Mark, value: Node, }; pub const Mapping = struct { entries: []const Entry, mark: events.Mark, pub fn find(self: Mapping, key: []const u8) ?*const Node { for (self.entries) |*entry| { if (std.mem.eql(u8, entry.key, key)) return &entry.value; } return null; } }; pub const Sequence = struct { items: []const Node, mark: events.Mark, }; pub const Node = union(enum) { mapping: Mapping, scalar: Scalar, sequence: Sequence, pub fn mark(self: Node) events.Mark { return switch (self) { .scalar => |s| s.mark, .mapping => |m| m.mark, .sequence => |s| s.mark, }; } pub fn kindName(self: Node) []const u8 { return switch (self) { .scalar => "a scalar", .mapping => "a mapping", .sequence => "a sequence", }; } }; // -- Core Schema resolution -------------------------------------------------- pub fn eqlAny(text: []const u8, options: []const []const u8) bool { for (options) |option| { if (std.mem.eql(u8, text, option)) return true; } return false; } fn resolvePlain(text: []const u8) Resolved { if (text.len == 0) return .null; if (eqlAny(text, &.{ "~", "null", "Null", "NULL" })) return .null; if (eqlAny(text, &.{ "true", "True", "TRUE" })) return .{ .boolean = true }; if (eqlAny(text, &.{ "false", "False", "FALSE" })) return .{ .boolean = false }; if (parseCoreInt(text)) |n| return .{ .integer = n }; if (parseCoreFloat(text)) |f| return .{ .float = f }; return .{ .string = text }; } fn parseCoreInt(text: []const u8) ?i64 { // Zig's parseInt accepts '_' separators; the Core Schema does not. if (std.mem.findScalar(u8, text, '_') != null) return null; if (std.mem.startsWith(u8, text, "0x") or std.mem.startsWith(u8, text, "0X")) { return std.fmt.parseInt(i64, text[2..], 16) catch null; } if (std.mem.startsWith(u8, text, "0o") or std.mem.startsWith(u8, text, "0O")) { return std.fmt.parseInt(i64, text[2..], 8) catch null; } return std.fmt.parseInt(i64, text, 10) catch null; } fn parseCoreFloat(text: []const u8) ?f64 { if (eqlAny(text, &.{ ".inf", ".Inf", ".INF", "+.inf", "+.Inf", "+.INF" })) { return std.math.inf(f64); } if (eqlAny(text, &.{ "-.inf", "-.Inf", "-.INF" })) return -std.math.inf(f64); if (eqlAny(text, &.{ ".nan", ".NaN", ".NAN" })) return std.math.nan(f64); // Require a '.' or exponent, so bare "inf" or "nan" stay strings. var has_marker = false; for (text) |ch| switch (ch) { '0'...'9', '+', '-' => {}, '.', 'e', 'E' => has_marker = true, else => return null, }; if (!has_marker) return null; return std.fmt.parseFloat(f64, text) catch null; } // -- tree building ----------------------------------------------------------- /// Parses a configuration file into a tree and returns its root node. pub fn parse( arena: std.mem.Allocator, file: []const u8, source: []const u8, diags: *diag.List, ) Error!*const Node { var reader = try events.Reader.init(arena, file, source, diags); defer reader.deinit(); var builder: Builder = .{ .arena = arena, .file = file, .diags = diags, .reader = &reader }; const first = (try reader.next()) orelse return builder.fail("", .{ .line = 1, .column = 1 }, "file contains no YAML document", .{}); const root = try arena.create(Node); root.* = try builder.node(first, ""); return root; } const Builder = struct { arena: std.mem.Allocator, diags: *diag.List, file: []const u8, reader: *events.Reader, fn node(self: *Builder, event: events.Event, path: []const u8) Error!Node { return switch (event) { .scalar => |s| .{ .scalar = .{ .text = s.value, .style = s.style, .mark = s.mark } }, .mapping_start => |mark| try self.mapping(mark, path), .sequence_start => |mark| try self.sequence(mark, path), .mapping_end, .sequence_end => self.fail(path, event.mark(), "unexpected end of collection", .{}), }; } fn mapping(self: *Builder, start: events.Mark, path: []const u8) Error!Node { var entries: std.ArrayList(Entry) = .empty; while (true) { const key_event = (try self.reader.next()) orelse return self.fail(path, start, "unterminated mapping", .{}); if (key_event == .mapping_end) break; // M1-YAML-006: keys are scalars, never nested collections. const key = switch (key_event) { .scalar => |s| s, else => return self.fail(path, key_event.mark(), "mapping keys must be scalar strings", .{}), }; // D5: M1-YAML-007 allows either behaviour; rejecting needs no // precedence rule and is deterministic. for (entries.items) |existing| { if (std.mem.eql(u8, existing.key, key.value)) { return self.fail(path, key.mark, "duplicate key '{s}'", .{key.value}); } } const child_path = try joinPath(self.arena, path, key.value); const value_event = (try self.reader.next()) orelse return self.fail(child_path, key.mark, "key '{s}' has no value", .{key.value}); const value = try self.node(value_event, child_path); try entries.append(self.arena, .{ .key = key.value, .key_mark = key.mark, .value = value }); } return .{ .mapping = .{ .entries = entries.items, .mark = start } }; } fn sequence(self: *Builder, start: events.Mark, path: []const u8) Error!Node { var items: std.ArrayList(Node) = .empty; while (true) { const event = (try self.reader.next()) orelse return self.fail(path, start, "unterminated sequence", .{}); if (event == .sequence_end) break; try items.append(self.arena, try self.node(event, path)); } return .{ .sequence = .{ .items = items.items, .mark = start } }; } fn fail( self: *Builder, path: []const u8, mark: events.Mark, comptime fmt: []const u8, args: anytype, ) Error { report(self.diags, configAt(self.file, path, mark), fmt, args); return error.InvalidConfig; } }; pub fn joinPath(arena: std.mem.Allocator, parent: []const u8, key: []const u8) Error![]const u8 { if (parent.len == 0) return arena.dupe(u8, key); return arena.print("{s}.{s}", .{ parent, key }); } /// The config location of `path` in `file`, as marked by the YAML event. pub fn configAt(file: []const u8, path: []const u8, mark: events.Mark) diag.ConfigAt { return .{ .file = file, .key_path = path, .line_col = .{ .line = mark.line, .column = mark.column }, }; } /// Best effort by design: a caller that cannot record a diagnostic has /// nothing better to say than the failure it was already reporting, so an /// unrecordable one is dropped rather than replacing it. pub fn report( diags: *diag.List, at: diag.ConfigAt, comptime fmt: []const u8, args: anytype, ) void { // zlinter-disable-next-line no_swallow_error - see the doc comment: dropping is the contract diags.addConfig(at, fmt, args) catch {}; } // -- tests ------------------------------------------------------------------- const expectEqual = std.testing.expectEqual; const expectEqualStrings = std.testing.expectEqualStrings; const expectError = std.testing.expectError; fn rootOf(arena: *std.heap.ArenaAllocator, source: []const u8) Error!*const Node { const alloc = arena.allocator(); const diags = diag.List.create(alloc) catch return error.OutOfMemory; return parse(alloc, "test.yaml", source, diags); } fn valueOf(root: *const Node, key: []const u8) Scalar { return root.mapping.find(key).?.scalar; } test "M1-YAML-005: a plain true is a boolean but a quoted one is a string" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const root = try rootOf(&arena, "a: true\nb: \"true\"\n"); try expectEqual(true, valueOf(root, "a").resolved().boolean); try expectEqualStrings("true", valueOf(root, "b").resolved().string); } test "M1-YAML-005: a plain 1 is an integer but a quoted one is a string" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const root = try rootOf(&arena, "a: 1\nb: \"1\"\n"); try expectEqual(@as(i64, 1), valueOf(root, "a").resolved().integer); try expectEqualStrings("1", valueOf(root, "b").resolved().string); } test "M1-YAML-005: a block scalar is a string whatever it contains" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const root = try rootOf(&arena, "a: |\n true\n"); try expectEqualStrings("true\n", valueOf(root, "a").resolved().string); } test "M1-YAML-005: the Core Schema resolves null, bools, ints and floats" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const root = try rootOf(&arena, @embedFile("../testdata/yaml/the_core_schema_resolves_null_bools_ints_and_floats.yaml")); try expectEqual(Resolved.null, valueOf(root, "a").resolved()); try expectEqual(Resolved.null, valueOf(root, "b").resolved()); try expectEqual(false, valueOf(root, "c").resolved().boolean); try expectEqual(@as(i64, 16), valueOf(root, "d").resolved().integer); try expectEqual(@as(i64, 15), valueOf(root, "e").resolved().integer); try expectEqual(@as(f64, 1.5), valueOf(root, "f").resolved().float); try expectEqualStrings("plain text", valueOf(root, "g").resolved().string); // Bare "inf" is not a Core Schema float; only ".inf" is. try expectEqualStrings("inf", valueOf(root, "h").resolved().string); } test "M1-YAML-005: underscores do not make a number, unlike Zig literals" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const root = try rootOf(&arena, "a: 1_000\n"); try expectEqualStrings("1_000", valueOf(root, "a").resolved().string); } test "M1-YAML-007: duplicate keys are rejected (D5)" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); try expectError(error.InvalidConfig, rootOf(&arena, "a: 1\na: 2\n")); } test "M1-YAML-006: a non-scalar mapping key is rejected" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); try expectError(error.InvalidConfig, rootOf(&arena, "? - a\n: 1\n")); } test "a sequence of scalars becomes a sequence node" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const root = try rootOf(&arena, "a:\n - x\n - y\n"); const items = root.mapping.find("a").?.sequence.items; try expectEqual(@as(usize, 2), items.len); try expectEqualStrings("x", items[0].scalar.text); }