//! Rules model (M1-RULE-001, 002, 011, 012, 013). //! //! M1-RULE-013 draws an asymmetry that shapes this module. A broken *action* //! must not stop the rule's condition being evaluated, so such a rule is kept //! with its condition intact and no action. A broken *condition* leaves //! nothing to evaluate and is fatal for the whole candidate, as is any other //! schema violation inside a rule. //! //! The condition is kept as text. Parsing it is M1-RULE-003 and belongs to the //! expression modules; storing the source here is what lets a rule with an //! unusable action still take part in matching. const std = @import("std"); const diag = @import("../diag.zig"); const schema = @import("../yaml/schema.zig"); pub const Error = schema.Error; /// What a matching rule writes (M1-RULE-011, M1-RULE-012). pub const Action = struct { /// Overrides the profile default when present (M1-RULE-012). source_account: ?[]const u8, target_account: []const u8, }; pub const Rule = struct { /// Null when the action was missing or invalid. A diagnostic has been /// recorded and generation must fail, but the condition is unaffected /// (M1-RULE-013). action: ?Action, /// Condition source, unparsed. match: []const u8, name: []const u8, /// M1-RULE-012: the profile default unless this rule overrides it. Null /// when the rule has no usable action at all. pub fn sourceAccount(self: Rule, profile_default: []const u8) ?[]const u8 { const action = self.action orelse return null; return action.source_account orelse profile_default; } }; pub const Ruleset = struct { /// Source order. Matching is order-independent (M1-RULE-006); this order /// exists only so diagnostics come out the same way twice (M1-SAFE-001). rules: []const Rule, pub fn find(self: Ruleset, name: []const u8) ?*const Rule { for (self.rules) |*rule| { if (std.mem.eql(u8, rule.name, name)) return rule; } return null; } }; /// Decodes a rules file. Rules whose action is unusable are retained without /// one rather than dropped (M1-RULE-013). pub fn load( arena: std.mem.Allocator, file: []const u8, source: []const u8, diags: *diag.List, ) Error!Ruleset { const root = try schema.parse(arena, file, source, diags); try schema.validateRulesRoot(root); const rules_cursor = try root.child("rules"); const mapping = try rules_cursor.mappingNode(); // M1-RULE-001. M1-UI-019 lets the editor hold zero rules in memory, but a // rules file on disk always has at least one. if (mapping.entries.len == 0) { return rules_cursor.fail("at least one rule is required", .{}); } var list: std.ArrayList(Rule) = .empty; for (mapping.entries) |entry| { const rule = try rules_cursor.child(entry.key); // M1-RULE-001. Duplicate names cannot reach here: the tree rejects // duplicate keys (D5), which is what keeps names unique in memory. if (entry.key.len == 0) return rule.fail("a rule name must not be empty", .{}); // M1-RULE-002. An unknown key is a schema error, not an action error, // so M1-RULE-013's tolerance does not extend to it. try rule.requireOnly(&.{ "match", "set" }); // A missing or non-string match leaves no condition to evaluate, which // M1-RULE-013 makes fatal for the complete candidate. const match = try (try rule.child("match")).string(); try list.append(arena, .{ .name = entry.key, .match = match, .action = try decodeAction(rule, diags), }); } return .{ .rules = list.items }; } /// Returns null after recording a diagnostic when the action cannot be used. /// Every failure path here is deliberately non-fatal (M1-RULE-013). fn decodeAction(rule: schema.Cursor, diags: *diag.List) Error!?Action { const set = (try rule.optionalChild("set")) orelse { try diags.addConfig( .{ .file = rule.file, .key_path = rule.path }, "rule has no 'set' action", .{}, ); return null; }; // M1-RULE-002: no action keys beyond these two. set.requireOnly(&.{ "targetAccount", "sourceAccount" }) catch return null; // M1-RULE-011: the destination comes from targetAccount. const target_cursor = set.child("targetAccount") catch return null; const target = target_cursor.string() catch return null; if (target.len == 0) { target_cursor.note("targetAccount must not be empty", .{}); return null; } var source: ?[]const u8 = null; if (try set.optionalChild("sourceAccount")) |cursor| { const text = cursor.string() catch return null; if (text.len == 0) { cursor.note("sourceAccount must not be empty", .{}); return null; } source = text; } return .{ .target_account = target, .source_account = source }; } // -- tests ------------------------------------------------------------------- const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; const expectEqualStrings = std.testing.expectEqualStrings; const expectError = std.testing.expectError; fn loadWith(arena: *std.heap.ArenaAllocator, body: []const u8) Error!Ruleset { const alloc = arena.allocator(); const diags = diag.List.create(alloc) catch return error.OutOfMemory; const source = alloc.print("schema:\n version: 1\nrules:\n{s}", .{body}) catch return error.OutOfMemory; return load(alloc, "rules.yaml", source, diags); } fn loadDiags(arena: *std.heap.ArenaAllocator, body: []const u8) !struct { diags: *diag.List, set: ?Ruleset, } { const alloc = arena.allocator(); const diags = try diag.List.create(alloc); const source = try alloc.print("schema:\n version: 1\nrules:\n{s}", .{body}); const set = load(alloc, "rules.yaml", source, diags) catch null; return .{ .set = set, .diags = diags }; } const one_rule = @embedFile("../testdata/config/one_rule.yaml"); test "M1-RULE-001: a rules file needs at least one rule" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); try expectError(error.InvalidConfig, loadWith(&arena, "")); } test "M1-RULE-001: an empty rule name is rejected" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); try expectError(error.InvalidConfig, loadWith(&arena, @embedFile("../testdata/config/empty_rule_name_is_rejected.yaml"))); } test "M1-RULE-001: duplicate rule names are rejected" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); try expectError(error.InvalidConfig, loadWith(&arena, @embedFile("../testdata/config/duplicate_rule_names_are_rejected.yaml"))); } test "M1-RULE-002: a rule takes exactly match and set" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); try expectError(error.InvalidConfig, loadWith(&arena, @embedFile("../testdata/config/a_rule_takes_exactly_match_and_set.yaml"))); } test "M1-RULE-002: match must be a string" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); try expectError(error.InvalidConfig, loadWith(&arena, @embedFile("../testdata/config/match_must_be_a_string.yaml"))); } test "M1-RULE-011: targetAccount carries the destination" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const set = try loadWith(&arena, one_rule); try expectEqual(@as(usize, 1), set.rules.len); try expectEqualStrings("groceries", set.rules[0].name); try expectEqualStrings("account == \"DE23\"", set.rules[0].match); try expectEqualStrings("expenses:food", set.rules[0].action.?.target_account); try expect(set.rules[0].action.?.source_account == null); } test "M1-RULE-012: a rule may override the profile default source account" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const set = try loadWith(&arena, @embedFile("../testdata/config/a_rule_may_override_the_profile_default_source_account.yaml")); try expectEqualStrings("assets:other", set.rules[0].action.?.source_account.?); try expectEqualStrings("assets:other", set.rules[0].sourceAccount("assets:default").?); } test "M1-RULE-012: without an override the profile default is used" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const set = try loadWith(&arena, one_rule); try expectEqualStrings("assets:default", set.rules[0].sourceAccount("assets:default").?); } test "M1-RULE-013: a missing action keeps the condition evaluable" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const result = try loadDiags(&arena, @embedFile("../testdata/config/a_missing_action_keeps_the_condition_evaluable.yaml")); const set = result.set.?; try expectEqual(@as(usize, 1), set.rules.len); try expectEqualStrings("x == \"1\"", set.rules[0].match); try expect(set.rules[0].action == null); try expect(!result.diags.isEmpty()); } test "M1-RULE-013: an invalid action keeps the condition evaluable" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const result = try loadDiags(&arena, @embedFile("../testdata/config/an_invalid_action_keeps_the_condition_evaluable.yaml")); const set = result.set.?; try expectEqual(@as(usize, 2), set.rules.len); try expect(set.rules[0].action == null); try expect(set.rules[1].action == null); // Both conditions survive, which is the whole point of M1-RULE-013. try expectEqualStrings("x == \"1\"", set.rules[0].match); try expectEqualStrings("x == \"2\"", set.rules[1].match); try expect(!result.diags.isEmpty()); } test "M1-RULE-013: one broken action does not break its neighbours" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const result = try loadDiags(&arena, @embedFile("../testdata/config/one_broken_action_does_not_break_its_neighbours.yaml")); const set = result.set.?; try expect(set.rules[0].action == null); try expectEqualStrings("expenses:food", set.rules[1].action.?.target_account); } test "M1-RULE-002: sourceAccount must be a string when present" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const result = try loadDiags(&arena, @embedFile("../testdata/config/source_account_must_be_a_string_when_present.yaml")); try expect(result.set.?.rules[0].action == null); } test "rules are retained in source order" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const set = try loadWith(&arena, @embedFile("../testdata/config/rules_are_retained_in_source_order.yaml")); try expectEqualStrings("zebra", set.rules[0].name); try expectEqualStrings("alpha", set.rules[1].name); try expectEqualStrings("alpha", set.find("alpha").?.name); try expect(set.find("absent") == null); } test "the shipped example rules file loads" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const alloc = arena.allocator(); const diags = try diag.List.create(alloc); const set = try load(alloc, "rules.yaml", @embedFile("example_rules_yaml"), diags); try expectEqual(@as(usize, 1), set.rules.len); try expectEqualStrings("groceries", set.rules[0].name); try expectEqualStrings("expenses:food", set.rules[0].action.?.target_account); try expectEqualStrings("assets:bank:something", set.rules[0].action.?.source_account.?); } test "M1-TPL-012: an account is a static string, never a template" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const alloc = arena.allocator(); const diags = try diag.List.create(alloc); const set = try load( alloc, "rules.yaml", @embedFile("../testdata/config/an_account_is_a_static_string_never_a_template.yaml"), diags, ); // Braces survive verbatim: nothing parses an account as a template, so // templates cannot construct account names. try expectEqualStrings("expenses:{posting}", set.rules[0].action.?.target_account); } test "M1-TPL-001: a rule cannot override the narration template" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); // narrationTemplate is a profile setting. M1-RULE-002 admits only // targetAccount and sourceAccount in an action, so a rule that tries to // carry one is refused rather than silently ignored. const result = try loadDiags(&arena, @embedFile("../testdata/config/a_rule_cannot_override_the_narration_template.yaml")); try expect(result.set.?.rules[0].action == null); }