Files
aji/docs/design/source-expression-depth-audit.md
T

137 lines
8.2 KiB
Markdown

# Source expression depth audit
This non-normative audit tracks Q-061 independently of the resolved compiler
type-traversal inventory (Q-059). It uses finite generated/public source only;
it does not set an expression-depth acceptance limit or report model outcomes.
## Confirmed baseline failures
On the Debug CLI preceding the unary-parser repair (code at `fb80413`),
`fn main() -> bool effects [] { return not … false; }` accepts 16 prefixes.
At 1,024 prefixes, checking aborts in `Lowerer.expr`, with repeated `.not`
operand calls. At 16,384 and 65,536 prefixes, it aborts earlier in
`Parser.unary`. Each failing check exits by signal (observed return code -6)
without a stdout diagnostic. These are observed native-stack failures, not
language rejection rules. Stderr reports a segmentation fault at the recursive
entry/operand call, followed by repeated native frames of that function.
The ignored evidence is under `.zig-cache/contract-gate/type-depth/`:
`expression-depth-before.json`, `prefix-not-*.stdout` and `prefix-not-*.stderr`.
No wall-clock timeout terminates these probes.
## Unary parser continuations
The parser records `-`, `not`, `*` and inline borrow prefixes in an explicit
pending list, parses the terminal operand and rebuilds the nodes inside out.
`move` remains a terminal name form. A borrow still parses its operand through
unary only when the next token is `*`; otherwise it uses postfix directly.
This preserves the existing place boundary, rather than admitting new spellings
such as `ref -value`, `mut not value` or `ref move value`.
Each rebuilt node retains its own start and the final operand end, including
comments, newlines and file provenance. AST node order, operator association,
postfix precedence and syntax failure positions are unchanged. Pending metadata
is host compiler storage and is released on completion/error. Allocation failure
still propagates OutOfMemory; no partial AST escapes, new code or depth rejection
is introduced. AIR, verifier ownership/borrow rules, runtime evaluation, fuel,
effects and source/reference bundle text are unchanged.
An independent shallow copy of the old unary derivation checks 448 combinations
of prefixes and successful/failed operands. It compares complete ASTs, failure
records, token cursors and last-consumed positions. Its shared postfix parser is
outside that oracle's scope. Separate tests parse 32,768 mixed prefix groups
including borrowed dereferences, inspect every node/span iteratively and check a
missing operand at the deepest position. A failing-allocator test covers all
arena backing requests in a longer chain, including pending-list growth and
output construction, and verifies complete release.
Syntax-only CLI probes format 1,024/16,384/65,536 `not` prefixes successfully
and idempotently, retaining every prefix. Missing-operand checks at
16,384/65,536 prefixes emit exactly one E7001 with independently computed
line/column and expected/found fields. These do **not** establish successful
deep lowering or execution. The permanent `source_grammar.py` suite includes
those formatting/diagnostic regressions at all three depths, with the same
syntax diagnostic across check/lower/run/report/explore/fmt.
Validation: build, units and format checks pass; all 1,793 ordinary conformance
cases pass with exact unique corpus coverage. Old/new public source checks and
successful lowerings are byte-identical (1,423/506). The grammar integration
suite passes 312 checks; the formatter suite passes 6,078 checks over 1,469 files
(1,414 parsed, 55 syntax-error fixtures, 782 identical successful AIR outputs).
These are compiler regressions, not a model-capability measurement or full GC
validation.
## Unary lowering and addressability continuations
Direct `.not`, `.neg`, `.deref` and `.cast` operand descent now records explicit
lowering continuations. Negative zero constants still precede their operands;
loads, boolean operations, checked subtraction and casts resume afterwards.
The special negative-literal magnitude rule remains separate, including
`-128i8` and the overflow from negating that value. Cast target validation still
precedes operand lowering; narrowing advice, atomic-load E4202 and operand
type/failure positions are unchanged. `peekType` skips a leading negation spine
without allocating; other recursive query paths are outside this repair.
The first intermediate full 16,384-prefix check exposes another native-stack
failure, in the preliminary `markExpr` walk, before the new expression handler
is reached. Its record/frame excerpt is retained as
`source-address-mark-before.json`. Addressability now uses a separate worklist
for blocks, statements, expressions, roots and pending sibling slices. It
preserves root-bound-before-base order, left/right and statement/tail order,
callee/argument order and the final split_at root visit. The old skipped select
and lock-place inputs stay skipped; storage policy is not extended here.
Both worklists are host metadata, released on error/completion; finished values
and addressability facts retain their caller-arena lifetime. OOM propagates
without a source diagnostic or public partial AIR. The verifier's load/borrow,
initialization and atomic-access rules, runtime operations, ownership, lexical
ends, effects and source/AIR formats are unchanged. Borrowed scalar reads remain
valid; slice/array dereference and implicit atomic reads retain their existing
E7006/E4202 failures. No acceptance limit, code, feature or bundle text is added.
An independent old unary derivation checks 3,072 shallow context combinations,
including divergent operands, signed boundaries, borrowed/atomic values and
invalid targets. It compares values, complete instruction/span/constant records,
names/counters and diagnostics. It shares the unchanged non-unary handlers and
query implementation, so it is not an independent oracle for those paths.
Separate 32,768-node cases inspect inside-out boolean/cast spans, outside-in
negative zeros and inside-out subtractions, and inner dereference rejection.
The allocation test fails every arena backing request and compares complete
emitted instruction prefixes, no output publication and full arena release.
An independent old addressability walk compares 17 shallow fixtures, including
roots/bounds, branches, aggregates, calls, loops, scopes and skipped inputs.
32,768 mixed expression/block levels and every failing backing allocation are
tested separately. Full generated checks/lowerings now accept 65,536 typed
scalar boolean/negative/cast nodes, with independently counted instructions;
direct malformed dereference spines reject E7005 at their inner position.
These do not prove that every expression/query path is bounded.
The permanent `source_expression_depth.py` CI suite checks deep full lowering,
exact instruction counts, source/AIR and hosted results, fuel boundaries and
signed-minimum overflow. Baseline/current runtime records match exactly in 47
deterministic/hosted pairs. Full ordinary conformance passes 1,793 unique cases
with exact corpus coverage; units and Zig format checks pass. Q-060's full
per-step validation remains separate.
Final CLI validation passes 114 expression-depth checks, 635 non-value operand
checks, 33 atomic-access checks, 312 grammar checks and the existing 6,078
formatter checks. All 1,423 public source checks and 506 successful lowerings
retain byte-identical old/new results with fixed baseline/current executables.
## Remaining work
A follow-up check of `( * … 1i64 ) as i64` at 16,384 dereferences confirms a
native-stack abort in `peekType`, before the expected ordinary type error;
its stdout is empty and stderr repeats the dereference-query frames. Evidence:
`unary-cast-deref-query-16384.json/.stdout/.stderr`. General query continuation
work is still needed, beyond the negation-spine shortcut above.
Other expression and statement paths, including parenthesized/nested primary
parsing, `useIn`, generic `expression`/`walk` and lowering's other recursive
expression/block handlers, need separate probes and repairs. Their complete
depth behavior is unverified here. The formatter's expression-marking traversal
already uses a worklist, as inspected and exercised by the deep syntax-only
probes. Q-061 and Phase 6 remain open; Q-060's unfinished full GC validation is
independent. No fresh Claude review covers these expression increments.