cli: query expression types and callee paths iteratively

This commit is contained in:
dev committed 2026-10-10 17:21:30 +03:00
1 parent dd73b84085
commit e862e03f2b
5 files changed
+531 -102

No files matched your search

+4
View File
@@ -525,4 +525,8 @@ Follow-up [expression-depth probes](source-expression-depth-audit.md) now confir
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.
The [expression-query increment](source-expression-depth-audit.md#expression-type-query-continuations) repairs that cast/dereference failure and the recursive callee path callbacks. Query continuations retain existing classification and fallback order; host metadata OOM follows the best-effort unknown-result contract. Deep cast/dereference checks now return the expected inner E7005, and deep unknown callees return E7002. This does not close `useIn`, other expression/statement lowering, nested primary parsing or generic expression transformation; no whole-frontend bound or new acceptance rule is claimed.
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.
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.
+56 -7
View File
@@ -119,18 +119,67 @@ 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.
## Expression type-query continuations
On `dd73b84`, `( * … 1i64 ) as i64` at 16,384 dereferences aborts in
`peekType`, before the expected ordinary type error. Its stdout is empty and
stderr repeats dereference-query frames. The retained baseline evidence is
`unary-cast-deref-query-16384.json/.stdout/.stderr`; the repaired check returns
one E7005 at line 2, column 32,805 without stderr
(`expression-query-repaired-cli.json`).
Expression and built-in result queries now share an explicit continuation
worklist. It preserves left-before-right fallback, first-known match arm,
first array element, branch-tail policy, field/len classification, callee
priority and built-in argument/borrow handling. Negation, shift, block and
if-tail queries use loop transitions. Queries remain best-effort: type-output
OOM already returned unknown, and continuation-allocation OOM now does too,
without a diagnostic. This adds host metadata requests; allocation counts and
failure-index classifications are not claimed identical. Pending storage is
released, and type nodes keep their caller-arena lifetime.
The query's callee callbacks also exposed recursive `expressionPath` and
bounded `dotted`. Both now walk field chains iteratively. `expressionPath`
allocates one complete string rather than every ancestor prefix; direct names
and invalid roots allocate nothing. Successful path bytes, the existing
64-byte built-in lookup buffer and null-result policy are retained. Partial
buffer contents on null are private and need not match the old implementation.
An independent copy of the old expression/built-in descent compares 703
shallow combinations. Name/signature/type lookup and callee path helpers are
shared, so this oracle does not independently validate those helpers. Separate
tests cover 32,768 structural/built-in expression levels, 16,384 fallback
levels, 65,536 callee fields and allocation-error cleanup without diagnostics
or emitted instructions. The permanent CLI suite adds cast/dereference and
deep unknown-callee rejection across check/lower/run/report/explore. These
helper fixtures do not establish arbitrary deep source acceptance.
Final build/units/Zig format checks and all 1,793 ordinary conformance cases
pass with exact unique corpus coverage (`source-expression-query-conformance.jsonl`
and its audit). The expression-depth/non-value/atomic-access suites pass
139/635/33 checks; formatter integration passes 6,078 checks. Fixed old/new
executables retain exact exit/stdout/stderr on all 1,423 public source checks
and 506 successful lowerings. These are compiler regressions, not completed
per-step GC validation or a model-capability measurement.
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
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.
After the 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. Their complete
depth behavior is unverified here. The formatter's expression-marking traversal
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.
+6
View File
@@ -532,3 +532,9 @@ Build/units/format checks, all 1,793 ordinary conformance cases with exact cover
[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.
## Source expression type queries (2026-10-10)
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.
+445 -95
View File
@@ -1586,53 +1586,172 @@ const Lowerer = struct {
return null;
}
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,
.boolean => .bool,
.name => |n| if (l.lookup(n)) |b| b.ty else null,
.deref => |x| if (l.peekType(x.*)) |t| t.inner() else null,
.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 => unreachable,
.not => .bool,
.cast => |x| l.typeOfNoFail(x.ty),
.binary => |x| switch (x.op) {
.eq, .ne, .lt, .le, .gt, .ge, .@"and", .@"or" => .bool,
.shl, .shr => l.peekType(x.l.*),
else => l.peekType(x.l.*) orelse l.peekType(x.r.*),
},
.call => |x| switch (x.callee.kind) {
.name => |n| if (l.functionSig(n, e.span)) |sig| sig.ret else null,
.variant => |v| l.enumType(v.@"enum", e.span),
else => if (l.calleeSig(x.callee.*)) |sig| sig.ret else if (pathOf(x.callee.*)) |p| l.peekPath(p, x.args) else null,
},
.move => |n| if (l.lookup(n)) |b| b.ty else null,
.variant => |v| l.enumType(v.@"enum", e.span),
.struct_lit => |x| l.enumOrStruct(x.name, e.span),
.field => |x| blk: {
const known = l.peekType(x.e.*);
if (std.mem.eql(u8, x.name, "len") and (known == null or !isNominalFieldBase(known.?))) break :blk Ty{ .int = "usize" };
var base = known orelse break :blk null;
if (base.isBorrow()) base = base.inner().?;
const d = l.decl(base) orelse break :blk null;
if (d.kind != .@"struct") break :blk null;
for (d.kind.@"struct") |f| if (std.mem.eql(u8, f.name, x.name)) break :blk l.typeOfNoFail(f.ty);
break :blk null;
},
.if_expr => |x| if (x.then.tail) |t| l.peekType(t.*) else null,
.match_expr => |x| for (x.arms) |a| {
if (l.peekType(a.body)) |t| break t;
} else null,
.block => |b| if (b.tail) |t| l.peekType(t.*) else null,
else => null,
};
// Best-effort query: output construction already treats host OOM as
// unknown. Continuation OOM follows that contract without a diagnostic.
fn peekType(l: *Lowerer, e: ast.Expr) ?Ty {
return l.queryType(.{ .expr = e }) catch null;
}
const TypeRequest = union(enum) { expr: ast.Expr, path: struct { name: []const u8, args: []const ast.Expr } };
const QueryOperation = enum { atomic_new, atomic_load_inline, atomic_load_borrow, graph_root, freeze, arc_from, arc_clone, channel_dup };
const TypeContinuation = union(enum) {
inner,
element,
array: u64,
field: []const u8,
alternative: ast.Expr,
arms: []const ast.Arm,
operation: QueryOperation,
};
fn queryType(l: *Lowerer, initial: TypeRequest) Allocator.Error!?Ty {
var pending: std.ArrayList(TypeContinuation) = .empty;
defer pending.deinit(l.arena);
var request = initial;
query: while (true) {
var result: ?Ty = switch (request) {
.expr => |e| switch (e.kind) {
.int => |x| if (parse_mod.intSuffix(x.text)) |s| Ty{ .int = s } else null,
.boolean, .not => .bool,
.name, .move => |n| if (l.lookup(n)) |b| b.ty else null,
.neg => |x| {
request = .{ .expr = x.* };
continue :query;
},
.deref => |x| {
try pending.append(l.arena, .inner);
request = .{ .expr = x.* };
continue :query;
},
.index => |x| blk: {
if (x.hi != null) break :blk null;
try pending.append(l.arena, .element);
request = .{ .expr = x.e.* };
continue :query;
},
.array_rep => |x| {
try pending.append(l.arena, .{ .array = x.len });
request = .{ .expr = x.e.* };
continue :query;
},
.array_list => |xs| blk: {
if (xs.len == 0) break :blk null;
try pending.append(l.arena, .{ .array = xs.len });
request = .{ .expr = xs[0] };
continue :query;
},
.cast => |x| l.typeOfNoFail(x.ty),
.binary => |x| switch (x.op) {
.eq, .ne, .lt, .le, .gt, .ge, .@"and", .@"or" => .bool,
else => {
if (x.op != .shl and x.op != .shr) try pending.append(l.arena, .{ .alternative = x.r.* });
request = .{ .expr = x.l.* };
continue :query;
},
},
.call => |x| switch (x.callee.kind) {
.name => |n| if (l.functionSig(n, e.span)) |sig| sig.ret else null,
.variant => |v| l.enumType(v.@"enum", e.span),
else => blk: {
if (l.calleeSig(x.callee.*)) |sig| break :blk sig.ret;
const name = pathOf(x.callee.*) orelse break :blk null;
request = .{ .path = .{ .name = name, .args = x.args } };
continue :query;
},
},
.variant => |v| l.enumType(v.@"enum", e.span),
.struct_lit => |x| l.enumOrStruct(x.name, e.span),
.field => |x| {
try pending.append(l.arena, .{ .field = x.name });
request = .{ .expr = x.e.* };
continue :query;
},
.if_expr => |x| blk: {
const tail = x.then.tail orelse break :blk null;
request = .{ .expr = tail.* };
continue :query;
},
.match_expr => |x| blk: {
if (x.arms.len == 0) break :blk null;
try pending.append(l.arena, .{ .arms = x.arms[1..] });
request = .{ .expr = x.arms[0].body };
continue :query;
},
.block => |b| blk: {
const tail = b.tail orelse break :blk null;
request = .{ .expr = tail.* };
continue :query;
},
else => null,
},
.path => |p| blk: {
const eq = std.mem.eql;
if (eq(u8, p.name, "buffer.len") or eq(u8, p.name, "buffer.capacity")) break :blk Ty{ .int = "usize" };
if (eq(u8, p.name, "task.cancelled")) break :blk Ty.bool;
if (eq(u8, p.name, "task.spawn") and p.args.len >= 2) {
const sig = l.calleeSig(p.args[1]) orelse break :blk null;
break :blk l.wrap(.task, sig.ret) catch null;
}
if ((eq(u8, p.name, "own.take") or eq(u8, p.name, "task.join")) and p.args.len == 1) {
try pending.append(l.arena, .inner);
} else if (std.mem.startsWith(u8, p.name, "atomic.") and p.args.len >= 1) {
if (eq(u8, p.name, "atomic.new")) {
try pending.append(l.arena, .{ .operation = .atomic_new });
} else if (eq(u8, p.name, "atomic.take")) {
try pending.append(l.arena, .inner);
} else if (eq(u8, p.name, "atomic.store") or eq(u8, p.name, "atomic.fence") or eq(u8, p.name, "atomic.compare_exchange")) {
break :blk null;
} else {
const inline_borrow = p.args[0].kind == .borrow;
try pending.append(l.arena, .{ .operation = if (inline_borrow) .atomic_load_inline else .atomic_load_borrow });
request = .{ .expr = if (inline_borrow) p.args[0].kind.borrow.place.* else p.args[0] };
continue :query;
}
} else if (p.args.len == 1) {
const op: QueryOperation = if (eq(u8, p.name, "island.root") or eq(u8, p.name, "frozen.root") or eq(u8, p.name, "arc.root")) .graph_root else if (eq(u8, p.name, "island.freeze")) .freeze else if (eq(u8, p.name, "arc.from_frozen")) .arc_from else if (eq(u8, p.name, "arc.clone")) .arc_clone else if (eq(u8, p.name, "channel.dup")) .channel_dup else break :blk null;
try pending.append(l.arena, .{ .operation = op });
} else break :blk null;
request = .{ .expr = p.args[0] };
continue :query;
},
};
while (pending.pop()) |frame| switch (frame) {
.inner => result = if (result) |t| t.inner() else null,
.element => result = if (result) |t| elemOf(t) else null,
.array => |len| result = if (result) |t| l.arrayOf(t, len) catch null else null,
.alternative => |e| if (result == null) {
request = .{ .expr = e };
continue :query;
},
.arms => |arms| if (result == null and arms.len != 0) {
try pending.append(l.arena, .{ .arms = arms[1..] });
request = .{ .expr = arms[0].body };
continue :query;
},
.field => |name| result = l.queryField(result, name),
.operation => |op| result = if (result) |t| switch (op) {
.atomic_new => l.wrap(.atomic, t) catch null,
.atomic_load_inline => if (t == .atomic) t.inner() else null,
.atomic_load_borrow => if (t.inner()) |c| (if (c == .atomic) c.inner() else null) else null,
.graph_root => if (t.inner()) |o| (if (o.inner()) |r| l.wrap(.iref, r) catch null else null) else null,
.freeze => if (t == .island) l.wrap(.frozen, t.inner().?) catch null else null,
.arc_from => if (t == .frozen) l.wrap(.arc, t.inner().?) catch null else null,
.arc_clone => if (t == .arc) t else if (t.inner()) |in| (if (in == .arc) in else null) else null,
.channel_dup => if (t == .sender) t else if (t.inner()) |in| (if (in == .sender) in else null) else null,
} else null,
};
return result;
}
}
fn queryField(l: *Lowerer, known: ?Ty, name: []const u8) ?Ty {
if (std.mem.eql(u8, name, "len") and (known == null or !isNominalFieldBase(known.?))) return .{ .int = "usize" };
var base = known orelse return null;
if (base.isBorrow()) base = base.inner().?;
const d = l.decl(base) orelse return null;
if (d.kind != .@"struct") return null;
for (d.kind.@"struct") |f| if (std.mem.eql(u8, f.name, name)) return l.typeOfNoFail(f.ty);
return null;
}
/// The type the following code expects for the name `n`, if any use
@@ -2356,34 +2475,6 @@ const Lowerer = struct {
return l.mergeArms(m.span, "match", ends.items, vars, before, "endmatch");
}
/// The result type of a built-in operation called plainly, if known
/// without lowering it.
fn peekPath(l: *Lowerer, p: []const u8, args: []const ast.Expr) ?Ty {
const eq = std.mem.eql;
if (eq(u8, p, "buffer.len") or eq(u8, p, "buffer.capacity")) return .{ .int = "usize" };
if ((eq(u8, p, "own.take") or eq(u8, p, "task.join")) and args.len == 1) return if (l.peekType(args[0])) |t| t.inner() else null;
if (eq(u8, p, "task.cancelled")) return .bool;
if (std.mem.startsWith(u8, p, "atomic.") and args.len >= 1) {
if (eq(u8, p, "atomic.new")) return if (l.peekType(args[0])) |t| (l.wrap(.atomic, t) catch null) else null;
if (eq(u8, p, "atomic.take")) return if (l.peekType(args[0])) |t| t.inner() else null;
if (eq(u8, p, "atomic.store") or eq(u8, p, "atomic.fence") or eq(u8, p, "atomic.compare_exchange")) return null;
// A `ref a` argument, or a `ref<atomic<T>>` binding: the cell's T.
const cell: ?Ty = if (args[0].kind == .borrow) l.peekType(args[0].kind.borrow.place.*) else if (l.peekType(args[0])) |t| t.inner() else null;
return if (cell) |c| (if (c == .atomic) c.inner() else null) else null;
}
if ((eq(u8, p, "island.root") or eq(u8, p, "frozen.root") or eq(u8, p, "arc.root")) and args.len == 1)
return if (l.peekType(args[0])) |t| (if (t.inner()) |o| (if (o.inner()) |root| l.wrap(.iref, root) catch null else null) else null) else null;
if (eq(u8, p, "island.freeze") and args.len == 1) return if (l.peekType(args[0])) |t| (if (t == .island) l.wrap(.frozen, t.inner().?) catch null else null) else null;
if (eq(u8, p, "arc.from_frozen") and args.len == 1) return if (l.peekType(args[0])) |t| (if (t == .frozen) l.wrap(.arc, t.inner().?) catch null else null) else null;
if (eq(u8, p, "arc.clone") and args.len == 1) return if (l.peekType(args[0])) |t| (if (t == .arc) t else if (t.inner()) |in| (if (in == .arc) in else null) else null) else null;
if (eq(u8, p, "channel.dup") and args.len == 1) return if (l.peekType(args[0])) |t| (if (t == .sender) t else if (t.inner()) |in| (if (in == .sender) in else null) else null) else null;
if (eq(u8, p, "task.spawn") and args.len >= 2) {
const sig = l.calleeSig(args[1]) orelse return null;
return l.wrap(.task, sig.ret) catch null;
}
return null;
}
fn armBody(l: *Lowerer, body: ast.Expr, want: ?Ty) Error!?Value {
const v = try l.expr(body, want);
if (v.ty == .void) return null;
@@ -3907,22 +3998,28 @@ fn pathOf(e: ast.Expr) ?[]const u8 {
}
fn dotted(e: ast.Expr, buf: []u8) ?[]const u8 {
switch (e.kind) {
.name => |n| {
if (n.len > buf.len) return null;
@memcpy(buf[0..n.len], n);
return buf[0..n.len];
},
.field => |f| {
const base = dotted(f.e.*, buf) orelse return null;
const len = base.len + 1 + f.name.len;
if (len > buf.len) return null;
buf[base.len] = '.';
@memcpy(buf[base.len + 1 .. len], f.name);
return buf[0..len];
},
else => return null,
var root = e;
var len: usize = 0;
while (root.kind == .field) {
const field = root.kind.field;
if (len >= buf.len or field.name.len > buf.len - len - 1) return null;
len += field.name.len + 1;
root = field.e.*;
}
if (root.kind != .name or root.kind.name.len > buf.len - len) return null;
len += root.kind.name.len;
var at = len;
var node = e;
while (node.kind == .field) {
const field = node.kind.field;
at -= field.name.len;
@memcpy(buf[at .. at + field.name.len], field.name);
at -= 1;
buf[at] = '.';
node = field.e.*;
}
@memcpy(buf[0..at], root.kind.name);
return buf[0..len];
}
fn standardPath(e: ast.Expr) bool {
@@ -4279,11 +4376,20 @@ fn localName(full: []const u8, module: []const u8, short: []const u8) bool {
}
fn expressionPath(arena: Allocator, e: ast.Expr) Allocator.Error!?[]const u8 {
return switch (e.kind) {
.name => |name| name,
.field => |field| if (try expressionPath(arena, field.e.*)) |base| try std.fmt.allocPrint(arena, "{s}.{s}", .{ base, field.name }) else null,
else => null,
};
var root = e;
while (root.kind == .field) root = root.kind.field.e.*;
if (root.kind != .name) return null;
if (e.kind == .name) return root.kind.name;
var len = root.kind.name.len;
var node = e;
while (node.kind == .field) {
len = std.math.add(usize, len, 1) catch return error.OutOfMemory;
len = std.math.add(usize, len, node.kind.field.name.len) catch return error.OutOfMemory;
node = node.kind.field.e.*;
}
const output = try arena.alloc(u8, len);
// The immutable chain was validated above; dotted fills this exact buffer.
return dotted(e, output).?;
}
test "terminated blocks reject further emission with a source diagnostic" {
@@ -4301,6 +4407,250 @@ test "terminated blocks reject further emission with a source diagnostic" {
try std.testing.expect(l.blocks.items[0].terminated);
}
// Independent pre-repair expression query and built-in result derivation.
// Name/signature/type lookup helpers are shared; the descent is not.
const ReferenceExpressionQuery = struct {
fn query(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,
.boolean => .bool,
.name => |n| if (l.lookup(n)) |b| b.ty else null,
.deref => |x| if (query(l, x.*)) |t| t.inner() else null,
.index => |x| if (x.hi == null) (if (query(l, x.e.*)) |t| elemOf(t) else null) else null,
.array_rep => |x| if (query(l, x.e.*)) |t| (l.arrayOf(t, x.len) catch null) else null,
.array_list => |xs| if (xs.len != 0) (if (query(l, xs[0])) |t| (l.arrayOf(t, xs.len) catch null) else null) else null,
.neg => unreachable,
.not => .bool,
.cast => |x| l.typeOfNoFail(x.ty),
.binary => |x| switch (x.op) {
.eq, .ne, .lt, .le, .gt, .ge, .@"and", .@"or" => .bool,
.shl, .shr => query(l, x.l.*),
else => query(l, x.l.*) orelse query(l, x.r.*),
},
.call => |x| switch (x.callee.kind) {
.name => |n| if (l.functionSig(n, e.span)) |sig| sig.ret else null,
.variant => |v| l.enumType(v.@"enum", e.span),
else => if (l.calleeSig(x.callee.*)) |sig| sig.ret else if (pathOf(x.callee.*)) |p| path(l, p, x.args) else null,
},
.move => |n| if (l.lookup(n)) |b| b.ty else null,
.variant => |v| l.enumType(v.@"enum", e.span),
.struct_lit => |x| l.enumOrStruct(x.name, e.span),
.field => |x| blk: {
const known = query(l, x.e.*);
if (std.mem.eql(u8, x.name, "len") and (known == null or !Lowerer.isNominalFieldBase(known.?))) break :blk Ty{ .int = "usize" };
var base = known orelse break :blk null;
if (base.isBorrow()) base = base.inner().?;
const d = l.decl(base) orelse break :blk null;
if (d.kind != .@"struct") break :blk null;
for (d.kind.@"struct") |f| if (std.mem.eql(u8, f.name, x.name)) break :blk l.typeOfNoFail(f.ty);
break :blk null;
},
.if_expr => |x| if (x.then.tail) |t| query(l, t.*) else null,
.match_expr => |x| for (x.arms) |a| {
if (query(l, a.body)) |t| break t;
} else null,
.block => |b| if (b.tail) |t| query(l, t.*) else null,
else => null,
};
}
fn path(l: *Lowerer, p: []const u8, args: []const ast.Expr) ?Ty {
const eq = std.mem.eql;
if (eq(u8, p, "buffer.len") or eq(u8, p, "buffer.capacity")) return .{ .int = "usize" };
if ((eq(u8, p, "own.take") or eq(u8, p, "task.join")) and args.len == 1) return if (query(l, args[0])) |t| t.inner() else null;
if (eq(u8, p, "task.cancelled")) return .bool;
if (std.mem.startsWith(u8, p, "atomic.") and args.len >= 1) {
if (eq(u8, p, "atomic.new")) return if (query(l, args[0])) |t| (l.wrap(.atomic, t) catch null) else null;
if (eq(u8, p, "atomic.take")) return if (query(l, args[0])) |t| t.inner() else null;
if (eq(u8, p, "atomic.store") or eq(u8, p, "atomic.fence") or eq(u8, p, "atomic.compare_exchange")) return null;
// A `ref a` argument, or a `ref<atomic<T>>` binding: the cell's T.
const cell: ?Ty = if (args[0].kind == .borrow) query(l, args[0].kind.borrow.place.*) else if (query(l, args[0])) |t| t.inner() else null;
return if (cell) |c| (if (c == .atomic) c.inner() else null) else null;
}
if ((eq(u8, p, "island.root") or eq(u8, p, "frozen.root") or eq(u8, p, "arc.root")) and args.len == 1)
return if (query(l, args[0])) |t| (if (t.inner()) |o| (if (o.inner()) |root| l.wrap(.iref, root) catch null else null) else null) else null;
if (eq(u8, p, "island.freeze") and args.len == 1) return if (query(l, args[0])) |t| (if (t == .island) l.wrap(.frozen, t.inner().?) catch null else null) else null;
if (eq(u8, p, "arc.from_frozen") and args.len == 1) return if (query(l, args[0])) |t| (if (t == .frozen) l.wrap(.arc, t.inner().?) catch null else null) else null;
if (eq(u8, p, "arc.clone") and args.len == 1) return if (query(l, args[0])) |t| (if (t == .arc) t else if (t.inner()) |in| (if (in == .arc) in else null) else null) else null;
if (eq(u8, p, "channel.dup") and args.len == 1) return if (query(l, args[0])) |t| (if (t == .sender) t else if (t.inner()) |in| (if (in == .sender) in else null) else null) else null;
if (eq(u8, p, "task.spawn") and args.len >= 2) {
const sig = l.calleeSig(args[1]) orelse return null;
return l.wrap(.task, sig.ret) catch null;
}
return null;
}
};
test "expression type queries match the independent shallow derivation" {
var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
const parsed = try parse_mod.parse(a, "module query\nstruct Record { len: u16, arr: [u8; 7] }\nenum Choice { Empty }\n");
try std.testing.expect(parsed == .ok);
var l: Lowerer = .{ .arena = a, .m = parsed.ok };
try l.sigs.put(a, "f", .{ .params = &.{}, .ret = .{ .int = "i64" }, .air_name = "f", .display_name = "f" });
try l.sigs.put(a, "worker", .{ .params = &.{}, .ret = .bool, .air_name = "worker", .display_name = "worker" });
try l.sigs.put(a, "ns.f", .{ .params = &.{}, .ret = .{ .int = "u32" }, .air_name = "ns.f", .display_name = "ns.f" });
const bindings = [_]Binding{
.{ .name = "n", .value = "n", .mutable = false, .ty = .{ .int = "u64" } },
.{ .name = "flag", .value = "flag", .mutable = false, .ty = .bool },
.{ .name = "record", .value = "r", .mutable = false, .ty = .{ .named = 0 } },
.{ .name = "record_ref", .value = "rr", .mutable = false, .ty = try l.wrap(.ref, .{ .named = 0 }) },
.{ .name = "arr", .value = "a", .mutable = false, .ty = try l.arrayOf(.{ .int = "u8" }, 7) },
.{ .name = "slice", .value = "s", .mutable = false, .ty = try l.wrap(.slice, .{ .int = "u8" }) },
.{ .name = "own", .value = "o", .mutable = false, .ty = try l.wrap(.own, .{ .int = "u64" }) },
.{ .name = "cell", .value = "c", .mutable = false, .ty = try l.wrap(.atomic, .{ .int = "u8" }) },
.{ .name = "cell_ref", .value = "cr", .mutable = false, .ty = try l.wrap(.ref, try l.wrap(.atomic, .{ .int = "u8" })) },
.{ .name = "graph", .value = "g", .mutable = false, .ty = try l.wrap(.island, .{ .named = 0 }) },
.{ .name = "graph_ref", .value = "gr", .mutable = false, .ty = try l.wrap(.mut, try l.wrap(.island, .{ .named = 0 })) },
.{ .name = "frozen", .value = "f", .mutable = false, .ty = try l.wrap(.frozen, .{ .named = 0 }) },
.{ .name = "shared", .value = "sh", .mutable = false, .ty = try l.wrap(.arc, .{ .named = 0 }) },
.{ .name = "shared_ref", .value = "shr", .mutable = false, .ty = try l.wrap(.ref, try l.wrap(.arc, .{ .named = 0 })) },
.{ .name = "tx", .value = "tx", .mutable = false, .ty = try l.wrap(.sender, .{ .int = "u8" }) },
.{ .name = "tx_ref", .value = "txr", .mutable = false, .ty = try l.wrap(.ref, try l.wrap(.sender, .{ .int = "u8" })) },
};
try l.bindings.appendSlice(a, &bindings);
const leaves = [_][]const u8{
"unknown", "n", "flag", "1", "1i64", "true", "move own", "ref n",
"record", "record_ref", "record.len", "record_ref.arr", "arr", "slice", "f()", "ns.f()",
"worker::<u8>", "Choice::Empty", "Record { len: 1u16, arr: [0u8; 7] }", "buffer.len(unknown)", "buffer.capacity()", "task.cancelled()", "task.spawn(unknown, worker)", "atomic.load(cell_ref)",
"atomic.load(ref cell)", "atomic.new(1u64)", "atomic.fence(1u64)", "atomic.take(cell)", "atomic.store(ref cell, 1u8)", "atomic.compare_exchange(cell_ref)", "island.root(graph_ref)", "island.freeze(graph)",
"arc.from_frozen(frozen)", "arc.clone(shared_ref)", "channel.dup(tx_ref)", "own.take(own)", "task.join(unknown)",
};
const forms = [_][]const u8{
"{s}", "- {s}", "not {s}", "* {s}", "({s})[0]", "[{s}; 2]", "[{s}, unknown]",
"({s}) as! u8", "({s}).len", "({s}).arr", "({s}) + unknown", "unknown + ({s})", "({s}) << unknown", "if true {{ {s} }} else {{ 1u64 }}",
"match 0u8 {{ 0 => unknown, _ => {s} }}", "{{ {s} }}", "atomic.new({s})", "own.take({s})", "arc.clone({s})",
};
inline for (forms) |form| for (leaves) |leaf| {
const expression = try std.fmt.allocPrint(a, form, .{leaf});
const source = try std.fmt.allocPrint(a, "module query\nfn probe() -> void effects [] {{ return {s}; }}", .{expression});
const r = try parse_mod.parse(a, source);
try std.testing.expect(r == .ok);
const e = r.ok.functions[0].body.stmts[0].kind.@"return".?;
const expected = ReferenceExpressionQuery.query(&l, e);
const actual = l.peekType(e);
if (expected) |ty| try std.testing.expect(actual != null and ty.eql(actual.?)) else try std.testing.expect(actual == null);
try std.testing.expect(l.problem == null);
try std.testing.expectEqual(@as(usize, 0), l.blocks.items.len);
};
}
test "expression queries suspend deep structural, branch and builtin requests" {
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 = "query", .types = &.{}, .functions = &.{} };
const root: ast.Expr = .{ .span = span, .kind = .{ .int = .{ .text = "1u8" } } };
const unknown: ast.Expr = .{ .span = span, .kind = .{ .name = "unknown" } };
const index: ast.Expr = .{ .span = span, .kind = .{ .int = .{ .text = "0usize" } } };
const atomic: ast.Expr = .{ .span = span, .kind = .{ .name = "atomic" } };
const new: ast.Expr = .{ .span = span, .kind = .{ .field = .{ .e = &atomic, .name = "new" } } };
const take: ast.Expr = .{ .span = span, .kind = .{ .field = .{ .e = &atomic, .name = "take" } } };
for ([_]enum { structure, branches, builtin }{ .structure, .branches, .builtin }) |mode| {
var l: Lowerer = .{ .arena = a, .m = m };
var e = root;
for (0..16_384) |_| {
const inner = try a.create(ast.Expr);
inner.* = e;
switch (mode) {
.structure => {
const array = try a.create(ast.Expr);
array.* = .{ .span = span, .kind = .{ .array_rep = .{ .e = inner, .len = 2 } } };
e = .{ .span = span, .kind = .{ .index = .{ .e = array, .lo = &index, .hi = null } } };
},
.branches => e = .{ .span = span, .kind = .{ .binary = .{ .op = .add, .l = &unknown, .r = inner } } },
.builtin => {
const args = try a.alloc(ast.Expr, 1);
args[0] = inner.*;
const allocated = try a.alloc(ast.Expr, 1);
allocated[0] = .{ .span = span, .kind = .{ .call = .{ .callee = &new, .type_arg = null, .args = args } } };
e = .{ .span = span, .kind = .{ .call = .{ .callee = &take, .type_arg = null, .args = allocated } } };
},
}
}
const result = l.peekType(e);
try std.testing.expect(result != null and result.?.eql(.{ .int = "u8" }));
try std.testing.expect(l.problem == null);
try std.testing.expectEqual(@as(usize, 0), l.blocks.items.len);
}
}
test "best-effort expression query OOM releases all backing blocks without diagnostics" {
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 = "query", .types = &.{}, .functions = &.{} };
var e: ast.Expr = .{ .span = span, .kind = .{ .boolean = true } };
for (0..128) |_| {
const inner = try a.create(ast.Expr);
inner.* = e;
e = .{ .span = span, .kind = .{ .array_rep = .{ .e = inner, .len = 1 } } };
}
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.peekType(e);
if (failing.has_induced_failure) try std.testing.expect(result == null) else {
var t = result.?;
for (0..128) |_| {
try std.testing.expect(t == .array and t.array.len == 1);
t = t.array.elem;
}
try std.testing.expect(t == .bool);
}
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;
}
var none: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 0 });
var l: Lowerer = .{ .arena = none.allocator(), .m = m };
const leaf: ast.Expr = .{ .span = span, .kind = .{ .boolean = false } };
try std.testing.expect(l.peekType(leaf).? == .bool);
try std.testing.expect(!none.has_induced_failure);
}
test "deep callee paths own one complete string and bounded lookup stays flat" {
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer fixture.deinit();
const a = fixture.allocator();
const span = unaryTestSpan(1);
var e: ast.Expr = .{ .span = span, .kind = .{ .name = "root" } };
for (0..65_536) |_| {
const base = try a.create(ast.Expr);
base.* = e;
e = .{ .span = span, .kind = .{ .field = .{ .e = base, .name = "x" } } };
}
const text = (try expressionPath(a, e)).?;
try std.testing.expectEqual(@as(usize, 4 + 2 * 65_536), text.len);
try std.testing.expectEqualStrings("root", text[0..4]);
var i: usize = 4;
while (i != text.len) : (i += 2) try std.testing.expectEqualStrings(".x", text[i .. i + 2]);
var buf: [64]u8 = undefined;
try std.testing.expect(dotted(e, &buf) == null);
try std.testing.expect(pathOf(e) == null);
var fail: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 0 });
try std.testing.expectError(error.OutOfMemory, expressionPath(fail.allocator(), e));
try std.testing.expectEqual(@as(usize, 0), fail.allocated_bytes);
try std.testing.expectEqual(@as(usize, 0), fail.freed_bytes);
const invalid: ast.Expr = .{ .span = span, .kind = .{ .field = .{ .e = &.{ .span = span, .kind = .{ .boolean = true } }, .name = "x" } } };
fail = .init(std.testing.allocator, .{ .fail_index = 0 });
try std.testing.expect((try expressionPath(fail.allocator(), invalid)) == null);
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 {
+20
View File
@@ -67,6 +67,26 @@ with tempfile.TemporaryDirectory(prefix='aji-expression-depth-') as directory:
for command in ('lower', 'run', 'report', 'explore'):
assert json.loads(cli(command, path, code=1)) == error
# A cast queries its operand before lowering it. This used to abort
# in peekType even after direct unary lowering had been repaired.
cast_header = header + '('
path = root / f'cast-deref-{depth}.aji'
path.write_text(cast_header + '* ' * depth + '1i64) as i64; }\n')
error = json.loads(cli('check', path, code=1))
col = len(cast_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
# Callee lookup and bounded built-in path recognition also stay flat.
for depth in (16384, 65536):
path = root / f'callee-{depth}.aji'
path.write_text('module depth\nfn main() -> i64 effects [] { return ' + 'ns.' * depth + 'unknown() as i64; }\n')
error = json.loads(cli('check', path, code=1))
assert error['code'] == 'E7002' and error['file'] == 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'