csv2journal Code Style #
This document is about the shape of the code, as distinct from PROCESS.md, which is about how work is done. It is binding on the same terms.
0. Where this came from #
Milestone one was largely written by an agent. It passed its tests, it passed nix flake check, and
the author then spent a series of commits — every one of them prefixed refa: — reshaping it by
hand without changing a single behaviour.
Every rule below is one of those diffs, generalised. They are not aesthetic preferences. They are the recurring ways the generated code failed §1 of PROCESS.md: maintainable without an LLM. An agent reading this should treat each section as a defect class it is known to produce, and check its own output against them before proposing a commit, not after the author has to.
The two headline faults, in the author's words: duplication, and code that is not local to what it operates on.
1. Locality #
Code lives with the data it operates on. A function that has one struct's fields as its whole subject is a method on that struct.
1.1 Verb-shaped modules are a smell #
journal/emit.zig, journal/compare.zig and journal/model.zig all existed, holding
emit(Journal), emit(Transaction), emit(Posting), compare(Journal), compare(Transaction),
compare(Posting). Three modules organised by what the code does, cutting across three types.
Changing Posting meant touching three files.
They are gone. Posting emits a posting, Transaction emits a transaction and delegates,
Journal emits a journal and delegates. Each type answers for the part of the format it defines.
One file per type, containing everything that type does.
Organise by noun, not by verb. If you are about to create validate.zig, render.zig,
convert.zig or helpers.zig, the functions in it almost certainly belong on the types they take.
The limit, so this is not over-applied: a module that is not a type is legitimate when what it holds
is genuinely shared and has no better owner — an error set three types return, a constant two of
them read — and when it is named for what it holds. utils.zig and helpers.zig are named for
nothing. They are where declarations end up when no one decided where they belong, and they grow.
1.2 Free functions that serve one type #
isIdentifier, isKeyword and isDigit sat at the top level of expr/lexer.zig, beside the
Lexer they exist for. They are now Lexer.isIdentifier, Lexer.isKeyword, Lexer.isDigit.
Callers import the type, not the module:
const Lexer = @import("../expr/lexer.zig").Lexer; // yes
const lexer = @import("../expr/lexer.zig"); // only for a real namespace
1.3 A file whose contents are one struct is that struct #
Zig's convention, and this repository's: when a file's top level is a single type, name the file in
CapitalCase, drop the wrapper, use @This().
// src/config/Manifest.zig
const Manifest = @This();
input_path: []const u8,
rules_file: []const u8,
Not manifest.zig containing pub const Manifest = struct { ... }, and not project.zig
containing pub const Opened = struct { ... } — that one became ui/Project.zig, a Project.
src/Journal.zig beside src/journal/ shows the pairing: the type file is the entry point and
re-exports what belongs to its subtree (pub const Transaction, pub const parse).
1.4 Validate where the data enters #
accountProblem was checked in the emit stage. Emission is the last thing that happens; by then an
invalid account has been carried through classification, templating and history comparison, and the
emit stage needs a diagnostic dependency it should not have.
It now runs in Posting.parse, which returns a ParseResult union rather than an error, leaving
the caller to phrase the diagnostic. Check invariants at the boundary that constructs the value, so
everything downstream can rely on them.
2. Duplication #
// TODO harmonize with Xis not an outcome. It is an unfinished commit.
2.1 Two structs with the same fields are one struct #
ui/editor.zig held Wire; ui/state.zig held RuleView; identical fields, one for the request
body and one for the response payload, each carrying a TODO pointing at the other. They are one
editor.Wire now, pub, documented as being both directions — and M1-UI-008 requires them to
agree, so the duplication was a latent bug, not only noise.
If you find yourself writing a TODO that says two things should be unified, unify them in that commit or do not write the second one.
2.2 A repeated call sequence is a missing constructor #
readFileToBytes → Manifest.load → verifyInputRoot appeared at two call sites, in that order,
with the same error handling. It is now Manifest.loadFromFileVerified, one call. The name says
what you get, and it is impossible to perform two of the three steps.
2.3 A repeated incantation is a missing method #
A dozen call sites across the tree did this:
const message = try std.fmt.allocPrint(arena, "'{s}' {s}", .{ path, what });
try diags.add(.{ .message = message, .file = path });
diag.List already owns an arena. diag.List.addFmt(fmt, args, .{ .file = path }) replaced all of
them — and with it, the arena parameter of every function that had only ever needed it to build
that message. See §3.
The rule of thumb: the same two lines in three places is a method on the type that owns the data.
2.4 Parse once, pass the value #
Session.open took a manifest_path and parsed the manifest; so did cli.run; so did
Project.open. Session.open now takes manifest: *const Manifest, and the manifest carries its
own manifest_path so nothing has to be threaded alongside it.
Pass the parsed thing down. A function that takes a path and re-reads what its caller already has is duplicated work and a second chance to disagree.
2.5 Test fixtures deduplicate like anything else #
ApiFixture and PreviewFixture in ui/server.zig differed only in which two YAML blobs they
wrote. One Fixture.init(project_yaml, rules_yaml) plus two small make*Fixture() helpers replaced
both. Tests are held to the same standard as the code they justify; the // -- tests divider
exempts them from the line count, not from review.
3. Allocators #
The fewer allocations, the better. An allocator parameter that exists only to build a string is dead weight in every signature it passes through.
Most of the journal code took an arena for no reason that survived inspection. Removing it was not a micro-optimisation — it shortened signatures, removed error cases, and made the types usable from places that have no arena to hand.
Two moves do most of the work:
- Let the type that owns an arena do the allocating (
diag.List.addFmt, §2.3). - Format into a writer instead of building a string (§4).
Before adding an arena: std.mem.Allocator parameter, check whether the value can be produced
lazily instead of materialised.
4. Use the standard interface #
Bespoke rendering methods — Decimal.render(buf), Currency.text(), Date.render(buf),
Posting.emit(arena, out), parser.render(arena) — were each replaced by the standard one:
pub fn format(self: Decimal, writer: *std.Io.Writer) std.Io.Writer.Error!void
used as {f}. What that bought, every time: no caller-supplied buffer and no max_render_len to
keep in sync, no allocator, composition for free ("date differs: approved {f}, candidate {f}"
instead of two scratch buffers), and std.testing.expectFmt in the tests.
When a type needs a second rendering that is not its canonical one, give it a named formatter struct rather than a second method with a different signature:
pub const JournalFormatter = struct {
posting: *const Posting,
pub fn format(self: JournalFormatter, writer: *std.Io.Writer) std.Io.Writer.Error!void { ... }
};
Posting.JournalFormatter, Transaction.JournalFormatter and Journal.JournalFormatter are all
this shape, and they nest through {f} like any other value.
The same principle holds beyond formatting: prefer the interface std already defines over one
invented for this codebase.
5. Construct fully, once #
Session.open created the struct with undefined, empty strings and zeroes, then handed the
half-built thing to a top-level load() that filled the fields in. Two functions, one of them
reaching into the other's value, and a window in which the struct was a lie.
It is now a single struct literal — if-expressions inline where a field is conditional — and the
load helper is gone. Build the value completely in one expression. undefined is a linter error
here for exactly this reason.
6. Errors are never dropped #
catch {} and catch unreachable are linter errors (no_swallow_error). Every occurrence must
become one of:
catch return error.OutOfMemory(or whatever it really is) — propagate;- a genuine handler;
// zlinter-disable-next-line no_swallow_error - <the reason>— and the reason must be an argument, not a shrug. The accepted ones in this tree are: a cleanup failure must not mask the failure that caused the cleanup; abufPrintwhose buffer is provably large enough; a diagnostic-recording path that is infallible by design.
Note what the fix commit also did: the newly propagated OutOfMemory paths came with
M1-SAFE-004: ... tests driving them through std.testing.FailingAllocator. Changing an error path
means testing the error path.
7. Comments #
- Doc comments explain why, and cite the requirement ID that forced the decision. That style is already pervasive and correct; keep it.
- Do not narrate imports.
root.zighad a paragraph above eachpub const, restating the module's own header. All of it was deleted. - Do not leave a
TODObehind.no_todois on. If the work is real, do it or record it in DESIGN_M1.md §11. no_comment_out_codeis an error. Commented-out code is deleted code.
8. Naming and mechanics #
zig build lint (also run by nix flake check) is authoritative. The rules that most often catch
generated code:
| Rule | What it means in practice |
|---|---|
declaration_naming, field_naming |
No one- or two-letter names. const a = arena.allocator() → alloc; const d = list.items[0] → first_diag. |
field_ordering |
Struct, enum and union fields are alphabetical. |
max_positional_args |
Group related parameters into a named struct (RowSite, Matched) rather than a long positional list. |
no_unsafe_undefined |
See §5. |
no_inferred_error_unions |
State the set the function really returns, inline: error{OutOfMemory}!bool. A module-wide pub const Error is for a set the module's functions genuinely share, not a convenient union to hang on everything. |
require_exhaustive_enum_switch, switch_case_ordering |
No else => catch-alls over an enum you own. |
no_hidden_allocations, no_global_vars, no_panic |
As they say. |
Run it before describing a change. A commit that needs a linter fix afterwards was not finished.
9. Commit shape for refactoring #
Refactoring commits carry no requirement ID. They use a refa: prefix, and otherwise follow
PROCESS.md §3 exactly: one logical concern, the why in the body, no trailers.
refa: move the emit functionality (for journals) to the appropriate structs
Prior to this change, all of it was contained in journal/emit.zig.
This change makes each structure responsible for the part it wants
to emit. This makes coupling of the related code much better.
A refactor changes no behaviour, so it usually carries no new test — the existing tests move with
the code they justify, and the suite is green at every commit, as always. The exception is when
collapsing a duplicate makes an invariant testable that was not before: merging Wire and
RuleView added the M1-UI-008 test asserting the payload and the PUT body share one shape. Removing
the duplication is what made that assertion possible, so it belongs in the same commit.
10. Before proposing a commit #
- Does any function take a struct's fields as its whole subject without being a method on that struct? (§1.1, §1.2)
- Is there a second thing with the same fields, or a second copy of the same call sequence? (§2)
- Does every
arenaparameter actually do something the callee could not do without it? (§3) - Is anything rendered by hand that
pub fn formatand{f}would render? (§4) - Is any value built in two stages, or initialised
undefined? (§5) - Is any error dropped without a written reason? (§6)
- Any
TODO, any commented-out code, any comment restating the line below it? (§7) - Does
zig build lintpass? (§8)