cli: add deterministic source formatter

This commit is contained in:
dev committed 2026-10-07 18:21:06 +03:00
1 parent d901d5227b
commit 462ddd2c5c
14 files changed
+787 -13

No files matched your search

+2
View File
@@ -140,3 +140,5 @@ RFC 0036 (Proposed), explicit source borrow returns (cl100k, relative to paths):
2026-10-07 review documentation follow-up: the historical layout is now labeled, Q-016 states the implemented reserved status, and Quick Reference explicitly excludes floating point. The last sentence adds 46 cl100k tokens: Quick Reference 8,642 → 8,688 (+0.53%), other source docs stay 64,160, full source 72,802 → 72,848 (+0.06%). o200k groups are 8,723 / 64,359 / 73,082; Qwen2.5 8,954 / 65,733 / 74,687. AIR stays 46,300 cl100k tokens / 179,282 bytes; library/std.md stays 26,454 cl100k tokens. The clarification reduces status ambiguity without adding language semantics. RFCs 0037/0038 are Proposed and outside the bundles; their normative integration growth is not measured yet.
RFC 0036 review fixes clarify reserved task borrow returns and known array bounds in unused generic signatures. These rules add 54 cl100k tokens: other source docs 64,160 → 64,214, full source 72,848 → 72,902 (+0.07%); Quick Reference stays 8,688. o200k groups are 8,723 / 64,413 / 73,136; Qwen2.5 8,954 / 65,794 / 74,748. language/ownership.md is 1,873 cl100k tokens; AIR and library/std.md stay unchanged. The additions make source rejection predictable without adding a semantic feature.
P6-8 source formatter (cl100k): Quick Reference 8,688 → 8,728 (+40), other source docs 64,214 → 64,677 (+463), full source 72,902 → 73,405 (+0.69%). language/tooling.md is 3,051 tokens. o200k groups are 8,763 / 64,876 / 73,639; Qwen2.5 8,994 / 66,259 / 75,253. AIR stays 179,282 bytes / 46,300 cl100k tokens, and library/std.md stays unchanged. One command with check/write modes reduces whitespace repair and diff noise while preserving tokens, comments and canonical AIR; it adds no language concept, feature, verifier/runtime state or diagnostic code. No empirical MCC benefit is claimed.
+1 -1
View File
@@ -1,6 +1,6 @@
# Aji Quick Reference (`.aji` 0.1)
Read this first; it covers most programs. Where to find the full rules is at the end. Every example below is part of a program the conformance suite checks. `aji check file.aji` verifies, `aji run file.aji` verifies and runs, `aji lower file.aji` prints the AIR it becomes. Diagnostics are JSON lines; fix the first one first.
Read this first; it covers most programs. Where to find the full rules is at the end. Every example below is part of a program the conformance suite checks. `aji check file.aji` verifies, `aji run file.aji` verifies and runs, `aji lower file.aji` prints the AIR it becomes. `aji fmt file.aji` prints formatted source; `--check` checks formatting, `--write` replaces the file. Formatting preserves tokens and comments; it does not verify or repair code. Diagnostics are JSON lines; fix the first one first.
Aji makes every significant action explicit — moves, borrows, allocation, closing, authority, effects, tasks, channel transfers, locking, cancellation, every failure outcome — and checks them all before running. The compiler writes the mechanics: SSA, control flow, borrow ends, frame storage, the feature header.
+4
View File
@@ -291,3 +291,7 @@ STD-6d.2 needs to return allocation-size validation failure without allocating.
General collections and algorithms need explicit typed hash/equality/order operations, while current generics carry only types.
**Resolved contract (RFC 0029 Implemented):** spec 15 §18 permits explicitly selected source functions as static parameters with exact typed/effect contracts. Selection is part of nominal specialization identity and lowers to existing named AIR calls/workers. No function pointers, capture environment, inferred effects or runtime dispatch are introduced. Q-037 is resolved by the implemented and verified generic map/set contracts (RFCs 0030/0031).
## Q-040 — Block statements followed by unary-leading expressions
P6-8 review found an existing parser ambiguity: `if true { *p = 2u64; } *p = *p + 1u64;` is consumed as an expression continued by multiplication and then rejects E7006 at the assignment. The same failure is reproduced after a standalone block or `match`; `while` dispatches separately and is not affected. Source whitespace is insignificant; spec 15 §4 and the grammar admit both block statements and expressions beginning with block/control-flow forms. The intended disambiguation must be specified before changing which previously parsed expressions are accepted. Decide how a standalone block statement ends before a dereference/other unary-leading statement while preserving block-valued expressions in explicit expression contexts. Add positive/rejected parser and lowering cases for the chosen rule. The formatter preserves the current tokens/AST and MUST NOT insert semicolons or infer the intended statement boundary. This question is separate from P6-8.
+1 -1
View File
@@ -141,7 +141,7 @@ Targets for Phase 6A, measured on dev tasks:
## Standard library track
At the owner’s request (2026-10-06), reusable std APIs were implemented in a separate work branch. On 2026-10-07 the owner requested adoption/merge of the completed STD-0..7 intermediate foundation and resumption of source-language work; Q-034/P6-11 is implemented for review (RFC 0036 Proposed). Larger syntax/contracts work retains its separate spec gate. Remaining std milestones stay in the backlog. [Standard library plan](standard-library.md) defines the bootstrap, prerequisites (`linear_aggregates`, general modules and generics), Std 0.1/0.2/0.3 and the public integration gate. P7/P8 remain on hold pending B1 analysis; this track does not change frozen evaluation inputs.
At the owner’s request (2026-10-06), reusable std APIs were implemented in a separate work branch. On 2026-10-07 the owner requested adoption/merge of the completed STD-0..7 intermediate foundation and resumption of source-language work; Q-034/P6-11 is implemented for review (RFC 0036 Proposed), and P6-8 implements the source formatter. The existing block-statement ambiguity Q-040 is recorded for P6-1/P6-2; larger syntax/contracts work retains its separate spec gate. Remaining std milestones stay in the backlog. [Standard library plan](standard-library.md) defines the bootstrap, prerequisites (`linear_aggregates`, general modules and generics), Std 0.1/0.2/0.3 and the public integration gate. P7/P8 remain on hold pending B1 analysis; this track does not change frozen evaluation inputs.
## Task conventions
+8 -2
View File
@@ -137,7 +137,7 @@ Lowering layers (P6A-3/4), each with accepted (golden AIR), rejected (`E7xxx`) a
| P6-5 | todo | Lowering to AIR: control flow, `?`, `defer` cleanup edges, borrow blocks, task scopes | P6-4 | `src/frontend/lower.zig` | lowered AIR verifies; lowering is a pure function (same input ⇒ same AIR bytes) |
| P6-6 | todo | Contracts: `requires`/`ensures`/invariants → contract table; status classification | P6-5 | frontend + verifier | each contract reported as PROVEN_STATICALLY / CHECKED_AT_RUNTIME / ASSUMED_UNSAFE / UNPROVEN |
| P6-7 | todo | Source spans in diagnostics for verifier errors on lowered AIR | P6-5 | `src/diag.zig`, lowering | every conformance reject test has a source-level twin with the same code |
| P6-8 | todo | Formatter | P6-2 | `aji fmt` | idempotent; output parses to the same AST |
| P6-8 | done | Formatter for implemented source syntax | P6-2 | `aji fmt`, spec 15 §11 | token/comment/declaration preservation; idempotence, identical AIR and CLI write/check tests |
| P6-9 | todo | Port reference programs and examples to `.aji` | P6-5 | `tests/programs/`, `examples/` | exit criterion passes |
| P6-11 | done (implementation; RFC 0036 Proposed) | Source functions/calls returning borrows with explicit `from` origin; Q-034 | P6-3/4 | spec 15, binding/call/return lowering, Quick Reference and source/AIR conformance | origin/lifetime and temporary-end rules specified; valid/rejected returned views use existing verifier/interpreter semantics |
| P6-10 | todo | Phase exit review | all | plan status | exit criterion passes |
@@ -149,4 +149,10 @@ The [standard-library track](standard-library.md) implements nineteen compiler-p
RFC 0036 remains Proposed for owner adoption; its spec integration and implementation are prepared together. Borrow functions preserve explicit origins through ordinary/generic/package calls; exact-mode ref/mut bindings retain a named parent. Named returns transfer only their owned ancestor chain, and ordinary verifier/interpreter semantics decide provenance, aliasing, task loans and traps. Static function parameter borrow contracts and borrow joins stay outside this task.
Validation: full conformance 1,135/1,135 with no failures or pending tests; 56 focused conformance cases including a frozen Phase 1 AIR twin and four canonical AIR goldens; per-step collection and 200 schedule seeds across four quanta for the concurrent fixture; 61 generic regression cases; unit tests, format and bundle/example checks; CLI integration 133 checks, generic/module integration 20/36 checks, hosted smoke. Independent read-only review by Claude found a misleading feature diagnostic when spawning a borrow-returning function and missing array bounds in unused generic signatures. Both were fixed and independently rechecked. Added cases cover those failures, valid generic bounds, normal scope/shield/lock returns, an unjoined task and lock-guard escape. Source construct coverage is 119/119. Quick Reference/source budget is recorded in RFC 0036 and docs/agent/README.md. Larger syntax/contracts work still needs its separate spec gate.
Validation: full conformance 1,135/1,135 with no failures or pending tests; 56 focused conformance cases including a frozen Phase 1 AIR twin and four canonical AIR goldens; per-step collection and 200 schedule seeds across four quanta for the concurrent fixture; 61 generic regression cases; unit tests, format and bundle/example checks; CLI integration 133 checks, generic/module integration 20/36 checks, hosted smoke. Independent read-only review by Claude found a misleading feature diagnostic when spawning a borrow-returning function and missing array bounds in unused generic signatures. Both were fixed and independently rechecked. Added cases cover those failures, valid generic bounds, normal scope/shield/lock returns, an unjoined task and lock-guard escape. Source construct coverage is 119/119. Quick Reference/source budget is recorded in RFC 0036 and docs/agent/README.md. P6-8 is implemented below; larger syntax/contracts work still needs its separate spec gate.
## P6-8 formatter (2026-10-07)
`aji fmt` formats one source file without linking, specializing, verifying or running it; `--check` emits a JSON status, and explicit `--write` atomically replaces a regular file while preserving permissions. Libraries and semantically rejected programs remain formattable. Original token spellings, comments and declaration order are retained; output is re-tokenized before exposure, and layout traversal is iterative. No syntax, AIR feature, verifier/runtime state or diagnostic code is added. Invalid syntax reports the existing E7001. The CLI contract and layout are spec 15 §11; the public-corpus/CLI script runs in CI.
Validation: unit tests and Zig formatting pass, including 10,000-term expressions, comments/CRLF, continuation indentation and statement groups. The formatter CLI suite passes 3,146 checks over 853 public files: 844 parse and format idempotently, nine existing syntax-error fixtures report E7001, and 548 successful lowerings retain byte-identical AIR. The suite also checks explicit writes, unchanged inode/mtime, permissions, symbolic/hard links, FIFO rejection, JSON/exit codes and a source run. Full conformance remains 1,135/1,135. Independent read-only review by Claude identified layout/comment handling defects; fixes were independently rechecked and covered by unit cases. Original source files are not rewritten. Documentation budgets are recorded in docs/agent/README.md. Review found the separate existing block-statement ambiguity Q-040; resolving its syntax belongs to P6-1/P6-2 and is not inferred by the formatter. This increment does not complete Phase 6.
+7
View File
@@ -426,11 +426,18 @@ Its diagnostics keep their AIR codes, reported at the source location.
| `aji lower file.aji` | print the canonical AIR |
| `aji lower --stats file.aji` | source and AIR size, expansion ratios and the two `mechanical_air_eliminated` metrics below |
| `aji lower --annotate file.aji` | the same with `; line:col-line:col` source spans before each instruction (not canonical; for debugging) |
| `aji fmt file.aji` | print formatted source; leave the file unchanged |
| `aji fmt --check file.aji` | emit a JSON format record; exit 0 if formatted, 1 if formatting is needed |
| `aji fmt --write file.aji` | atomically replace a regular file when needed; emit a JSON format record |
`check`, `lower`, `report`, `run` and `explore` also accept `--manifest PATH` for explicit package inputs (§14, spec 12 §1.3). Check/lower/report do not instantiate grants.
Lowering is deterministic: the same source inputs and compiler give byte-identical AIR, and the lowered AIR is canonical (parse → print reproduces it). The conformance runner checks both for every accepted `.aji` test.
**Source formatting.** `fmt` MUST parse one `.aji` file without linking, specializing, verifying or executing it. Libraries without `main`, unresolved imports and semantically rejected programs MAY be formatted. A syntax error MUST produce the existing E7001 JSON diagnostic and exit 1, with no formatted output or file modification; usage/I/O errors or an internal token-preservation failure exit 2 with a note on stderr. There is no manifest/directory discovery. `--check` and `--write` are mutually exclusive. Their record is `{ "file": PATH, "status": "formatted" | "needs_format", "changed": BOOL }`; `changed` reports whether the input differs from the formatted bytes, and `--write` reports `formatted` after a successful write. An unchanged file MUST NOT be rewritten. `--write` MUST preserve file permissions and reject non-regular files, including symbolic links. Atomic replacement changes one directory entry; other hard links retain the previous contents.
Formatting MUST preserve the ordered token spellings, comment contents (including trailing spaces/tabs, apart from terminal CR bytes normalized to LF) and declaration order, changing only whitespace between tokens and around comments. The result MUST parse to the same AST, ignoring source positions, and formatting it again MUST be byte-identical. Thus ownership/effects/capabilities, literal bytes, operator grouping and generated AIR remain unchanged; source diagnostic positions follow the formatted text. The reference layout uses LF, one final newline, four-space block/continuation indentation, expanded declaration/match bodies and compact struct literals. It retains at most one existing blank line between statements. Operators are spaced, type/application angles and paths are compact, and commas separate inline lists or start the next line in expanded bodies. Comments remain at their token boundary; trailing comments stay with the preceding token. Formatting MUST NOT introduce a line-width limit, reorder effects/imports or repair code.
**Size metrics** (`--stats`, non-normative tooling with a fixed definition):
- With `--manifest`, source sizes count the entry file only; AIR sizes count the combined module. These ratios MUST NOT be interpreted as whole-package compression.