# csv_utils — Parsing Implementation Tasks Ordered, dependency-aware task list for implementing the design in `design.md`. Run `zig build test` after every task. --- ## Phase 1 — Foundations - [x] (required) **Task 1: Implement `Dialect` and its validator.** In `src/dialect.zig`, replace the stub with the `Dialect` struct (`delimiter`, `quote_char`, `strip_bom: bool = true`). Drop the `trim` field (out of scope). Add `pub fn validate(self: Dialect) Error!void` per design. Unit tests: default dialect is valid; delimiter == quote_char → `InvalidDialect`; delimiter or quote equal to `\n` or `\r` → `InvalidDialect`. - [x] (required) **Task 2: Expand the unified `Error` set.** In `src/error.zig`, replace the stub with the full set: `UnterminatedQuotedField`, `UnexpectedQuote`, `UnexpectedByteAfterQuote`, `FieldTooLong`, `RowTooWide`, `InvalidDialect`, `UnknownHeader`, `DuplicateHeader`, `RowWidthMismatch`, `OutOfMemory`, unioned with `std.Io.Reader.Error`. No tests needed. --- ## Phase 2 — The state machine - [x] (required) **Task 3: Implement `FieldIterator` core.** In `src/field_iterator.zig`, implement the state machine from the design's transition table. States: `start`, `field_start`, `in_unquoted`, `in_quoted`, `after_quote`, `eof`, `failed`. Internal flags: `last_was_row_end`, `bytes_consumed`, `pending_error`. `init` calls `dialect.validate()`. `next()` uses `reader.peekByte()` for `\r`/`\n` and doubled-quote lookahead; uses `reader.peek(3)` + `discardAll(3)` for lazy BOM strip on the first call from `.start`. Byte-at-a-time correctness first; no chunked fast path yet. Sticky `failed` state. - [ ] (optional) **Task 4: Add chunked fast path to `FieldIterator`.** Inside `in_unquoted` / `in_quoted`, use `reader.peek(n)` / `take(n)` to copy runs of non-structural bytes into `field_buf` in bulk, falling back to byte-at-a-time when the next byte is structural. Goal: N-8 (avoid per-byte call overhead). Verified by reusing Task 5's tests unchanged. - [x] (required) **Task 5: Test `FieldIterator` exhaustively.** Table-driven tests `(input, dialect, expected_fields, expected_error)`. Cover: empty input (correctness #7); `"\n"`, `"\r"`, `"\r\n"` (correctness #8); `"a\n"`, `"a\nb\n"` (correctness #9); `",,"` / `"a,,c"` (correctness #6); quoted fields with embedded delimiter / `\n` / `\r` / `\r\n` / doubled quote (correctness #3–5); each malformed-input error (correctness #11–13); sticky-error retry returns same error (correctness #14); non-default dialects (tab, semicolon, alternative quote); `Dialect.validate` failures via `init`; field exactly fills buffer and one byte too large (`FieldTooLong`); BOM-on stripping; BOM-off preserving; BOM-only input yields 0 rows. --- ## Phase 3 — Row iterator family - [x] (required) **Task 6: Define the shared `Row` type.** In `src/row_iterator.zig`, declare `pub const Row = struct { fields: []const []const u8, ... }` with `count()` and `at(i)`. Document the lifetime contract on `fields` ("invalidated by the next call on the iterator"). - [x] (required) **Task 7: Implement `RowIterator` (allocating).** Wraps a `FieldIterator`; backs its row-slot list with a `std.ArrayListUnmanaged([]const u8)` using a caller-provided allocator. Signature: `init(reader, field_buf, allocator, dialect) Error!RowIterator`, plus `deinit` and `next`. No `RowTooWide` path — width is unbounded. - [x] (required) **Task 8: Implement `BoundedRowIterator(comptime N)`.** Generic function returning a struct with an inline `[N][]const u8` row buffer and a `row_len: usize` cursor. Signature: `init(reader, field_buf, dialect) Error!Self`, plus `next`. Returns `error.RowTooWide` when a row exceeds `N`. Also export `pub const default_max_fields: usize = 64;`. - [x] (required) **Task 9: Implement `FixedBufferRowIterator`.** Same shape as `BoundedRowIterator` but with a caller-provided `[][]const u8` row buffer. Signature: `init(reader, field_buf, row_buf, dialect) Error!Self`, plus `next`. - [x] (required) **Task 10: Test the row-iterator family.** Shared corpus exercised by all three variants in parallel (parameterised helper) to confirm they produce identical `Row`s. Include: `RowIterator` under `std.testing.allocator` (leaks fail the suite); `BoundedRowIterator(4)` triggering `RowTooWide` on a 5-field input; `BoundedRowIterator(default_max_fields)` on a happy path; `FixedBufferRowIterator` with a 4-slot caller buffer (RowTooWide + happy path); `Row.at(i)` returns null for `i >= count()`. --- ## Phase 4 — Header-aware iterator - [x] (required) **Task 11: Implement `HeaderIterator`.** Wraps an allocating `RowIterator`. Reads one row at `init` and `dupe`s each header string into the iterator's allocator. `HeaderRow` struct with `at(i)`, `get(name)` (linear scan), `count()`. `strict_width` option: on `next()`, if `row.count() != headers.len`, set sticky `pending_error = RowWidthMismatch` and return it. `deinit` frees headers and calls `row_iter.deinit()`. Empty input → iterator whose `next()` always returns null and whose `headers.len == 0`. - [x] (required) **Task 12: Test `HeaderIterator`.** Header capture from a 3-column input; `get(name)` returns matching field, returns null for unknown name and for short rows; duplicate headers → first-wins via `get`; `strict_width = false` accepts ragged row, `get` for absent column returns null; `strict_width = true` returns `RowWidthMismatch` (sticky); all under `std.testing.allocator`. --- ## Phase 5 — Materialising tiers - [x] (required) **Task 13: Implement `Table`.** Owns an `ArenaAllocator(child_allocator)`. All per-row and per-field allocations go through the arena. `parse`: validate dialect; create arena with `errdefer arena.deinit()`; allocate 4 KiB initial `field_buf` in arena; construct internal `RowIterator` using `arena.allocator()`; loop, copying each row into the arena (`dupe` each field, allocate row slice); finish with `toOwnedSlice` on the row list. `deinit` calls `arena.deinit()`. Oversize single field → propagate `FieldTooLong` (Task 14 adds doubling-buffer growth). - [ ] (optional) **Task 14: Doubling-buffer growth in `Table` / `HeaderTable`.** Implement the design's strategy: track previous row's max field size and double `field_buf` when it exceeds half the current capacity. Add a `max_field_size: usize = 16 << 20` cap to `Table.Options`. Surface `FieldTooLong` only when a single field exceeds the cap. Resolves open question O-1. - [x] (required) **Task 15: Test `Table`.** Empty input → 0 rows; `"a,b\n1,2\n"` → 2 rows × 2 fields with correct contents; mid-parse error (`"\"unterminated"` → `UnterminatedQuotedField`) leaks nothing under `std.testing.allocator`; a sanity test that returned slices remain valid after subsequent arena operations. - [x] (required) **Task 16: Implement `HeaderTable`.** Define `DuplicatePolicy { error, first_wins, last_wins }` and `WidthPolicy { strict, permissive }`. `Options` struct with `dialect`, `on_duplicate = .error`, `width = .permissive`. `parse`: validate dialect; create arena; read header row, `dupe` into arena; build a `StringHashMapUnmanaged(usize)` honouring `on_duplicate`; read remaining rows (under `strict`, error on width mismatch; else append as-is). `columnIndex(name)` is a map lookup; `get(row, name)` returns the cell or null. - [x] (required) **Task 17: Test `HeaderTable`.** Happy path: 3-column file, `columnIndex` and `get` correct. `on_duplicate`: `.error` → `DuplicateHeader` on `"a,a\n1,2\n"`; `.first_wins` → `get(row, "a")` resolves to first column; `.last_wins` → resolves to last column. `width`: `.permissive` accepts `"a,b\n1\n"` and `get(0, "b")` returns null; `.strict` returns `RowWidthMismatch` on the same input. All under `std.testing.allocator`. --- ## Phase 6 — Public surface & wiring - [x] (required) **Task 18: Update `root.zig` re-exports and wrappers.** Re-export `Dialect`, `Error`, `Row`, `FieldIterator`, `RowIterator`, `BoundedRowIterator`, `FixedBufferRowIterator`, `default_max_fields`, `HeaderIterator`, `Table`, `HeaderTable`. Convenience wrappers (all return `Error!T` where applicable): `rows(reader, field_buf)` → `BoundedRowIterator(default_max_fields)`; `rowsAlloc(reader, field_buf, allocator)` → `RowIterator`; `headerRows(reader, field_buf, allocator)` → `HeaderIterator`; `parseTable(reader, allocator)` → `Table`. Keep the `test {}` block pulling in every submodule. - [x] (required) **Task 19: Doc-comment audit.** Every `pub` declaration in every module must have a doc comment covering purpose, parameters, return value, error conditions, and any ownership/lifetime contract on returned slices (N-11). Pay special attention to `Row.fields` lifetime, `FieldIterator.next` result lifetime, `HeaderIterator.deinit` ownership, and `Table`'s arena lifetime tied to the `Table` value. - [x] (required) **Task 20: Per-tier runnable examples in `root.zig`.** One runnable example per parser tier (N-12), as `test "example: "` blocks so the compiler checks them: `FieldIterator`, `BoundedRowIterator`, `RowIterator` (allocating), `HeaderIterator`, `Table`, `HeaderTable`. --- ## Phase 7 — Verification - [x] (required) **Task 21: Verify acceptance-criterion coverage.** Cross-reference every numbered acceptance criterion in `requirements.md` (Stories 1–6) and every parsing-correctness requirement (#1–19) against ≥1 passing test (N-13). Add a short trailing comment to each test indicating which requirement(s) it covers. Add tests for any requirement not yet covered. - [x] (required) **Task 22: Final `zig build test` clean run.** `zig build test` passes with zero failures and no leaks reported by `std.testing.allocator`. Grep + manual review confirms no `@panic`, `unreachable`, or `std.process.fatal` is reachable from any public API path. - [ ] (optional) **Task 23: Resolve or defer remaining open design questions.** For each of O-1, O-2, O-2a, O-3, O-4 in `design.md`, either resolve (capture the resolution in a code comment near the affected declaration) or explicitly defer (TODO comment referencing the open question).