diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1dd6cbc..9139534 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -37,6 +37,7 @@ jobs: - run: python3 tests/hosted/source_store_modes.py - run: python3 tests/hosted/source_nominal_queries.py - run: python3 tests/hosted/source_grammar.py + - run: python3 tests/hosted/source_expression_depth.py - run: python3 tests/hosted/source_effect_names.py - run: python3 tests/hosted/source_repair_advice.py - run: python3 tests/hosted/source_independent_errors.py diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b1604a7..f5e24bb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -33,6 +33,7 @@ python3 tests/hosted/source_nonvalue_operands.py # never operands, divergent rec python3 tests/hosted/source_store_modes.py # exclusive places, source positions, array modes and package provenance python3 tests/hosted/source_nominal_queries.py # deep shared types, deterministic limits and package cache indices python3 tests/hosted/source_grammar.py # syntax boundaries, canonical enum lists and formatter/AIR fidelity +python3 tests/hosted/source_expression_depth.py # deep unary chains, exact AIR/fuel and rejection positions python3 tests/hosted/source_effect_names.py # effect-name errors, signature priority and package provenance python3 tests/hosted/source_repair_advice.py # contextual syntax/cast/array-call advice and CLI/package parity python3 tests/hosted/source_independent_errors.py # bounded source error collection without cascades or partial AIR diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index 8ce6dc6..e55d4c5 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -523,4 +523,6 @@ Inspection during Q-059's closing inventory finds native recursion through sourc Follow-up [expression-depth probes](source-expression-depth-audit.md) now confirm native-stack aborts without JSON diagnostics: 1,024 `not` prefixes fail in lowering; 16,384/65,536 fail earlier in the unary parser. The parser's direct prefix recursion is replaced by explicit continuations with unchanged grammar, AST spans, syntax errors and OOM propagation. Deep parse/format/missing-operand checks pass, but the confirmed lowering failure and other expression/statement paths remain open. The preceding inspection-only statement describes the initial checkpoint, not the current evidence. +The [unary lowering/addressability increment](source-expression-depth-audit.md#unary-lowering-and-addressability-continuations) removes direct not/neg/deref/cast descent and the separately confirmed recursive storage-marking prepass. Typed scalar checks/lowerings pass through 65,536 nodes; direct malformed dereferences return their inner E7005. Instruction order, signed-boundary literals, storage policy, diagnostics and host OOM propagation are retained. Q-061 remains open: a separate 16,384-dereference operand beneath a cast still aborts in `peekType` without stdout JSON, confirming the next query path; other expression/statement and generic paths remain to be audited. No normative depth limit is inferred from these repairs or tests. + Audit these paths separately with finite public/generated source inputs before claiming whole-frontend bounded native-stack processing. Prefer explicit continuations preserving existing syntax, evaluation/query order, diagnostics and OOM behavior. A new depth rejection requires a normative decision; Q-059's type-traversal resolution does not authorize one. diff --git a/docs/design/source-expression-depth-audit.md b/docs/design/source-expression-depth-audit.md index b12d352..9b293a6 100644 --- a/docs/design/source-expression-depth-audit.md +++ b/docs/design/source-expression-depth-audit.md @@ -61,13 +61,76 @@ suite passes 312 checks; the formatter suite passes 6,078 checks over 1,469 file 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 -The confirmed `.not` lowering recursion remains unchanged. Other expression -and statement paths, including parenthesized/nested primary parsing, -`peekType`/`useIn`, generic `expression`/`walk` and lowering's other recursive +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 this parser increment. +independent. No fresh Claude review covers these expression increments. diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index 637281c..11f7fc4 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -526,3 +526,9 @@ The earlier Debug full GC process is also still live, as is ReleaseSafe; host na [Q-061 probes](../design/source-expression-depth-audit.md) confirm native-stack aborts without JSON: 1,024 `not` prefixes fail in lowering, while 16,384/65,536 fail earlier in parsing. Direct unary-prefix parsing now uses explicit continuations, preserving the grammar, borrow/place boundary, AST spans, exact failures and host OOM propagation. Independent shallow-oracle (448 cases), 32,768 mixed-prefix, deep missing-operand and allocation-failure tests pass. Syntax-only formatting works through 65,536 prefixes; this does not close the confirmed lowering failure. Build/units/format checks, all 1,793 ordinary conformance cases with exact coverage, 312 grammar CLI checks and 6,078 formatter checks pass. Old/new public source check/lower output remains identical (1,423/506). No normative/reference bundle, feature, code or acceptance-limit change; P6-2, Q-061's remaining expression/statement paths, Q-060 GC validation and Phase 6 exit review remain open. No fresh Claude review covers this increment. + +## Source unary lowering and storage marking (2026-10-10) + +[Q-061 unary operand lowering](../design/source-expression-depth-audit.md#unary-lowering-and-addressability-continuations) now uses explicit continuations for not/neg/deref/cast, preserving pre-operand negative zeros, the signed-minimum literal rule, operand/target checks, atomic-load diagnostics and instruction/span order. A separate confirmed storage-marking failure is repaired by a block/statement/expression/root worklist retaining the existing traversal order and storage policy. Generated full scalar checks/lowerings pass through 65,536 nodes; deep invalid direct dereferences retain inner E7005. Both worklists propagate host OOM without diagnostics or public partial AIR. No verifier/runtime/ownership/format/bundle/feature/code/acceptance-limit change. + +Independent unary/addressability oracles, 32,768-node cases and allocation cleanup tests pass. Final build/units/format checks and all 1,793 ordinary conformance cases with exact coverage pass, as do 114 expression-depth, 635 non-value, 33 atomic-access, 312 grammar and 6,078 formatter CLI checks. Old/new public checks/lowerings (1,423/506) and 47 deterministic/hosted fuel/value records are exact. A new full check independently confirms the remaining 16,384-dereference query failure beneath a cast in peekType. Q-061's general queries, other expression/statement and generic paths remain open, as do Q-060's full per-step validation and Phase 6 exit review. No fresh Claude review covers this increment. diff --git a/src/frontend/lower.zig b/src/frontend/lower.zig index cacd344..d35375d 100644 --- a/src/frontend/lower.zig +++ b/src/frontend/lower.zig @@ -1586,7 +1586,11 @@ const Lowerer = struct { return null; } - fn peekType(l: *Lowerer, e: ast.Expr) ?Ty { + fn peekType(l: *Lowerer, initial: ast.Expr) ?Ty { + // Negation preserves the operand's queried type; skip its unary + // spine without host-stack growth or extra query allocations. + var e = initial; + while (e.kind == .neg) e = e.kind.neg.*; return switch (e.kind) { .specialize => null, .int => |x| if (parse_mod.intSuffix(x.text)) |s| Ty{ .int = s } else null, @@ -1596,7 +1600,7 @@ const Lowerer = struct { .index => |x| if (x.hi == null) (if (l.peekType(x.e.*)) |t| elemOf(t) else null) else null, .array_rep => |x| if (l.peekType(x.e.*)) |t| (l.arrayOf(t, x.len) catch null) else null, .array_list => |xs| if (xs.len != 0) (if (l.peekType(xs[0])) |t| (l.arrayOf(t, xs.len) catch null) else null) else null, - .neg => |x| l.peekType(x.*), + .neg => unreachable, .not => .bool, .cast => |x| l.typeOfNoFail(x.ty), .binary => |x| switch (x.op) { @@ -1747,6 +1751,7 @@ const Lowerer = struct { fn expr(l: *Lowerer, e: ast.Expr, want: ?Ty) Error!Value { switch (e.kind) { + .not, .neg, .deref, .cast => return l.unaryExpr(e, want), .specialize => return l.invalid(.invalid_generic, e.span, "explicit type arguments require a generic function", &.{}), .int => |x| { const ty: Ty = if (parse_mod.intSuffix(x.text)) |s| .{ .int = s } else want orelse @@ -1765,17 +1770,6 @@ const Lowerer = struct { if (b.kind == .storage) return l.def(n, b.ty, try l.fmt("local.load %{s}", .{b.value}), e.span); return .{ .name = b.value, .ty = b.ty }; }, - .deref => |x| { - const r = try l.expr(x.*, null); - const in = r.ty.inner() orelse return l.fail("E7005", e.span, "`*` reads through a borrow", &.{.{ .name = "found", .value = try l.diagnosticTyText(r.ty) }}); - if (r.ty == .slice or r.ty == .slice_mut or in == .array) return l.invalid(.invalid_expression, e.span, "read slice and array elements with `s[i]`, not `*`", &.{}); - // Source-prescribed E4202 (spec 15 §12); no load is emitted. - if (in == .atomic) return l.fail("E4202", e.span, "an atomic cell is read only by atomic operations: use `atomic.load(r, ordering)`", &.{ - .{ .name = "found", .value = try l.diagnosticTyText(r.ty) }, - .{ .name = "use", .value = "atomic.load" }, - }); - return l.def("v", in, try l.fmt("load %{s}", .{r.name}), e.span); - }, .index => |x| { if (x.hi != null) return l.invalid(.invalid_borrow, e.span, "a range `s[a..b]` is a borrow: bind it with `ref r = s[a..b];` or pass `ref s[a..b]`", &.{}); const p = try l.placeBorrow(e, false, false, e.span); @@ -1806,49 +1800,7 @@ const Lowerer = struct { }, .bytes => return l.invalid(.invalid_literal, e.span, "a byte string is an array in storage: bind it with `let`/`ref`, or pass it where a slice is expected", &.{}), .borrow => return l.invalid(.invalid_borrow, e.span, "`ref`/`mut` here: borrows are bound with `ref name = place;` / `mut name = place;` or passed as arguments", &.{}), - .neg => |x| { - const ty = want orelse l.peekType(x.*) orelse return l.fail("E7007", e.span, "the type of this negation cannot be determined", &.{}); - if (ty != .int) return l.fail("E7005", e.span, "negation of a non-integer", &.{}); - // `-literal` is the negative literal. - if (x.kind == .int) { - const v = parse_mod.parseIntText(x.kind.int.text) orelse return l.fail("E7001", e.span, "malformed integer literal", &.{}); - if (!isSigned(ty.int)) return l.fail("E7005", e.span, "negative literal of an unsigned type", &.{.{ .name = "type", .value = ty.int }}); - const min_mag: u128 = @as(u128, 1) << @intCast(intBits(ty.int) - 1); - if (v > min_mag) return l.fail("E7005", e.span, "integer literal out of range for its type", &.{.{ .name = "type", .value = ty.int }}); - return l.def("c", ty, try l.fmt("const.{s} -{d}", .{ ty.int, v }), e.span); - } - const z = try l.def("zero", ty, try l.fmt("const.{s} 0", .{ty.int}), e.span); - const v = try l.expr(x.*, ty); - try l.checkOperandTy(x.span, v.ty, ty); - return l.def("neg", ty, try l.fmt("sub.checked.{s} %{s}, %{s}", .{ ty.int, z.name, v.name }), e.span); - }, - .not => |x| { - const v = try l.expr(x.*, .bool); - try l.checkOperandTy(x.span, v.ty, .bool); - const t = try l.def("c", .bool, "const.bool true", e.span); - return l.def("not", .bool, try l.fmt("xor.bool %{s}, %{s}", .{ v.name, t.name }), e.span); - }, .binary => |x| return l.binary(e, x.op, x.l.*, x.r.*, want), - .cast => |x| { - const to = try l.typeOf(x.ty); - if (to != .int) return l.fail("E7005", x.ty.span, "casts convert between integer types", &.{}); - const from = l.peekType(x.e.*) orelse to; - const v = try l.expr(x.e.*, from); - if (v.ty != .int) return l.fail("E7005", x.e.span, "casts convert between integer types", &.{.{ .name = "found", .value = try l.diagnosticTyText(v.ty) }}); - // `as` widens without loss, by the verifier's own rule (spec 02 §2). - if (x.mode == .widen) { - const a = std.meta.stringToEnum(air_module.IntType, v.ty.int).?; - const b = std.meta.stringToEnum(air_module.IntType, to.int).?; - if (!verifier_types.lossless(a, b)) - return l.invalidWidening(e.span, &.{ .{ .name = "from", .value = v.ty.int }, .{ .name = "to", .value = to.int } }); - } - const mode = switch (x.mode) { - .widen => "widen", - .checked => "checked", - .wrap => "wrap", - }; - return l.def("cast", to, try l.fmt("cast.{s}.{s} %{s}", .{ mode, to.int, v.name }), e.span); - }, .call => |x| return l.call(e, x.callee.*, x.args, false), .if_expr => |x| return l.ifExpr(e.span, x.*, want), .block => |b| { @@ -1872,6 +1824,87 @@ const Lowerer = struct { } } + fn unaryExpr(l: *Lowerer, initial: ast.Expr, initial_want: ?Ty) Error!Value { + const Frame = struct { e: ast.Expr, ty: Ty = .void, zero: ?Value = null }; + var pending: std.ArrayList(Frame) = .empty; + defer pending.deinit(l.arena); + var e = initial; + var want = initial_want; + var v: Value = while (true) { + switch (e.kind) { + .not, .deref => |x| { + try pending.append(l.arena, .{ .e = e }); + want = if (e.kind == .not) .bool else null; + e = x.*; + }, + .neg => |x| { + const ty = want orelse l.peekType(x.*) orelse return l.fail("E7007", e.span, "the type of this negation cannot be determined", &.{}); + if (ty != .int) return l.fail("E7005", e.span, "negation of a non-integer", &.{}); + // Negative literals retain the boundary magnitude rule + // and bypass ordinary positive-literal lowering. + if (x.kind == .int) { + const bits = parse_mod.parseIntText(x.kind.int.text) orelse return l.fail("E7001", e.span, "malformed integer literal", &.{}); + if (!isSigned(ty.int)) return l.fail("E7005", e.span, "negative literal of an unsigned type", &.{.{ .name = "type", .value = ty.int }}); + const min_mag: u128 = @as(u128, 1) << @intCast(intBits(ty.int) - 1); + if (bits > min_mag) return l.fail("E7005", e.span, "integer literal out of range for its type", &.{.{ .name = "type", .value = ty.int }}); + break try l.def("c", ty, try l.fmt("const.{s} -{d}", .{ ty.int, bits }), e.span); + } + // This zero precedes operand lowering, as before. Other + // unary instructions resume after their operand completes. + const zero = try l.def("zero", ty, try l.fmt("const.{s} 0", .{ty.int}), e.span); + try pending.append(l.arena, .{ .e = e, .ty = ty, .zero = zero }); + want = ty; + e = x.*; + }, + .cast => |x| { + const to = try l.typeOf(x.ty); + if (to != .int) return l.fail("E7005", x.ty.span, "casts convert between integer types", &.{}); + want = l.peekType(x.e.*) orelse to; + try pending.append(l.arena, .{ .e = e, .ty = to }); + e = x.e.*; + }, + else => break try l.expr(e, want), + } + }; + while (pending.pop()) |frame| switch (frame.e.kind) { + .not => |x| { + try l.checkOperandTy(x.span, v.ty, .bool); + const t = try l.def("c", .bool, "const.bool true", frame.e.span); + v = try l.def("not", .bool, try l.fmt("xor.bool %{s}, %{s}", .{ v.name, t.name }), frame.e.span); + }, + .neg => |x| { + try l.checkOperandTy(x.span, v.ty, frame.ty); + v = try l.def("neg", frame.ty, try l.fmt("sub.checked.{s} %{s}, %{s}", .{ frame.ty.int, frame.zero.?.name, v.name }), frame.e.span); + }, + .deref => { + const in = v.ty.inner() orelse return l.fail("E7005", frame.e.span, "`*` reads through a borrow", &.{.{ .name = "found", .value = try l.diagnosticTyText(v.ty) }}); + if (v.ty == .slice or v.ty == .slice_mut or in == .array) return l.invalid(.invalid_expression, frame.e.span, "read slice and array elements with `s[i]`, not `*`", &.{}); + // Source-prescribed E4202 (spec 15 §12); no load is emitted. + if (in == .atomic) return l.fail("E4202", frame.e.span, "an atomic cell is read only by atomic operations: use `atomic.load(r, ordering)`", &.{ + .{ .name = "found", .value = try l.diagnosticTyText(v.ty) }, + .{ .name = "use", .value = "atomic.load" }, + }); + v = try l.def("v", in, try l.fmt("load %{s}", .{v.name}), frame.e.span); + }, + .cast => |x| { + if (v.ty != .int) return l.fail("E7005", x.e.span, "casts convert between integer types", &.{.{ .name = "found", .value = try l.diagnosticTyText(v.ty) }}); + if (x.mode == .widen) { + const from = std.meta.stringToEnum(air_module.IntType, v.ty.int).?; + const to = std.meta.stringToEnum(air_module.IntType, frame.ty.int).?; + if (!verifier_types.lossless(from, to)) return l.invalidWidening(frame.e.span, &.{ .{ .name = "from", .value = v.ty.int }, .{ .name = "to", .value = frame.ty.int } }); + } + const mode = switch (x.mode) { + .widen => "widen", + .checked => "checked", + .wrap => "wrap", + }; + v = try l.def("cast", frame.ty, try l.fmt("cast.{s}.{s} %{s}", .{ mode, frame.ty.int, v.name }), frame.e.span); + }, + else => unreachable, + }; + return v; + } + fn binary(l: *Lowerer, e: ast.Expr, op: ast.BinOp, a: ast.Expr, b: ast.Expr, want: ?Ty) Error!Value { switch (op) { .@"and", .@"or" => { @@ -2777,94 +2810,120 @@ const Lowerer = struct { /// borrowed, indexed, or written through a field or element (spec 15 §9). /// Deterministic and by name. fn findAddressable(l: *Lowerer, body: ast.Block) Error!void { - try l.markBlock(body); + try l.markAddressable(.{ .block = body }); } - fn markBlock(l: *Lowerer, b: ast.Block) Error!void { - for (b.stmts) |s| try l.markStmt(s); - if (b.tail) |t| try l.markExpr(t.*); - } + const AddressNode = union(enum) { + block: ast.Block, + stmt: ast.Stmt, + expr: ast.Expr, + root: ast.Expr, + stmts: []const ast.Stmt, + exprs: []const ast.Expr, + fields: []const ast.FieldInit, + arms: []const ast.Arm, + }; - fn markRoot(l: *Lowerer, e: ast.Expr) Error!void { - var x = e; - while (true) switch (x.kind) { - .name => |n| return l.addressable.put(l.arena, n, {}), - .field => |f| x = f.e.*, - .index => |i| { - try l.markExpr(i.lo.*); - if (i.hi) |h| try l.markExpr(h.*); - x = i.e.*; + fn markAddressable(l: *Lowerer, initial: AddressNode) Error!void { + var pending: std.ArrayList(AddressNode) = .empty; + defer pending.deinit(l.arena); + try pending.append(l.arena, initial); + while (pending.pop()) |node| switch (node) { + .block => |b| { + if (b.tail) |t| try pending.append(l.arena, .{ .expr = t.* }); + try pending.append(l.arena, .{ .stmts = b.stmts }); + }, + .stmts => |xs| if (xs.len != 0) { + try pending.append(l.arena, .{ .stmts = xs[1..] }); + try pending.append(l.arena, .{ .stmt = xs[0] }); + }, + .exprs => |xs| if (xs.len != 0) { + try pending.append(l.arena, .{ .exprs = xs[1..] }); + try pending.append(l.arena, .{ .expr = xs[0] }); + }, + .fields => |xs| if (xs.len != 0) { + try pending.append(l.arena, .{ .fields = xs[1..] }); + try pending.append(l.arena, .{ .expr = xs[0].e }); + }, + .arms => |xs| if (xs.len != 0) { + try pending.append(l.arena, .{ .arms = xs[1..] }); + try pending.append(l.arena, .{ .expr = xs[0].body }); + }, + .root => |e| switch (e.kind) { + .name => |n| try l.addressable.put(l.arena, n, {}), + .field => |x| try pending.append(l.arena, .{ .root = x.e.* }), + .index => |x| { + // Bounds precede descending the base, matching the old + // root loop even for multiple nested projections. + try pending.append(l.arena, .{ .root = x.e.* }); + if (x.hi) |h| try pending.append(l.arena, .{ .expr = h.* }); + try pending.append(l.arena, .{ .expr = x.lo.* }); + }, + else => try pending.append(l.arena, .{ .expr = e }), + }, + .stmt => |s| switch (s.kind) { + .let => |x| try pending.append(l.arena, .{ .expr = x.e }), + .@"var" => |x| if (x.init) |e| try pending.append(l.arena, .{ .expr = e }), + .assign => |x| { + try pending.append(l.arena, .{ .expr = x.e }); + if (x.place.kind != .name) try pending.append(l.arena, .{ .root = x.place }); + }, + .borrow => |x| try pending.append(l.arena, .{ .root = x.place }), + .@"return" => |e| if (e) |x| try pending.append(l.arena, .{ .expr = x }), + .expr => |e| try pending.append(l.arena, .{ .expr = e }), + .@"while" => |x| { + try pending.append(l.arena, .{ .block = x.body }); + try pending.append(l.arena, .{ .expr = x.cond }); + }, + .@"for" => |x| { + try pending.append(l.arena, .{ .block = x.body }); + try pending.append(l.arena, .{ .expr = x.hi }); + try pending.append(l.arena, .{ .expr = x.lo }); + }, + .loop, .shield => |b| try pending.append(l.arena, .{ .block = b }), + .scope => |x| try pending.append(l.arena, .{ .block = x.body }), + .lock => |x| { + try pending.append(l.arena, .{ .block = x.cancelled }); + try pending.append(l.arena, .{ .block = x.body }); + }, + else => {}, + }, + .expr => |e| switch (e.kind) { + .borrow => |x| try pending.append(l.arena, .{ .root = x.place.* }), + .index => try pending.append(l.arena, .{ .root = e }), + .neg, .not, .deref, .or_trap => |x| try pending.append(l.arena, .{ .expr = x.* }), + .binary => |x| { + try pending.append(l.arena, .{ .expr = x.r.* }); + try pending.append(l.arena, .{ .expr = x.l.* }); + }, + .cast => |x| try pending.append(l.arena, .{ .expr = x.e.* }), + .call => |x| { + if (x.callee.kind == .field and std.mem.eql(u8, x.callee.kind.field.name, "split_at")) try pending.append(l.arena, .{ .root = x.callee.kind.field.e.* }); + try pending.append(l.arena, .{ .exprs = x.args }); + try pending.append(l.arena, .{ .expr = x.callee.* }); + }, + .field => |x| try pending.append(l.arena, .{ .expr = x.e.* }), + .struct_lit => |x| try pending.append(l.arena, .{ .fields = x.fields }), + .array_rep => |x| try pending.append(l.arena, .{ .expr = x.e.* }), + .array_list => |xs| try pending.append(l.arena, .{ .exprs = xs }), + .if_expr => |x| { + if (x.@"else") |els| switch (els) { + .block => |b| try pending.append(l.arena, .{ .block = b }), + .@"if" => |inner| try pending.append(l.arena, .{ .expr = .{ .span = e.span, .kind = .{ .if_expr = inner } } }), + }; + try pending.append(l.arena, .{ .block = x.then }); + try pending.append(l.arena, .{ .expr = x.cond }); + }, + .match_expr => |x| { + try pending.append(l.arena, .{ .arms = x.arms }); + try pending.append(l.arena, .{ .expr = x.scrutinee }); + }, + .block => |b| try pending.append(l.arena, .{ .block = b.* }), + else => {}, }, - else => return l.markExpr(x), }; } - fn markStmt(l: *Lowerer, s: ast.Stmt) Error!void { - switch (s.kind) { - .let => |x| try l.markExpr(x.e), - .@"var" => |x| if (x.init) |e| try l.markExpr(e), - .assign => |x| { - if (x.place.kind != .name) try l.markRoot(x.place); - try l.markExpr(x.e); - }, - .borrow => |x| try l.markRoot(x.place), - .@"return" => |e| if (e) |x| try l.markExpr(x), - .expr => |e| try l.markExpr(e), - .@"while" => |x| { - try l.markExpr(x.cond); - try l.markBlock(x.body); - }, - .@"for" => |x| { - try l.markExpr(x.lo); - try l.markExpr(x.hi); - try l.markBlock(x.body); - }, - .loop, .shield => |b| try l.markBlock(b), - .scope => |x| try l.markBlock(x.body), - .lock => |x| { - try l.markBlock(x.body); - try l.markBlock(x.cancelled); - }, - else => {}, - } - } - - fn markExpr(l: *Lowerer, e: ast.Expr) Error!void { - switch (e.kind) { - .borrow => |x| try l.markRoot(x.place.*), - .index => try l.markRoot(e), - .neg, .not, .deref, .or_trap => |x| try l.markExpr(x.*), - .binary => |x| { - try l.markExpr(x.l.*); - try l.markExpr(x.r.*); - }, - .cast => |x| try l.markExpr(x.e.*), - .call => |x| { - try l.markExpr(x.callee.*); - for (x.args) |a| try l.markExpr(a); - if (x.callee.kind == .field and std.mem.eql(u8, x.callee.kind.field.name, "split_at")) try l.markRoot(x.callee.kind.field.e.*); - }, - .field => |x| try l.markExpr(x.e.*), - .struct_lit => |x| for (x.fields) |f| try l.markExpr(f.e), - .array_rep => |x| try l.markExpr(x.e.*), - .array_list => |xs| for (xs) |x| try l.markExpr(x), - .if_expr => |x| { - try l.markExpr(x.cond); - try l.markBlock(x.then); - if (x.@"else") |els| switch (els) { - .block => |b| try l.markBlock(b), - .@"if" => |inner| try l.markExpr(.{ .span = e.span, .kind = .{ .if_expr = inner } }), - }; - }, - .match_expr => |x| { - try l.markExpr(x.scrutinee); - for (x.arms) |a| try l.markExpr(a.body); - }, - .block => |b| try l.markBlock(b.*), - else => {}, - } - } - // ------------------------------------------------------------ fallible operations (layer 5) const Outcome = struct { role: []const u8, params: []const Ty }; @@ -4242,6 +4301,412 @@ test "terminated blocks reject further emission with a source diagnostic" { try std.testing.expect(l.blocks.items[0].terminated); } +// Independent pre-repair unary expression derivation. Non-unary leaves use +// the unchanged expression handlers; this oracle is only for shallow chains. +const ReferenceUnary = struct { + fn expr(l: *Lowerer, e: ast.Expr, want: ?Ty) Error!Value { + switch (e.kind) { + .not => |x| { + const v = try expr(l, x.*, .bool); + try l.checkOperandTy(x.span, v.ty, .bool); + const t = try l.def("c", .bool, "const.bool true", e.span); + return l.def("not", .bool, try l.fmt("xor.bool %{s}, %{s}", .{ v.name, t.name }), e.span); + }, + .neg => |x| { + const ty = want orelse l.peekType(x.*) orelse return l.fail("E7007", e.span, "the type of this negation cannot be determined", &.{}); + if (ty != .int) return l.fail("E7005", e.span, "negation of a non-integer", &.{}); + if (x.kind == .int) { + const v = parse_mod.parseIntText(x.kind.int.text) orelse return l.fail("E7001", e.span, "malformed integer literal", &.{}); + if (!isSigned(ty.int)) return l.fail("E7005", e.span, "negative literal of an unsigned type", &.{.{ .name = "type", .value = ty.int }}); + const min_mag: u128 = @as(u128, 1) << @intCast(intBits(ty.int) - 1); + if (v > min_mag) return l.fail("E7005", e.span, "integer literal out of range for its type", &.{.{ .name = "type", .value = ty.int }}); + return l.def("c", ty, try l.fmt("const.{s} -{d}", .{ ty.int, v }), e.span); + } + const z = try l.def("zero", ty, try l.fmt("const.{s} 0", .{ty.int}), e.span); + const v = try expr(l, x.*, ty); + try l.checkOperandTy(x.span, v.ty, ty); + return l.def("neg", ty, try l.fmt("sub.checked.{s} %{s}, %{s}", .{ ty.int, z.name, v.name }), e.span); + }, + .deref => |x| { + const r = try expr(l, x.*, null); + const in = r.ty.inner() orelse return l.fail("E7005", e.span, "`*` reads through a borrow", &.{.{ .name = "found", .value = try l.diagnosticTyText(r.ty) }}); + if (r.ty == .slice or r.ty == .slice_mut or in == .array) return l.invalid(.invalid_expression, e.span, "read slice and array elements with `s[i]`, not `*`", &.{}); + if (in == .atomic) return l.fail("E4202", e.span, "an atomic cell is read only by atomic operations: use `atomic.load(r, ordering)`", &.{ + .{ .name = "found", .value = try l.diagnosticTyText(r.ty) }, + .{ .name = "use", .value = "atomic.load" }, + }); + return l.def("v", in, try l.fmt("load %{s}", .{r.name}), e.span); + }, + .cast => |x| { + const to = try l.typeOf(x.ty); + if (to != .int) return l.fail("E7005", x.ty.span, "casts convert between integer types", &.{}); + const from = l.peekType(x.e.*) orelse to; + const v = try expr(l, x.e.*, from); + if (v.ty != .int) return l.fail("E7005", x.e.span, "casts convert between integer types", &.{.{ .name = "found", .value = try l.diagnosticTyText(v.ty) }}); + if (x.mode == .widen) { + const a = std.meta.stringToEnum(air_module.IntType, v.ty.int).?; + const b = std.meta.stringToEnum(air_module.IntType, to.int).?; + if (!verifier_types.lossless(a, b)) return l.invalidWidening(e.span, &.{ .{ .name = "from", .value = v.ty.int }, .{ .name = "to", .value = to.int } }); + } + const mode = switch (x.mode) { + .widen => "widen", + .checked => "checked", + .wrap => "wrap", + }; + return l.def("cast", to, try l.fmt("cast.{s}.{s} %{s}", .{ mode, to.int, v.name }), e.span); + }, + else => return l.expr(e, want), + } + } +}; + +fn expectUnaryMatches(a: Allocator, e: ast.Expr, want: ?Ty, bindings: []const Binding) !void { + const m: ast.Module = .{ .name = "unary", .types = &.{}, .functions = &.{} }; + const parameter: ast.Param = .{ .name = "c_1", .ty = .{ .span = e.span, .kind = .{ .name = "bool" } }, .span = e.span }; + var old: Lowerer = .{ .arena = a, .m = m, .params = &.{parameter}, .in_constant = 7 }; + var current: Lowerer = .{ .arena = a, .m = m, .params = &.{parameter}, .in_constant = 7 }; + try old.bindings.appendSlice(a, bindings); + try current.bindings.appendSlice(a, bindings); + old.cur = try old.newBlock("entry", e.span); + current.cur = try current.newBlock("entry", e.span); + const expected = ReferenceUnary.expr(&old, e, want); + const actual = current.expr(e, want); + if (expected) |v| { + const result = try actual; + try std.testing.expectEqualStrings(v.name, result.name); + try std.testing.expect(v.ty.eql(result.ty)); + } else |err| try std.testing.expectError(err, actual); + try std.testing.expectEqualDeep(old.problem, current.problem); + try std.testing.expectEqualDeep(old.unimpl, current.unimpl); + try std.testing.expectEqualDeep(old.blocks.items, current.blocks.items); + try std.testing.expectEqual(old.counter, current.counter); + try std.testing.expectEqualDeep(old.uses, current.uses); +} + +test "unary expression lowering preserves instruction order and diagnostic priority" { + var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer scratch.deinit(); + const a = scratch.allocator(); + var builder: Lowerer = .{ .arena = a, .m = .{ .name = "unary", .types = &.{}, .functions = &.{} } }; + const bindings = [_]Binding{ + .{ .name = "p", .value = "pointer", .mutable = false, .ty = try builder.wrap(.ref, .{ .int = "i64" }) }, + .{ .name = "s", .value = "slice", .mutable = false, .ty = try builder.wrap(.slice, .{ .int = "u8" }) }, + .{ .name = "r", .value = "array", .mutable = false, .ty = try builder.wrap(.ref, try builder.arrayOf(.{ .int = "u8" }, 2)) }, + .{ .name = "atomic", .value = "atomic_view", .mutable = false, .ty = try builder.wrap(.ref, try builder.wrap(.atomic, .{ .int = "u64" })) }, + }; + const operands = [_][]const u8{ "true", "0i64", "1u64", "127i8", "128i8", "1", "unknown", "*p", "*s", "*r", "*atomic", "{ trap; }" }; + const forms = [_][]const u8{ "{s}", "not {s}", "- {s}", "* {s}", "({s}) as i64", "({s}) as! u8", "({s}) as% usize", "({s}) as bool" }; + inline for (forms) |outer| inline for (forms) |inner| for (operands) |operand| { + const nested = try std.fmt.allocPrint(a, inner, .{operand}); + const expression = try std.fmt.allocPrint(a, outer, .{nested}); + const source = try std.fmt.allocPrint(a, "module unary\nfn f() -> void effects [] {{ return {s}; }}", .{expression}); + const parsed = try parse_mod.parseWithFile(a, source, "unary.aji"); + try std.testing.expect(parsed == .ok); + const e = parsed.ok.functions[0].body.stmts[0].kind.@"return".?; + for ([_]?Ty{ null, .bool, .{ .int = "i64" }, .{ .int = "u8" } }) |want| try expectUnaryMatches(a, e, want, &bindings); + }; +} + +fn unaryTestSpan(column: u32) Span { + return .{ .file = "deep.aji", .start = .{ .line = 2, .col = column }, .end = .{ .line = 2, .col = 100_000 } }; +} + +// Independent old addressability walk. Its deliberately skipped select/lock +// inputs are retained: this repair changes traversal, not storage policy. +const ReferenceAddress = struct { + fn block(l: *Lowerer, b: ast.Block) Error!void { + for (b.stmts) |s| try stmt(l, s); + if (b.tail) |t| try expr(l, t.*); + } + fn root(l: *Lowerer, e: ast.Expr) Error!void { + var x = e; + while (true) switch (x.kind) { + .name => |n| return l.addressable.put(l.arena, n, {}), + .field => |f| x = f.e.*, + .index => |i| { + try expr(l, i.lo.*); + if (i.hi) |h| try expr(l, h.*); + x = i.e.*; + }, + else => return expr(l, x), + }; + } + fn stmt(l: *Lowerer, s: ast.Stmt) Error!void { + switch (s.kind) { + .let => |x| try expr(l, x.e), + .@"var" => |x| if (x.init) |e| try expr(l, e), + .assign => |x| { + if (x.place.kind != .name) try root(l, x.place); + try expr(l, x.e); + }, + .borrow => |x| try root(l, x.place), + .@"return" => |e| if (e) |x| try expr(l, x), + .expr => |e| try expr(l, e), + .@"while" => |x| { + try expr(l, x.cond); + try block(l, x.body); + }, + .@"for" => |x| { + try expr(l, x.lo); + try expr(l, x.hi); + try block(l, x.body); + }, + .loop, .shield => |b| try block(l, b), + .scope => |x| try block(l, x.body), + .lock => |x| { + try block(l, x.body); + try block(l, x.cancelled); + }, + else => {}, + } + } + fn expr(l: *Lowerer, e: ast.Expr) Error!void { + switch (e.kind) { + .borrow => |x| try root(l, x.place.*), + .index => try root(l, e), + .neg, .not, .deref, .or_trap => |x| try expr(l, x.*), + .binary => |x| { + try expr(l, x.l.*); + try expr(l, x.r.*); + }, + .cast => |x| try expr(l, x.e.*), + .call => |x| { + try expr(l, x.callee.*); + for (x.args) |arg| try expr(l, arg); + if (x.callee.kind == .field and std.mem.eql(u8, x.callee.kind.field.name, "split_at")) try root(l, x.callee.kind.field.e.*); + }, + .field => |x| try expr(l, x.e.*), + .struct_lit => |x| for (x.fields) |f| try expr(l, f.e), + .array_rep => |x| try expr(l, x.e.*), + .array_list => |xs| for (xs) |x| try expr(l, x), + .if_expr => |x| { + try expr(l, x.cond); + try block(l, x.then); + if (x.@"else") |els| switch (els) { + .block => |b| try block(l, b), + .@"if" => |inner| try expr(l, .{ .span = e.span, .kind = .{ .if_expr = inner } }), + }; + }, + .match_expr => |x| { + try expr(l, x.scrutinee); + for (x.arms) |arm| try expr(l, arm.body); + }, + .block => |b| try block(l, b.*), + else => {}, + } + } +}; + +fn expectAddressMatches(a: Allocator, b: ast.Block) !void { + const m: ast.Module = .{ .name = "address", .types = &.{}, .functions = &.{} }; + var old: Lowerer = .{ .arena = a, .m = m }; + var current: Lowerer = .{ .arena = a, .m = m }; + try ReferenceAddress.block(&old, b); + try current.findAddressable(b); + try std.testing.expectEqual(old.addressable.count(), current.addressable.count()); + var before = old.addressable.keyIterator(); + var after = current.addressable.keyIterator(); + while (before.next()) |name| try std.testing.expectEqualStrings(name.*, after.next().?.*); + try std.testing.expect(after.next() == null); + try std.testing.expect(current.problem == null); + try std.testing.expectEqual(@as(usize, 0), current.blocks.items.len); +} + +test "addressability continuations retain roots, skipped inputs and sibling order" { + var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer scratch.deinit(); + const a = scratch.allocator(); + const expressions = [_][]const u8{ + "x", "ref x", "mut x", "x[y[0]..z[0]]", "x[y[0]].field[z[0]]", + "foo(ref a, b[i], mut c[j])", "r.split_at(i[0])", "[ref a, ref b]", "[ref a; 2]", "Holder { left: ref x, right: ref y }", + "not - *x[i]", "x[i] as! u8", "foo(ref a) or trap", "if cond[i] { ref a } else if flag[j] { mut b } else { mut c }", "match value[i] { Shape::A => ref a, Shape::B => mut b }", + }; + for (expressions) |expression| { + const source = try std.fmt.allocPrint(a, "module address fn f() -> void effects [] {{ let result = {s}; }}", .{expression}); + const parsed = try parse_mod.parse(a, source); + try std.testing.expect(parsed == .ok); + try expectAddressMatches(a, parsed.ok.functions[0].body); + } + const parsed = try parse_mod.parse(a, "module address fn f() -> void effects [] { " ++ + "let a = ref alpha; var b: [u8; 2] = [other[i]; 2]; " ++ + "target[j] = call(ref source); while cond[k] { body[l]; break; } " ++ + "for i in lo[0]..hi[0] { element[i]; continue; } " ++ + "loop { ref r = data[j]; break; } shield { foo(ref shared); } " ++ + "scope s { bar(ref scoped); } " ++ + "lock ref skipped[0] as g { normal[0]; } cancelled { cancel[0]; } " ++ + "return ref tail; }"); + try std.testing.expect(parsed == .ok); + try expectAddressMatches(a, parsed.ok.functions[0].body); + const span = unaryTestSpan(1); + const ignored: ast.Expr = .{ .span = span, .kind = .{ .name = "ignored" } }; + const ignored_borrow: ast.Expr = .{ .span = span, .kind = .{ .borrow = .{ .place = &ignored, .mutable = false, .unchecked = false } } }; + const statements = [_]ast.Stmt{ + .{ .span = span, .kind = .{ .select = .{ .arms = &.{}, .cancelled_binds = &.{}, .cancelled = ignored_borrow, .span = span } } }, + .{ .span = span, .kind = .{ .@"return" = null } }, + .{ .span = span, .kind = .trap }, + }; + try expectAddressMatches(a, .{ .span = span, .stmts = &statements, .tail = &ignored }); +} + +test "addressability descends deep expressions and blocks and releases OOM metadata" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const span = unaryTestSpan(1); + const m: ast.Module = .{ .name = "address", .types = &.{}, .functions = &.{} }; + const name: ast.Expr = .{ .span = span, .kind = .{ .name = "root" } }; + var e: ast.Expr = .{ .span = span, .kind = .{ .borrow = .{ .place = &name, .mutable = false, .unchecked = false } } }; + for (0..32_768) |i| { + const inner = try a.create(ast.Expr); + inner.* = e; + if (i % 2 == 0) e = .{ .span = span, .kind = .{ .not = inner } } else { + const b = try a.create(ast.Block); + const statements = try a.alloc(ast.Stmt, 1); + statements[0] = .{ .span = span, .kind = .{ .expr = inner.* } }; + b.* = .{ .span = span, .stmts = statements, .tail = null }; + e = .{ .span = span, .kind = .{ .block = b } }; + } + } + var successful: Lowerer = .{ .arena = a, .m = m }; + try successful.markAddressable(.{ .expr = e }); + try std.testing.expectEqual(@as(u32, 1), successful.addressable.count()); + try std.testing.expect(successful.addressable.contains("root")); + var fail_index: usize = 0; + while (true) : (fail_index += 1) { + try std.testing.expect(fail_index < 256); + var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = fail_index }); + var arena: std.heap.ArenaAllocator = .init(failing.allocator()); + var l: Lowerer = .{ .arena = arena.allocator(), .m = m }; + const result = l.markAddressable(.{ .expr = e }); + if (failing.has_induced_failure) try std.testing.expectError(error.OutOfMemory, result) else { + try result; + try std.testing.expectEqual(@as(u32, 1), l.addressable.count()); + try std.testing.expect(l.addressable.contains("root")); + } + try std.testing.expect(l.problem == null); + try std.testing.expectEqual(@as(usize, 0), l.out.items.len); + arena.deinit(); + try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes); + if (!failing.has_induced_failure) break; + } +} + +test "unary lowering processes deep boolean, negative and cast spines" { + var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer scratch.deinit(); + const a = scratch.allocator(); + const count = 32_768; + const m: ast.Module = .{ .name = "deep", .types = &.{}, .functions = &.{} }; + for ([_]enum { not, neg, cast, deref }{ .not, .neg, .cast, .deref }) |kind| { + var l: Lowerer = .{ .arena = a, .m = m }; + try l.bindings.append(a, .{ .name = "n", .value = "input", .mutable = false, .ty = .{ .int = "i64" } }); + var e: ast.Expr = .{ .span = unaryTestSpan(count + 1), .kind = if (kind == .not or kind == .deref) .{ .boolean = false } else .{ .name = "n" } }; + var i: usize = count; + while (i != 0) { + i -= 1; + const inner = try l.arena.create(ast.Expr); + inner.* = e; + const span = unaryTestSpan(@intCast(i + 1)); + e = .{ .span = span, .kind = switch (kind) { + .not => .{ .not = inner }, + .neg => .{ .neg = inner }, + .deref => .{ .deref = inner }, + .cast => .{ .cast = .{ .e = inner, .mode = switch (i % 3) { + 0 => .widen, + 1 => .checked, + else => .wrap, + }, .ty = .{ .span = span, .kind = .{ .name = "i64" } } } }, + } }; + } + l.cur = try l.newBlock("entry", e.span); + const result = l.expr(e, null); + if (kind == .deref) { + try std.testing.expectError(error.Lower, result); + try std.testing.expectEqualStrings("E7005", l.problem.?.code); + try std.testing.expectEqualDeep(unaryTestSpan(count), l.problem.?.span); + try std.testing.expectEqual(@as(usize, 1), l.blocks.items[0].insts.items.len); + continue; + } + const value = try result; + try std.testing.expectEqualDeep(if (kind == .not) Ty.bool else Ty{ .int = "i64" }, value.ty); + const instructions = l.blocks.items[0].insts.items; + try std.testing.expectEqual(@as(usize, switch (kind) { + .not => 2 * count + 1, + .neg => 2 * count, + .cast => count, + .deref => unreachable, + }), instructions.len); + for (0..count) |index| { + const span = unaryTestSpan(@intCast(count - index)); + switch (kind) { + .not => { + try std.testing.expectEqualDeep(@as(?Span, span), instructions[2 * index + 1].span); + try std.testing.expectEqualDeep(@as(?Span, span), instructions[2 * index + 2].span); + }, + .neg => { + try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(@intCast(index + 1))), instructions[index].span); + const previous = if (index == 0) "input" else try std.fmt.allocPrint(a, "neg_{d}", .{count + index}); + const expected = try std.fmt.allocPrint(a, "%neg_{d} = sub.checked.i64 %zero_{d}, %{s}", .{ count + index + 1, count - index, previous }); + try std.testing.expectEqualStrings(expected, instructions[count + index].text); + try std.testing.expectEqualDeep(@as(?Span, span), instructions[count + index].span); + }, + .cast => try std.testing.expectEqualDeep(@as(?Span, span), instructions[index].span), + .deref => unreachable, + } + } + try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(1)), instructions[instructions.len - 1].span); + try std.testing.expect(l.problem == null); + } +} + +test "unary lowering OOM retains complete instruction prefixes and no output" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const m: ast.Module = .{ .name = "oom", .types = &.{}, .functions = &.{} }; + const span = unaryTestSpan(1); + var e: ast.Expr = .{ .span = span, .kind = .{ .int = .{ .text = "1i64" } } }; + for (0..64) |_| { + const operand = try a.create(ast.Expr); + operand.* = e; + e = .{ .span = span, .kind = .{ .neg = operand } }; + const cast = try a.create(ast.Expr); + cast.* = e; + e = .{ .span = span, .kind = .{ .cast = .{ .e = cast, .mode = .checked, .ty = .{ .span = span, .kind = .{ .name = "i64" } } } } }; + } + var old: Lowerer = .{ .arena = a, .m = m }; + old.cur = try old.newBlock("entry", span); + _ = try ReferenceUnary.expr(&old, e, null); + const expected = old.blocks.items[0].insts.items; + var fail_index: usize = 0; + while (true) : (fail_index += 1) { + try std.testing.expect(fail_index < 256); + var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = fail_index }); + var arena: std.heap.ArenaAllocator = .init(failing.allocator()); + var l: Lowerer = .{ .arena = arena.allocator(), .m = m }; + const result: Error!Value = blk: { + l.cur = l.newBlock("entry", span) catch |err| break :blk err; + break :blk l.expr(e, null); + }; + if (failing.has_induced_failure) { + try std.testing.expectError(error.OutOfMemory, result); + try std.testing.expect(l.problem == null); + } else { + try std.testing.expect((try result).ty.eql(.{ .int = "i64" })); + try std.testing.expectEqual(expected.len, l.blocks.items[0].insts.items.len); + } + if (l.cur) |index| { + const actual = l.blocks.items[index].insts.items; + try std.testing.expect(actual.len <= expected.len); + try std.testing.expectEqualDeep(expected[0..actual.len], actual); + } + try std.testing.expectEqual(@as(usize, 0), l.out.items.len); + arena.deinit(); + try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes); + if (!failing.has_induced_failure) break; + } +} + test "source property queries prune deep diamonds without changing witnesses" { var scratch = std.heap.ArenaAllocator.init(std.testing.allocator); defer scratch.deinit(); diff --git a/tests/hosted/source_expression_depth.py b/tests/hosted/source_expression_depth.py new file mode 100644 index 0000000..5d1570b --- /dev/null +++ b/tests/hosted/source_expression_depth.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +"""Unary depth, exact lowering/fuel and rejected-value positions (Q-061).""" +import json +from pathlib import Path +import subprocess +import tempfile + +REPO = Path(__file__).resolve().parents[2] +AJI = REPO / 'zig-out/bin/aji' +checks = 0 + + +def cli(command, path, *options, code=0): + global checks + result = subprocess.run([str(AJI), command, *map(str, options), str(path)], capture_output=True) + assert (result.returncode, result.stderr) == (code, b''), (command, path, result.returncode, result.stdout, result.stderr) + checks += 1 + return result.stdout + + +def source(kind, depth): + if kind == 'not': + ty, setup, expression = 'bool', '', 'not ' * depth + 'false' + instructions, expected = 2 * depth + 2, bool(depth % 2) + elif kind == 'neg': + ty, setup, expression = 'i64', 'let n: i64 = 1i64; ', '- ' * depth + 'n' + instructions, expected = 2 * depth + 2, 1 if depth % 2 == 0 else -1 + else: + ty, setup = 'i64', '' + expression = '1i64' + ''.join(' ' + ('as i64', 'as! i64', 'as% i64')[i % 3] for i in range(depth)) + instructions, expected = depth + 2, 1 + return f'module depth\nfn main() -> {ty} effects [] {{ {setup}return {expression}; }}\n', instructions, expected + + +with tempfile.TemporaryDirectory(prefix='aji-expression-depth-') as directory: + root = Path(directory) + for depth in (0, 1, 16, 1024, 16384, 65536): + for kind in ('not', 'neg', 'cast'): + path = root / f'{kind}-{depth}.aji' + text, instructions, expected = source(kind, depth) + path.write_text(text) + assert cli('check', path) == b'' + lowered = cli('lower', path) + actual = sum(b' = ' in line or line.strip().startswith(b'ret ') for line in lowered.splitlines()) + assert actual == instructions, (kind, depth, actual, instructions) + if depth <= 1024: + # Independently count every emitted instruction and ret. + # No wall-clock timeout changes execution or ends a test. + assert json.loads(cli('run', path, '--fuel', instructions)) == {'status': 'returned', 'value': expected} + assert json.loads(cli('run', path, '--fuel', instructions - 1, code=5)) == { + 'status': 'limit_exceeded', 'kind': 'fuel', 'limit': instructions - 1, 'steps': instructions - 1} + air = path.with_suffix('.air') + air.write_bytes(lowered) + assert cli('run', air, '--fuel', instructions) == cli('run', path, '--fuel', instructions) + record = root / 'hosted.json' + assert cli('run', path, '--fuel', instructions, '--profile', 'hosted', '--result-file', record) == b'' + assert json.loads(record.read_text()) == {'status': 'returned', 'value': expected} + print(f'unary depth: {kind} {depth}', flush=True) + + for depth in (1024, 16384, 65536): + header = 'module depth\nfn main() -> i64 effects [] { return ' + path = root / f'deref-{depth}.aji' + path.write_text(header + '* ' * depth + '1i64; }\n') + error = json.loads(cli('check', path, code=1)) + col = len(header) - len('module depth\n') + 1 + 2 * (depth - 1) + assert (error['code'], error['line'], error['col'], error['file']) == ('E7005', 2, col, str(path)), error + for command in ('lower', 'run', 'report', 'explore'): + assert json.loads(cli(command, path, code=1)) == error + + # Signed boundary literal remains one negative constant; the outer + # checked negation traps rather than changing literal acceptance. + minimum = root / 'minimum.aji' + minimum.write_text('module depth\nfn main() -> i8 effects [] { return -128i8; }\n') + assert json.loads(cli('run', minimum, '--fuel', 2)) == {'status': 'returned', 'value': -128} + minimum.write_text('module depth\nfn main() -> i8 effects [] { return - -128i8; }\n') + assert json.loads(cli('run', minimum, '--fuel', 2, code=5)) == { + 'status': 'limit_exceeded', 'kind': 'fuel', 'limit': 2, 'steps': 2} + trapped = json.loads(cli('run', minimum, '--fuel', 3, code=4)) + assert (trapped['status'], trapped['code'], trapped['kind'], trapped['inst']) == ( + 'trapped', 'T0003', 'trap.overflow', 2), trapped + +print(f'source expression depth: {checks} checks passed') diff --git a/tests/hosted/source_grammar.py b/tests/hosted/source_grammar.py index 3ef512f..d560d39 100644 --- a/tests/hosted/source_grammar.py +++ b/tests/hosted/source_grammar.py @@ -69,7 +69,8 @@ with tempfile.TemporaryDirectory(prefix='aji-grammar-') as directory: assert result['value'] == 42, result # Prefix depth is a parser/formatter regression, not an acceptance bound - # or a claim that deep lowering is already iterative (Q-061). + # or a claim about all lowering paths (Q-061). Unary lowering has separate + # full-pipeline coverage in source_expression_depth.py. for depth in (1024, 16384, 65536): prefix = 'module deep\nfn main() -> bool effects [] { return ' + 'not ' * depth deep = root / f'deep-{depth}.aji'