From e3f4695efe073b24b1bfd9363b4dbab8ed404b77 Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Sat, 10 Oct 2026 17:34:57 +0300 Subject: [PATCH] cli: search expected source types iteratively --- docs/design/open-questions.md | 2 + docs/design/source-expression-depth-audit.md | 66 ++- docs/plan/phase-6-source-language.md | 6 + src/frontend/lower.zig | 469 +++++++++++++++++-- tests/hosted/source_expression_depth.py | 18 +- 5 files changed, 504 insertions(+), 57 deletions(-) diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index 47674e6..2a95737 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -529,4 +529,6 @@ The [expression-query increment](source-expression-depth-audit.md#expression-typ A subsequent finite source probe, `let n = 1; return - … n;` in an i64 function, accepts 1,024 negations but aborts without stdout JSON at 16,384 in `useIn`, during expected-use inference for the unsuffixed binding. Its raw evidence is in the linked audit. Q-061 remains open for that confirmed path and the other unverified paths above. +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. + 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 4ca5249..a3cc29b 100644 --- a/docs/design/source-expression-depth-audit.md +++ b/docs/design/source-expression-depth-audit.md @@ -166,20 +166,66 @@ No normative rule, source/AIR format, feature, error code, bundle text, ownership/runtime behavior or acceptance limit changes. Q-061's other paths remain open; this increment has no fresh Claude review. -## Remaining work +## Expected-use query continuations -After the query repair, `let n = 1; return - … n;` in an i64 function accepts +After the preceding query repair, `let n = 1; return - … n;` in an i64 function accepts 16 and 1,024 negations, but at 16,384 aborts in `useIn` while inferring the unsuffixed binding's type. The failing check returns -6 with empty stdout and repeated `useIn` frames. Evidence is retained as `inferred-use-depth-before.json` and `inferred-use-neg-16384.stdout/.stderr`. This confirms the next expected-use query failure independently of the repaired `peekType` path. -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. Beyond the `useIn` -case above, their complete depth behavior is unverified here. The formatter's -expression-marking traversal -already uses a worklist, as inspected and exercised by the deep syntax-only -probes. Q-061 and Phase 6 remain open; Q-060's unfinished full GC validation is -independent. No fresh Claude review covers these expression increments. +`useIn`, `usesInStmt` and `usesInBlock` now share an explicit request worklist. +It retains first-known use, left/right and call-argument order, condition/then/ +else order, statement-before-tail order, return hints and cast hint removal. +Comparison/shift right-hand hints and the second for bound are queried only +after the earlier use fails. The outer `inferUses` rest cursor and top-level +let rebinding barrier are unchanged; nested blocks and skipped expression/ +statement kinds retain their original policy. No new inference is introduced. + +The requests are host metadata, released on success/error; hint type nodes +retain their caller-arena lifetime. As in other best-effort type queries, +metadata OOM produces unknown without a diagnostic or instructions. This adds +allocation requests and does not promise identical failure-index outcomes. +Plain unary descent is a loop without work allocations. Runtime memory, +ownership, fuel and verifier rules are unchanged; no normative rule, format, +feature, error code, source/reference bundle or acceptance limit is added. + +The independent old expected-use descent and outer cursor compare 967 shallow +expression, statement/block and two-scope combinations. Name/signature/type +queries are shared and outside that oracle's independence. Separate tests cover +32,768 unary and mixed branch/call groups, 32,768 nested statement blocks, +deferred-hint allocation traps and every worklist backing-allocation failure. +They check complete cleanup and no query diagnostic/output; helper fixtures do +not establish arbitrary deep source acceptance. + +The baseline 16,384-negation source now accepts without stdout/stderr +(`inferred-use-depth-repaired.json`). Permanent CLI tests check inferred +negations through 65,536, exact instruction counts and fuel/source/AIR/hosted +results through 1,024. Cast-cleared context still returns E7007 at the unsuffixed +initializer through 65,536 negations across check/lower/run/report/explore. + +Final build/unit/format checks and all 1,793 ordinary conformance cases pass +with exact unique corpus coverage (`source-use-query-conformance.jsonl` and its +audit). The permanent expression-depth suite passes 186 checks; non-value and +independent-error suites pass 635/234 checks. These do not complete Q-060's +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 + +Follow-up probes after the expected-use repair 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 +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. + +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 +remain open; Q-060's unfinished full GC validation is 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 f63dec4..0d84277 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -538,3 +538,9 @@ Independent unary/addressability oracles, 32,768-node cases and allocation clean The [Q-061 query increment](../design/source-expression-depth-audit.md#expression-type-query-continuations) replaces expression/built-in result recursion with explicit continuations, retaining classification, lazy fallback and callee priority. Its callee callbacks build qualified paths iteratively with one complete string. Best-effort queries retain unknown on output OOM and now use the same outcome on continuation OOM; host allocation counts need not match. No normative/bundle/feature/code/acceptance-limit or runtime/ownership change. Independent shallow descent comparisons (703), deep structural/built-in/fallback cases, 65,536-field path construction and allocation cleanup tests pass. Final build/units/format checks and all 1,793 ordinary conformance cases with exact coverage pass, as do 139 expression-depth, 635 non-value, 33 atomic-access and 6,078 formatter CLI checks; old/new public checks/lowerings remain exact (1,423/506). The formerly crashing cast/dereference source now returns its inner E7005. A separate unsuffixed-binding probe accepts 1,024 negations but confirms the next native failure in useIn at 16,384. Q-061's expected-use, other expression/statement and generic paths, Q-060's full per-step validation and Phase 6 exit review remain open. Claude's earlier Q-059 property review does not cover this increment. + +## Source expected-use queries (2026-10-10) + +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. diff --git a/src/frontend/lower.zig b/src/frontend/lower.zig index 582fca6..0ef160b 100644 --- a/src/frontend/lower.zig +++ b/src/frontend/lower.zig @@ -1771,58 +1771,171 @@ const Lowerer = struct { } fn usesInStmt(l: *Lowerer, n: []const u8, s: ast.Stmt) ?Ty { - return switch (s.kind) { - .let => |x| l.useIn(n, x.e, if (x.ty) |t| l.typeOfNoFail(t) else null), - .@"var" => |x| if (x.init) |e| l.useIn(n, e, l.typeOfNoFail(x.ty)) else null, - .assign => |x| l.useIn(n, x.e, if (x.place.kind == .name) (if (l.lookup(x.place.kind.name)) |b| b.ty else null) else null), - .@"return" => |e| if (e) |x| l.useIn(n, x, l.ret) else null, - .expr => |e| l.useIn(n, e, null), - .@"while" => |x| l.useIn(n, x.cond, .bool) orelse l.usesInBlock(n, x.body), - .@"for" => |x| l.useIn(n, x.lo, l.peekType(x.hi)) orelse l.useIn(n, x.hi, l.peekType(x.lo)) orelse l.usesInBlock(n, x.body), - .loop, .shield => |b| l.usesInBlock(n, b), - .scope => |x| l.usesInBlock(n, x.body), - else => null, - }; + return l.queryUse(n, .{ .statement = s }) catch null; } fn usesInBlock(l: *Lowerer, n: []const u8, b: ast.Block) ?Ty { - for (b.stmts) |s| if (l.usesInStmt(n, s)) |t| return t; - if (b.tail) |t| return l.useIn(n, t.*, null); - return null; + return l.queryUse(n, .{ .block = b }) catch null; } /// The expected type of `n` inside `e`, evaluated where `e` is expected - /// to have type `want`. + /// to have type `want`. Like peekType, this is a best-effort query. fn useIn(l: *Lowerer, n: []const u8, e: ast.Expr, want: ?Ty) ?Ty { - return switch (e.kind) { - .name => |x| if (std.mem.eql(u8, x, n)) want else null, - .neg => |x| l.useIn(n, x.*, want), - .not => |x| l.useIn(n, x.*, .bool), - .cast => |x| l.useIn(n, x.e.*, null), - .binary => |x| switch (x.op) { - .@"and", .@"or" => l.useIn(n, x.l.*, .bool) orelse l.useIn(n, x.r.*, .bool), - .eq, .ne, .lt, .le, .gt, .ge => l.useIn(n, x.l.*, l.peekType(x.r.*)) orelse l.useIn(n, x.r.*, l.peekType(x.l.*)), - .shl, .shr => l.useIn(n, x.l.*, want) orelse l.useIn(n, x.r.*, l.peekType(x.l.*) orelse want), - else => blk: { - const t = want orelse l.peekType(x.l.*) orelse l.peekType(x.r.*); - break :blk l.useIn(n, x.l.*, t) orelse l.useIn(n, x.r.*, t); + return l.queryUse(n, .{ .expression = .{ .e = e, .want = .{ .known = want } } }) catch null; + } + + // Right-hand hints are resolved only after an earlier use was unknown. + // In particular, do not eagerly query a comparison/shift/for left operand. + const UseExpected = union(enum) { + known: ?Ty, + peek: ast.Expr, + peek_or: struct { e: ast.Expr, fallback: ?Ty }, + }; + const UseRequest = union(enum) { + expression: struct { e: ast.Expr, want: UseExpected }, + statement: ast.Stmt, + block: ast.Block, + statements: []const ast.Stmt, + arguments: struct { args: []const ast.Expr, params: []const Ty, at: usize }, + }; + + fn queryUse(l: *Lowerer, n: []const u8, initial: UseRequest) Allocator.Error!?Ty { + var pending: std.ArrayList(UseRequest) = .empty; + defer pending.deinit(l.arena); + var request = initial; + search: while (true) { + switch (request) { + .expression => |x| { + const e = x.e; + const want: ?Ty = switch (x.want) { + .known => |t| t, + .peek => |other| l.peekType(other), + .peek_or => |other| l.peekType(other.e) orelse other.fallback, + }; + switch (e.kind) { + .name => |name| if (std.mem.eql(u8, name, n)) { + if (want) |t| return t; + }, + .neg, .not, .cast => { + const operand = switch (e.kind) { + .neg => |v| v.*, + .not => |v| v.*, + .cast => |v| v.e.*, + else => unreachable, + }; + const hint: ?Ty = switch (e.kind) { + .neg => want, + .not => .bool, + .cast => null, + else => unreachable, + }; + request = .{ .expression = .{ .e = operand, .want = .{ .known = hint } } }; + continue :search; + }, + .binary => |b| { + const left: ?Ty = switch (b.op) { + .@"and", .@"or" => .bool, + .eq, .ne, .lt, .le, .gt, .ge => l.peekType(b.r.*), + .shl, .shr => want, + else => want orelse l.peekType(b.l.*) orelse l.peekType(b.r.*), + }; + const right: UseExpected = switch (b.op) { + .eq, .ne, .lt, .le, .gt, .ge => .{ .peek = b.l.* }, + .shl, .shr => .{ .peek_or = .{ .e = b.l.*, .fallback = want } }, + else => .{ .known = left }, + }; + try pending.append(l.arena, .{ .expression = .{ .e = b.r.*, .want = right } }); + request = .{ .expression = .{ .e = b.l.*, .want = .{ .known = left } } }; + continue :search; + }, + .call => |c| { + const sig = l.calleeSig(c.callee.*) orelse { + request = pending.pop() orelse return null; + continue :search; + }; + request = .{ .arguments = .{ .args = c.args, .params = sig.params, .at = 0 } }; + continue :search; + }, + .if_expr => |branch| { + if (branch.@"else") |otherwise| switch (otherwise) { + .block => |b| try pending.append(l.arena, .{ .block = b }), + .@"if" => |inner| try pending.append(l.arena, .{ .expression = .{ + .e = .{ .span = e.span, .kind = .{ .if_expr = inner } }, + .want = .{ .known = want }, + } }), + }; + try pending.append(l.arena, .{ .block = branch.then }); + request = .{ .expression = .{ .e = branch.cond, .want = .{ .known = .bool } } }; + continue :search; + }, + .block => |b| { + request = .{ .block = b.* }; + continue :search; + }, + else => {}, + } }, - }, - .call => |x| blk: { - const sig = l.calleeSig(x.callee.*) orelse break :blk null; - for (x.args, 0..) |a, i| { - const pt: ?Ty = if (i < sig.params.len) sig.params[i] else null; - if (l.useIn(n, a, pt)) |t| break :blk t; - } - break :blk null; - }, - .if_expr => |x| l.useIn(n, x.cond, .bool) orelse l.usesInBlock(n, x.then) orelse if (x.@"else") |els| switch (els) { - .block => |b| l.usesInBlock(n, b), - .@"if" => |inner| l.useIn(n, .{ .span = e.span, .kind = .{ .if_expr = inner } }, want), - } else null, - .block => |b| l.usesInBlock(n, b.*), - else => null, - }; + .statement => |s| switch (s.kind) { + .let => |x| { + request = .{ .expression = .{ .e = x.e, .want = .{ .known = if (x.ty) |t| l.typeOfNoFail(t) else null } } }; + continue :search; + }, + .@"var" => |x| if (x.init) |e| { + request = .{ .expression = .{ .e = e, .want = .{ .known = l.typeOfNoFail(x.ty) } } }; + continue :search; + }, + .assign => |x| { + const hint: ?Ty = if (x.place.kind == .name) (if (l.lookup(x.place.kind.name)) |b| b.ty else null) else null; + request = .{ .expression = .{ .e = x.e, .want = .{ .known = hint } } }; + continue :search; + }, + .@"return" => |value| if (value) |e| { + request = .{ .expression = .{ .e = e, .want = .{ .known = l.ret } } }; + continue :search; + }, + .expr => |e| { + request = .{ .expression = .{ .e = e, .want = .{ .known = null } } }; + continue :search; + }, + .@"while" => |x| { + try pending.append(l.arena, .{ .block = x.body }); + request = .{ .expression = .{ .e = x.cond, .want = .{ .known = .bool } } }; + continue :search; + }, + .@"for" => |x| { + try pending.append(l.arena, .{ .block = x.body }); + try pending.append(l.arena, .{ .expression = .{ .e = x.hi, .want = .{ .peek = x.lo } } }); + request = .{ .expression = .{ .e = x.lo, .want = .{ .peek = x.hi } } }; + continue :search; + }, + .loop, .shield => |b| { + request = .{ .block = b }; + continue :search; + }, + .scope => |x| { + request = .{ .block = x.body }; + continue :search; + }, + else => {}, + }, + .block => |b| { + if (b.tail) |e| try pending.append(l.arena, .{ .expression = .{ .e = e.*, .want = .{ .known = null } } }); + request = .{ .statements = b.stmts }; + continue :search; + }, + .statements => |stmts| if (stmts.len != 0) { + if (stmts.len > 1) try pending.append(l.arena, .{ .statements = stmts[1..] }); + request = .{ .statement = stmts[0] }; + continue :search; + }, + .arguments => |args| if (args.at < args.args.len) { + if (args.at + 1 < args.args.len) try pending.append(l.arena, .{ .arguments = .{ .args = args.args, .params = args.params, .at = args.at + 1 } }); + request = .{ .expression = .{ .e = args.args[args.at], .want = .{ .known = if (args.at < args.params.len) args.params[args.at] else null } } }; + continue :search; + }, + } + request = pending.pop() orelse return null; + } } fn typeOfNoFail(l: *Lowerer, annotation: ast.Type) ?Ty { @@ -4407,6 +4520,274 @@ test "terminated blocks reject further emission with a source diagnostic" { try std.testing.expect(l.blocks.items[0].terminated); } +// Independent old expected-use descent, including the outer rest/shadow +// cursor. Type/name/signature queries are shared, not independently derived. +const ReferenceUseQuery = struct { + fn infer(l: *Lowerer, n: []const u8) ?Ty { + var i = l.rest.items.len; + while (i > 0) { + i -= 1; + const r = l.rest.items[i]; + for (r.stmts) |s| { + if (statement(l, n, s)) |t| return t; + if (s.kind == .let) for (s.kind.let.names) |bn| if (std.mem.eql(u8, bn, n)) return null; + } + if (r.tail) |t| if (expression(l, n, t.*, if (i == 0) l.ret else null)) |ty| return ty; + } + return null; + } + + fn statement(l: *Lowerer, n: []const u8, s: ast.Stmt) ?Ty { + return switch (s.kind) { + .let => |x| expression(l, n, x.e, if (x.ty) |t| l.typeOfNoFail(t) else null), + .@"var" => |x| if (x.init) |e| expression(l, n, e, l.typeOfNoFail(x.ty)) else null, + .assign => |x| expression(l, n, x.e, if (x.place.kind == .name) (if (l.lookup(x.place.kind.name)) |b| b.ty else null) else null), + .@"return" => |e| if (e) |x| expression(l, n, x, l.ret) else null, + .expr => |e| expression(l, n, e, null), + .@"while" => |x| expression(l, n, x.cond, .bool) orelse block(l, n, x.body), + .@"for" => |x| expression(l, n, x.lo, l.peekType(x.hi)) orelse expression(l, n, x.hi, l.peekType(x.lo)) orelse block(l, n, x.body), + .loop, .shield => |b| block(l, n, b), + .scope => |x| block(l, n, x.body), + else => null, + }; + } + + fn block(l: *Lowerer, n: []const u8, b: ast.Block) ?Ty { + for (b.stmts) |s| if (statement(l, n, s)) |t| return t; + if (b.tail) |t| return expression(l, n, t.*, null); + return null; + } + + /// The expected type of `n` inside `e`, evaluated where `e` is expected + /// to have type `want`. + fn expression(l: *Lowerer, n: []const u8, e: ast.Expr, want: ?Ty) ?Ty { + return switch (e.kind) { + .name => |x| if (std.mem.eql(u8, x, n)) want else null, + .neg => |x| expression(l, n, x.*, want), + .not => |x| expression(l, n, x.*, .bool), + .cast => |x| expression(l, n, x.e.*, null), + .binary => |x| switch (x.op) { + .@"and", .@"or" => expression(l, n, x.l.*, .bool) orelse expression(l, n, x.r.*, .bool), + .eq, .ne, .lt, .le, .gt, .ge => expression(l, n, x.l.*, l.peekType(x.r.*)) orelse expression(l, n, x.r.*, l.peekType(x.l.*)), + .shl, .shr => expression(l, n, x.l.*, want) orelse expression(l, n, x.r.*, l.peekType(x.l.*) orelse want), + else => blk: { + const t = want orelse l.peekType(x.l.*) orelse l.peekType(x.r.*); + break :blk expression(l, n, x.l.*, t) orelse expression(l, n, x.r.*, t); + }, + }, + .call => |x| blk: { + const sig = l.calleeSig(x.callee.*) orelse break :blk null; + for (x.args, 0..) |a, i| { + const pt: ?Ty = if (i < sig.params.len) sig.params[i] else null; + if (expression(l, n, a, pt)) |t| break :blk t; + } + break :blk null; + }, + .if_expr => |x| expression(l, n, x.cond, .bool) orelse block(l, n, x.then) orelse if (x.@"else") |els| switch (els) { + .block => |b| block(l, n, b), + .@"if" => |inner| expression(l, n, .{ .span = e.span, .kind = .{ .if_expr = inner } }, want), + } else null, + .block => |b| block(l, n, b.*), + else => null, + }; + } +}; + +fn expectUseQueryEqual(expected: ?Ty, actual: ?Ty) !void { + if (expected) |t| try std.testing.expect(actual != null and t.eql(actual.?)) else try std.testing.expect(actual == null); +} + +test "expected-use queries match independent shallow expression and statement descent" { + var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer scratch.deinit(); + const a = scratch.allocator(); + const m: ast.Module = .{ .name = "uses", .types = &.{}, .functions = &.{} }; + var l: Lowerer = .{ .arena = a, .m = m, .ret = .{ .int = "i64" } }; + try l.bindings.appendSlice(a, &.{ + .{ .name = "known", .value = "known", .mutable = false, .ty = .{ .int = "u32" } }, + .{ .name = "flag", .value = "flag", .mutable = false, .ty = .bool }, + .{ .name = "x", .value = "x", .mutable = true, .ty = .{ .int = "u16" } }, + }); + for ([_][]const u8{ "f", "ns.f" }) |name| try l.sigs.put(a, name, .{ .params = &.{ .{ .int = "u8" }, .bool, .{ .int = "u64" } }, .ret = .bool, .air_name = name, .display_name = name }); + const leaves = [_][]const u8{ "n", "unknown", "known", "flag", "1", "1u8", "move n", "ref n", "* n", "n.len", "[n; 2]", "match 0u8 { _ => n }" }; + const forms = [_][]const u8{ + "{s}", "- {s}", "not {s}", "({s}) as! u8", "({s}) + known", "known + ({s})", "({s}) + unknown", "unknown + ({s})", + "({s}) == known", "known == ({s})", "({s}) << known", "known >> ({s})", "({s}) and flag", "flag or ({s})", "f({s}, n, n)", "f(unknown, {s}, n)", + "f(unknown, unknown, {s}, n)", "ns.f(unknown, {s})", "unknown({s})", "if {s} {{ return n; }} else {{ let y: u16 = n; }}", "if false {{ {s} }} else if n {{ return n; }}", "{{ let y: u16 = {s}; n }}", + }; + inline for (forms) |form| for (leaves) |leaf| { + const text = try std.fmt.allocPrint(a, form, .{leaf}); + const source = try std.fmt.allocPrint(a, "module uses\nfn probe() -> i64 effects [] {{ return {s}; }}", .{text}); + const parsed = try parse_mod.parse(a, source); + try std.testing.expect(parsed == .ok); + const e = parsed.ok.functions[0].body.stmts[0].kind.@"return".?; + for ([_]?Ty{ null, .bool, .{ .int = "u64" } }) |want| try expectUseQueryEqual(ReferenceUseQuery.expression(&l, "n", e, want), l.useIn("n", e, want)); + }; + const statements = [_][]const u8{ + "let y: u8 = n;", "let y = n;", "let n: u8 = n;", "let (n, y) = f(n);", "var y: u32 = n;", "var y: u32 = zero;", + "x = n;", "unknown = n;", "x.len = n;", "return n;", "return;", "n;", + "f(unknown, n);", "while n { return n; }", "while false { let y: u16 = n; }", "for i in n..5u8 { return n; }", "for i in 0u16..n { return n; }", "for i in 0u16..5u8 { return n; }", + "loop { return n; }", "shield { let y: u8 = n; }", "scope s { let y: u16 = n; }", "ref r = n;", "mut r = n;", "break;", + "continue;", "trap;", "lock ref n as guard { return n; } cancelled { return n; }", + }; + for (statements) |text| { + const source = try std.fmt.allocPrint(a, "module uses\nfn probe() -> i64 effects [] {{ {s} }}", .{text}); + const parsed = try parse_mod.parse(a, source); + if (parsed != .ok) std.debug.print("failed expected-use fixture: {s}\n", .{text}); + try std.testing.expect(parsed == .ok); + const body = parsed.ok.functions[0].body; + try expectUseQueryEqual(ReferenceUseQuery.block(&l, "n", body), l.usesInBlock("n", body)); + for (body.stmts) |stmt| try expectUseQueryEqual(ReferenceUseQuery.statement(&l, "n", stmt), l.usesInStmt("n", stmt)); + } + try std.testing.expect(l.problem == null); + try std.testing.expectEqual(@as(usize, 0), l.blocks.items.len); + try std.testing.expectEqual(@as(usize, 0), l.out.items.len); +} + +test "expected-use rest queries preserve scope order tails and top-level let rebinding" { + var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer scratch.deinit(); + const a = scratch.allocator(); + const fixtures = [_][]const u8{ + "return n;", "let y: u8 = n; return n;", "let n = 0u8; return n;", "let (x, n) = unknown; return n;", + "let n: u8 = n; return n;", "var n: u8 = 0u8; return n;", "{ let n = 0u8; return n; };", "n", + "let y: u8 = unknown; n", "{ n };", "if false { return n; } else { let y: u8 = n; };", + }; + const m: ast.Module = .{ .name = "uses", .types = &.{}, .functions = &.{} }; + for (fixtures) |inner| for (fixtures) |outer| { + var l: Lowerer = .{ .arena = a, .m = m, .ret = .{ .int = "i64" } }; + for ([_][]const u8{ outer, inner }) |text| { + const source = try std.fmt.allocPrint(a, "module uses\nfn probe() -> i64 effects [] {{ {s} }}", .{text}); + const parsed = try parse_mod.parse(a, source); + try std.testing.expect(parsed == .ok); + const b = parsed.ok.functions[0].body; + try l.rest.append(a, .{ .stmts = b.stmts, .tail = b.tail }); + } + try expectUseQueryEqual(ReferenceUseQuery.infer(&l, "n"), l.inferUses("n")); + }; +} + +test "expected-use queries do not evaluate deferred right-hand type hints after success" { + const span = unaryTestSpan(1); + const n: ast.Expr = .{ .span = span, .kind = .{ .name = "n" } }; + const value: ast.Expr = .{ .span = span, .kind = .{ .boolean = true } }; + const array: ast.Expr = .{ .span = span, .kind = .{ .array_rep = .{ .e = &value, .len = 2 } } }; + const left: ast.Expr = .{ .span = span, .kind = .{ .binary = .{ .op = .add, .l = &n, .r = &array } } }; + const right: ast.Expr = .{ .span = span, .kind = .{ .int = .{ .text = "1u16" } } }; + for ([_]ast.BinOp{ .eq, .shl }) |op| { + var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 1 }); + var l: Lowerer = .{ .arena = failing.allocator(), .m = .{ .name = "uses", .types = &.{}, .functions = &.{} } }; + const e: ast.Expr = .{ .span = span, .kind = .{ .binary = .{ .op = op, .l = &left, .r = &right } } }; + try expectUseQueryEqual(.{ .int = "u16" }, l.useIn("n", e, .{ .int = "u16" })); + // One worklist allocation is allowed. An eager peekType(left) would + // construct the array type on a second request and induce host OOM. + try std.testing.expect(!failing.has_induced_failure); + try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes); + } + var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 1 }); + var l: Lowerer = .{ .arena = failing.allocator(), .m = .{ .name = "uses", .types = &.{}, .functions = &.{} } }; + const loop: ast.Stmt = .{ .span = span, .kind = .{ .@"for" = .{ + .name = "i", + .lo = left, + .hi = right, + .body = .{ .span = span, .stmts = &.{}, .tail = null }, + } } }; + try expectUseQueryEqual(.{ .int = "u16" }, l.usesInStmt("n", loop)); + try std.testing.expect(!failing.has_induced_failure); + try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes); +} + +test "expected-use queries handle deep unary branches calls and statement blocks" { + var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer scratch.deinit(); + const a = scratch.allocator(); + const span = unaryTestSpan(1); + const m: ast.Module = .{ .name = "uses", .types = &.{}, .functions = &.{} }; + const name: ast.Expr = .{ .span = span, .kind = .{ .name = "n" } }; + const unknown: ast.Expr = .{ .span = span, .kind = .{ .name = "unknown" } }; + const callee: ast.Expr = .{ .span = span, .kind = .{ .name = "f" } }; + const empty: ast.Block = .{ .span = span, .stmts = &.{}, .tail = null }; + var l: Lowerer = .{ .arena = a, .m = m, .ret = .{ .int = "u64" } }; + try l.sigs.put(a, "f", .{ .params = &.{.bool}, .ret = .bool, .air_name = "f", .display_name = "f" }); + var unary = name; + var mixed: ast.Expr = .{ .span = span, .kind = .{ .not = &name } }; + for (0..32_768) |i| { + const operand = try a.create(ast.Expr); + operand.* = unary; + unary = .{ .span = span, .kind = .{ .neg = operand } }; + const inner = try a.create(ast.Expr); + inner.* = mixed; + switch (i % 3) { + 0 => mixed = .{ .span = span, .kind = .{ .binary = .{ .op = .@"or", .l = &unknown, .r = inner } } }, + 1 => { + const args = try a.alloc(ast.Expr, 1); + args[0] = inner.*; + mixed = .{ .span = span, .kind = .{ .call = .{ .callee = &callee, .type_arg = null, .args = args } } }; + }, + else => { + const branch = try a.create(ast.If); + const next = try a.create(ast.If); + next.* = .{ .cond = unknown, .then = .{ .span = span, .stmts = &.{}, .tail = inner }, .@"else" = null }; + branch.* = .{ .cond = unknown, .then = empty, .@"else" = .{ .@"if" = next } }; + mixed = .{ .span = span, .kind = .{ .if_expr = branch } }; + }, + } + } + try expectUseQueryEqual(.{ .int = "u16" }, l.useIn("n", unary, .{ .int = "u16" })); + try expectUseQueryEqual(.bool, l.useIn("n", mixed, null)); + // Plain unary traversal does not need host metadata allocation. + var none: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 0 }); + var no_alloc: Lowerer = .{ .arena = none.allocator(), .m = m }; + try expectUseQueryEqual(.bool, no_alloc.useIn("n", unary, .bool)); + try std.testing.expect(!none.has_induced_failure); + var body: ast.Block = .{ .span = span, .stmts = &.{.{ .span = span, .kind = .{ .@"return" = name } }}, .tail = null }; + for (0..32_768) |_| { + const stmts = try a.alloc(ast.Stmt, 3); + stmts[0] = .{ .span = span, .kind = .{ .expr = unknown } }; + stmts[1] = .{ .span = span, .kind = .{ .shield = body } }; + stmts[2] = .{ .span = span, .kind = .{ .@"return" = unknown } }; + // The first successful statement wins over every enclosing tail. + const tail = try a.create(ast.Expr); + tail.* = .{ .span = span, .kind = .{ .not = &name } }; + body = .{ .span = span, .stmts = stmts, .tail = tail }; + } + try expectUseQueryEqual(.{ .int = "u64" }, l.usesInBlock("n", body)); + try std.testing.expect(l.problem == null); + try std.testing.expectEqual(@as(usize, 0), l.out.items.len); + try std.testing.expectEqual(@as(usize, 0), l.blocks.items.len); +} + +test "expected-use worklist OOM is unknown and releases all backing allocations" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const span = unaryTestSpan(1); + const name: ast.Expr = .{ .span = span, .kind = .{ .name = "n" } }; + const unknown: ast.Expr = .{ .span = span, .kind = .{ .name = "unknown" } }; + var e = name; + for (0..128) |_| { + const inner = try a.create(ast.Expr); + inner.* = e; + // Descend left with a pending right request, forcing worklist growth. + e = .{ .span = span, .kind = .{ .binary = .{ .op = .@"and", .l = inner, .r = &unknown } } }; + } + var fail_index: usize = 0; + while (true) : (fail_index += 1) { + try std.testing.expect(fail_index < 128); + 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 = .{ .name = "uses", .types = &.{}, .functions = &.{} } }; + const result = l.useIn("n", e, null); + if (failing.has_induced_failure) try std.testing.expect(result == null) else try expectUseQueryEqual(.bool, result); + try std.testing.expect(l.problem == null); + try std.testing.expectEqual(@as(usize, 0), l.out.items.len); + try std.testing.expectEqual(@as(usize, 0), l.blocks.items.len); + arena.deinit(); + try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes); + if (!failing.has_induced_failure) break; + } +} + // Independent pre-repair expression query and built-in result derivation. // Name/signature/type lookup helpers are shared; the descent is not. const ReferenceExpressionQuery = struct { diff --git a/tests/hosted/source_expression_depth.py b/tests/hosted/source_expression_depth.py index 42dfa70..8b14ef7 100644 --- a/tests/hosted/source_expression_depth.py +++ b/tests/hosted/source_expression_depth.py @@ -22,8 +22,9 @@ 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' + elif kind in ('neg', 'inferred_neg'): + setup = 'let n = 1; ' if kind == 'inferred_neg' else 'let n: i64 = 1i64; ' + ty, expression = 'i64', '- ' * depth + 'n' instructions, expected = 2 * depth + 2, 1 if depth % 2 == 0 else -1 else: ty, setup = 'i64', '' @@ -35,7 +36,7 @@ def source(kind, depth): 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'): + for kind in ('not', 'neg', 'cast', 'inferred_neg'): path = root / f'{kind}-{depth}.aji' text, instructions, expected = source(kind, depth) path.write_text(text) @@ -58,6 +59,17 @@ with tempfile.TemporaryDirectory(prefix='aji-expression-depth-') as directory: print(f'unary depth: {kind} {depth}', flush=True) 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. + hint_header = 'module depth\nfn main() -> i64 effects [] { let n = ' + path = root / f'inferred-no-hint-{depth}.aji' + path.write_text(hint_header + '1; return (' + '- ' * depth + 'n) as i64; }\n') + error = json.loads(cli('check', path, code=1)) + col = len(hint_header.split('\n')[-1]) + 1 + assert (error['code'], error['line'], error['col'], error['file']) == ('E7007', 2, col, str(path)), error + for command in ('lower', 'run', 'report', 'explore'): + assert json.loads(cli(command, path, code=1)) == error + header = 'module depth\nfn main() -> i64 effects [] { return ' path = root / f'deref-{depth}.aji' path.write_text(header + '* ' * depth + '1i64; }\n')