From 6945b511a4e4710969a14bdb8efbbbd54c75d6d9 Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Sat, 10 Oct 2026 17:55:46 +0300 Subject: [PATCH] cli: lower scalar binary operands iteratively --- docs/design/open-questions.md | 2 + docs/design/source-expression-depth-audit.md | 63 ++- docs/plan/phase-6-source-language.md | 6 + src/frontend/lower.zig | 533 +++++++++++++++---- tests/hosted/source_expression_depth.py | 85 ++- 5 files changed, 572 insertions(+), 117 deletions(-) diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index 2a95737..d2812fe 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -531,4 +531,6 @@ A subsequent finite source probe, `let n = 1; return - … n;` in an i64 functio The [expected-use increment](source-expression-depth-audit.md#expected-use-query-continuations) repairs that mutual expression/statement/block query path. It preserves lazy hint queries, search order, cast hint removal and the outer let rebinding barrier; deep inferred unary checks accept through 65,536 and missing hints retain E7007. No new inference or acceptance limit is introduced. Follow-up finite probes now confirm separate native failures at 1,024 levels in binary lowering, parenthesized parsing and generic expression transformation. Q-061 remains open for those observed paths and the remaining inventory. +The [binary operand increment](source-expression-depth-audit.md#binary-operand-lowering-continuations) shares explicit continuations with unary lowering, preserving type/error priority, instruction order and short-circuit CFG. Arithmetic checks/lowerings accept through 65,536 operations; deep boolean chains now reach the existing E5101 block limit without stack failure. No normative depth limit or operator rule changes. Current parenthesized and generic-unary checks still abort at 1,024 levels; Q-061's remaining inventory and independent Phase 6 gates stay open. + 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 a3cc29b..45287fb 100644 --- a/docs/design/source-expression-depth-audit.md +++ b/docs/design/source-expression-depth-audit.md @@ -214,9 +214,9 @@ per-step GC validation or measure model capability. Fixed pre/post executables retain exact exit/stdout/stderr for all 1,423 public source checks and 506 successful lowerings (`source-use-query-cli-compatibility.json`). -## Remaining work +## Binary operand lowering continuations -Follow-up probes after the expected-use repair accept 16 levels but abort at +The preceding follow-up probes accept 16 levels but abort at 1,024, with empty stdout, in three independent paths: a left-associated `1i64 + … + 1i64` chain in `Lowerer.binary`; nested parentheses in the parser's primary/postfix expression path; and a unary chain in a specialized generic @@ -224,6 +224,65 @@ function body in `generics.expression`/`walk`. Evidence is retained as `post-use-query-depth-probes.json` and `post-use-*.stdout/.stderr`. These are observed native failures, not normative depth rejections. +Unary and binary scalar operands now share one continuation driver. Eager +operators retain operand-type selection, left lowering/check before right, +post-operand operator validation and exact instruction/span/name order. This +also removes native re-entry on alternating unary/binary trees. Non-operand +handlers remain outside this repair. + +Boolean continuations preserve short-circuit lowering: validate left, emit +the short constant, create RHS/join blocks and the join parameter, branch, +lower/check right, branch to the stored join and resume there. Runtime still +evaluates right only when needed; both operands are lowered and type checked. +Negative zero order, signed-minimum literal handling, cast checks, atomic +diagnostics and iref identity rules remain unchanged. Host worklist OOM +propagates without a query diagnostic or public partial AIR; its metadata is +released while generated values retain their caller-arena lifetime. Allocation +counts/failure-index outcomes are not promised identical. + +The independent old scalar derivation now covers binary rules as well as +unary descent. It compares 6,048 binary/wrapper/context combinations, in +addition to the existing unary cases: values/errors, blocks, parameters, +instructions/spans, counter, current block and features. Name/type/query and +non-operand handlers are shared, outside this oracle's independence. Separate +tests cover 32,768 left/right arithmetic nodes, 32,768 alternating groups, +16,384 boolean/unary groups in both orientations, and every backing-allocation +failure on numeric and boolean fixtures with exact complete block prefixes and +full cleanup. These helper tests do not assert arbitrary source acceptance. + +The old 1,024-addition source now accepts, as do full arithmetic checks and +lowerings through 65,536 operations. Boolean chains accept at 1,024; at 16,384 +both and/or now reach the existing E5101 block limit (spec 08 §7), with +`limit: blocks per function`, `max: 16384`, `found: 32769`, rather than aborting. +The raw source checks are retained in `binary-lowering-repaired-depth.json` +and `binary-repaired-*.stdout/.stderr`. The permanent CLI suite checks exact +instruction counts, fuel boundaries, values/profiles/source-to-AIR parity, +the block-limit refusal, and skipped/executed RHS division traps. Trap source +locations are checked separately; plain AIR has no source map. + +Build/unit/Zig format checks and all 1,793 ordinary conformance cases pass +with exact unique corpus coverage (`source-binary-lowering-conformance.jsonl` +and its audit). The permanent expression-depth suite passes 360 checks. +Non-value/independent-error CLI suites pass 635/234 checks; +fixed pre/post executables retain exact exit/stdout/stderr on all 1,423 public +source checks and 506 successful lowerings +(`source-binary-lowering-cli-compatibility.json`). These do not establish full +GC validation or a model-capability result. + +No normative rule, source/AIR format, feature, error code, bundle text, runtime +instruction, ownership rule or acceptance limit changes. Q-061 remains open. + +## Remaining work + +Current follow-up checks still abort with empty stdout at 1,024 parenthesized +levels and 1,024 generic unary levels (`binary-followup-depth-probes.json` and +`binary-followup-*.stdout/.stderr`). Parenthesized parsing and generic expression +transformation require separate repairs. + +Inspection of the generic transformation also finds a recursive qualified-path +callback (`generics.path`). Its deep full-source behavior is unverified here; +it belongs in that repair's callback inventory, rather than Q-059's type scope. + Other expression/block handlers and their complete depth behavior need further auditing. 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 diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index 0d84277..7b14f97 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -544,3 +544,9 @@ Independent shallow descent comparisons (703), deep structural/built-in/fallback The [Q-061 expected-use increment](../design/source-expression-depth-audit.md#expected-use-query-continuations) replaces mutual expression/statement/block query recursion with explicit requests. Deferred comparison/shift/for hints preserve lazy search order; the outer rest cursor, top-level let rebinding barrier, cast hint removal and skipped kinds retain their original policy. Host metadata OOM is unknown without diagnostics/output; no new inference, normative/bundle/feature/code/acceptance-limit or runtime/ownership rule is introduced. Independent shallow comparisons (967), 32,768-level unary/mixed/block helpers, deferred-hint allocation traps and worklist-OOM cleanup tests pass. Final build/units/format checks, all 1,793 ordinary conformance cases with exact coverage, 186 expression-depth, 635 non-value and 234 independent-error CLI checks pass; old/new public checks/lowerings remain exact (1,423/506). The previously crashing inferred-binding source accepts through 65,536 negations, while missing context retains E7007. Follow-up probes confirm separate native failures at 1,024 levels in binary lowering, parenthesized parsing and generic expression transformation. Q-061's remaining inventory, Q-060's full per-step validation and Phase 6 exit review remain open. No fresh Claude review covers this increment. + +## Source binary operand lowering (2026-10-10) + +The [Q-061 binary increment](../design/source-expression-depth-audit.md#binary-operand-lowering-continuations) shares scalar continuations with unary lowering, eliminating native re-entry on alternating operator trees. Eager operand type/error priority, instruction/span/name order and boolean RHS/join construction are retained; runtime short-circuit behavior and fuel remain unchanged. Worklist OOM propagates without public partial AIR. No normative/bundle/feature/code/acceptance-limit or ownership/runtime rule changes. + +Independent binary/wrapper/context comparisons (6,048), deep left/right/mixed/boolean helpers and exact failed-allocation block prefixes pass. Build/units/format checks, all 1,793 ordinary conformance cases with exact coverage, 360 expression-depth, 635 non-value and 234 independent-error CLI checks pass; old/new public checks/lowerings remain exact (1,423/506). Arithmetic checks/lowerings accept through 65,536 operations. Boolean chains accept at 1,024; at 16,384 they reach the existing E5101 block limit (`max: 16384`, `found: 32769`), rather than aborting. Current probes retain separate parenthesized/generic failures at 1,024 levels; their callbacks and other expression/block paths still need repair/audit. Q-061, Q-060's full per-step validation and Phase 6 exit review remain open. No fresh Claude review covers this increment. diff --git a/src/frontend/lower.zig b/src/frontend/lower.zig index 0ef160b..8e30b32 100644 --- a/src/frontend/lower.zig +++ b/src/frontend/lower.zig @@ -1983,7 +1983,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), + .not, .neg, .deref, .cast, .binary => return l.operandExpr(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 @@ -2032,7 +2032,6 @@ 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", &.{}), - .binary => |x| return l.binary(e, x.op, x.l.*, x.r.*, want), .call => |x| return l.call(e, x.callee.*, x.args, false), .if_expr => |x| return l.ifExpr(e.span, x.*, want), .block => |b| { @@ -2056,122 +2055,160 @@ 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 }; + // Scalar unary and binary operands share one worklist so alternating + // operator trees do not re-enter the native stack through expr. + fn operandExpr(l: *Lowerer, initial: ast.Expr, initial_want: ?Ty) Error!Value { + const Frame = union(enum) { + unary: struct { e: ast.Expr, ty: Ty = .void, zero: ?Value = null }, + binary_left: struct { e: ast.Expr, ty: Ty }, + binary_right: struct { e: ast.Expr, ty: Ty, left: Value }, + boolean_left: ast.Expr, + boolean_right: struct { e: ast.Expr, join: usize, name: []const u8 }, + }; 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 } }); + evaluate: while (true) { + var v: Value = while (true) { + switch (e.kind) { + .not, .deref => |x| { + try pending.append(l.arena, .{ .unary = .{ .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, .{ .unary = .{ .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, .{ .unary = .{ .e = e, .ty = to } }); + e = x.e.*; + }, + .binary => |x| { + if (x.op == .@"and" or x.op == .@"or") { + try pending.append(l.arena, .{ .boolean_left = e }); + want = .bool; + } else { + const cmp = switch (x.op) { + .eq, .ne, .lt, .le, .gt, .ge => true, + else => false, + }; + const shift = x.op == .shl or x.op == .shr; + const operand: ?Ty = if (cmp) (l.peekType(x.l.*) orelse l.peekType(x.r.*)) else if (shift) (want orelse l.peekType(x.l.*)) else (want orelse l.peekType(x.l.*) orelse l.peekType(x.r.*)); + const ty = operand orelse return l.fail("E7007", e.span, "the type of this operation cannot be determined; add a suffix or annotation", &.{}); + try pending.append(l.arena, .{ .binary_left = .{ .e = e, .ty = ty } }); + want = ty; + } + e = x.l.*; + }, + else => break try l.expr(e, want), } - 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; + }; + while (pending.pop()) |continuation| switch (continuation) { + .unary => |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, + }, + .binary_left => |frame| { + const x = frame.e.kind.binary; + try l.checkOperandTy(x.l.span, v.ty, frame.ty); + try pending.append(l.arena, .{ .binary_right = .{ .e = frame.e, .ty = frame.ty, .left = v } }); + e = x.r.*; + want = frame.ty; + continue :evaluate; + }, + .binary_right => |frame| { + try l.checkOperandTy(frame.e.kind.binary.r.span, v.ty, frame.ty); + v = try l.binaryValue(frame.e, frame.ty, frame.left, v); + }, + .boolean_left => |parent| { + const x = parent.kind.binary; + const lv = v; + try l.checkOperandTy(x.l.span, lv.ty, .bool); + const short = try l.def("c", .bool, if (x.op == .@"and") "const.bool false" else "const.bool true", parent.span); + const rhs_b = try l.newBlock(if (x.op == .@"and") "and_rhs" else "or_rhs", x.r.span); + const join = try l.newBlock(if (x.op == .@"and") "and_end" else "or_end", parent.span); + const rname = try l.freshName(if (x.op == .@"and") "and" else "or"); + try l.blocks.items[join].params.append(l.arena, .{ .name = rname, .ty = .bool }); + const jn = l.blocks.items[join].name; + if (x.op == .@"and") { + try l.term(try l.fmt("cbr %{s}, @{s}(), @{s}(%{s})", .{ lv.name, l.blocks.items[rhs_b].name, jn, short.name }), parent.span); + } else try l.term(try l.fmt("cbr %{s}, @{s}(%{s}), @{s}()", .{ lv.name, jn, short.name, l.blocks.items[rhs_b].name }), parent.span); + l.cur = rhs_b; + try pending.append(l.arena, .{ .boolean_right = .{ .e = parent, .join = join, .name = rname } }); + e = x.r.*; + want = .bool; + continue :evaluate; + }, + .boolean_right => |frame| { + try l.checkOperandTy(frame.e.kind.binary.r.span, v.ty, .bool); + try l.term(try l.fmt("br @{s}(%{s})", .{ l.blocks.items[frame.join].name, v.name }), frame.e.span); + l.cur = frame.join; + v = .{ .name = frame.name, .ty = .bool }; + }, + }; + 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" => { - // Short-circuit: the right operand runs only when needed. - const lv = try l.expr(a, .bool); - try l.checkOperandTy(a.span, lv.ty, .bool); - const short = try l.def("c", .bool, if (op == .@"and") "const.bool false" else "const.bool true", e.span); - const rhs_b = try l.newBlock(if (op == .@"and") "and_rhs" else "or_rhs", b.span); - const join = try l.newBlock(if (op == .@"and") "and_end" else "or_end", e.span); - const rname = try l.freshName(if (op == .@"and") "and" else "or"); - try l.blocks.items[join].params.append(l.arena, .{ .name = rname, .ty = .bool }); - const jn = l.blocks.items[join].name; - if (op == .@"and") { - try l.term(try l.fmt("cbr %{s}, @{s}(), @{s}(%{s})", .{ lv.name, l.blocks.items[rhs_b].name, jn, short.name }), e.span); - } else try l.term(try l.fmt("cbr %{s}, @{s}(%{s}), @{s}()", .{ lv.name, jn, short.name, l.blocks.items[rhs_b].name }), e.span); - l.cur = rhs_b; - const rv = try l.expr(b, .bool); - try l.checkOperandTy(b.span, rv.ty, .bool); - try l.term(try l.fmt("br @{s}(%{s})", .{ jn, rv.name }), e.span); - l.cur = join; - return .{ .name = rname, .ty = .bool }; - }, - else => {}, - } + // Both operands and their type checks are complete before this step. + fn binaryValue(l: *Lowerer, e: ast.Expr, ty: Ty, lv: Value, rv: Value) Error!Value { + const op = e.kind.binary.op; const cmp = switch (op) { .eq, .ne, .lt, .le, .gt, .ge => true, else => false, }; - const shift = op == .shl or op == .shr; - const operand: ?Ty = if (cmp) (l.peekType(a) orelse l.peekType(b)) else if (shift) (want orelse l.peekType(a)) else (want orelse l.peekType(a) orelse l.peekType(b)); - const ty = operand orelse return l.fail("E7007", e.span, "the type of this operation cannot be determined; add a suffix or annotation", &.{}); - const lv = try l.expr(a, ty); - try l.checkOperandTy(a.span, lv.ty, ty); - const rv = try l.expr(b, ty); - try l.checkOperandTy(b.span, rv.ty, ty); // `iref` identity (spec 03 §22): equal graph and slot; never a trap. if (ty == .iref) { if (op != .eq and op != .ne) return l.fail("E7005", e.span, "`iref` handles are compared with `==` and `!=` only", &.{}); @@ -5032,9 +5069,9 @@ test "deep callee paths own one complete string and bounded lookup stays flat" { try std.testing.expect(!fail.has_induced_failure); } -// Independent pre-repair unary expression derivation. Non-unary leaves use -// the unchanged expression handlers; this oracle is only for shallow chains. -const ReferenceUnary = struct { +// Independent pre-repair unary/binary expression derivation. Other leaves +// share expression handlers; this oracle is only for shallow operand trees. +const ReferenceOperands = struct { fn expr(l: *Lowerer, e: ast.Expr, want: ?Ty) Error!Value { switch (e.kind) { .not => |x| { @@ -5086,12 +5123,84 @@ const ReferenceUnary = struct { }; return l.def("cast", to, try l.fmt("cast.{s}.{s} %{s}", .{ mode, to.int, v.name }), e.span); }, + .binary => |x| return binary(l, e, x.op, x.l.*, x.r.*, want), else => return l.expr(e, want), } } + fn binary(l: *Lowerer, e: ast.Expr, op: ast.BinOp, a: ast.Expr, b: ast.Expr, want: ?Ty) Error!Value { + switch (op) { + .@"and", .@"or" => { + // Short-circuit: the right operand runs only when needed. + const lv = try expr(l, a, .bool); + try l.checkOperandTy(a.span, lv.ty, .bool); + const short = try l.def("c", .bool, if (op == .@"and") "const.bool false" else "const.bool true", e.span); + const rhs_b = try l.newBlock(if (op == .@"and") "and_rhs" else "or_rhs", b.span); + const join = try l.newBlock(if (op == .@"and") "and_end" else "or_end", e.span); + const rname = try l.freshName(if (op == .@"and") "and" else "or"); + try l.blocks.items[join].params.append(l.arena, .{ .name = rname, .ty = .bool }); + const jn = l.blocks.items[join].name; + if (op == .@"and") { + try l.term(try l.fmt("cbr %{s}, @{s}(), @{s}(%{s})", .{ lv.name, l.blocks.items[rhs_b].name, jn, short.name }), e.span); + } else try l.term(try l.fmt("cbr %{s}, @{s}(%{s}), @{s}()", .{ lv.name, jn, short.name, l.blocks.items[rhs_b].name }), e.span); + l.cur = rhs_b; + const rv = try expr(l, b, .bool); + try l.checkOperandTy(b.span, rv.ty, .bool); + try l.term(try l.fmt("br @{s}(%{s})", .{ jn, rv.name }), e.span); + l.cur = join; + return .{ .name = rname, .ty = .bool }; + }, + else => {}, + } + const cmp = switch (op) { + .eq, .ne, .lt, .le, .gt, .ge => true, + else => false, + }; + const shift = op == .shl or op == .shr; + const operand: ?Ty = if (cmp) (l.peekType(a) orelse l.peekType(b)) else if (shift) (want orelse l.peekType(a)) else (want orelse l.peekType(a) orelse l.peekType(b)); + const ty = operand orelse return l.fail("E7007", e.span, "the type of this operation cannot be determined; add a suffix or annotation", &.{}); + const lv = try expr(l, a, ty); + try l.checkOperandTy(a.span, lv.ty, ty); + const rv = try expr(l, b, ty); + try l.checkOperandTy(b.span, rv.ty, ty); + // `iref` identity (spec 03 §22): equal graph and slot; never a trap. + if (ty == .iref) { + if (op != .eq and op != .ne) return l.fail("E7005", e.span, "`iref` handles are compared with `==` and `!=` only", &.{}); + const c = try l.def("cmp", .bool, try l.fmt("iref.eq %{s}, %{s}", .{ lv.name, rv.name }), e.span); + if (op == .eq) return c; + const t = try l.def("c", .bool, "const.bool true", e.span); + return l.def("cmp", .bool, try l.fmt("xor.bool %{s}, %{s}", .{ c.name, t.name }), e.span); + } + if (ty == .bool and !(op == .eq or op == .ne or op == .bit_and or op == .bit_or or op == .bit_xor)) + return l.fail("E7005", e.span, "this operation needs integer operands", &.{}); + if (ty != .bool and ty != .int) return l.fail("E7005", e.span, "this operation needs integer or boolean operands", &.{}); + const t = try l.tyText(ty); + const text = switch (op) { + .add => try l.fmt("add.checked.{s}", .{t}), + .sub => try l.fmt("sub.checked.{s}", .{t}), + .mul => try l.fmt("mul.checked.{s}", .{t}), + .div => try l.fmt("div.checked.{s}", .{t}), + .rem => try l.fmt("rem.checked.{s}", .{t}), + .add_wrap => try l.fmt("add.wrap.{s}", .{t}), + .sub_wrap => try l.fmt("sub.wrap.{s}", .{t}), + .mul_wrap => try l.fmt("mul.wrap.{s}", .{t}), + .bit_and => try l.fmt("and.{s}", .{t}), + .bit_or => try l.fmt("or.{s}", .{t}), + .bit_xor => try l.fmt("xor.{s}", .{t}), + .shl => try l.fmt("shl.{s}", .{t}), + .shr => try l.fmt("shr.{s}", .{t}), + .eq => try l.fmt("eq.{s}", .{t}), + .ne => try l.fmt("ne.{s}", .{t}), + .lt => try l.fmt("lt.{s}", .{t}), + .le => try l.fmt("le.{s}", .{t}), + .gt => try l.fmt("gt.{s}", .{t}), + .ge => try l.fmt("ge.{s}", .{t}), + .@"and", .@"or" => unreachable, + }; + return l.def(if (cmp) "cmp" else "t", if (cmp) .bool else ty, try l.fmt("{s} %{s}, %{s}", .{ text, lv.name, rv.name }), e.span); + } }; -fn expectUnaryMatches(a: Allocator, e: ast.Expr, want: ?Ty, bindings: []const Binding) !void { +fn expectOperandMatches(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 }; @@ -5100,7 +5209,7 @@ fn expectUnaryMatches(a: Allocator, e: ast.Expr, want: ?Ty, bindings: []const Bi 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 expected = ReferenceOperands.expr(&old, e, want); const actual = current.expr(e, want); if (expected) |v| { const result = try actual; @@ -5111,6 +5220,7 @@ fn expectUnaryMatches(a: Allocator, e: ast.Expr, want: ?Ty, bindings: []const Bi 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.expectEqual(old.cur, current.cur); try std.testing.expectEqualDeep(old.uses, current.uses); } @@ -5134,10 +5244,205 @@ test "unary expression lowering preserves instruction order and diagnostic prior 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); + for ([_]?Ty{ null, .bool, .{ .int = "i64" }, .{ .int = "u8" } }) |want| try expectOperandMatches(a, e, want, &bindings); }; } +test "binary operand continuations match old typing CFG emission and failure priority" { + var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer scratch.deinit(); + const a = scratch.allocator(); + const span = unaryTestSpan(1); + var builder: Lowerer = .{ .arena = a, .m = .{ .name = "operands", .types = &.{}, .functions = &.{} } }; + const bindings = [_]Binding{ + .{ .name = "p", .value = "pointer", .mutable = false, .ty = try builder.wrap(.ref, .{ .int = "i64" }) }, + .{ .name = "atomic", .value = "cell", .mutable = false, .ty = try builder.wrap(.ref, try builder.wrap(.atomic, .{ .int = "u64" })) }, + .{ .name = "handle", .value = "handle", .mutable = false, .ty = try builder.wrap(.iref, .{ .int = "u8" }) }, + }; + const p: ast.Expr = .{ .span = unaryTestSpan(4), .kind = .{ .name = "p" } }; + const atomic: ast.Expr = .{ .span = unaryTestSpan(4), .kind = .{ .name = "atomic" } }; + const trapped: ast.Block = .{ .span = span, .stmts = &.{.{ .span = span, .kind = .trap }}, .tail = null }; + const leaves = [_]ast.Expr{ + .{ .span = unaryTestSpan(3), .kind = .{ .int = .{ .text = "1i64" } } }, + .{ .span = unaryTestSpan(4), .kind = .{ .int = .{ .text = "1u8" } } }, + .{ .span = unaryTestSpan(5), .kind = .{ .boolean = true } }, + .{ .span = unaryTestSpan(6), .kind = .{ .name = "handle" } }, + p, + .{ .span = unaryTestSpan(7), .kind = .{ .int = .{ .text = "1" } } }, + .{ .span = unaryTestSpan(8), .kind = .{ .name = "unknown" } }, + .{ .span = unaryTestSpan(9), .kind = .{ .block = &trapped } }, + .{ .span = unaryTestSpan(10), .kind = .{ .int = .{ .text = "256u8" } } }, + .{ .span = unaryTestSpan(11), .kind = .{ .deref = &atomic } }, + }; + const pairs = [_][2]usize{ + .{ 0, 0 }, .{ 1, 1 }, .{ 2, 2 }, .{ 3, 3 }, .{ 4, 4 }, .{ 5, 0 }, .{ 0, 5 }, .{ 6, 7 }, .{ 7, 6 }, + .{ 2, 6 }, .{ 0, 2 }, .{ 2, 0 }, .{ 8, 6 }, .{ 6, 8 }, .{ 9, 0 }, .{ 0, 9 }, .{ 5, 5 }, .{ 7, 2 }, + }; + inline for (std.meta.tags(ast.BinOp)) |op| for (pairs) |pair| { + const base: ast.Expr = .{ .span = span, .kind = .{ .binary = .{ .op = op, .l = &leaves[pair[0]], .r = &leaves[pair[1]] } } }; + const neg: ast.Expr = .{ .span = span, .kind = .{ .neg = &base } }; + const logical: ast.Expr = .{ .span = span, .kind = .{ .not = &base } }; + const cast: ast.Expr = .{ .span = span, .kind = .{ .cast = .{ .mode = .checked, .e = &base, .ty = .{ .span = span, .kind = .{ .name = "u8" } } } } }; + // Wrappers exercise shared unary/binary suspension, including a + // target whose expected type differs from the queried operand type. + for ([_]ast.Expr{ base, neg, logical, cast }) |e| for ([_]?Ty{ null, .bool, .{ .int = "i64" }, .{ .int = "u8" } }) |want| + try expectOperandMatches(a, e, want, &bindings); + }; +} + +test "deep left right and alternating operand trees emit in their original order" { + var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer scratch.deinit(); + const a = scratch.allocator(); + const m: ast.Module = .{ .name = "deep", .types = &.{}, .functions = &.{} }; + const literal: ast.Expr = .{ .span = unaryTestSpan(90_000), .kind = .{ .int = .{ .text = "1i64" } } }; + const count = 32_768; + for ([_]enum { left, right, mixed }{ .left, .right, .mixed }) |shape| { + var l: Lowerer = .{ .arena = a, .m = m }; + try l.bindings.append(a, .{ .name = "n", .value = "input", .mutable = false, .ty = .{ .int = "i64" } }); + l.cur = try l.newBlock("entry", unaryTestSpan(1)); + var e: ast.Expr = .{ .span = unaryTestSpan(90_001), .kind = .{ .name = "n" } }; + for (0..count) |i| { + const inner = try a.create(ast.Expr); + inner.* = e; + const span = unaryTestSpan(@intCast(i + 1)); + var operand = inner; + if (shape == .mixed) { + operand = try a.create(ast.Expr); + operand.* = .{ .span = span, .kind = .{ .neg = inner } }; + } + e = .{ .span = span, .kind = .{ .binary = .{ .op = .add, .l = if (shape == .right) &literal else operand, .r = if (shape == .right) operand else &literal } } }; + } + const value = try l.expr(e, .{ .int = "i64" }); + try std.testing.expect(value.ty.eql(.{ .int = "i64" })); + const insts = l.blocks.items[0].insts.items; + try std.testing.expectEqual(@as(usize, if (shape == .mixed) 4 * count else 2 * count), insts.len); + for (0..count) |i| { + const at = if (shape == .left) 2 * i + 1 else if (shape == .right) count + i else count + 3 * i + 2; + try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(@intCast(i + 1))), insts[at].span); + try std.testing.expect(std.mem.indexOf(u8, insts[at].text, " = add.checked.i64 ") != null); + if (shape == .mixed) { + try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(@intCast(count - i))), insts[i].span); + try std.testing.expect(std.mem.endsWith(u8, insts[i].text, " = const.i64 0")); + } else { + const previous = if (i == 0) "input" else try std.fmt.allocPrint(a, "t_{d}", .{if (shape == .left) 2 * i else count + i}); + const expected = if (shape == .left) + try std.fmt.allocPrint(a, "%t_{d} = add.checked.i64 %{s}, %c_{d}", .{ 2 * i + 2, previous, 2 * i + 1 }) + else + try std.fmt.allocPrint(a, "%t_{d} = add.checked.i64 %c_{d}, %{s}", .{ count + i + 1, count - i, previous }); + try std.testing.expectEqualStrings(expected, insts[at].text); + } + } + try std.testing.expect(l.problem == null); + try std.testing.expectEqual(@as(usize, 0), l.out.items.len); + } +} + +test "deep boolean operands retain RHS blocks join parameters and suspended unary parents" { + var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer scratch.deinit(); + const a = scratch.allocator(); + const m: ast.Module = .{ .name = "deep", .types = &.{}, .functions = &.{} }; + const literal: ast.Expr = .{ .span = unaryTestSpan(90_000), .kind = .{ .boolean = true } }; + const count = 16_384; + for ([_]bool{ false, true }) |right| { + var l: Lowerer = .{ .arena = a, .m = m }; + l.cur = try l.newBlock("entry", unaryTestSpan(1)); + var e = literal; + for (0..count) |i| { + const inner = try a.create(ast.Expr); + inner.* = e; + const span = unaryTestSpan(@intCast(i + 1)); + const binary = try a.create(ast.Expr); + binary.* = .{ .span = span, .kind = .{ .binary = .{ .op = if (i % 2 == 0) .@"and" else .@"or", .l = if (right) &literal else inner, .r = if (right) inner else &literal } } }; + e = .{ .span = span, .kind = .{ .not = binary } }; + } + const result = try l.expr(e, .bool); + try std.testing.expect(result.ty == .bool); + try std.testing.expectEqual(@as(usize, 2 * count + 1), l.blocks.items.len); + var cbrs: usize = 0; + var branches: usize = 0; + var inversions: usize = 0; + for (l.blocks.items, 0..) |b, index| { + try std.testing.expectEqual(index != l.cur.?, b.terminated); + if (index != 0 and index % 2 == 0) { + try std.testing.expectEqual(@as(usize, 1), b.params.items.len); + try std.testing.expect(b.params.items[0].ty == .bool); + } else try std.testing.expectEqual(@as(usize, 0), b.params.items.len); + for (b.insts.items) |inst| { + if (std.mem.startsWith(u8, inst.text, "cbr ")) cbrs += 1; + if (std.mem.startsWith(u8, inst.text, "br ")) branches += 1; + if (std.mem.indexOf(u8, inst.text, " = xor.bool ") != null) inversions += 1; + } + } + try std.testing.expectEqual(@as(usize, count), cbrs); + try std.testing.expectEqual(@as(usize, count), branches); + try std.testing.expectEqual(@as(usize, count), inversions); + try std.testing.expect(l.problem == null); + try std.testing.expectEqual(@as(usize, 0), l.out.items.len); + } +} + +test "operand continuation OOM retains complete block prefixes and no output" { + 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 = "oom", .types = &.{}, .functions = &.{} }; + const one: ast.Expr = .{ .span = span, .kind = .{ .int = .{ .text = "1i64" } } }; + const yes: ast.Expr = .{ .span = span, .kind = .{ .boolean = true } }; + for ([_]bool{ false, true }) |logical| { + var e = if (logical) yes else one; + for (0..64) |i| { + const inner = try a.create(ast.Expr); + inner.* = e; + const binary = try a.create(ast.Expr); + binary.* = .{ .span = span, .kind = .{ .binary = .{ + .op = if (logical) (if (i % 2 == 0) .@"and" else .@"or") else .add, + .l = if (logical) &yes else inner, + .r = if (logical) inner else &one, + } } }; + e = .{ .span = span, .kind = if (logical) .{ .not = binary } else .{ .neg = binary } }; + } + const want: Ty = if (logical) .bool else .{ .int = "i64" }; + var old: Lowerer = .{ .arena = a, .m = m }; + old.cur = try old.newBlock("entry", span); + _ = try ReferenceOperands.expr(&old, e, want); + var fail_index: usize = 0; + while (true) : (fail_index += 1) { + try std.testing.expect(fail_index < 1024); + 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, want); + }; + 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(want)); + try std.testing.expectEqualDeep(old.blocks.items, l.blocks.items); + try std.testing.expectEqual(old.cur, l.cur); + } + try std.testing.expect(l.blocks.items.len <= old.blocks.items.len); + for (l.blocks.items, old.blocks.items[0..l.blocks.items.len]) |actual, expected| { + try std.testing.expectEqualStrings(expected.name, actual.name); + try std.testing.expectEqualDeep(expected.span, actual.span); + try std.testing.expect(actual.params.items.len <= expected.params.items.len); + try std.testing.expectEqualDeep(expected.params.items[0..actual.params.items.len], actual.params.items); + try std.testing.expect(actual.insts.items.len <= expected.insts.items.len); + try std.testing.expectEqualDeep(expected.insts.items[0..actual.insts.items.len], actual.insts.items); + } + 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; + } + } +} + fn unaryTestSpan(column: u32) Span { return .{ .file = "deep.aji", .start = .{ .line = 2, .col = column }, .end = .{ .line = 2, .col = 100_000 } }; } @@ -5407,7 +5712,7 @@ test "unary lowering OOM retains complete instruction prefixes and no output" { } var old: Lowerer = .{ .arena = a, .m = m }; old.cur = try old.newBlock("entry", span); - _ = try ReferenceUnary.expr(&old, e, null); + _ = try ReferenceOperands.expr(&old, e, null); const expected = old.blocks.items[0].insts.items; var fail_index: usize = 0; while (true) : (fail_index += 1) { diff --git a/tests/hosted/source_expression_depth.py b/tests/hosted/source_expression_depth.py index 8b14ef7..c7a5496 100644 --- a/tests/hosted/source_expression_depth.py +++ b/tests/hosted/source_expression_depth.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Unary depth, exact lowering/fuel and rejected-value positions (Q-061).""" +"""Operand depth, exact lowering/CFG/fuel and rejected-value positions (Q-061).""" import json from pathlib import Path import subprocess @@ -58,6 +58,89 @@ with tempfile.TemporaryDirectory(prefix='aji-expression-depth-') as directory: assert json.loads(record.read_text()) == {'status': 'returned', 'value': expected} print(f'unary depth: {kind} {depth}', flush=True) + for depth in (0, 1, 16, 1024, 16384, 65536): + path = root / f'add-{depth}.aji' + path.write_text('module depth\nfn main() -> i64 effects [] { return ' + ' + '.join(['1i64'] * (depth + 1)) + '; }\n') + assert cli('check', path) == b'' + lowered = cli('lower', path) + instructions = 2 * depth + 2 + assert sum(b' = ' in line or line.strip().startswith(b'ret ') for line in lowered.splitlines()) == instructions + if depth <= 1024: + assert json.loads(cli('run', path, '--fuel', instructions)) == {'status': 'returned', 'value': depth + 1} + 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': depth + 1} + print(f'binary depth: add {depth}', flush=True) + + for depth in (0, 1, 16, 256, 1024): + for op in ('and', 'or'): + for short in (False, True): + path = root / f'{op}-{short}-{depth}.aji' + value = (op == 'and') != short + leaf = 'true' if op == 'and' else 'false' + text = ('true' if value else 'false') + (' ' + op + ' ' + leaf) * depth + path.write_text('module depth\nfn main() -> bool effects [] { return ' + text + '; }\n') + assert cli('check', path) == b'' + lowered = cli('lower', path) + # Every node emits a short constant, cbr, RHS literal and br. + instructions = sum(b' = ' in line or line.strip().startswith((b'ret ', b'cbr ', b'br ')) for line in lowered.splitlines()) + assert instructions == 4 * depth + 2, (op, short, depth, instructions) + if depth <= 256: + fuel = (2 if short else 4) * depth + 2 + assert json.loads(cli('run', path, '--fuel', fuel)) == {'status': 'returned', 'value': value} + assert json.loads(cli('run', path, '--fuel', fuel - 1, code=5)) == { + 'status': 'limit_exceeded', 'kind': 'fuel', 'limit': fuel - 1, 'steps': fuel - 1} + air = path.with_suffix('.air') + air.write_bytes(lowered) + assert cli('run', air, '--fuel', fuel) == cli('run', path, '--fuel', fuel) + record = root / 'hosted.json' + assert cli('run', path, '--fuel', fuel, '--profile', 'hosted', '--result-file', record) == b'' + assert json.loads(record.read_text()) == {'status': 'returned', 'value': value} + print(f'binary depth: {op} short={short} {depth}', flush=True) + + # The same lowering reaches the existing normative block limit, not a + # host-stack failure. `lower` emits AIR; verification entry points reject it. + limit_path = root / 'boolean-block-limit.aji' + limit_path.write_text('module depth\nfn main() -> bool effects [] { return ' + ' and '.join(['true'] * 16385) + '; }\n') + error = json.loads(cli('check', limit_path, code=1)) + assert (error['code'], error['kind'], error['limit'], error['max'], error['found']) == ( + 'E5101', 'verifier.resource_limit', 'blocks per function', 16384, 32769), error + assert (error['file'], error['line'], error['col']) == (str(limit_path), 2, 1), error + limit_air = cli('lower', limit_path) + assert limit_air.startswith(b'module depth\n') + assert sum(line.rstrip().endswith(b':') for line in limit_air.splitlines()) == 32769 + + # The skipped operand still lowers, but its division trap must not execute. + for op in ('and', 'or'): + for short in (False, True): + value = (op == 'and') != short + path = root / f'short-trap-{op}-{short}.aji' + path.write_text('module depth\nfn main() -> bool effects [] { return ' + ('true' if value else 'false') + ' ' + op + ' bad(); }\n' + 'fn bad() -> bool effects [] { return (1u64 / 0u64) == 0u64; }\n') + assert cli('check', path) == b'' + air = path.with_suffix('.air') + air.write_bytes(cli('lower', path)) + if short: + result = cli('run', path, '--fuel', 4) + assert json.loads(result) == {'status': 'returned', 'value': value} + assert cli('run', air, '--fuel', 4) == result + assert json.loads(cli('run', path, '--fuel', 3, code=5)) == { + 'status': 'limit_exceeded', 'kind': 'fuel', 'limit': 3, 'steps': 3} + else: + result = cli('run', path, '--fuel', 7, code=4) + trap = json.loads(result) + assert (trap['status'], trap['code'], trap['kind'], trap['function'], trap['inst']) == ( + 'trapped', 'T0004', 'trap.division_by_zero', 'bad', 2), trap + assert trap.pop('source_location') == {'file': str(path), 'line': 3, 'col': 39} + assert json.loads(cli('run', air, '--fuel', 7, code=4)) == trap + assert json.loads(cli('run', path, '--fuel', 6, code=5)) == { + 'status': 'limit_exceeded', 'kind': 'fuel', 'limit': 6, 'steps': 6} + for depth in (1024, 16384, 65536): # A cast removes the expected-use hint; deep traversal must retain # E7007 at the original unsuffixed initializer, without new inference.