From 6d2c4d40a8772c55dac5ad86a58b226f84f2a2b3 Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Sun, 11 Oct 2026 00:22:18 +0300 Subject: [PATCH] cli: lower struct fields iteratively --- docs/design/open-questions.md | 2 + docs/design/source-expression-depth-audit.md | 64 ++- docs/plan/phase-6-source-language.md | 24 + src/frontend/lower.zig | 442 ++++++++++++++++--- tests/hosted/source_expression_depth.py | 78 ++++ 5 files changed, 557 insertions(+), 53 deletions(-) diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index 9fff20e..09b065d 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -544,3 +544,5 @@ The [shared expression parser increment](source-expression-depth-audit.md#shared 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. The [ordinary-call increment](source-expression-depth-audit.md#ordinary-call-argument-continuations) shares call arguments with scalar continuations, preserving signature/error priority, left-to-right consumption, loans, retained parents, CFG and host OOM behavior. Stable arena-owned states retain bounded builtin/control regression capacity. Build/units/format checks, exact ordinary conformance coverage and call-related CLI suites pass. A separate alternating struct/field program still aborts at 1,024 before and after; builtin/variant/place, aggregate/control and remaining liveness/read/assignment paths keep Q-061 open. No semantic or depth limit changes and no fresh external review are claimed. + +The [struct/value-field increment](source-expression-depth-audit.md#struct-construction-and-value-field-continuations) preserves declaration-order initializer checks, receiver lookup and deferred annotation queries, nominal/static/slice length rules, loans and host OOM. Independent shallow/deep comparisons, output-arena failure cleanup, exact ordinary conformance coverage and public CLI parity pass. The former struct/field abort is repaired; nested array literals still abort at 4,096 before and after. Remaining array/variant/place/control callbacks and liveness/read/assignment walks keep Q-061 open. No semantic or new depth limit changes are made. Independent read-only Claude core/follow-up reviews found no concrete defects, without running tests or establishing whole-Q-061 completion. diff --git a/docs/design/source-expression-depth-audit.md b/docs/design/source-expression-depth-audit.md index 885e157..7ca7be7 100644 --- a/docs/design/source-expression-depth-audit.md +++ b/docs/design/source-expression-depth-audit.md @@ -540,6 +540,65 @@ AIR format, feature, diagnostic, bundle, limit or ownership/runtime change; Q-060 full per-step GC validation and Phase 6 exit gates remain separate. This increment has no external review yet. +## Struct construction and value-field continuations + +Struct initializers and value-field receivers now share the scalar/call driver. +Provided duplicate/unknown fields still reject before any initializer; missing +fields reject when reached in declaration order. Each field's type and consuming +name check precede its initializer, followed by its exact operand check. +Receiver type/field lookup precedes value evaluation; the field annotation is +resolved afterward, as before. Nominal `.len` keeps its extra query, static +array length skips receiver evaluation, and slice length evaluates it. +Borrow/place loads and temporary endings retain their existing native helper. + +Constructor/read states and worklist backing belong to the caller's arena, +including on errors; only stable pointers are queued. Recovering direct/public +allocation failures remain host OOM without source diagnostics or public partial +AIR; persistent backing failures check arena cleanup. No ownership/verifier/ +runtime, normative, format, feature, diagnostic, bundle or limit change. + +The copied former struct/field/length descent, linked to the shallow scalar/call +oracle, passes 864 comparisons of values, constants, full emission/CFG, errors +and loan parents, including `and/or` inside constructors and field receivers. +Borrow-place and array/variant helpers are shared, outside this oracle's +independence. Separate 32,768-level struct/field and mixed scalar/call tests retain +exact instruction/span order. Build/unit/format checks and all 1,793 ordinary +conformance cases pass with terminal exit 0 and exact coverage, repeated after +cleanup (`struct-fields-conformance-reviewed.jsonl` and its audit). Call/ownership +CLI suites pass 635/49/348/133/302/152/42/234 checks; frozen old/new public source +checks and lowerings are byte-identical (1,423/506). + +The focused struct/field CLI suite passes 302 checks on the frozen pre-cleanup +binary (`struct-fields-focused-depth.log`). Full checks/lowerings and formatter +parity accept pure, nominal-length and generic chains through 65,536 levels; +mixed negation/call chains accept through 32,768. At 65,536 mixed levels the +existing instruction limit rejects with E5101 (`instructions per function`, +`max: 262144`, `found: 327682`); lowering retains the complete AIR. Bounded runs +check exact values, fuel and source/AIR parity. Deep missing/duplicate/unknown +fields retain exact codes, reasons and positions across five CLI commands. +Final cleanup removes test-only wrappers and routes query OOM checks through +`expr`; it does not change production traversal. Thirty-six final pre/post +cleanup CLI comparisons at depths 0/16/1,024 retain exact exit/stdout/stderr +(`struct-fields-cleanup-cli-parity.json`). + +Before/after native assert/block/if probes remain identical at 16/64/256 +(`struct-fields-callback-initial.json`). The former alternating struct/field +abort at 1,024 is repaired. A separate array-literal probe accepts 1,024 but +still aborts at 4,096 in both binaries (`struct-fields-followup-array-probes.json` +and raw stdout/stderr). This is the next confirmed lowering path; array/variant/ +place and control callbacks plus liveness/read/assignment scans still keep +Q-061 open. Q-060 full per-step GC validation and Phase 6 exit gates remain +separate. + +Claude's independent read-only core review and narrower cleanup follow-up found +no concrete defects (`/tmp/aji-struct-fields-review.md` and +`/tmp/aji-struct-fields-followup-review.md`). The follow-up read current code +and its own diff but could not reopen the first report outside the repo. Neither +reviewer ran builds or tests; terminal checks above are separate evidence. +The follow-up's unverified CLI E5101 byte-parity assumption is covered by the +302-check run. Deep boolean/field interactions beyond the shallow oracle, +borrow-place depth and full Q-061 completion are not established. + ## Remaining work Follow-up checks accept 16 parenthesized/mixed-call levels but abort @@ -554,7 +613,7 @@ includes a confirmed lowerer failure and inspection-only risks: | Production path | Evidence and next scope | |---|---| | Parser `ifExpr`, block/statement and match/arm expression entry | Native callback re-entry remains. Bounded block/if regression probes above pass; arbitrary and alternating control/statement depth is unverified. | -| Lowerer non-scalar `expr` callbacks: builtin/variant calls, fields/indices/places, arrays/structs, if/match/arms and blocks/statements | Ordinary-call argument descent is repaired above. Alternating struct/field lowering still aborts at 1,024 in both binaries. Other callback depth remains unverified; include alternating scalar/non-scalar expressions. | +| Lowerer non-scalar `expr` callbacks: builtin/variant calls, fields/indices/places, arrays/structs, if/match/arms and blocks/statements | Ordinary calls and struct/value-field descent are repaired above. Nested array-literal lowering still aborts at 4,096 in both binaries. Other callback depth remains unverified; include alternating scalar/non-scalar expressions. | | Lowerer use-after-region/liveness and assignment scans (`After`, first-use/read scans, `blockAssigns`/`stmtAssigns`/`exprAssigns`, match/select helpers) | Recursive AST walks inspected; audit their callers and finite deep inputs separately. | The formatter's expression-marking traversal already uses a worklist, as @@ -562,4 +621,5 @@ inspected and exercised by deep syntax-only probes. This inventory does not claim every listed callback fails, or that all other paths have been cleared. Q-061 and Phase 6 remain open; Q-060's unfinished full GC validation is independent. The five reviewed increments now have a scoped external review; -the host-OOM follow-up and later repairs need their own review. +the host-OOM follow-up and intermediate repairs have no separate review. +The struct/value-field increment has the scoped reviews recorded above. diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index 9bdab6f..4ec5ae4 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -657,3 +657,27 @@ abort at 1,024 is repaired, while a separate alternating struct/field program still aborts there in both binaries. Remaining Q-061 callbacks/walks, Q-060 validation and Phase 6 exit gates remain open. No fresh external review covers this increment. + +### Struct/value-field depth increment + +The [Q-061 struct/value-field increment](../design/source-expression-depth-audit.md#struct-construction-and-value-field-continuations) +shares constructor fields and value receivers with scalar/call continuations. +Declaration-order consumption, duplicate/unknown/missing-field priority, +receiver-first queries, deferred annotation checks and nominal/static/slice +length rules are preserved. Stable states remain in the caller's arena; host +OOM never becomes a source diagnostic, and backing failures free that arena. +Borrow/place helpers retain their existing rules and native callbacks. + +Independent shallow (864) and 32,768-level mixed comparisons, recovering/ +persistent OOM tests, build/units/format and all 1,793 ordinary conformance +cases with exact coverage pass. Call/ownership CLI checks (635/49/348/133/302/ +152/42/234) and frozen public check/lower parity (1,423/506) pass. Bounded native +assert/block/if probes remain exact through 256. The focused depth CLI suite +passes 302 checks: pure/length/generic chains accept at 65,536; mixed chains +accept at 32,768 and reach the existing instruction limit at 65,536. The +struct/field abort at 1,024 is repaired; nested array literals still abort at +4,096 in both binaries. +No normative/bundle/feature/code/limit or ownership/runtime rule changes. +Remaining Q-061 callbacks/walks, Q-060 validation and Phase 6 exit gates remain +open. Independent read-only Claude core/follow-up reviews found no concrete +defects; neither ran tests or established whole-Q-061 completion. diff --git a/src/frontend/lower.zig b/src/frontend/lower.zig index 6e67040..dbc0180 100644 --- a/src/frontend/lower.zig +++ b/src/frontend/lower.zig @@ -2034,7 +2034,7 @@ const Lowerer = struct { .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", &.{}), .call => |x| return switch (try l.prepareCall(e, x.callee.*, x.args, false)) { .done => |v| v, - .ordinary => |c| l.operandExprPrepared(e, null, c), + .ordinary => |c| l.operandExprPrepared(e, null, .{ .call = c }), }, .if_expr => |x| return l.ifExpr(e.span, x.*, want), .block => |b| { @@ -2044,9 +2044,9 @@ const Lowerer = struct { .match_expr => |x| return l.matchExpr(x.*, want), .struct_lit => |x| return l.structLit(e, x.name, x.fields), .variant => |v| return l.variantValue(e, v.@"enum", v.name, &.{}), - .field => |x| { - if (std.mem.eql(u8, x.name, "len")) return l.lenOf(e, x.e.*); - return l.fieldValue(e, x.e.*, x.name); + .field => |x| return switch (try l.prepareFieldExpression(e, x.e.*, x.name)) { + .done => |v| v, + .read => |f| l.operandExprPrepared(e, null, .{ .field = f }), }, .or_trap => |x| return l.orTrap(e, x.*), .move => |n| { @@ -2058,13 +2058,13 @@ const Lowerer = struct { } } - // Scalar operands and ordinary call arguments share one worklist so - // alternating operator/call trees do not re-enter the native stack. + // Scalar operands, ordinary calls, struct initializers and value fields + // share one worklist for arbitrary alternation of those expression forms. fn operandExpr(l: *Lowerer, initial: ast.Expr, initial_want: ?Ty) Error!Value { - return l.operandExprPrepared(initial, initial_want, null); + return l.operandExprPrepared(initial, initial_want, .none); } - fn operandExprPrepared(l: *Lowerer, initial: ast.Expr, initial_want: ?Ty, initial_call: ?*OrdinaryCall) Error!Value { + fn operandExprPrepared(l: *Lowerer, initial: ast.Expr, initial_want: ?Ty, initial_prepared: PreparedExpr) 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 }, @@ -2072,30 +2072,57 @@ const Lowerer = struct { boolean_left: ast.Expr, boolean_right: struct { e: ast.Expr, join: usize, name: []const u8 }, call_argument: *OrdinaryCall, + struct_field: *StructConstruction, + field_value: *FieldRead, }; var pending: std.ArrayList(Frame) = .empty; defer pending.deinit(l.arena); var e = initial; var want = initial_want; - var prepared_call = initial_call; + var prepared = initial_prepared; evaluate: while (true) { var v: Value = while (true) { - if (prepared_call) |c| { - prepared_call = null; - if (c.index == c.args.len) break try l.finishCall(c); - const a = c.args[c.index]; - const pt = c.sig.params[c.index]; - if (a.kind == .borrow or a.kind == .bytes) { - const argument_value = try l.argument(a, pt, &c.temps); - try l.collectCallArgument(c, argument_value); - prepared_call = c; + switch (prepared) { + .none => {}, + .call => |c| { + prepared = .none; + if (c.index == c.args.len) break try l.finishCall(c); + const a = c.args[c.index]; + const pt = c.sig.params[c.index]; + if (a.kind == .borrow or a.kind == .bytes) { + const argument_value = try l.argument(a, pt, &c.temps); + try l.collectCallArgument(c, argument_value); + prepared = .{ .call = c }; + continue; + } + try l.checkConsumingName(a); + try pending.append(l.arena, .{ .call_argument = c }); + e = a; + want = pt; continue; - } - try l.checkConsumingName(a); - try pending.append(l.arena, .{ .call_argument = c }); - e = a; - want = pt; - continue; + }, + .structure => |c| { + prepared = .none; + if (c.index == c.fields.len) break try l.finishStruct(c); + const f = c.fields[c.index]; + const fi = for (c.inits) |*x| { + if (std.mem.eql(u8, x.name, f.name)) break x; + } else return l.invalid(.invalid_literal, c.span, "missing field", &.{ .{ .name = "type", .value = c.display_name }, .{ .name = "field", .value = f.name } }); + c.current_ty = try l.typeOf(f.ty); + c.current_span = fi.e.span; + try l.checkConsumingName(fi.e); + try pending.append(l.arena, .{ .struct_field = c }); + e = fi.e; + want = c.current_ty; + continue; + }, + .field => |f| { + prepared = .none; + try pending.append(l.arena, .{ .field_value = f }); + e = f.base; + want = f.want; + continue; + }, } switch (e.kind) { .not, .deref => |x| { @@ -2148,7 +2175,12 @@ const Lowerer = struct { }, .call => |x| switch (try l.prepareCall(e, x.callee.*, x.args, false)) { .done => |v| break v, - .ordinary => |c| prepared_call = c, + .ordinary => |c| prepared = .{ .call = c }, + }, + .struct_lit => |x| prepared = .{ .structure = try l.prepareStruct(e, x.name, x.fields) }, + .field => |x| switch (try l.prepareFieldExpression(e, x.e.*, x.name)) { + .done => |v| break v, + .read => |f| prepared = .{ .field = f }, }, else => break try l.expr(e, want), } @@ -2229,11 +2261,19 @@ const Lowerer = struct { }, .call_argument => |c| { try l.collectCallArgument(c, v); - prepared_call = c; + prepared = .{ .call = c }; e = c.e; want = null; continue :evaluate; }, + .struct_field => |c| { + try l.checkOperandTy(c.current_span, v.ty, c.current_ty); + try c.names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (c.index == 0) "" else ", ", v.name })); + c.index += 1; + prepared = .{ .structure = c }; + continue :evaluate; + }, + .field_value => |f| v = try l.finishField(f, v), }; return v; } @@ -2283,6 +2323,13 @@ const Lowerer = struct { 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); } + const PreparedExpr = union(enum) { + none, + call: *OrdinaryCall, + structure: *StructConstruction, + field: *FieldRead, + }; + const OrdinaryCall = struct { e: ast.Expr, callee: ast.Expr, @@ -2298,7 +2345,7 @@ const Lowerer = struct { fn call(l: *Lowerer, e: ast.Expr, callee: ast.Expr, args: []const ast.Expr, borrow_allowed: bool) Error!Value { return switch (try l.prepareCall(e, callee, args, borrow_allowed)) { .done => |v| v, - .ordinary => |c| l.operandExprPrepared(e, null, c), + .ordinary => |c| l.operandExprPrepared(e, null, .{ .call = c }), }; } @@ -2436,10 +2483,26 @@ const Lowerer = struct { return result; } + const StructConstruction = struct { + span: Span, + ty: Ty, + display_name: []const u8, + fields: []const ast.Field, + inits: []const ast.FieldInit, + index: usize = 0, + current_ty: Ty = .void, + current_span: Span = undefined, + names: std.ArrayList(u8) = .empty, + }; + /// `Name { f: e, … }`: every field exactly once; initializers are /// evaluated in declaration order, so the AIR does not depend on the /// order the fields are written in (spec 15 §5). fn structLit(l: *Lowerer, e: ast.Expr, name: []const u8, inits: []const ast.FieldInit) Error!Value { + return l.operandExprPrepared(e, null, .{ .structure = try l.prepareStruct(e, name, inits) }); + } + + fn prepareStruct(l: *Lowerer, e: ast.Expr, name: []const u8, inits: []const ast.FieldInit) Error!*StructConstruction { const t = l.enumOrStruct(name, e.span) orelse return l.fail("E7002", e.span, "unknown type", &.{.{ .name = "name", .value = name }}); const d = l.m.types[t.named]; if (d.kind != .@"struct") return l.fail("E7005", e.span, "`Name { … }` constructs a struct; this is an enum (use `Enum::Variant`)", &.{.{ .name = "type", .value = d.display_name orelse name }}); @@ -2451,17 +2514,13 @@ const Lowerer = struct { } else false; if (!known) return l.fail("E7002", fi.span, "no such field", &.{ .{ .name = "type", .value = d.display_name orelse name }, .{ .name = "field", .value = fi.name } }); } - var args: std.ArrayList(u8) = .empty; - for (fields, 0..) |f, i| { - const fi = for (inits) |x| { - if (std.mem.eql(u8, x.name, f.name)) break x; - } else return l.invalid(.invalid_literal, e.span, "missing field", &.{ .{ .name = "type", .value = d.display_name orelse name }, .{ .name = "field", .value = f.name } }); - const ft = try l.typeOf(f.ty); - const v = try l.consuming(fi.e, ft); - try l.checkOperandTy(fi.e.span, v.ty, ft); - try args.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", v.name })); - } - return l.def("s", t, try l.fmt("struct.make {s}({s})", .{ try l.tyText(t), args.items }), e.span); + const c = try l.arena.create(StructConstruction); + c.* = .{ .span = e.span, .ty = t, .display_name = d.display_name orelse name, .fields = fields, .inits = inits }; + return c; + } + + fn finishStruct(l: *Lowerer, c: *const StructConstruction) Error!Value { + return l.def("s", c.ty, try l.fmt("struct.make {s}({s})", .{ try l.tyText(c.ty), c.names.items }), c.span); } fn variantValue(l: *Lowerer, e: ast.Expr, enum_name: []const u8, variant: []const u8, args: []const ast.Expr) Error!Value { @@ -2486,8 +2545,23 @@ const Lowerer = struct { return l.def("e", t, try l.fmt("enum.make {s}.{s}({s})", .{ try l.tyText(t), variant, names.items }), e.span); } - /// `v.f` on a struct value: `struct.get` (borrows come in layer 4). - fn fieldValue(l: *Lowerer, e: ast.Expr, base: ast.Expr, name: []const u8) Error!Value { + const FieldRead = struct { + span: Span, + base: ast.Expr, + want: Ty, + kind: union(enum) { + nominal: struct { name: []const u8, declaration: []const u8, annotation: ast.Type }, + slice_length, + }, + }; + const FieldDispatch = union(enum) { done: Value, read: *FieldRead }; + + fn prepareFieldExpression(l: *Lowerer, e: ast.Expr, base: ast.Expr, name: []const u8) Error!FieldDispatch { + return if (std.mem.eql(u8, name, "len")) l.prepareLength(e, base) else l.prepareFieldValue(e, base, name); + } + + /// Field lookup precedes value lowering; borrow places finish immediately. + fn prepareFieldValue(l: *Lowerer, e: ast.Expr, base: ast.Expr, name: []const u8) Error!FieldDispatch { var bt = (try l.peekType(base)) orelse return l.fail("E7007", base.span, "the type of this expression cannot be determined", &.{}); if (bt.isBorrow()) bt = bt.inner().?; const d = l.decl(bt) orelse return l.fail("E7005", e.span, "field access on a value that is not a struct", &.{.{ .name = "found", .value = try l.diagnosticTyText(bt) }}); @@ -2500,10 +2574,18 @@ const Lowerer = struct { const p = try l.placeBorrow(e, false, false, e.span); const v = try l.def(name, p.v.ty.inner().?, try l.fmt("load %{s}", .{p.v.name}), e.span); try l.endNow(p.ends, e.span); - return v; + return .{ .done = v }; + }; + const state = try l.arena.create(FieldRead); + state.* = .{ .span = e.span, .base = base, .want = bt, .kind = .{ .nominal = .{ .name = name, .declaration = d.air_name orelse d.name, .annotation = f.ty } } }; + return .{ .read = state }; + } + + fn finishField(l: *Lowerer, f: *const FieldRead, v: Value) Error!Value { + return switch (f.kind) { + .nominal => |n| l.def(n.name, try l.typeOf(n.annotation), try l.fmt("struct.get @{s}.{s}, %{s}", .{ n.declaration, n.name, v.name }), f.span), + .slice_length => l.def("len", .{ .int = "usize" }, try l.fmt("slice.len %{s}", .{v.name}), f.span), }; - const v = try l.expr(base, bt); - return l.def(name, try l.typeOf(f.ty), try l.fmt("struct.get @{s}.{s}, %{s}", .{ d.air_name orelse d.name, name, v.name }), e.span); } /// One branch of a conditional or `match`: where it ended (null if it @@ -3043,19 +3125,20 @@ const Lowerer = struct { return t == .named or ((t == .ref or t == .mut) and t.inner().? == .named); } - /// `x.len`: a nominal field, `slice.len`, or the static array length. - fn lenOf(l: *Lowerer, e: ast.Expr, base: ast.Expr) Error!Value { + /// Nominal length fields, static array lengths and slice metadata reads. + fn prepareLength(l: *Lowerer, e: ast.Expr, base: ast.Expr) Error!FieldDispatch { const bt = (try l.peekType(base)) orelse return l.fail("E7007", base.span, "the type of this expression cannot be determined", &.{}); - if (isNominalFieldBase(bt)) return l.fieldValue(e, base, "len"); + if (isNominalFieldBase(bt)) return l.prepareFieldValue(e, base, "len"); const arr: ?u64 = switch (bt) { .array => |a| a.len, .ref, .mut => |x| if (x.* == .array) x.array.len else null, else => null, }; - if (arr) |n| return l.def("len", .{ .int = "usize" }, try l.fmt("const.usize {d}", .{n}), e.span); + if (arr) |n| return .{ .done = try l.def("len", .{ .int = "usize" }, try l.fmt("const.usize {d}", .{n}), e.span) }; if (bt != .slice and bt != .slice_mut) return l.fail("E7005", e.span, "`.len` needs an array or a slice", &.{.{ .name = "found", .value = try l.diagnosticTyText(bt) }}); - const s_ = try l.expr(base, bt); - return l.def("len", .{ .int = "usize" }, try l.fmt("slice.len %{s}", .{s_.name}), e.span); + const state = try l.arena.create(FieldRead); + state.* = .{ .span = e.span, .base = base, .want = bt, .kind = .slice_length }; + return .{ .read = state }; } /// `let (left, right) = s.split_at(k);`: two disjoint borrows of `s`, @@ -5283,6 +5366,69 @@ const ReferenceCalls = struct { // Independent pre-repair unary/binary expression derivation. Other leaves // share expression handlers; this oracle is only for shallow operand trees. +// Copied former struct/field/length descent, linked to the independent +// shallow scalar/call oracle. Borrow-place and array/variant helpers remain +// shared and are outside this oracle's independence. +const ReferenceFields = struct { + fn structLit(l: *Lowerer, e: ast.Expr, name: []const u8, inits: []const ast.FieldInit) Error!Value { + const t = l.enumOrStruct(name, e.span) orelse return l.fail("E7002", e.span, "unknown type", &.{.{ .name = "name", .value = name }}); + const d = l.m.types[t.named]; + if (d.kind != .@"struct") return l.fail("E7005", e.span, "`Name { … }` constructs a struct; this is an enum (use `Enum::Variant`)", &.{.{ .name = "type", .value = d.display_name orelse name }}); + const fields = d.kind.@"struct"; + for (inits, 0..) |fi, i| { + for (inits[0..i]) |prev| if (std.mem.eql(u8, prev.name, fi.name)) return l.invalid(.invalid_literal, fi.span, "field given twice", &.{.{ .name = "field", .value = fi.name }}); + const known = for (fields) |f| { + if (std.mem.eql(u8, f.name, fi.name)) break true; + } else false; + if (!known) return l.fail("E7002", fi.span, "no such field", &.{ .{ .name = "type", .value = d.display_name orelse name }, .{ .name = "field", .value = fi.name } }); + } + var args: std.ArrayList(u8) = .empty; + for (fields, 0..) |f, i| { + const fi = for (inits) |x| { + if (std.mem.eql(u8, x.name, f.name)) break x; + } else return l.invalid(.invalid_literal, e.span, "missing field", &.{ .{ .name = "type", .value = d.display_name orelse name }, .{ .name = "field", .value = f.name } }); + const ft = try l.typeOf(f.ty); + const v = try ReferenceCalls.consuming(l, fi.e, ft); + try l.checkOperandTy(fi.e.span, v.ty, ft); + try args.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", v.name })); + } + return l.def("s", t, try l.fmt("struct.make {s}({s})", .{ try l.tyText(t), args.items }), e.span); + } + + fn fieldValue(l: *Lowerer, e: ast.Expr, base: ast.Expr, name: []const u8) Error!Value { + var bt = (try l.peekType(base)) orelse return l.fail("E7007", base.span, "the type of this expression cannot be determined", &.{}); + if (bt.isBorrow()) bt = bt.inner().?; + const d = l.decl(bt) orelse return l.fail("E7005", e.span, "field access on a value that is not a struct", &.{.{ .name = "found", .value = try l.diagnosticTyText(bt) }}); + if (d.kind != .@"struct") return l.fail("E7005", e.span, "field access on an enum; use `match`", &.{.{ .name = "type", .value = d.display_name orelse d.name }}); + const f = for (d.kind.@"struct") |x| { + if (std.mem.eql(u8, x.name, name)) break x; + } else return l.fail("E7002", e.span, "no such field", &.{ .{ .name = "type", .value = d.display_name orelse d.name }, .{ .name = "field", .value = name } }); + // Through a borrow: borrow the field and load it. + if (l.rootBinding(base)) |rb| if (rb.kind == .borrow) { + const p = try l.placeBorrow(e, false, false, e.span); + const v = try l.def(name, p.v.ty.inner().?, try l.fmt("load %{s}", .{p.v.name}), e.span); + try l.endNow(p.ends, e.span); + return v; + }; + const v = try ReferenceOperands.expr(l, base, bt); + return l.def(name, try l.typeOf(f.ty), try l.fmt("struct.get @{s}.{s}, %{s}", .{ d.air_name orelse d.name, name, v.name }), e.span); + } + + fn lenOf(l: *Lowerer, e: ast.Expr, base: ast.Expr) Error!Value { + const bt = (try l.peekType(base)) orelse return l.fail("E7007", base.span, "the type of this expression cannot be determined", &.{}); + if (Lowerer.isNominalFieldBase(bt)) return fieldValue(l, e, base, "len"); + const arr: ?u64 = switch (bt) { + .array => |a| a.len, + .ref, .mut => |x| if (x.* == .array) x.array.len else null, + else => null, + }; + if (arr) |n| return l.def("len", .{ .int = "usize" }, try l.fmt("const.usize {d}", .{n}), e.span); + if (bt != .slice and bt != .slice_mut) return l.fail("E7005", e.span, "`.len` needs an array or a slice", &.{.{ .name = "found", .value = try l.diagnosticTyText(bt) }}); + const s_ = try ReferenceOperands.expr(l, base, bt); + return l.def("len", .{ .int = "usize" }, try l.fmt("slice.len %{s}", .{s_.name}), e.span); + } +}; + const ReferenceOperands = struct { fn expr(l: *Lowerer, e: ast.Expr, want: ?Ty) Error!Value { switch (e.kind) { @@ -5336,6 +5482,8 @@ const ReferenceOperands = struct { return l.def("cast", to, try l.fmt("cast.{s}.{s} %{s}", .{ mode, to.int, v.name }), e.span); }, .call => |x| return ReferenceCalls.call(l, e, x.callee.*, x.args, false), + .struct_lit => |x| return ReferenceFields.structLit(l, e, x.name, x.fields), + .field => |x| return if (std.mem.eql(u8, x.name, "len")) ReferenceFields.lenOf(l, e, x.e.*) else ReferenceFields.fieldValue(l, e, x.e.*, x.name), .binary => |x| return binary(l, e, x.op, x.l.*, x.r.*, want), else => return l.expr(e, want), } @@ -7147,13 +7295,15 @@ test "recovering host OOM escapes query callers without language diagnostics or .let_peek, .let_use => l.stmt(.{ .span = span, .kind = .{ .let = .{ .names = &.{"n"}, .ty = null, .e = if (mode == .let_use) unsuffixed else sum } } }), .range => l.forLoop(span, "i", sum, unsuffixed, empty), .field => blk: { - _ = l.fieldValue(field, sum, "x") catch |err| break :blk err; + _ = l.expr(field, null) catch |err| break :blk err; }, .match => blk: { _ = l.matchExpr(.{ .scrutinee = sum, .arms = &.{}, .span = span, .kind = .integer }, null) catch |err| break :blk err; }, .length => blk: { - _ = l.lenOf(field, sum) catch |err| break :blk err; + var length = field; + length.kind.field.name = "len"; + _ = l.expr(length, null) catch |err| break :blk err; }, .assignment => l.assignPlace(span, field, unsuffixed), }; @@ -7249,6 +7399,7 @@ test "public source lowering propagates each recovering allocation failure" { "module oom\nstruct S { items: [u8; 7] }\nfn main() -> usize effects [] { let s: S = S { items: [1u8; 7] }; return s.items.len; }\n", "module oom\nfn worker(x: i64) -> i64 effects [] { return - x; }\nfn main() -> i64 effects [] { let n = 1; return worker(n + 1i64); }\n", "module oom\nfn id(x: i64) -> i64 effects [] { return x; }\nfn read(p: ref) -> i64 effects [] { return *p; }\nfn bytes(s: slice) -> i64 effects [] { return s.len as! i64; }\nfn pair(x: i64, y: i64) -> i64 effects [] { return x + y; }\nfn main() -> i64 effects [] { var n: i64 = 1i64; return pair(id(read(ref n)), id(bytes(b\"xy\"))); }\n", + "module oom\nstruct Box { n: i64, len: i64 }\nfn main() -> i64 effects [] { var b: Box = Box { len: 2i64, n: 1i64 }; ref p = b; return (Box { len: p.len, n: p.n }).n; }\n", }; for (sources) |source| { var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); @@ -7464,3 +7615,192 @@ test "persistent backing OOM in public call lowering frees its output arena" { } } } + +fn fieldTestLowerer(a: Allocator, m: ast.Module, span: Span) !Lowerer { + var l = try callTestLowerer(a, span); + l.m = m; + const names = try a.alloc([]const u8, m.types.len); + for (m.types, names) |decl, *name| name.* = try l.fmt("@{s}", .{decl.air_name orelse decl.name}); + l.typeNames = names; + try l.checkRequirements(); + const box_ty: Ty = .{ .named = 0 }; + try l.bindings.appendSlice(a, &.{ + .{ .name = "box", .value = "box_value", .mutable = false, .ty = box_ty }, + .{ .name = "stored", .value = "box_storage", .mutable = true, .ty = box_ty, .kind = .storage }, + .{ .name = "borrowed", .value = "box_loan", .mutable = false, .ty = try l.wrap(.ref, box_ty), .kind = .borrow }, + .{ .name = "mutable", .value = "box_mut", .mutable = false, .ty = try l.wrap(.mut, box_ty), .kind = .borrow }, + .{ .name = "sl", .value = "slice_value", .mutable = false, .ty = try l.wrap(.slice, .{ .int = "u8" }), .kind = .borrow }, + }); + try l.borrow_parents.put(a, "box_loan", "box_storage"); + try l.sigs.put(a, "box_id", .{ .params = try a.dupe(Ty, &.{box_ty}), .ret = box_ty, .air_name = "box_id", .display_name = "box_id" }); + return l; +} + +const fieldTestDeclarations = + "module fields\n" ++ + "struct Box { n: i64 }\n" ++ + "struct Length { len: i64 }\n" ++ + "struct Pair { first: i64, second: i64 }\n" ++ + "struct Nested { inner: Box }\n" ++ + "struct Owner { item: own }\n" ++ + "struct Empty {}\n" ++ + "enum Choice { some(i64), none }\n" ++ + "struct Bool { flag: bool }\n"; + +fn expectFieldMatches(a: Allocator, m: ast.Module, e: ast.Expr, want: ?Ty) !void { + var old = try fieldTestLowerer(a, m, e.span); + var current = try fieldTestLowerer(a, m, e.span); + const expected = ReferenceOperands.expr(&old, e, want); + const actual = current.expr(e, want); + if (expected) |v| { + const result = try actual; + try std.testing.expectEqualStrings(v.name, result.name); + try std.testing.expect(v.ty.eql(result.ty)); + } else |err| try std.testing.expectError(err, actual); + try std.testing.expectEqualDeep(old.problem, current.problem); + try std.testing.expectEqualDeep(old.unimpl, current.unimpl); + try std.testing.expectEqualDeep(old.blocks.items, current.blocks.items); + try std.testing.expectEqualDeep(old.allocs.items, current.allocs.items); + try std.testing.expectEqualDeep(old.constants.items, current.constants.items); + try std.testing.expectEqualDeep(old.bindings.items, current.bindings.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); + try std.testing.expectEqual(old.linear_enabled, current.linear_enabled); + try std.testing.expectEqual(old.in_constant, current.in_constant); + try std.testing.expectEqual(old.borrow_parents.count(), current.borrow_parents.count()); + var parents = old.borrow_parents.iterator(); + while (parents.next()) |item| try std.testing.expectEqualStrings(item.value_ptr.*, current.borrow_parents.get(item.key_ptr.*).?); +} + +test "struct field continuations match former declaration order and diagnostic priority" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const expressions = [_][]const u8{ + "Box { n: 1i64 }", "Box { n: id(1i64) }.n", "Box { n: Box { n: n }.n }.n", + "Nested { inner: Box { n: 1i64 } }.inner.n", "box.n", "stored.n", + "borrowed.n", "mutable.n", "box_id(Box { n: 1i64 }).n", + "Length { len: 2i64 }.len", "Length { len: unknown }.len", "Pair { second: id(2i64), first: id(1i64) }", + "Pair { second: false, first: unknown }", "Pair { second: unknown, first: false }", "Pair { first: unknown, first: false, second: 1i64 }", + "Pair { first: unknown, extra: false }", "Pair { first: 1i64 }", "Pair { second: unknown }", + "Pair { second: 1i64 }", "Pair { first: unknown }.missing", "Box { n: unknown }.missing", + "Empty {}", "Empty {}.n", "Choice {}", + "Missing { n: unknown }", "unknown.n", "1i64.n", + "Owner { item: o }", "Owner { item: move o }", "Owner { item: unknown }", + "Box { n: void_call(b\"xy\") }", "Box { n: stop(b\"xy\") }", "Box { n: move n }", + "Box { n: true }.n", "Box {}.n", "Choice::none.n", + "Box { n: 1 }.n", "sl.len", "sl.n", + "a.len", "[id(unknown); 2].len", "Box { n: 1 }.len", + "not (Box { n: 1i64 }.n == id(1i64))", "Box { n: id(- (2i64 + Box { n: 1i64 }.n)) }.n", "bool_id(Box { n: 1i64 }.n == 1i64 and Box { n: 2i64 }.n == 2i64)", + "Bool { flag: bool_id(true) and bool_id(false) }.flag", "Bool { flag: true }.flag or Bool { flag: bool_id(unknown) }.flag", "Bool { flag: Box { n: id(1i64) }.n == 1i64 or false }.flag", + }; + const forms = [_][]const u8{ "{s}", "id({s})", "Box {{ n: {s} }}.n", "- ({s})", "not ({s})", "({s}) as! u8" }; + inline for (forms) |form| for (expressions) |text| { + const expression = try std.fmt.allocPrint(a, form, .{text}); + const source_text = try std.fmt.allocPrint(a, "{s}fn f() -> void effects [] {{ return {s}; }}", .{ fieldTestDeclarations, expression }); + const parsed = try parse_mod.parse(a, source_text); + if (parsed != .ok) std.debug.print("field test did not parse: {s}\n", .{expression}); + try std.testing.expect(parsed == .ok); + const e = parsed.ok.functions[0].body.stmts[0].kind.@"return".?; + for ([_]?Ty{ null, .{ .int = "i64" }, .{ .named = 0 } }) |want| try expectFieldMatches(a, parsed.ok, e, want); + }; +} + +test "deep struct fields share scalar and call continuations with exact emission spans" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const m = (try parse_mod.parse(a, fieldTestDeclarations)).ok; + const count = 32_768; + for ([_]bool{ false, true }) |mixed| { + const span = unaryTestSpan(1); + var l = try fieldTestLowerer(a, m, span); + const callee: ast.Expr = .{ .span = span, .kind = .{ .name = "id" } }; + var e: ast.Expr = .{ .span = unaryTestSpan(90_000), .kind = .{ .int = .{ .text = "1i64" } } }; + for (0..count) |i| { + const here = unaryTestSpan(@intCast(i + 1)); + if (mixed) { + const args = try a.alloc(ast.Expr, 1); + args[0] = e; + const call = try a.create(ast.Expr); + call.* = .{ .span = here, .kind = .{ .call = .{ .callee = &callee, .type_arg = null, .args = args } } }; + e = .{ .span = here, .kind = .{ .neg = call } }; + } + const inits = try a.alloc(ast.FieldInit, 1); + inits[0] = .{ .name = "n", .span = here, .e = e }; + const constructor = try a.create(ast.Expr); + constructor.* = .{ .span = here, .kind = .{ .struct_lit = .{ .name = "Box", .fields = inits } } }; + e = .{ .span = here, .kind = .{ .field = .{ .e = constructor, .name = "n" } } }; + } + const v = try l.expr(e, .{ .int = "i64" }); + try std.testing.expect(v.ty.eql(.{ .int = "i64" })); + const insts = l.blocks.items[0].insts.items; + try std.testing.expectEqual(@as(usize, (if (mixed) @as(usize, 5) else 2) * count + 1), insts.len); + const base: usize = if (mixed) count + 1 else 1; + for (0..count) |i| { + const index = base + (if (mixed) @as(usize, 4) else 2) * i; + const make_index = index + (if (mixed) @as(usize, 2) else 0); + try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(@intCast(i + 1))), insts[make_index].span); + try std.testing.expect(std.mem.indexOf(u8, insts[make_index].text, " = struct.make @Box(") != null); + try std.testing.expectEqualDeep(insts[make_index].span, insts[make_index + 1].span); + try std.testing.expect(std.mem.indexOf(u8, insts[make_index + 1].text, " = struct.get @Box.n, ") != null); + if (mixed) { + try std.testing.expect(std.mem.indexOf(u8, insts[index].text, " = call @id(") != null); + try std.testing.expect(std.mem.indexOf(u8, insts[index + 1].text, " = sub.checked.i64 ") != null); + } + } + try std.testing.expect(l.problem == null and l.unimpl == null); + } +} + +test "recovering OOM in struct field continuations is never a source diagnosis" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const source_text = fieldTestDeclarations ++ "fn f() -> void effects [] { return Box { n: id(Box { n: n }.n) }.n; }"; + const parsed = try parse_mod.parse(fixture.allocator(), source_text); + try std.testing.expect(parsed == .ok); + const e = parsed.ok.functions[0].body.stmts[0].kind.@"return".?; + var fail_at: usize = 0; + while (true) : (fail_at += 1) { + try std.testing.expect(fail_at < 512); + var output: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer output.deinit(); + var l = try fieldTestLowerer(output.allocator(), parsed.ok, e.span); + var failure: QueryAllocationFailure = .{ .backing = output.allocator(), .fail_at = fail_at }; + l.arena = failure.allocator(); + const result = l.expr(e, .{ .int = "i64" }); + if (failure.failed) { + try std.testing.expectError(error.OutOfMemory, result); + try std.testing.expect(l.problem == null and l.unimpl == null); + try std.testing.expectEqual(fail_at + 1, failure.attempts); + try std.testing.expectEqual(@as(usize, 0), l.out.items.len); + } else { + _ = try result; + break; + } + } +} + +test "persistent backing OOM in public struct field lowering frees output arena" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const parsed = try parse_mod.parse(fixture.allocator(), "module oom\nstruct Box { n: i64 }\nfn id(x: i64) -> i64 effects [] { return x; }\nfn main() -> i64 effects [] { return Box { n: id(- Box { n: 1i64 }.n) }.n; }\n"); + try std.testing.expect(parsed == .ok); + var fail_at: usize = 0; + while (true) : (fail_at += 1) { + try std.testing.expect(fail_at < 128); + var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = fail_at }); + var output: std.heap.ArenaAllocator = .init(failing.allocator()); + const result = lower(output.allocator(), parsed.ok); + output.deinit(); + try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes); + if (failing.has_induced_failure) { + try std.testing.expectError(error.OutOfMemory, result); + } else { + // Returned bytes are dead; inspect only the result tag. + try std.testing.expect((try result) == .ok); + break; + } + } +} diff --git a/tests/hosted/source_expression_depth.py b/tests/hosted/source_expression_depth.py index 531c720..258c724 100644 --- a/tests/hosted/source_expression_depth.py +++ b/tests/hosted/source_expression_depth.py @@ -372,6 +372,84 @@ with tempfile.TemporaryDirectory(prefix='aji-expression-depth-') as directory: assert cli(command, path, code=1) == expected print(f'nested call invalid depth: {depth}', flush=True) + # Constructors and value-field reads share the scalar/call driver. + for depth in (0, 1, 16, 1024, 16384, 32768, 65536): + for kind in ('field', 'length-field', 'mixed-field', 'generic-field'): + if depth == 32768 and kind != 'mixed-field': + continue + field = 'len' if kind == 'length-field' else 'n' + generic = kind == 'generic-field' + name = 'Box::' if generic else 'Box' + prefix = name + ' { ' + field + ': ' + if kind == 'mixed-field': + prefix += '- id(' + suffix = (')' if kind == 'mixed-field' else '') + ' }.' + field + expression = prefix * depth + '1i64' + suffix * depth + declaration = ('struct Box { n: T }\n' if generic else + 'struct Box { ' + field + ': i64 }\n') + helper = 'fn id(x: i64) -> i64 effects [] { return x; }\n' if kind == 'mixed-field' else '' + path = root / f'struct-{kind}-{depth}.aji' + path.write_text('module depth\n' + declaration + helper + + 'fn main() -> i64 effects [] { return ' + expression + '; }\n') + main_instructions = (5 if kind == 'mixed-field' else 2) * depth + 2 + limited = main_instructions > 262144 + expected_check = cli('check', path, code=1 if limited else 0) + if limited: + diagnostic = json.loads(expected_check) + assert (diagnostic['code'], diagnostic['limit'], diagnostic['max'], diagnostic['found']) == ( + 'E5101', 'instructions per function', 262144, main_instructions), diagnostic + for command in ('run', 'report', 'explore'): + assert cli(command, path, code=1) == expected_check + else: + assert expected_check == b'' + lowered = cli('lower', path) + instructions = sum((line.lstrip().startswith(b'%') and b' = ' in line) or line.strip().startswith(b'ret ') for line in lowered.splitlines()) + assert instructions == main_instructions + (1 if helper else 0), (kind, depth, instructions) + if depth <= 1024: + fuel = main_instructions + (depth if helper else 0) + value = -1 if kind == 'mixed-field' and depth % 2 else 1 + 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) + formatted = path.with_suffix('.formatted.aji') + output = cli('fmt', path) + formatted.write_bytes(output) + assert cli('fmt', formatted) == output + assert json.loads(cli('fmt', formatted, '--check')) == { + 'file': str(formatted), 'status': 'formatted', 'changed': False} + formatted_check = cli('check', formatted, code=1 if limited else 0) + if limited: + diagnostic = json.loads(formatted_check) + assert (diagnostic['code'], diagnostic['limit'], diagnostic['max'], diagnostic['found']) == ( + 'E5101', 'instructions per function', 262144, main_instructions), diagnostic + else: + assert formatted_check == b'' + assert cli('lower', formatted) == lowered + print(f'struct field depth: {kind} {depth}', flush=True) + + for depth in (1024, 16384, 65536): + # Exact missing/duplicate/unknown-field priorities at the inner leaf. + for leaf, code, reason in (('Box {}.n', 'E7006', 'invalid_literal'), + ('Box { n: 1i64, n: false }.n', 'E7006', 'invalid_literal'), + ('Box { missing: unknown }.n', 'E7002', None)): + path = root / f'struct-invalid-{depth}-{code}-{len(leaf)}.aji' + header = 'fn main() -> i64 effects [] { return ' + prefix = 'Box { n: ' * depth + path.write_text('module depth\nstruct Box { n: i64 }\n' + header + prefix + leaf + ' }.n' * depth + '; }\n') + expected = cli('check', path, code=1) + error = json.loads(expected) + offset = 0 if 'Box {}' in leaf else (len('Box { n: 1i64, ') if code == 'E7006' else len('Box { ')) + assert (error['code'], error['line'], error['col'], error['file']) == ( + code, 3, len(header) + len(prefix) + offset + 1, str(path)), error + if reason: + assert error['reason'] == reason, error + for command in ('lower', 'run', 'report', 'explore'): + assert cli(command, path, code=1) == expected + print(f'struct field invalid depth: {depth}', flush=True) + # Builtin callbacks are still native; preserve the prior diagnostic at # bounded nesting while ordinary calls gain explicit continuations. for depth in (16, 64, 256):