//! Mapping-shape validation (M1-YAML-008, M1-YAML-012). //! //! Walks the tree from tree.zig with a cursor that remembers how it got there, //! so every diagnostic can name the key path (M1-YAML-006). //! //! Scope. The validators here check *mapping shapes*, which is what M1-YAML-008 //! and M1-YAML-012 specify: exactly these keys, or exactly one of those two. //! Value constraints belong to the requirement that states them -- the //! delimiter enum is M1-CSV-002, the date format is M1-CSV-016 -- so they are //! applied by the modules that own them, using the accessors here. The one //! exception is `schema: version: 1`, which M1-YAML-008 states itself. const std = @import("std"); const diag = @import("../diag.zig"); const tree = @import("tree.zig"); pub const Error = tree.Error; pub const Node = tree.Node; pub const Mapping = tree.Mapping; pub const Resolved = tree.Resolved; /// Parses a configuration file and returns a cursor at its root. pub fn parse( arena: std.mem.Allocator, file: []const u8, source: []const u8, diags: *diag.List, ) Error!Cursor { const root = try tree.parse(arena, file, source, diags); return .{ .arena = arena, .file = file, .diags = diags, .node = root, .path = "" }; } // -- cursor ------------------------------------------------------------------ /// A position in the tree that remembers how it got there, so diagnostics can /// name the key path (M1-YAML-006). pub const Cursor = struct { arena: std.mem.Allocator, diags: *diag.List, file: []const u8, node: *const Node, path: []const u8, /// Records a diagnostic without failing. For problems that are /// deliberately non-fatal, such as M1-RULE-013's tolerance of a broken /// rule action. pub fn note(self: Cursor, comptime fmt: []const u8, args: anytype) void { tree.report(self.diags, tree.configAt(self.file, self.path, self.node.mark()), fmt, args); } pub fn fail(self: Cursor, comptime fmt: []const u8, args: anytype) Error { self.note(fmt, args); return error.InvalidConfig; } pub fn mappingNode(self: Cursor) Error!Mapping { return switch (self.node.*) { .mapping => |m| m, else => self.fail("expected a mapping, found {s}", .{self.node.kindName()}), }; } /// A required child. Reports the missing key at its own path. pub fn child(self: Cursor, key: []const u8) Error!Cursor { const mapping = try self.mappingNode(); const path = try tree.joinPath(self.arena, self.path, key); const found = mapping.find(key) orelse { tree.report(self.diags, tree.configAt(self.file, path, mapping.mark), "required key '{s}' is missing", .{key}); return error.InvalidConfig; }; return .{ .arena = self.arena, .file = self.file, .diags = self.diags, .node = found, .path = path }; } pub fn optionalChild(self: Cursor, key: []const u8) Error!?Cursor { const mapping = try self.mappingNode(); const found = mapping.find(key) orelse return null; return .{ .arena = self.arena, .file = self.file, .diags = self.diags, .node = found, .path = try tree.joinPath(self.arena, self.path, key), }; } /// Null when this node is not a scalar at all. pub fn resolved(self: Cursor) ?Resolved { return switch (self.node.*) { .scalar => |s| s.resolved(), else => null, }; } fn requireResolved(self: Cursor) Error!Resolved { return self.resolved() orelse self.fail("expected a scalar, found {s}", .{self.node.kindName()}); } pub fn string(self: Cursor) Error![]const u8 { return switch (try self.requireResolved()) { .string => |s| s, else => self.fail("expected a string", .{}), }; } pub fn boolean(self: Cursor) Error!bool { return switch (try self.requireResolved()) { .boolean => |b| b, else => self.fail("expected a boolean", .{}), }; } pub fn integer(self: Cursor) Error!i64 { return switch (try self.requireResolved()) { .integer => |n| n, else => self.fail("expected an integer", .{}), }; } pub fn unsignedInteger(self: Cursor) Error!u32 { const value = try self.integer(); if (value < 0 or value > std.math.maxInt(u32)) { return self.fail("expected a non-negative integer, found {d}", .{value}); } return @intCast(value); } /// M1-YAML-006: an invalid enum value names what was allowed. pub fn enumValue(self: Cursor, allowed: []const []const u8) Error![]const u8 { return allowed[try self.enumIndex(allowed)]; } /// `enumValue` for an enum whose tag names are its spellings. pub fn enumTag(self: Cursor, E: type) Error!E { const tags = comptime std.enums.values(E); const names = comptime blk: { var spellings: [tags.len][]const u8 = @splat(""); for (tags, &spellings) |tag, *spelling| spelling.* = @tagName(tag); break :blk spellings; }; return tags[try self.enumIndex(&names)]; } /// `enumValue`, as a position in `allowed`, so the caller can pick the /// typed value from an array in the same order. pub fn enumIndex(self: Cursor, allowed: []const []const u8) Error!usize { const text = try self.string(); for (allowed, 0..) |option, index| { if (std.mem.eql(u8, text, option)) return index; } return self.fail("'{s}' is not one of the allowed values", .{text}); } /// No key outside `allowed`. Presence is not required. pub fn requireOnly(self: Cursor, allowed: []const []const u8) Error!void { const mapping = try self.mappingNode(); for (mapping.entries) |entry| { if (!tree.eqlAny(entry.key, allowed)) { const path = try tree.joinPath(self.arena, self.path, entry.key); tree.report(self.diags, tree.configAt(self.file, path, entry.key_mark), "unknown key '{s}'", .{entry.key}); return error.InvalidConfig; } } } /// Every key present, and nothing else. This is what "exactly" means in /// M1-YAML-008 and M1-YAML-012. pub fn requireExactly(self: Cursor, keys: []const []const u8) Error!void { try self.requireOnly(keys); for (keys) |key| _ = try self.child(key); } /// M1-YAML-012: a fields entry, and the currency mapping, carry one /// selector and not the other. pub fn requireExactlyOneOf(self: Cursor, options: []const []const u8) Error![]const u8 { try self.requireOnly(options); var found: ?[]const u8 = null; for (options) |option| { if (try self.optionalChild(option)) |_| { if (found != null) { return self.fail("exactly one of these keys is allowed, found more than one", .{}); } found = option; } } return found orelse self.fail("exactly one of these keys is required, found none", .{}); } pub fn nonEmpty(self: Cursor) Error![]const u8 { const text = try self.string(); if (text.len == 0) return self.fail("must not be empty", .{}); return text; } pub fn relativeNonEmpty(self: Cursor) Error![]const u8 { const text = try self.nonEmpty(); if (std.Io.Dir.path.isAbsolute(text)) { return self.fail("must be a relative path, found '{s}'", .{text}); } return text; } }; // -- shape validators -------------------------------------------------------- /// M1-YAML-008 and M1-YAML-012, applied to a manifest root. pub fn validateManifest(root: Cursor) Error!void { try root.requireExactly(&.{ "schema", "project", "profile" }); try validateSchemaSection(try root.child("schema")); try (try root.child("project")).requireExactly(&.{"inputPath"}); const profile = try root.child("profile"); try profile.requireExactly(&.{ "name", "rulesFile", "csv", "transaction" }); try validateCsvSection(try profile.child("csv")); try validateTransactionSection(try profile.child("transaction")); } /// M1-YAML-008, applied to a rules-file root. pub fn validateRulesRoot(root: Cursor) Error!void { try root.requireExactly(&.{ "schema", "rules" }); try validateSchemaSection(try root.child("schema")); _ = try (try root.child("rules")).mappingNode(); } /// M1-YAML-008: `schema` contains exactly `version: 1`. pub fn validateSchemaSection(schema: Cursor) Error!void { try schema.requireExactly(&.{"version"}); const version = try schema.child("version"); const value = try version.integer(); if (value != 1) return version.fail("schema version must be 1, found {d}", .{value}); } fn validateCsvSection(csv: Cursor) Error!void { try csv.requireExactly(&.{ "delimiter", "lineEnding", "skipRecords", "header", "fields" }); const fields = try csv.child("fields"); const mapping = try fields.mappingNode(); for (mapping.entries) |entry| { try validateFieldEntry(try fields.child(entry.key)); } } /// M1-YAML-012: exactly one of `header` or `index`. pub fn validateFieldEntry(entry: Cursor) Error!void { _ = try entry.requireExactlyOneOf(&.{ "header", "index" }); } /// M1-YAML-012: exactly one of `fixed` or `field`. pub fn validateCurrency(currency: Cursor) Error!void { _ = try currency.requireExactlyOneOf(&.{ "fixed", "field" }); } fn validateTransactionSection(transaction: Cursor) Error!void { try transaction.requireOnly(&.{ "date", "amount", "currency", "sourceAccount", "narrationTemplate", "postingCommentTemplates", }); try (try transaction.child("date")).requireExactly(&.{ "field", "format" }); const amount = try transaction.child("amount"); try amount.requireOnly(&.{ "field", "decimalSeparator", "groupSeparator" }); _ = try amount.child("field"); _ = try amount.child("decimalSeparator"); try validateCurrency(try transaction.child("currency")); _ = try transaction.child("sourceAccount"); _ = try transaction.child("narrationTemplate"); if (try transaction.optionalChild("postingCommentTemplates")) |templates| { try templates.requireOnly(&.{ "source", "destination" }); } } // -- tests ------------------------------------------------------------------- const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; const expectEqualStrings = std.testing.expectEqualStrings; const expectError = std.testing.expectError; fn cursorOf(arena: *std.heap.ArenaAllocator, source: []const u8) Error!Cursor { const alloc = arena.allocator(); const diags = diag.List.create(alloc) catch return error.OutOfMemory; return parse(alloc, "test.yaml", source, diags); } /// Asserts the source is rejected and that a diagnostic naming `path` was /// recorded (M1-YAML-006 requires the key path). fn expectRejectedAt(source: []const u8, path: []const u8) !void { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const alloc = arena.allocator(); const diags = try diag.List.create(alloc); const cursor = parse(alloc, "test.yaml", source, diags) catch { try expect(!diags.isEmpty()); for (diags.items.items) |d| { if (d.key_path != null and std.mem.eql(u8, d.key_path.?, path)) return; } return error.TestDiagnosticPathMismatch; }; validateManifest(cursor) catch { try expect(!diags.isEmpty()); for (diags.items.items) |d| { if (d.key_path != null and std.mem.eql(u8, d.key_path.?, path)) return; } return error.TestDiagnosticPathMismatch; }; return error.TestExpectedRejection; } const valid_manifest = @embedFile("../testdata/yaml/valid_manifest.yaml"); test "M1-YAML-006: a missing required key is reported with its path" { try expectRejectedAt("schema:\n version: 1\nproject:\n inputPath: x\n", "profile"); } test "M1-YAML-006: an unknown key is reported with its path" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const c = try cursorOf(&arena, "a: 1\nb: 2\n"); try expectError(error.InvalidConfig, c.requireOnly(&.{"a"})); } test "M1-YAML-008: a valid manifest passes every shape rule" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const c = try cursorOf(&arena, valid_manifest); try validateManifest(c); } test "M1-YAML-008: the manifest root takes exactly schema, project and profile" { try expectRejectedAt(valid_manifest ++ "extra: 1\n", "extra"); } test "M1-YAML-008: schema must be exactly version 1" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const two = try cursorOf(&arena, "schema:\n version: 2\n"); try expectError(error.InvalidConfig, validateSchemaSection(try two.child("schema"))); // Quoted "1" is a string, not the integer the field requires. const quoted = try cursorOf(&arena, "schema:\n version: \"1\"\n"); try expectError(error.InvalidConfig, validateSchemaSection(try quoted.child("schema"))); } test "M1-YAML-008: the rules root takes exactly schema and rules" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const accepted = try cursorOf(&arena, "schema:\n version: 1\nrules:\n a:\n match: x\n"); try validateRulesRoot(accepted); const extra = try cursorOf(&arena, "schema:\n version: 1\nrules:\n a: 1\nextra: 2\n"); try expectError(error.InvalidConfig, validateRulesRoot(extra)); } test "M1-YAML-012: project takes exactly inputPath" { try expectRejectedAt(@embedFile("../testdata/yaml/project_takes_exactly_inputPath.yaml"), "project.extra"); } test "M1-YAML-012: a fields entry takes exactly one of header or index" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const both = try cursorOf(&arena, "d:\n header: A\n index: 1\n"); try expectError(error.InvalidConfig, validateFieldEntry(try both.child("d"))); const neither = try cursorOf(&arena, "d:\n other: A\n"); try expectError(error.InvalidConfig, validateFieldEntry(try neither.child("d"))); const just_index = try cursorOf(&arena, "d:\n index: 1\n"); try validateFieldEntry(try just_index.child("d")); } test "M1-YAML-012: currency takes exactly one of fixed or field" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const both = try cursorOf(&arena, "c:\n fixed: EUR\n field: cur\n"); try expectError(error.InvalidConfig, validateCurrency(try both.child("c"))); const one = try cursorOf(&arena, "c:\n field: cur\n"); try validateCurrency(try one.child("c")); } test "M1-YAML-012: postingCommentTemplates is an optional subset" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const only_source = try cursorOf(&arena, "t:\n source: a\n"); try (try only_source.child("t")).requireOnly(&.{ "source", "destination" }); const unknown = try cursorOf(&arena, "t:\n other: a\n"); try expectError( error.InvalidConfig, (try unknown.child("t")).requireOnly(&.{ "source", "destination" }), ); } test "M1-YAML-012: amount takes field and decimalSeparator, with optional groupSeparator" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const alloc = arena.allocator(); const decimal = " decimalSeparator: comma\n"; const grouped = try std.mem.replaceOwned(u8, alloc, valid_manifest, decimal, decimal ++ " groupSeparator: dot\n"); try validateManifest(try cursorOf(&arena, grouped)); const unknown = try std.mem.replaceOwned(u8, alloc, valid_manifest, decimal, decimal ++ " other: dot\n"); try expectError(error.InvalidConfig, validateManifest(try cursorOf(&arena, unknown))); const only_group = try std.mem.replaceOwned(u8, alloc, valid_manifest, decimal, " groupSeparator: dot\n"); try expectError(error.InvalidConfig, validateManifest(try cursorOf(&arena, only_group))); } test "M1-YAML-012: skipRecords must be a non-negative integer" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const c = try cursorOf(&arena, "a: -1\nb: 0\nc: text\n"); try expectEqual(@as(u32, 0), try (try c.child("b")).unsignedInteger()); try expectError(error.InvalidConfig, (try c.child("a")).unsignedInteger()); try expectError(error.InvalidConfig, (try c.child("c")).unsignedInteger()); } test "M1-YAML-006: an invalid enum value is reported" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const c = try cursorOf(&arena, "d: pipe\n"); try expectError( error.InvalidConfig, (try c.child("d")).enumValue(&.{ "comma", "semicolon", "tab" }), ); const accepted = try cursorOf(&arena, "d: tab\n"); try expectEqualStrings("tab", try (try accepted.child("d")).enumValue(&.{ "comma", "tab" })); } test "M1-YAML-010: schema diagnostics identify the file and key path" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const alloc = arena.allocator(); const diags = try diag.List.create(alloc); const c = try parse(alloc, "project.yaml", "profile:\n csv:\n header: 1\n", diags); const csv = try (try c.child("profile")).child("csv"); _ = (try csv.child("header")).boolean() catch {}; const first_diag = diags.items.items[0]; try expectEqualStrings("project.yaml", first_diag.file.?); try expectEqualStrings("profile.csv.header", first_diag.key_path.?); } test "the shipped example manifests satisfy every shape rule" { const examples = [_][]const u8{ @embedFile("example_project_yaml"), @embedFile("example_headerless_yaml"), }; for (examples) |source| { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); try validateManifest(try cursorOf(&arena, source)); } } test "the shipped example rules file satisfies the root shape" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); try validateRulesRoot(try cursorOf(&arena, @embedFile("example_rules_yaml"))); } test "M1-YAML-006: a collection where a scalar is required is rejected" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const c = try cursorOf(&arena, "a:\n nested: 1\nb:\n - x\n"); // Without this check a mapping resolves to the empty string and passes. try expectError(error.InvalidConfig, (try c.child("a")).string()); try expectError(error.InvalidConfig, (try c.child("b")).string()); try expectError(error.InvalidConfig, (try c.child("a")).boolean()); try expectError(error.InvalidConfig, (try c.child("a")).integer()); }