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

+1
View File
@@ -23,6 +23,7 @@ jobs:
- run: python3 tests/hosted/source_modules.py
- run: python3 tests/hosted/source_generics.py
- run: python3 tests/hosted/source_borrow_returns.py
- run: python3 tests/hosted/source_format.py
- run: python3 tests/hosted/source_static_functions.py
- run: python3 tests/hosted/source_linear.py
- run: python3 tests/hosted/source_buffers.py
+1
View File
@@ -19,6 +19,7 @@ python3 tests/hosted/smoke.py # hosted profile against the real OS
python3 tests/hosted/source_modules.py # explicit package CLI and file-loading contracts
python3 tests/hosted/source_generics.py # explicit generics, constraints and provenance
python3 tests/hosted/source_borrow_returns.py # explicit origins, retained views, packages and profiles
python3 tests/hosted/source_format.py # formatter CLI, comments, idempotence and public-corpus AIR fidelity
python3 tests/hosted/source_static_functions.py # explicit operations, effects, nominal policy identity and workers
python3 tests/hosted/source_linear.py # whole-value owners, canonical AIR and CLI errors
python3 tests/hosted/source_buffers.py # initialized storage, owning vectors and CLI contracts
+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.
+15 -9
View File
@@ -11,6 +11,7 @@ pub const lower_mod = @import("frontend/lower.zig");
pub const generics = @import("frontend/generics.zig");
pub const modules = @import("frontend/modules.zig");
pub const stdlib = @import("frontend/stdlib.zig");
pub const format = @import("frontend/format.zig");
pub const Span = ast.Span;
@@ -30,15 +31,7 @@ pub fn compileWithModules(arena: std.mem.Allocator, file: []const u8, source: []
const parsed = try parse.parse(arena, source);
const m = switch (parsed) {
.ok => |m| m,
.err => |f| return .{ .err = .{
.code = diag.lookup("E7001").?,
.span = .{ .file = file, .line = f.pos.line, .col = f.pos.col },
.message = try std.fmt.allocPrint(arena, "expected {s}", .{f.expected}),
.fields = try arena.dupe(diag.Field, &.{
.{ .name = "expected", .value = .{ .str = f.expected } },
.{ .name = "found", .value = .{ .str = f.found } },
}),
} },
.err => |f| return .{ .err = try syntaxDiagnostic(arena, file, f) },
};
const linked = try modules.link(arena, m, sources);
const result = switch (linked) {
@@ -64,6 +57,18 @@ pub fn compileWithModules(arena: std.mem.Allocator, file: []const u8, source: []
};
}
pub fn syntaxDiagnostic(arena: std.mem.Allocator, file: []const u8, f: parse.Failure) std.mem.Allocator.Error!diag.Diagnostic {
return .{
.code = diag.lookup("E7001").?,
.span = .{ .file = file, .line = f.pos.line, .col = f.pos.col },
.message = try std.fmt.allocPrint(arena, "expected {s}", .{f.expected}),
.fields = try arena.dupe(diag.Field, &.{
.{ .name = "expected", .value = .{ .str = f.expected } },
.{ .name = "found", .value = .{ .str = f.found } },
}),
};
}
/// Moves a diagnostic on lowered AIR to its source location; the AIR
/// location stays as `air_line`/`air_col` metadata (spec 15 §10).
pub fn mapDiagnostic(arena: std.mem.Allocator, d: diag.Diagnostic, file: []const u8, lines: []const ?Span) std.mem.Allocator.Error!diag.Diagnostic {
@@ -83,6 +88,7 @@ test {
_ = lex;
_ = parse;
_ = lower_mod;
_ = format;
}
pub const Size = struct { bytes: usize, lines: usize };
+470
View File
@@ -0,0 +1,470 @@
//! Source formatter (spec 15 §11). Only token gaps are rewritten.
//! AST annotations choose layout; unchanged tokens preserve syntax and meaning.
const std = @import("std");
const lex = @import("lex.zig");
const ast = @import("ast.zig");
const parse = @import("parse.zig");
const Allocator = std.mem.Allocator;
const Tag = lex.Tag;
const Token = lex.Token;
const Error = error{ OutOfMemory, Invariant };
pub const Result = union(enum) { ok: []const u8, err: parse.Failure };
const Curly = enum { block, list, literal };
const Mark = struct { angle: bool = false, prefix: bool = false, curly: Curly = .block, top: bool = false, module_end: bool = false, mate: usize = 0, multiline: bool = false, layout_scope: usize = 0 };
const Node = union(enum) { block: *const ast.Block, stmt: *const ast.Stmt, expr: *const ast.Expr };
pub fn format(arena: Allocator, source: []const u8) Error!Result {
const module = switch (try parse.parse(arena, source)) {
.err => |f| return .{ .err = f },
.ok => |m| m,
};
const tokens = try lex.tokenize(arena, source);
var f: Formatter = .{ .arena = arena, .source = source, .tokens = tokens, .marks = try arena.alloc(Mark, tokens.len) };
@memset(f.marks, .{});
try f.annotate(module);
try f.continuations();
const output = try f.render();
// Check the boundary invariant before exposing output or allowing a write.
const after = try lex.tokenize(arena, output);
if (tokens.len != after.len) return error.Invariant;
for (tokens, after) |a, b| if (a.tag != b.tag or !std.mem.eql(u8, a.text, b.text)) return error.Invariant;
return .{ .ok = output };
}
const Frame = struct { tag: Tag, curly: Curly = .block, expanded: bool = false, indented: bool = false };
const Formatter = struct {
arena: Allocator,
source: []const u8,
tokens: []const Token,
marks: []Mark,
output: std.ArrayList(u8) = .empty,
frames: std.ArrayList(Frame) = .empty,
indent: usize = 0,
pending_line: bool = false,
fn offset(f: *Formatter, t: Token) usize {
return @intFromPtr(t.text.ptr) - @intFromPtr(f.source.ptr);
}
fn index(f: *Formatter, pos: lex.Pos) usize {
var lo: usize = 0;
var hi = f.tokens.len;
while (lo < hi) {
const mid = lo + (hi - lo) / 2;
const p = f.tokens[mid].pos;
if (p.line < pos.line or (p.line == pos.line and p.col < pos.col)) lo = mid + 1 else hi = mid;
}
return lo;
}
fn angles(f: *Formatter, start: lex.Pos, end: lex.Pos) void {
for (f.marks[f.index(start)..f.index(end)], f.tokens[f.index(start)..f.index(end)]) |*m, t| switch (t.tag) {
.lt, .gt, .shr => m.angle = true,
else => {},
};
}
fn curly(f: *Formatter, span: ast.Span, kind: Curly) void {
const end = f.index(span.end);
if (end != 0 and f.tokens[end - 1].tag == .r_brace) f.marks[f.marks[end - 1].mate].curly = kind;
}
fn pattern(f: *Formatter, p: ast.Pattern) void {
f.angles(p.span.start, p.span.end);
}
fn arms(f: *Formatter, queue: *std.ArrayList(Node), values: []const ast.Arm) Error!void {
for (values) |*arm| {
f.pattern(arm.pattern);
try queue.append(f.arena, .{ .expr = &arm.body });
}
}
fn annotate(f: *Formatter, module: ast.Module) Error!void {
var opens: std.ArrayList(usize) = .empty;
for (f.tokens, 0..) |t, i| switch (t.tag) {
.l_brace, .l_paren, .l_bracket => try opens.append(f.arena, i),
.r_brace, .r_paren, .r_bracket => {
const open = opens.pop().?;
f.marks[i].mate = open;
f.marks[open].mate = i;
},
else => {},
};
var queue: std.ArrayList(Node) = .empty;
var first = f.tokens.len - 1;
for (module.imports) |imp| first = @min(first, f.index(imp.span.start));
for (module.types) |t| {
const i = f.index(t.span.start);
first = @min(first, i);
f.marks[i].top = true;
f.angles(t.span.start, t.span.end);
f.curly(t.span, .list);
}
for (module.functions) |*func| {
const i = f.index(func.span.start);
first = @min(first, i);
f.marks[i].top = true;
f.angles(func.span.start, func.body.span.start);
try queue.append(f.arena, .{ .block = &func.body });
}
f.marks[first - 1].module_end = true;
// Iterative traversal also handles long left-associated expressions.
while (queue.pop()) |node| switch (node) {
.block => |b| {
for (b.stmts) |*s| try queue.append(f.arena, .{ .stmt = s });
if (b.tail) |e| try queue.append(f.arena, .{ .expr = e });
},
.stmt => |s| switch (s.kind) {
.let => |*x| {
if (x.ty) |t| f.angles(t.span.start, t.span.end);
try queue.append(f.arena, .{ .expr = &x.e });
},
.@"var" => |*x| {
f.angles(x.ty.span.start, x.ty.span.end);
if (x.init) |*e| try queue.append(f.arena, .{ .expr = e });
},
.assign => |*x| {
try queue.append(f.arena, .{ .expr = &x.place });
try queue.append(f.arena, .{ .expr = &x.e });
},
.borrow => |*x| try queue.append(f.arena, .{ .expr = &x.place }),
.@"return" => |*e| if (e.*) |*v| {
try queue.append(f.arena, .{ .expr = v });
},
.expr => |*e| try queue.append(f.arena, .{ .expr = e }),
.@"while" => |*x| {
try queue.append(f.arena, .{ .expr = &x.cond });
try queue.append(f.arena, .{ .block = &x.body });
},
.@"for" => |*x| {
try queue.append(f.arena, .{ .expr = &x.lo });
try queue.append(f.arena, .{ .expr = &x.hi });
try queue.append(f.arena, .{ .block = &x.body });
},
.loop, .shield => |*b| try queue.append(f.arena, .{ .block = b }),
.scope => |*x| try queue.append(f.arena, .{ .block = &x.body }),
.lock => |*x| {
try queue.append(f.arena, .{ .expr = &x.place });
try queue.append(f.arena, .{ .block = &x.body });
try queue.append(f.arena, .{ .block = &x.cancelled });
},
.select => |*x| {
f.curly(x.span, .list);
for (x.arms) |*a| {
f.curly(a.span, .list);
if (a.value) |*e| try queue.append(f.arena, .{ .expr = e });
try f.arms(&queue, a.arms);
}
try queue.append(f.arena, .{ .expr = &x.cancelled });
},
.@"break", .@"continue", .trap => {},
},
.expr => |e| switch (e.kind) {
.neg, .not, .deref => |x| {
f.marks[f.index(e.span.start)].prefix = true;
try queue.append(f.arena, .{ .expr = x });
},
.borrow => |x| try queue.append(f.arena, .{ .expr = x.place }),
.binary => |x| {
try queue.append(f.arena, .{ .expr = x.l });
try queue.append(f.arena, .{ .expr = x.r });
},
.cast => |x| {
f.angles(x.ty.span.start, x.ty.span.end);
try queue.append(f.arena, .{ .expr = x.e });
},
.specialize => |x| {
f.angles(x.base.span.end, e.span.end);
try queue.append(f.arena, .{ .expr = x.base });
},
.call => |*x| {
if (x.type_arg) |t| {
const end = if (x.args.len != 0) x.args[0].span.start else e.span.end;
f.angles(x.callee.span.end, end);
f.angles(t.span.start, t.span.end);
}
try queue.append(f.arena, .{ .expr = x.callee });
for (x.args) |*a| try queue.append(f.arena, .{ .expr = a });
},
.field => |x| try queue.append(f.arena, .{ .expr = x.e }),
.index => |x| {
try queue.append(f.arena, .{ .expr = x.e });
try queue.append(f.arena, .{ .expr = x.lo });
if (x.hi) |h| try queue.append(f.arena, .{ .expr = h });
},
.struct_lit => |x| {
f.curly(e.span, .literal);
const open = f.marks[f.index(e.span.end) - 1].mate;
f.angles(e.span.start, f.tokens[open].pos);
for (x.fields) |*field| try queue.append(f.arena, .{ .expr = &field.e });
},
.array_rep => |x| try queue.append(f.arena, .{ .expr = x.e }),
.array_list => |xs| for (xs) |*x| {
try queue.append(f.arena, .{ .expr = x });
},
.or_trap => |x| try queue.append(f.arena, .{ .expr = x }),
.if_expr => |x| {
try queue.append(f.arena, .{ .expr = &x.cond });
try queue.append(f.arena, .{ .block = &x.then });
var els = x.@"else";
while (els) |branch| switch (branch) {
.block => |*b| { // Payload copies cannot be queued by address.
for (b.stmts) |*s| try queue.append(f.arena, .{ .stmt = s });
if (b.tail) |v| try queue.append(f.arena, .{ .expr = v });
els = null;
},
.@"if" => |next| {
try queue.append(f.arena, .{ .expr = &next.cond });
try queue.append(f.arena, .{ .block = &next.then });
els = next.@"else";
},
};
},
.match_expr => |x| {
f.curly(e.span, .list);
try queue.append(f.arena, .{ .expr = &x.scrutinee });
try f.arms(&queue, x.arms);
},
.block => |b| try queue.append(f.arena, .{ .block = b }),
.variant => f.angles(e.span.start, e.span.end),
.int, .boolean, .bytes, .name, .move => {},
},
};
}
fn continuations(f: *Formatter) Error!void {
const counts = try f.arena.alloc(usize, f.tokens.len + 1);
@memset(counts, 0);
const starts = try f.arena.alloc(usize, f.tokens.len);
var scopes: std.ArrayList(usize) = .empty;
try scopes.append(f.arena, 0);
var end: usize = 0;
for (f.tokens, 0..) |t, i| {
const start = if (t.tag == .eof) f.source.len else f.offset(t);
const scope = scopes.items[scopes.items.len - 1];
if (std.mem.indexOf(u8, f.source[end..start], "//") != null) counts[scope] += 1;
switch (t.tag) {
.l_brace => if (f.marks[i].curly != .literal) {
// A block's internal comments belong to its own layout,
// not to a surrounding argument or compact literal.
try scopes.append(f.arena, i + 1);
} else {
f.marks[i].layout_scope = scope;
starts[i] = counts[scope];
},
.l_paren, .l_bracket => {
f.marks[i].layout_scope = scope;
starts[i] = counts[scope];
},
.r_brace, .r_paren, .r_bracket => {
const open = f.marks[i].mate;
if (t.tag == .r_brace and f.marks[open].curly != .literal) {
_ = scopes.pop();
} else f.marks[open].multiline = counts[f.marks[open].layout_scope] > starts[open];
},
else => {},
}
end = start + t.text.len;
}
}
fn newline(f: *Formatter) Error!void {
while (f.output.items.len != 0 and f.output.items[f.output.items.len - 1] == ' ') _ = f.output.pop();
if (f.output.items.len != 0 and f.output.items[f.output.items.len - 1] != '\n') try f.output.append(f.arena, '\n');
f.pending_line = false;
}
fn blank(f: *Formatter) Error!void {
try f.newline();
if (f.output.items.len != 0 and (f.output.items.len < 2 or f.output.items[f.output.items.len - 2] != '\n')) try f.output.append(f.arena, '\n');
}
fn padding(f: *Formatter) Error!void {
if (f.output.items.len == 0 or f.output.items[f.output.items.len - 1] == '\n') try f.output.appendNTimes(f.arena, ' ', f.indent * 4);
}
fn space(f: *Formatter) Error!void {
if (f.output.items.len != 0 and f.output.items[f.output.items.len - 1] != ' ' and f.output.items[f.output.items.len - 1] != '\n') try f.output.append(f.arena, ' ');
}
fn gap(f: *Formatter, bytes: []const u8, top: bool, has_prev: bool, allow_blank: bool) Error!void {
var make_blank = top;
var blank_pending = false;
var lines = std.mem.splitScalar(u8, bytes, '\n');
var first_line = true;
while (lines.next()) |line| {
const body = std.mem.trimEnd(u8, line, "\r");
const text = std.mem.trimStart(u8, body, " \t");
if (std.mem.startsWith(u8, text, "//")) {
if (first_line and has_prev) {
try f.space();
} else {
if (make_blank or blank_pending) {
try f.blank();
make_blank = false;
} else try f.newline();
try f.padding();
}
try f.output.appendSlice(f.arena, text);
// Comment contents, including trailing spaces/tabs, are data.
try f.output.append(f.arena, '\n');
f.pending_line = false;
blank_pending = false;
} else if (allow_blank and !first_line and text.len == 0 and lines.index != null) {
blank_pending = true;
}
first_line = false;
}
if (make_blank or blank_pending) try f.blank() else if (f.pending_line) try f.newline();
}
fn render(f: *Formatter) Error![]const u8 {
var end: usize = 0;
for (f.tokens, 0..) |t, i| {
const start = if (t.tag == .eof) f.source.len else f.offset(t);
const bytes = f.source[end..start];
const allow_blank = i != 0 and t.tag != .r_brace and f.tokens[i - 1].tag != .l_brace and
(f.pending_line or std.mem.indexOf(u8, bytes, "//") != null);
try f.gap(bytes, f.marks[i].top, i != 0, allow_blank);
if (t.tag == .eof) break;
end = start + t.text.len;
var closing: ?Frame = null;
if (t.tag == .r_brace or t.tag == .r_paren or t.tag == .r_bracket) {
closing = f.frames.pop().?;
if (closing.?.indented) f.indent -= 1;
if (closing.?.expanded) try f.newline();
}
try f.padding();
if (i != 0 and (needsSpace(f.tokens[i - 1], t, f.marks[i - 1], f.marks[i]) or merges(f.tokens[i - 1].text, t.text))) try f.space();
try f.output.appendSlice(f.arena, t.text);
const next = f.tokens[i + 1];
switch (t.tag) {
.l_brace => {
const between = f.source[end..(if (next.tag == .eof) f.source.len else f.offset(next))];
const expanded = f.marks[i].curly != .literal and (next.tag != .r_brace or std.mem.trim(u8, between, " \t\r\n").len != 0);
const indented = expanded or f.marks[i].multiline;
try f.frames.append(f.arena, .{ .tag = t.tag, .curly = f.marks[i].curly, .expanded = expanded, .indented = indented });
if (indented) f.indent += 1;
if (expanded) f.pending_line = true;
},
.l_paren, .l_bracket => {
try f.frames.append(f.arena, .{ .tag = t.tag, .indented = f.marks[i].multiline });
if (f.marks[i].multiline) f.indent += 1;
},
.semicolon => f.pending_line = f.frames.items.len == 0 or f.frames.items[f.frames.items.len - 1].tag == .l_brace,
.comma => if (f.frames.items.len != 0) {
const frame = f.frames.items[f.frames.items.len - 1];
f.pending_line = frame.tag == .l_brace and frame.curly == .list;
},
.r_brace => f.pending_line = closing.?.curly != .literal and afterBlock(next),
else => {},
}
if (f.marks[i].module_end) f.pending_line = true;
}
try f.newline();
while (f.output.items.len >= 2 and f.output.items[f.output.items.len - 2] == '\n') _ = f.output.pop();
return f.output.items;
}
};
fn word(t: Token, name: []const u8) bool {
return t.tag == .ident and std.mem.eql(u8, t.text, name);
}
fn afterBlock(next: Token) bool {
if (word(next, "else") or word(next, "cancelled")) return false;
return switch (next.tag) {
.ident, .int, .bytes, .underscore, .l_brace, .eof => true,
else => false,
};
}
fn needsSpace(a: Token, b: Token, am: Mark, bm: Mark) bool {
if (b.tag == .comma or b.tag == .semicolon or b.tag == .colon or b.tag == .dot or b.tag == .colon_colon or b.tag == .r_paren or b.tag == .r_bracket) return false;
if (a.tag == .dot or a.tag == .colon_colon or a.tag == .l_paren or a.tag == .l_bracket) return false;
if (bm.angle) return false;
if (am.angle and a.tag == .lt) return false;
if (am.prefix) return word(a, "not");
if (b.tag == .l_paren) {
if (a.tag == .ident) return word(a, "if") or word(a, "while") or word(a, "return") or word(a, "match") or word(a, "not") or word(a, "and") or word(a, "or");
if (am.angle and (a.tag == .gt or a.tag == .shr)) return false;
return a.tag != .r_paren and a.tag != .r_bracket and a.tag != .int and a.tag != .bytes;
}
if (b.tag == .l_bracket and (a.tag == .ident or a.tag == .r_bracket or a.tag == .r_paren)) return word(a, "effects") or word(a, "return") or word(a, "in") or word(a, "and") or word(a, "or");
if (a.tag == .l_brace and b.tag == .r_brace) return false;
if (a.tag == .dot_dot or b.tag == .dot_dot) return false;
return true;
}
fn merges(a: []const u8, b: []const u8) bool {
const x = a[a.len - 1];
const y = b[0];
if ((std.ascii.isAlphanumeric(x) or x == '_') and (std.ascii.isAlphanumeric(y) or y == '_')) return true;
const pair = [_]u8{ x, y };
for ([_][]const u8{ "::", "..", "->", "=>", "==", "!=", "<=", ">=", "<<", ">>", "+%", "-%", "*%", "//" }) |p| if (std.mem.eql(u8, &pair, p)) return true;
return false;
}
test "source layout, comments, token boundaries and idempotence" {
var a = std.heap.ArenaAllocator.init(std.testing.allocator);
defer a.deinit();
const input = "// header\r\nmodule demo\r\nfn main()->u64 effects[]{let x=1u64; // trailing\nreturn x+2u64;} // final\n";
const output = (try format(a.allocator(), input)).ok;
try std.testing.expectEqualStrings("// header\nmodule demo\n\nfn main() -> u64 effects [] {\n let x = 1u64; // trailing\n return x + 2u64;\n} // final\n", output);
try std.testing.expectEqualStrings(output, (try format(a.allocator(), output)).ok);
}
test "libraries and syntax failures are independent of semantics" {
var a = std.heap.ArenaAllocator.init(std.testing.allocator);
defer a.deinit();
try std.testing.expect((try format(a.allocator(), "module lib import absent; fn f(x: Unknown)->Unknown effects [] {x}")) == .ok);
try std.testing.expect((try format(a.allocator(), "module bad fn main()->u64 effects [] {return 1}")) == .err);
}
test "angles, shifts, literals, grouping and standalone comments" {
var a = std.heap.ArenaAllocator.init(std.testing.allocator);
defer a.deinit();
const input = "module m fn f<T>(p:own<own<own<T> > >)->u64 effects [] {let b=b\"//\\x41\\n\"; let n=\n// standalone\n(1u64+2u64)*3u64; if n<12u64 { return -(-1i64) as! u64; } else { return n>>1u64; }}";
const output = (try format(a.allocator(), input)).ok;
try std.testing.expect(std.mem.indexOf(u8, output, "own<own<own<T> > >") != null);
try std.testing.expect(std.mem.indexOf(u8, output, "b\"//\\x41\\n\"") != null);
try std.testing.expect(std.mem.indexOf(u8, output, "let n =\n // standalone\n (1u64 + 2u64) * 3u64;") != null);
try std.testing.expect(std.mem.indexOf(u8, output, "n >> 1u64") != null);
try std.testing.expectEqualStrings(output, (try format(a.allocator(), output)).ok);
}
test "long left-associated expressions use an iterative layout traversal" {
var a = std.heap.ArenaAllocator.init(std.testing.allocator);
defer a.deinit();
var source: std.ArrayList(u8) = .empty;
try source.appendSlice(a.allocator(), "module m fn f()->u64 effects [] { return 0u64");
for (0..10000) |_| try source.appendSlice(a.allocator(), "+1u64");
try source.appendSlice(a.allocator(), ";}");
const output = (try format(a.allocator(), source.items)).ok;
try std.testing.expectEqualStrings(output, (try format(a.allocator(), output)).ok);
}
test "continuation indentation, comment contents and statement grouping" {
var a = std.heap.ArenaAllocator.init(std.testing.allocator);
defer a.deinit();
const input = "module m struct P {a:u64,b:u64} fn f()->void effects [] {let p=P{a:1u64, // lit \t\nb:2u64};\n\n\nlet v=g( // arg\n1u64,2u64);let n=not (true and false);}";
const output = (try format(a.allocator(), input)).ok;
try std.testing.expect(std.mem.indexOf(u8, output, "// lit \t\n b: 2u64 };") != null);
try std.testing.expect(std.mem.indexOf(u8, output, "};\n\n let v = g( // arg\n 1u64, 2u64);") != null);
try std.testing.expect(std.mem.indexOf(u8, output, "not (true and false)") != null);
try std.testing.expectEqualStrings(output, (try format(a.allocator(), output)).ok);
}
test "terminal CR normalization is idempotent" {
var a = std.heap.ArenaAllocator.init(std.testing.allocator);
defer a.deinit();
const output = (try format(a.allocator(), "// heading\r\r\nmodule m // ending\r\r")).ok;
try std.testing.expectEqualStrings("// heading\nmodule m // ending\n", output);
try std.testing.expectEqualStrings(output, (try format(a.allocator(), output)).ok);
}
test "blank statement groups beside comments and block arguments" {
var a = std.heap.ArenaAllocator.init(std.testing.allocator);
defer a.deinit();
const input = "module m fn f()->void effects [] {let x=1u64;\n\n// section two\nlet y=2u64;\n// trailing note\n\nlet w=g(match x {0=>1u64,_=>2u64,});}";
const output = (try format(a.allocator(), input)).ok;
try std.testing.expect(std.mem.indexOf(u8, output, "let x = 1u64;\n\n // section two\n let y = 2u64;") != null);
try std.testing.expect(std.mem.indexOf(u8, output, "// trailing note\n\n let w = g(match x {\n 0 => 1u64,") != null);
try std.testing.expectEqualStrings(output, (try format(a.allocator(), output)).ok);
}
test "comments inside a block argument do not indent the enclosing call" {
var a = std.heap.ArenaAllocator.init(std.testing.allocator);
defer a.deinit();
const input = "module m fn f()->void effects [] {let w=g(match 1u64 { // block\n0=>1u64,_=>2u64,});}";
const output = (try format(a.allocator(), input)).ok;
try std.testing.expect(std.mem.indexOf(u8, output, "g(match 1u64 { // block\n 0 => 1u64,") != null);
try std.testing.expect(std.mem.indexOf(u8, output, "\n });") != null);
try std.testing.expectEqualStrings(output, (try format(a.allocator(), output)).ok);
}
+83
View File
@@ -33,6 +33,9 @@ const usage =
\\ print the canonical AIR a source module lowers to;
\\ --annotate adds source spans as comments (not canonical);
\\ --stats prints source/AIR size and expansion ratio
\\ fmt [--check | --write] <file.aji>
\\ print formatted source; --check checks without writing,
\\ --write replaces a regular file; both print a JSON record
\\ explore [--max-runs N] [--grant P=KIND[:SCOPE]]... <file.air | file.aji | --manifest aji.toml>
\\ run @main under every schedule and weak-memory choice
\\ (depth first, up to N runs, default 100000) and print the
@@ -71,6 +74,7 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
return .usage;
}
const cmd = args[1];
if (std.mem.eql(u8, cmd, "fmt")) return formatCommand(io, arena, args[2..], out);
if (std.mem.eql(u8, cmd, "version")) {
try out.print("aji {s} (air format {d})\n", .{ aji.version, aji.air.format_version });
return .accepted;
@@ -485,6 +489,85 @@ test "standard library trap record identifies the bundled source" {
try std.testing.expectEqual(@as(i64, 20), location.get("line").?.integer);
}
fn formatCommand(io: std.Io, arena: std.mem.Allocator, arguments: []const [:0]const u8, out: *std.Io.Writer) !ExitCode {
var rest = arguments;
const Mode = enum { stdout, check, write };
var mode: Mode = .stdout;
if (rest.len != 0 and (std.mem.eql(u8, rest[0], "--check") or std.mem.eql(u8, rest[0], "--write"))) {
mode = if (std.mem.eql(u8, rest[0], "--check")) .check else .write;
rest = rest[1..];
}
if (rest.len != 1 or std.mem.startsWith(u8, rest[0], "--") or !std.mem.endsWith(u8, rest[0], ".aji")) return usageError("fmt takes [--check | --write] and one .aji file");
const path = rest[0];
var permissions: ?std.Io.File.Permissions = null;
if (mode == .write) {
const stat = std.Io.Dir.cwd().statFile(io, path, .{ .follow_symlinks = false }) catch |err| {
std.debug.print("aji: {s}: {t}\n", .{ path, err });
return .usage;
};
if (stat.kind != .file) {
std.debug.print("aji: fmt --write requires a regular file\n", .{});
return .usage;
}
permissions = stat.permissions;
}
const input = try readInput(arena, io, path, false) orelse return .usage;
const formatted = aji.frontend.format.format(arena, input.source) catch |err| switch (err) {
error.Invariant => {
std.debug.print("aji: formatter token preservation invariant failed\n", .{});
return .usage;
},
error.OutOfMemory => return error.OutOfMemory,
};
const text = switch (formatted) {
.err => |f| {
const d = try aji.frontend.syntaxDiagnostic(arena, path, f);
try d.writeJson(out);
try out.writeByte('\n');
return .rejected;
},
.ok => |text| text,
};
if (mode == .stdout) {
try out.writeAll(text);
return .accepted;
}
const changed = !std.mem.eql(u8, input.source, text);
if (mode == .write) {
const dir = std.Io.Dir.cwd();
if (changed) {
var file = dir.createFileAtomic(io, path, .{ .replace = true, .permissions = permissions.? }) catch |err| {
std.debug.print("aji: {s}: {t}\n", .{ path, err });
return .usage;
};
defer file.deinit(io);
// Creation may apply umask; restore the complete original mode.
file.file.setPermissions(io, permissions.?) catch |err| {
std.debug.print("aji: {s}: {t}\n", .{ path, err });
return .usage;
};
var buffer: [4096]u8 = undefined;
var writer = file.file.writer(io, &buffer);
writer.interface.writeAll(text) catch |err| {
std.debug.print("aji: {s}: {t}\n", .{ path, writer.err orelse err });
return .usage;
};
writer.flush() catch |err| {
std.debug.print("aji: {s}: {t}\n", .{ path, err });
return .usage;
};
file.replace(io) catch |err| {
std.debug.print("aji: {s}: {t}\n", .{ path, err });
return .usage;
};
}
}
var json: std.json.Stringify = .{ .writer = out };
try json.write(.{ .file = path, .status = if (mode == .check and changed) "needs_format" else "formatted", .changed = changed });
try out.writeByte('\n');
return if (mode == .check and changed) .rejected else .accepted;
}
fn readInput(arena: std.mem.Allocator, io: std.Io, path: []const u8, from_manifest: bool) !?aji.source_package.Input {
return switch (if (from_manifest) try aji.source_package.load(arena, io, path) else try aji.source_package.single(arena, io, path)) {
.ok => |input| input,
+11
View File
@@ -0,0 +1,11 @@
// Header stays before the module.
module fmt.layout
import std.option; // explicit import
// Generic declaration.
struct Pair<T:Copy>{first:T,second:T,}
enum Choice<T:Copy>{some(T),none}
fn identity(x:u64)->u64 effects[]{x}
fn apply<T:Copy,F:fn(T)->T effects []>(x:T)->T effects[]{return F(x);}
fn main()->u64 effects[]{let pair=Pair::<u64>{first:40u64,second:2u64}; // keep trailing
let bytes=b"//not a comment\x00";let x=(pair.first+pair.second)*1u64;
if x<43u64{match Choice::<u64>::some(x){Choice::<u64>::some(v)=>{return apply::<u64,fn identity>(v);}Choice::<u64>::none=>{return 0u64;}}}else{return x>>1u64;}} // final
+40
View File
@@ -0,0 +1,40 @@
// Header stays before the module.
module fmt.layout
import std.option; // explicit import
// Generic declaration.
struct Pair<T: Copy> {
first: T,
second: T,
}
enum Choice<T: Copy> {
some(T),
none
}
fn identity(x: u64) -> u64 effects [] {
x
}
fn apply<T: Copy, F: fn(T) -> T effects []>(x: T) -> T effects [] {
return F(x);
}
fn main() -> u64 effects [] {
let pair = Pair::<u64> { first: 40u64, second: 2u64 }; // keep trailing
let bytes = b"//not a comment\x00";
let x = (pair.first + pair.second) * 1u64;
if x < 43u64 {
match Choice::<u64>::some(x) {
Choice::<u64>::some(v) => {
return apply::<u64, fn identity>(v);
}
Choice::<u64>::none => {
return 0u64;
}
}
} else {
return x >> 1u64;
}
} // final
+143
View File
@@ -0,0 +1,143 @@
#!/usr/bin/env python3
"""P6-8 formatter: public corpus, token/AST fidelity, canonical AIR and CLI I/O.
Read only the source conformance corpus, std and examples. Never format originals
in place; --write tests use temporary files. Runs use fuel, without timeouts.
"""
import json
import os
from pathlib import Path
import subprocess
import tempfile
REPO = Path(__file__).resolve().parents[2]
AJI = REPO / "zig-out/bin/aji"
checks = 0
def cli(*args, code=0):
global checks
result = subprocess.run([str(AJI), *map(str, args)], capture_output=True)
assert result.returncode == code, (args, result.returncode, result.stdout, result.stderr)
checks += 1
return result.stdout
with tempfile.TemporaryDirectory(prefix="aji-format-") as directory:
root = Path(directory)
fixture = REPO / "tests/format/layout.aji"
before = fixture.read_bytes()
golden = (REPO / "tests/format/layout.expected").read_bytes()
assert cli("fmt", fixture) == golden
assert fixture.read_bytes() == before
record = json.loads(cli("fmt", "--check", fixture, code=1))
assert record == {"file": str(fixture), "status": "needs_format", "changed": True}
formatted = root / "formatted.aji"
formatted.write_bytes(golden)
assert cli("fmt", formatted) == golden
assert json.loads(cli("fmt", "--check", formatted)) == {
"file": str(formatted), "status": "formatted", "changed": False}
assert cli("lower", fixture) == cli("lower", formatted)
original_run = json.loads(cli("run", "--fuel", "100000", fixture))
assert original_run["value"] == 42
assert json.loads(cli("run", "--fuel", "100000", formatted)) == original_run
# Explicit writes are atomic, preserve mode despite umask, and do not touch
# an unchanged file (including its inode and modification time).
target = root / 'quoted "name.aji'
target.write_bytes(before)
target.chmod(0o664)
initial = target.stat()
assert json.loads(cli("fmt", "--write", target)) == {
"file": str(target), "status": "formatted", "changed": True}
assert target.read_bytes() == golden and target.stat().st_mode == initial.st_mode
os.utime(target, ns=(1234567890000000000, 1234567890000000000))
unchanged = target.stat()
assert json.loads(cli("fmt", "--write", target))["changed"] is False
assert (target.stat().st_ino, target.stat().st_mtime_ns) == (unchanged.st_ino, unchanged.st_mtime_ns)
link = root / "link.aji"
link.symlink_to(target)
cli("fmt", "--write", link, code=2)
assert link.is_symlink() and target.read_bytes() == golden
assert cli("fmt", link) == golden
hard = root / "hard.aji"
twin = root / "twin.aji"
hard.write_bytes(before)
os.link(hard, twin)
cli("fmt", "--write", hard)
assert hard.read_bytes() == golden and twin.read_bytes() == before
pipe = root / "pipe.aji"
os.mkfifo(pipe)
# Reject before reading: no writer or wall-clock timeout is needed.
cli("fmt", "--write", pipe, code=2)
broken = root / "broken.aji"
broken.write_bytes(b"module broken\nfn f()->u64 effects [] {return 1}\n")
for flags in ((), ("--check",), ("--write",)):
error = json.loads(cli("fmt", *flags, broken, code=1))
assert error["code"] == "E7001" and error["file"] == str(broken)
assert error == json.loads(cli("lower", broken, code=1))
assert broken.read_bytes().endswith(b"{return 1}\n")
for args in ((), ("--check",), ("--unknown", fixture),
("--check", "--write", fixture), ("--manifest", fixture),
(root / "missing.aji",), (fixture, fixture), ("not.air",), (root,)):
assert cli("fmt", *args, code=2) == b""
library = root / "lib.aji"
library.write_bytes(b"module lib import absent; fn f(p: Unknown)->Unknown effects [] {p}")
text = cli("fmt", library)
assert b"import absent;" in text and b"p: Unknown" in text
# Scope delimiters, inline/standalone comments, UTF-8 comments, CRLF and
# missing final newline must be stable, even in semantically invalid code.
cases = [
b"module empty",
b"// heading\r\r\nmodule m // ending\r\r",
b"// header\r\nmodule m // module\r\nfn f()->void effects [] { // body\r\n// end\r\n} // final",
"module m fn f()->u64 effects [] {let x=\n// отдельный комментарий\n42u64;return x;}".encode(),
b"module m struct S {x:u64} fn f()->S effects [] {S {// inner\nx:42u64 // trailing\n}}",
b"module m fn f()->void effects [] {let n=1u64; if true{} // after empty\nelse{} // after else\n}",
b"module m fn f(p:own<own<u64> >)->u64 effects [] {let n=(1u64+2u64)*3u64;return n>>1u64;}",
b"module m fn f()->void effects [] {select { recv(rx){ok(x)=>{},closed=>{},cancelled=>{},} cancelled=>{},}}",
b"module m fn f()->void effects [] {let p=P{a:1u64, // lit \t\nb:2u64};\n\n\nlet n=not (true and false);}",
]
for i, source in enumerate(cases):
sample = root / f"case{i}.aji"
sample.write_bytes(source)
text = cli("fmt", sample)
sample.write_bytes(text)
assert cli("fmt", sample) == text, (i, text)
cli("fmt", "--check", sample)
if b"// lit" in source:
assert b"// lit \t\n b: 2u64" in text
assert b"not (true and false)" in text
parsed = syntax_errors = lowered = 0
files = sorted({p for directory in (REPO / "tests/conformance/source", REPO / "std", REPO / "examples")
for p in directory.rglob("*.aji")})
for i, path in enumerate(files, 1):
original = path.read_bytes()
result = subprocess.run([str(AJI), "fmt", str(path)], capture_output=True)
checks += 1
if result.returncode == 1:
assert json.loads(result.stdout)["code"] == "E7001", (path, result.stdout, result.stderr)
syntax_errors += 1
else:
assert result.returncode == 0, (path, result.returncode, result.stdout, result.stderr)
formatted.write_bytes(result.stdout)
assert cli("fmt", formatted) == result.stdout, path
parsed += 1
# CLI packages require explicit mappings; for ordinary files,
# accepted lowering must remain byte-identical after formatting.
lower = subprocess.run([str(AJI), "lower", str(path)], capture_output=True)
checks += 1
if lower.returncode == 0:
assert cli("lower", formatted) == lower.stdout, path
lowered += 1
else:
assert lower.returncode in (1, 3), (path, lower.returncode, lower.stderr)
assert path.read_bytes() == original, path
if i % 100 == 0:
print(f"formatter corpus: {i}/{len(files)} files", flush=True)
print(f"source formatter passed ({checks} checks; {parsed} parsed, "
f"{syntax_errors} syntax errors, {lowered} identical AIR outputs)")