From f18b41dd3d1145904a0b79b249a952b71847715d Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Sat, 10 Oct 2026 14:31:50 +0300 Subject: [PATCH] cli: print source types iteratively and propagate allocation errors --- docs/design/air-type-depth-audit.md | 8 + docs/design/open-questions.md | 2 + docs/plan/phase-6-source-language.md | 6 + src/frontend/lower.zig | 381 ++++++++++++++++++++------- 4 files changed, 308 insertions(+), 89 deletions(-) diff --git a/docs/design/air-type-depth-audit.md b/docs/design/air-type-depth-audit.md index 4703508..a8bfdd1 100644 --- a/docs/design/air-type-depth-audit.md +++ b/docs/design/air-type-depth-audit.md @@ -156,3 +156,11 @@ The independently reproduced 8,192-declaration linear/declaration failure is rep The old recursive nominal declaration algorithm is now copied into the shallow oracle as well, removing the shared-nominal limitation of the preceding tests. Tests compare 4,613 roots over 128 generated six-declaration graphs and targeted nested-argument/parameter states, each queried three times with retained caches: results, lookup counts, complete entry order/keys/values/generations and final generation all agree. The existing 2,160 shallow syntax comparisons now use this independent nominal derivation too. Three 16,384-declaration mixed struct/enum queries cover negative content, positive leaves and a deep cyclic back-edge with a later positive witness. Six argument/cycle/result shapes fail every underlying arena allocation request in turn, checking OOM and full arena cleanup. Units/format checks, nominal/Copy-content/static-function CLI integration (110/119/25) and all 1,791 conformance cases pass with exact corpus coverage; all 1,421 source checks and 506 accepted lowerings preserve exact old/new exit/stdout/stderr. The complete formerly failing Copy chain accepts with no output. Replacing its final field with own returns exactly one E7005 at 8194:19, with constraint Copy and type_constructor own_array. No timeout ends these probes; only child core capture is disabled. A separate 65,536-array invalid-atomic source now confirms source typeText native-stack exhaustion (10,001 frames, exit -6, no JSON), before any diagnostic is emitted. Source Ty equality/text/AIR conversion and closing query paths keep Q-059 open; Q-060 validation and Phase 6/contract gates remain separate. No syntax/feature/code/bundle growth, runtime/effect/ownership rule, generic traversal guard or accepted-depth limit changes. No fresh Claude review is claimed. + +## Source type text repair + +The 65,536-array invalid-atomic source's confirmed typeText abort is repaired by an iterative prefix/leaf/suffix writer. One growing byte buffer replaces recursively copied ancestor strings; temporary parent storage and failed output buffers are released. Canonical spelling, array decimal lengths/spaces, source-versus-AIR nominal names and the resources feature side effect are preserved. The internal typeText/tyText/diagnosticTyText APIs now propagate host OutOfMemory at every caller, replacing the old array/borrow/cap fallback strings. Failed metadata allocation must not fabricate a found type or generated AIR; ordinary diagnostics, syntax, effects, ownership/runtime/fuel and acceptance rules are unchanged. + +Independent shallow tests compare 3,696 canonical/diagnostic outputs and feature states against the old printer, covering every wrapper/leaf, nominal display-name fallbacks and zero/max-u64 array lengths. A 65,536-level mixed chain has independently assembled exact text in both modes. Allocation failures cover direct printing, diagnostics and local AIR emission, with arena cleanup and no fabricated diagnostic/partial instruction; constant leaves retain the allocation-free path. Units and format checks pass. Repair-advice/nonvalue/static-function CLI integration passes 299/635/25 checks; all 1,421 public source checks and 506 accepted lowerings preserve exact old/new exit/stdout/stderr. All 1,791 conformance cases pass with exact corpus coverage. + +The formerly aborting invalid-atomic check now returns exactly one E7005 at 2:9 without stderr; its complete found type is byte-identical to the independent 655,362-byte expectation. A separate correct 65,536-array parameter check accepts without output. A struct field containing 16,384 arrays then confirms remaining native recursion in source-to-AIR type conversion: 4,425 airType frames, exit -6, no JSON. Only child core capture is disabled, and no timeout ends a probe. Source-to-AIR repair, Ty equality and closing query paths keep Q-059 open; Q-060 validation and Phase 6 gates remain separate. No syntax/feature/code/bundle growth, runtime/effect/ownership rule, generic guard or accepted-depth limit is introduced. No fresh Claude review is claimed. diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index ccfeaf1..cceaef9 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -485,6 +485,8 @@ The [source anonymous property increment](air-type-depth-audit.md#source-anonymo The [source nominal property increment](air-type-depth-audit.md#source-nominal-property-continuations) repairs the confirmed linear/declaration failure with explicit argument/member continuations, retaining cache generations and known-parameter cycle states. An independent recursive nominal oracle checks ordered cache records; complete checking accepts the 8,192-Copy chain and rejects linear content with E7005. A separate 65,536-array invalid-atomic source confirms typeText native-stack exhaustion. Source Ty text/equality/AIR conversion and closing call-path work keep Q-059 open; no semantic limit or rule changes. +The [source type text increment](air-type-depth-audit.md#source-type-text-repair) repairs the confirmed diagnostic printing failure with iterative prefix/suffix output and exact canonical/source naming. Host OOM propagates instead of supplying fabricated type strings. The deep invalid atomic now returns E7005 with its complete found type, and a correct 65,536-array parameter accepts. A 16,384-array struct member independently confirms the remaining airType native-stack failure. Source-to-AIR repair, Ty equality and closing query audits still keep Q-059 open. No semantic limit or rule changes. + ## Q-060 — Native recursion while materializing runtime values The [executed runtime audit](runtime-value-depth-audit.md) confirms that a verified one-byte value with 32,768 length-one nested arrays aborts inside zeroValue under `aji run --fuel 8`, rather than producing a run record. The instruction has not exhausted fuel. Iterative runtime traversal must preserve initialization, value shape, allocator/root lifetimes, collection safety and instruction accounting; adding a depth trap/acceptance limit needs a normative decision. At that baseline, recursive copying, value sizing, collection and serialization were additional audit candidates with unverified failure paths; the increment below records subsequent executed failures. Compiler type repairs in Q-059 do not resolve Q-060. diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index 7e1d07c..c584c03 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -478,3 +478,9 @@ Units/format checks, Copy-content/generic CLI integration (119/32) and byte-iden The [Q-059 nominal-source increment](../design/air-type-depth-audit.md#source-nominal-property-continuations) replaces native argument/declaration recursion with explicit continuations, retaining environment/path binding, ordered fields/payloads and cache generation rules. The previously crashing 8,192-Copy declaration check accepts; linear content returns E7005. Independent ordered-cache comparisons cover 4,613 roots (three queries each), while deep mixed/cyclic graphs and allocation-failure cleanup pass. Units/format checks, nominal/Copy-content/static-function integration (110/119/25), all 1,791 conformance cases with exact coverage and byte-identical old/new checks/lowerings (1,421/506) pass. A separate invalid-atomic source confirms typeText stack failure at 65,536 array levels. Source Ty/query closing checks, Q-060 validation and Phase 6 gates remain open. No normative/bundle/feature/code change or accepted-depth limit is introduced; no fresh Claude review is claimed. + +## Source type text repair (2026-10-10) + +The [Q-059 source text increment](../design/air-type-depth-audit.md#source-type-text-repair) removes recursive and repeatedly copied ancestor strings, preserving exact spelling/source nominal names and resource feature discovery. Its internal fallible APIs propagate host OOM instead of generating shortened type facts or AIR. The formerly aborting deep invalid-atomic check returns one E7005 with the complete 655,362-byte found type. + +Units/format checks, 3,696 independent shallow comparisons, deep mixed output and failed-allocation/cleanup tests pass. Repair-advice/nonvalue/static-function integration (299/635/25) and old/new source checks/lowerings (1,421/506) pass; all 1,791 conformance cases pass with exact corpus coverage. A correct 65,536-array parameter accepts; a 16,384-array struct member independently confirms remaining airType native-stack failure. Source-to-AIR repair, Ty/query closing checks, Q-060 validation and Phase 6 gates remain open. No normative/bundle/feature/code change or accepted-depth limit is introduced; no fresh Claude review is claimed. diff --git a/src/frontend/lower.zig b/src/frontend/lower.zig index e39705a..a83dcfb 100644 --- a/src/frontend/lower.zig +++ b/src/frontend/lower.zig @@ -383,36 +383,69 @@ const Lowerer = struct { return error.Unimplemented; } - fn tyText(l: *Lowerer, t: Ty) []const u8 { + fn tyText(l: *Lowerer, t: Ty) Allocator.Error![]const u8 { return l.typeText(t, false); } - fn diagnosticTyText(l: *Lowerer, t: Ty) []const u8 { + fn diagnosticTyText(l: *Lowerer, t: Ty) Allocator.Error![]const u8 { return l.typeText(t, true); } - fn typeText(l: *Lowerer, t: Ty, source_names: bool) []const u8 { - return switch (t) { + fn typeText(l: *Lowerer, annotation: Ty, source_names: bool) Allocator.Error![]const u8 { + var pending: std.ArrayList(Ty) = .empty; + defer pending.deinit(l.arena); + var out: std.ArrayList(u8) = .empty; + defer out.deinit(l.arena); + var t = annotation; + while (t.inner()) |inner| { + try pending.append(l.arena, t); + if (t == .array) { + try out.appendSlice(l.arena, "array<"); + } else { + try out.appendSlice(l.arena, @tagName(t)); + try out.append(l.arena, '<'); + } + t = inner; + } + const leaf: ?[]const u8 = switch (t) { .int => |x| x, .bool => "bool", .void => "void", .never => "never", .named => |i| if (source_names and l.m.types[i].air_name != null) (l.m.types[i].display_name orelse l.m.types[i].name) else l.typeNames[i], - .array => |a| std.fmt.allocPrint(l.arena, "array<{s}, {d}>", .{ l.typeText(a.elem, source_names), a.len }) catch "array", - .ref, .mut, .slice, .slice_mut, .own, .own_array, .buffer, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| std.fmt.allocPrint(l.arena, "{s}<{s}>", .{ @tagName(t), l.typeText(x.*, source_names) }) catch "borrow", .scope => "scope", .shield => "shield", .region => "region", - .cap => |k| std.fmt.allocPrint(l.arena, "cap<{s}>", .{k}) catch "cap", - .builtin => |b| blk: { + .cap => |k| leaf: { + try out.appendSlice(l.arena, "cap<"); + try out.appendSlice(l.arena, k); + try out.append(l.arena, '>'); + break :leaf null; + }, + .builtin => |b| leaf: { if (b == .io_error) l.uses.insert(.resources); - break :blk @tagName(b); + break :leaf @tagName(b); }, - .resource => |r| blk: { + .resource => |r| leaf: { l.uses.insert(.resources); - break :blk r.text(); + break :leaf r.text(); }, + else => unreachable, // All anonymous unary nodes were visited above. }; + if (leaf) |text| { + if (pending.items.len == 0) return text; + try out.appendSlice(l.arena, text); + } + while (pending.pop()) |parent| { + if (parent == .array) { + var digits: [20]u8 = undefined; + const length = std.fmt.bufPrint(&digits, "{d}", .{parent.array.len}) catch unreachable; + try out.appendSlice(l.arena, ", "); + try out.appendSlice(l.arena, length); + } + try out.append(l.arena, '>'); + } + return out.toOwnedSlice(l.arena); } fn wrap(l: *Lowerer, comptime tag: std.meta.Tag(Ty), t: Ty) Error!Ty { @@ -612,7 +645,7 @@ const Lowerer = struct { if (r.property.len == 0) { var context: @import("../verifier.zig").Context = .{ .arena = l.arena, .file = "", .module = l.property_module.? }; try verifier_types.checkTypeArgument(&context, .{ .line = 1, .col = 1 }, t); - if (context.diags.items.len != 0) return l.fail("E7005", r.span, "generic argument is not a well-formed concrete type", &.{ .{ .name = "parameter", .value = r.parameter }, .{ .name = "found", .value = l.diagnosticTyText(ty) } }); + if (context.diags.items.len != 0) return l.fail("E7005", r.span, "generic argument is not a well-formed concrete type", &.{ .{ .name = "parameter", .value = r.parameter }, .{ .name = "found", .value = try l.diagnosticTyText(ty) } }); continue; } const cached = l.property_module.?; @@ -620,7 +653,7 @@ const Lowerer = struct { if (!ok) return l.fail("E7005", r.span, "generic argument does not satisfy structural constraint", &.{ .{ .name = "parameter", .value = r.parameter }, .{ .name = "constraint", .value = r.property }, - .{ .name = "found", .value = l.diagnosticTyText(ty) }, + .{ .name = "found", .value = try l.diagnosticTyText(ty) }, }); } } @@ -635,7 +668,7 @@ const Lowerer = struct { for (l.fns.items) |f| { try texts.append(l.arena, f.header); for (f.blocks) |b| { - for (b.params.items) |p| try texts.append(l.arena, l.tyText(p.ty)); + for (b.params.items) |p| try texts.append(l.arena, try l.tyText(p.ty)); for (b.insts.items) |inst| try texts.append(l.arena, inst.text); } } @@ -693,7 +726,7 @@ const Lowerer = struct { for (fields, 0..) |f, i| { for (fields[0..i]) |prev| if (std.mem.eql(u8, prev.name, f.name)) return l.invalid(.duplicate_declaration, f.span, "field declared twice", &.{.{ .name = "field", .value = f.name }}); const ft = try l.memberType(f.ty); - try w.appendSlice(l.arena, try l.fmt("{s}{s}: {s}", .{ if (i == 0) " " else ", ", f.name, l.tyText(ft) })); + try w.appendSlice(l.arena, try l.fmt("{s}{s}: {s}", .{ if (i == 0) " " else ", ", f.name, try l.tyText(ft) })); } try w.appendSlice(l.arena, if (fields.len == 0) "}" else " }"); }, @@ -706,7 +739,7 @@ const Lowerer = struct { try w.appendSlice(l.arena, v.name); if (v.payload.len != 0) { try w.append(l.arena, '('); - for (v.payload, 0..) |pt, j| try w.appendSlice(l.arena, try l.fmt("{s}{s}", .{ if (j == 0) "" else ", ", l.tyText(try l.memberType(pt)) })); + for (v.payload, 0..) |pt, j| try w.appendSlice(l.arena, try l.fmt("{s}{s}", .{ if (j == 0) "" else ", ", try l.tyText(try l.memberType(pt)) })); try w.append(l.arena, ')'); } } @@ -816,7 +849,7 @@ const Lowerer = struct { .frozen => l.wrap(.frozen, ty), .arc => l.wrap(.arc, ty), .iref => l.wrap(.iref, ty), - .atomic => if (atomicScalar(ty)) l.wrap(.atomic, ty) else l.fail("E7005", w.span, "atomic needs bool or an integer of at most 64 bits", &.{.{ .name = "found", .value = l.diagnosticTyText(ty) }}), + .atomic => if (atomicScalar(ty)) l.wrap(.atomic, ty) else l.fail("E7005", w.span, "atomic needs bool or an integer of at most 64 bits", &.{.{ .name = "found", .value = try l.diagnosticTyText(ty) }}), }; }, }; @@ -896,9 +929,9 @@ const Lowerer = struct { const v = p.name; // Borrow parameters are lent by the caller: never ended here. try l.bindings.append(l.arena, .{ .name = p.name, .mutable = false, .value = v, .ty = t, .kind = if (t.isBorrow()) .borrow else .ssa }); - try header.appendSlice(l.arena, try l.fmt("{s}%{s}: {s}", .{ if (i == 0) "" else ", ", v, l.tyText(t) })); + try header.appendSlice(l.arena, try l.fmt("{s}%{s}: {s}", .{ if (i == 0) "" else ", ", v, try l.tyText(t) })); } - try header.appendSlice(l.arena, try l.fmt(") -> {s}", .{l.tyText(sig.ret)})); + try header.appendSlice(l.arena, try l.fmt(") -> {s}", .{try l.tyText(sig.ret)})); if (f.from) |origin| try header.appendSlice(l.arena, try l.fmt(" from %{s}", .{origin})); _ = try l.newBlock("entry", f.span); @@ -936,7 +969,7 @@ const Lowerer = struct { try head.appendSlice(l.arena, b.name); if (b.params.items.len != 0) { try head.append(l.arena, '('); - for (b.params.items, 0..) |p, i| try head.appendSlice(l.arena, try l.fmt("{s}%{s}: {s}", .{ if (i == 0) "" else ", ", p.name, l.tyText(p.ty) })); + for (b.params.items, 0..) |p, i| try head.appendSlice(l.arena, try l.fmt("{s}%{s}: {s}", .{ if (i == 0) "" else ", ", p.name, try l.tyText(p.ty) })); try head.append(l.arena, ')'); } try head.appendSlice(l.arena, ":"); @@ -1327,7 +1360,7 @@ const Lowerer = struct { try l.term(try l.retText(v), s.span); } } else { - if (l.ret != .void) return l.fail("E7005", s.span, "`return` without a value in a function that returns one", &.{.{ .name = "expected", .value = l.diagnosticTyText(l.ret) }}); + if (l.ret != .void) return l.fail("E7005", s.span, "`return` without a value in a function that returns one", &.{.{ .name = "expected", .value = try l.diagnosticTyText(l.ret) }}); try l.endScopes(0, s.span); try l.term("ret", s.span); } @@ -1374,13 +1407,13 @@ const Lowerer = struct { fn checkTy(l: *Lowerer, span: Span, found: Ty, want: Ty) Error!void { if (found == .never or found.eql(want)) return; - return l.fail("E7005", span, "type mismatch", &.{ .{ .name = "expected", .value = l.diagnosticTyText(want) }, .{ .name = "found", .value = l.diagnosticTyText(found) } }); + return l.fail("E7005", span, "type mismatch", &.{ .{ .name = "expected", .value = try l.diagnosticTyText(want) }, .{ .name = "found", .value = try l.diagnosticTyText(found) } }); } /// Operation inputs must yield an actual value, unlike divergent returns /// or statement receivers. Check before lowering the next input. fn checkOperandTy(l: *Lowerer, span: Span, found: Ty, want: Ty) Error!void { - if (found == .never) return l.noOperandValue(span, l.diagnosticTyText(want)); + if (found == .never) return l.noOperandValue(span, try l.diagnosticTyText(want)); return l.checkTy(span, found, want); } @@ -1424,8 +1457,8 @@ const Lowerer = struct { l.cur = cont; l.rebindToParams(cont, vars, 0); const i = l.lookup(st.name).?; - const one = try l.def("one", i.ty, try l.fmt("const.{s} 1", .{l.tyText(i.ty)}), st.span); - const next = try l.def(st.name, i.ty, try l.fmt("add.checked.{s} %{s}, %{s}", .{ l.tyText(i.ty), i.value, one.name }), st.span); + const one = try l.def("one", i.ty, try l.fmt("const.{s} 1", .{try l.tyText(i.ty)}), st.span); + const next = try l.def(st.name, i.ty, try l.fmt("add.checked.{s} %{s}, %{s}", .{ try l.tyText(i.ty), i.value, one.name }), st.span); l.lookup(st.name).?.value = next.name; try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[header].name, try l.argsOf(vars, null) }), st.span); } @@ -1443,7 +1476,7 @@ const Lowerer = struct { const depth = l.bindings.items.len; defer l.bindings.shrinkRetainingCapacity(depth); const ty = l.peekType(lo) orelse l.peekType(hi) orelse return l.fail("E7007", lo.span, "the type of the range cannot be determined; add a suffix such as `0usize`", &.{}); - if (ty != .int) return l.fail("E7005", lo.span, "a range needs an integer type", &.{.{ .name = "found", .value = l.diagnosticTyText(ty) }}); + if (ty != .int) return l.fail("E7005", lo.span, "a range needs an integer type", &.{.{ .name = "found", .value = try l.diagnosticTyText(ty) }}); const a = try l.expr(lo, ty); try l.checkOperandTy(lo.span, a.ty, ty); const b = try l.expr(hi, ty); @@ -1670,7 +1703,7 @@ const Lowerer = struct { .int => |x| { const ty: Ty = if (parse_mod.intSuffix(x.text)) |s| .{ .int = s } else want orelse return l.fail("E7007", e.span, "the type of this integer literal cannot be determined; add a suffix such as `0u64` or a type annotation", &.{}); - if (ty != .int) return l.fail("E7005", e.span, "an integer literal where another type is expected", &.{.{ .name = "expected", .value = l.diagnosticTyText(ty) }}); + if (ty != .int) return l.fail("E7005", e.span, "an integer literal where another type is expected", &.{.{ .name = "expected", .value = try l.diagnosticTyText(ty) }}); const v = parse_mod.parseIntText(x.text) orelse return l.fail("E7001", e.span, "malformed integer literal", &.{}); const n = ty.int; const bits = intBits(n); @@ -1686,11 +1719,11 @@ const Lowerer = struct { }, .deref => |x| { const r = try l.expr(x.*, null); - const in = r.ty.inner() orelse return l.fail("E7005", e.span, "`*` reads through a borrow", &.{.{ .name = "found", .value = l.diagnosticTyText(r.ty) }}); + const in = r.ty.inner() orelse return l.fail("E7005", e.span, "`*` reads through a borrow", &.{.{ .name = "found", .value = try l.diagnosticTyText(r.ty) }}); if (r.ty == .slice or r.ty == .slice_mut or in == .array) return l.invalid(.invalid_expression, e.span, "read slice and array elements with `s[i]`, not `*`", &.{}); // Source-prescribed E4202 (spec 15 §12); no load is emitted. if (in == .atomic) return l.fail("E4202", e.span, "an atomic cell is read only by atomic operations: use `atomic.load(r, ordering)`", &.{ - .{ .name = "found", .value = l.diagnosticTyText(r.ty) }, + .{ .name = "found", .value = try l.diagnosticTyText(r.ty) }, .{ .name = "use", .value = "atomic.load" }, }); return l.def("v", in, try l.fmt("load %{s}", .{r.name}), e.span); @@ -1713,7 +1746,7 @@ const Lowerer = struct { try names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", v.name })); } const at = try l.arrayOf(ty.?, xs.len); - return l.def("arr", at, try l.fmt("array.make {s}({s})", .{ l.tyText(at), names.items }), e.span); + return l.def("arr", at, try l.fmt("array.make {s}({s})", .{ try l.tyText(at), names.items }), e.span); }, .array_rep => |x| { if (x.len == 0 or x.len > (@as(u64, 1) << 32)) return l.fail("E7005", e.span, "array length must be between 1 and 2^32", &.{}); @@ -1721,7 +1754,7 @@ const Lowerer = struct { const v = try l.expr(x.e.*, want_elem); try l.arrayElement(x.e.span, v.ty, true); const at = try l.arrayOf(v.ty, x.len); - return l.def("arr", at, try l.fmt("array.splat {s} %{s}", .{ l.tyText(at), v.name }), e.span); + return l.def("arr", at, try l.fmt("array.splat {s} %{s}", .{ try l.tyText(at), v.name }), e.span); }, .bytes => return l.invalid(.invalid_literal, e.span, "a byte string is an array in storage: bind it with `let`/`ref`, or pass it where a slice is expected", &.{}), .borrow => return l.invalid(.invalid_borrow, e.span, "`ref`/`mut` here: borrows are bound with `ref name = place;` / `mut name = place;` or passed as arguments", &.{}), @@ -1753,7 +1786,7 @@ const Lowerer = struct { if (to != .int) return l.fail("E7005", x.ty.span, "casts convert between integer types", &.{}); const from = l.peekType(x.e.*) orelse to; const v = try l.expr(x.e.*, from); - if (v.ty != .int) return l.fail("E7005", x.e.span, "casts convert between integer types", &.{.{ .name = "found", .value = l.diagnosticTyText(v.ty) }}); + if (v.ty != .int) return l.fail("E7005", x.e.span, "casts convert between integer types", &.{.{ .name = "found", .value = try l.diagnosticTyText(v.ty) }}); // `as` widens without loss, by the verifier's own rule (spec 02 §2). if (x.mode == .widen) { const a = std.meta.stringToEnum(air_module.IntType, v.ty.int).?; @@ -1784,7 +1817,7 @@ const Lowerer = struct { .or_trap => |x| return l.orTrap(e, x.*), .move => |n| { const b = try l.valueBinding(e.span, n); - if (!l.isLinear(b.ty) and !(e.generic_transfer and b.ty != .void and b.ty != .never and !b.ty.isBorrow() and b.ty != .task and b.ty != .scope and b.ty != .guard and b.ty != .shield)) return l.invalid(if (b.ty.isBorrow()) .move_borrow else if (b.ty == .void or b.ty == .never) .invalid_move else .move_copy, e.span, "`move` applies to linear values; copyable values are passed plainly", &.{ .{ .name = "name", .value = n }, .{ .name = "type", .value = l.diagnosticTyText(b.ty) } }); + if (!l.isLinear(b.ty) and !(e.generic_transfer and b.ty != .void and b.ty != .never and !b.ty.isBorrow() and b.ty != .task and b.ty != .scope and b.ty != .guard and b.ty != .shield)) return l.invalid(if (b.ty.isBorrow()) .move_borrow else if (b.ty == .void or b.ty == .never) .invalid_move else .move_copy, e.span, "`move` applies to linear values; copyable values are passed plainly", &.{ .{ .name = "name", .value = n }, .{ .name = "type", .value = try l.diagnosticTyText(b.ty) } }); if (b.kind == .storage) return l.def(n, b.ty, try l.fmt("local.load %{s}", .{b.value}), e.span); return .{ .name = b.value, .ty = b.ty }; }, @@ -1837,7 +1870,7 @@ const Lowerer = struct { if (ty == .bool and !(op == .eq or op == .ne or op == .bit_and or op == .bit_or or op == .bit_xor)) return l.fail("E7005", e.span, "this operation needs integer operands", &.{}); if (ty != .bool and ty != .int) return l.fail("E7005", e.span, "this operation needs integer or boolean operands", &.{}); - const t = l.tyText(ty); + const t = try l.tyText(ty); const text = switch (op) { .add => try l.fmt("add.checked.{s}", .{t}), .sub => try l.fmt("sub.checked.{s}", .{t}), @@ -1897,21 +1930,21 @@ const Lowerer = struct { if (std.mem.eql(u8, p, "own.take")) { if (args.len != 1) return l.fail("E7005", e.span, "`own.take` takes one owner", &.{}); const o = try l.consuming(args[0], null); - if (o.ty != .own) return l.fail("E7005", args[0].span, "`own.take` takes an `own`", &.{.{ .name = "found", .value = l.diagnosticTyText(o.ty) }}); + if (o.ty != .own) return l.fail("E7005", args[0].span, "`own.take` takes an `own`", &.{.{ .name = "found", .value = try l.diagnosticTyText(o.ty) }}); return l.def("v", o.ty.own.*, try l.fmt("own.take %{s}", .{o.name}), e.span); } if (std.mem.eql(u8, p, "own.free") or std.mem.eql(u8, p, "region.destroy")) { if (args.len != 1) return l.fail("E7005", e.span, "this operation takes one linear value", &.{}); const o = try l.consuming(args[0], null); const ok = if (std.mem.eql(u8, p, "own.free")) (o.ty == .own or o.ty == .own_array) else o.ty == .region; - if (!ok) return l.fail("E7005", args[0].span, if (std.mem.eql(u8, p, "own.free")) "`own.free` takes an `own` or `own_array`" else "`region.destroy` takes a region", &.{.{ .name = "found", .value = l.diagnosticTyText(o.ty) }}); + if (!ok) return l.fail("E7005", args[0].span, if (std.mem.eql(u8, p, "own.free")) "`own.free` takes an `own` or `own_array`" else "`region.destroy` takes a region", &.{.{ .name = "found", .value = try l.diagnosticTyText(o.ty) }}); try l.emit(try l.fmt("{s} %{s}", .{ p, o.name }), e.span); return .{ .name = "", .ty = .void }; } if (std.mem.eql(u8, p, "region.reset")) { if (args.len != 1 or args[0].kind != .name) return l.fail("E7005", e.span, "`region.reset` takes the region by name", &.{}); const r = l.lookup(args[0].kind.name) orelse return l.unknown(args[0].span, args[0].kind.name); - if (r.ty != .region) return l.fail("E7005", args[0].span, "`region.reset` takes a region", &.{.{ .name = "found", .value = l.diagnosticTyText(r.ty) }}); + if (r.ty != .region) return l.fail("E7005", args[0].span, "`region.reset` takes a region", &.{.{ .name = "found", .value = try l.diagnosticTyText(r.ty) }}); try l.emit(try l.fmt("region.reset %{s}", .{r.value}), e.span); return .{ .name = "", .ty = .void }; } @@ -2010,7 +2043,7 @@ const Lowerer = struct { 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})", .{ l.tyText(t), args.items }), e.span); + return l.def("s", t, try l.fmt("struct.make {s}({s})", .{ try l.tyText(t), args.items }), e.span); } fn variantValue(l: *Lowerer, e: ast.Expr, enum_name: []const u8, variant: []const u8, args: []const ast.Expr) Error!Value { @@ -2032,14 +2065,14 @@ const Lowerer = struct { try l.checkOperandTy(a.span, av.ty, ty); try names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", av.name })); } - return l.def("e", t, try l.fmt("enum.make {s}.{s}({s})", .{ l.tyText(t), variant, names.items }), e.span); + 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 { var bt = 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 = l.diagnosticTyText(bt) }}); + 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; @@ -2068,7 +2101,7 @@ const Lowerer = struct { const vt: Ty = if (a.value) |v| v.ty else .void; if (vt == .never) continue; if (result_ty) |prev| { - if (!prev.eql(vt)) return l.fail("E7005", a.span, try l.fmt("the branches of this `{s}` have different types", .{what}), &.{ .{ .name = "expected", .value = l.diagnosticTyText(prev) }, .{ .name = "found", .value = l.diagnosticTyText(vt) } }); + if (!prev.eql(vt)) return l.fail("E7005", a.span, try l.fmt("the branches of this `{s}` have different types", .{what}), &.{ .{ .name = "expected", .value = try l.diagnosticTyText(prev) }, .{ .name = "found", .value = try l.diagnosticTyText(vt) } }); } else result_ty = vt; }; if (result_ty == null) { @@ -2113,7 +2146,7 @@ const Lowerer = struct { const vs = d.kind.@"enum"; const blocks = try l.arena.alloc(usize, m.arms.len); var head: std.ArrayList(u8) = .empty; - try head.appendSlice(l.arena, try l.fmt("{s} {s} %{s}", .{ if (l.isLinear(st)) "enum.take" else "enum.switch", l.tyText(st), sv.name })); + try head.appendSlice(l.arena, try l.fmt("{s} {s} %{s}", .{ if (l.isLinear(st)) "enum.take" else "enum.switch", try l.tyText(st), sv.name })); for (m.arms, blocks, 0..) |arm, *blk, i| { if (arm.pattern.kind != .ctor or arm.pattern.kind.ctor.qualifier == null) return l.invalid(.invalid_match, arm.pattern.span, "an arm of a `match` over an enum names one variant as `Enum::Variant`; `_` is not allowed", &.{.{ .name = "enum", .value = d.display_name orelse d.name }}); @@ -2157,7 +2190,7 @@ const Lowerer = struct { return l.mergeArms(m.span, "match", ends.items, vars, before, "endmatch"); } - if (st != .int) return l.fail("E7005", m.scrutinee.span, "`match` needs an enum or integer value; use `if` for booleans", &.{.{ .name = "found", .value = l.diagnosticTyText(st) }}); + if (st != .int) return l.fail("E7005", m.scrutinee.span, "`match` needs an enum or integer value; use `if` for booleans", &.{.{ .name = "found", .value = try l.diagnosticTyText(st) }}); var head: std.ArrayList(u8) = .empty; try head.appendSlice(l.arena, try l.fmt("switch.{s} %{s}, ", .{ st.int, sv.name })); const blocks = try l.arena.alloc(usize, m.arms.len); @@ -2294,7 +2327,7 @@ const Lowerer = struct { /// Frame storage for a variable, allocated in the entry block. fn storageFor(l: *Lowerer, name: []const u8, ty: Ty, span: Span) Error![]const u8 { const st = try l.freshName(name); - try l.allocs.append(l.arena, .{ .text = try l.fmt("%{s} = local.alloc {s}", .{ st, l.tyText(ty) }), .span = span }); + try l.allocs.append(l.arena, .{ .text = try l.fmt("%{s} = local.alloc {s}", .{ st, try l.tyText(ty) }), .span = span }); return st; } @@ -2304,7 +2337,7 @@ const Lowerer = struct { .bool => l.def(base, ty, "const.bool false", span), .array => |a| blk: { const z = try l.zeroValue(a.elem, base, span); - break :blk l.def(base, ty, try l.fmt("array.splat {s} %{s}", .{ l.tyText(ty), z.name }), span); + break :blk l.def(base, ty, try l.fmt("array.splat {s} %{s}", .{ try l.tyText(ty), z.name }), span); }, else => l.invalid(.zero_not_zeroable, span, "`zero` needs a zeroable type (integers, booleans, arrays of them)", &.{}), }; @@ -2436,7 +2469,7 @@ const Lowerer = struct { fn requireExclusivePlace(l: *Lowerer, span: Span, t: Ty) Error!void { if (t.isMutBorrow()) return; const expected = if (t == .slice) try l.wrap(.slice_mut, t.inner().?) else try l.wrap(.mut, t.inner().?); - return l.fail("E7005", span, "mut needs an exclusive place", &.{ .{ .name = "expected", .value = l.diagnosticTyText(expected) }, .{ .name = "found", .value = l.diagnosticTyText(t) } }); + return l.fail("E7005", span, "mut needs an exclusive place", &.{ .{ .name = "expected", .value = try l.diagnosticTyText(expected) }, .{ .name = "found", .value = try l.diagnosticTyText(t) } }); } /// Explicit argument/binding modes apply independently of array shape. @@ -2505,7 +2538,7 @@ const Lowerer = struct { .field => |f| { const base = try l.placeRaw(f.e.*, mutable, span); const st = base.v.ty.inner() orelse return l.fail("E7005", place.span, "field of a value that is not a struct", &.{}); - const d = l.decl(st) orelse return l.fail("E7005", place.span, "field of a value that is not a struct", &.{.{ .name = "found", .value = l.diagnosticTyText(st) }}); + const d = l.decl(st) orelse return l.fail("E7005", place.span, "field of a value that is not a struct", &.{.{ .name = "found", .value = try l.diagnosticTyText(st) }}); if (d.kind != .@"struct") return l.fail("E7005", place.span, "field of an enum; use `match`", &.{}); const fd = for (d.kind.@"struct") |x| { if (std.mem.eql(u8, x.name, f.name)) break x; @@ -2520,7 +2553,7 @@ const Lowerer = struct { const base = try l.placeRaw(x.e.*, mutable, span); l.unchecked = outer_unchecked; const bt = base.v.ty; - const elem = elemOf(bt) orelse return l.fail("E7005", place.span, "indexing needs an array or a slice", &.{.{ .name = "found", .value = l.diagnosticTyText(bt) }}); + const elem = elemOf(bt) orelse return l.fail("E7005", place.span, "indexing needs an array or a slice", &.{.{ .name = "found", .value = try l.diagnosticTyText(bt) }}); if (x.hi) |hi| { // `s[a..b]`: slice.sub with start a and length b - a (checked). var sl = base.v; @@ -2572,11 +2605,11 @@ const Lowerer = struct { // store (spec 15 §4), so `s[i] = s[i] + 1` reads before it writes. const target_type = l.placeType(place); const v = try l.expr(value, target_type); - if (v.ty == .never) return l.noOperandValue(value.span, if (target_type) |t| l.diagnosticTyText(t) else "a stored value"); + if (v.ty == .never) return l.noOperandValue(value.span, if (target_type) |t| try l.diagnosticTyText(t) else "a stored value"); const p = try l.placeBorrow(place, true, false, span); const in = p.v.ty.inner() orelse return l.fail("E7005", place.span, "assignment needs a mutable place", &.{}); if (in == .array and place.kind == .deref) return l.invalid(.invalid_assignment, place.span, "write array elements with `s[i] = …`", &.{}); - if (p.v.ty != .mut) return l.fail("E7005", place.span, "assignment needs a mutable place", &.{ .{ .name = "expected", .value = l.diagnosticTyText(try l.wrap(.mut, in)) }, .{ .name = "found", .value = l.diagnosticTyText(p.v.ty) } }); + if (p.v.ty != .mut) return l.fail("E7005", place.span, "assignment needs a mutable place", &.{ .{ .name = "expected", .value = try l.diagnosticTyText(try l.wrap(.mut, in)) }, .{ .name = "found", .value = try l.diagnosticTyText(p.v.ty) } }); try l.checkOperandTy(value.span, v.ty, in); try l.emit(try l.fmt("store %{s}, %{s}", .{ p.v.name, v.name }), span); try l.endNow(p.ends, span); @@ -2607,7 +2640,7 @@ const Lowerer = struct { 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 = l.diagnosticTyText(bt) }}); + 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); } @@ -2633,7 +2666,7 @@ const Lowerer = struct { try l.blocks.items[next].params.append(l.arena, .{ .name = pn, .ty = t }); if (!std.mem.eql(u8, n, "_")) try l.bindings.append(l.arena, .{ .name = n, .value = pn, .ty = t, .mutable = false }); } - try l.term(try l.fmt("{s} {s} %{s}, next -> @{s}", .{ operation, l.tyText(v.ty), v.name, l.blocks.items[next].name }), s.span); + try l.term(try l.fmt("{s} {s} %{s}, next -> @{s}", .{ operation, try l.tyText(v.ty), v.name, l.blocks.items[next].name }), s.span); l.cur = next; l.linear_enabled = true; } @@ -2645,7 +2678,7 @@ const Lowerer = struct { const rb = l.rootBinding(base) orelse return l.fail("E7002", base.span, "unknown name", &.{}); const mutable = rb.ty.isMutBorrow() or rb.kind == .storage and rb.mutable; const p = try l.placeBorrow(base, mutable, true, s.span); - if (p.v.ty != .slice and p.v.ty != .slice_mut) return l.fail("E7005", base.span, "`split_at` splits a slice", &.{.{ .name = "found", .value = l.diagnosticTyText(p.v.ty) }}); + if (p.v.ty != .slice and p.v.ty != .slice_mut) return l.fail("E7005", base.span, "`split_at` splits a slice", &.{.{ .name = "found", .value = try l.diagnosticTyText(p.v.ty) }}); const k = try l.expr(e.kind.call.args[0], .{ .int = "usize" }); try l.checkOperandTy(e.kind.call.args[0].span, k.ty, .{ .int = "usize" }); const left = try l.freshName(names[0]); @@ -2665,9 +2698,9 @@ const Lowerer = struct { var temps: std.ArrayList([]const u8) = .empty; const d = try l.argument(args[0], null, &temps); const src = try l.argument(args[1], null, &temps); - if (d.ty != .slice_mut) return l.fail("E7005", args[0].span, "`slice.copy` writes to `mut dst` (a `slice_mut`)", &.{.{ .name = "found", .value = l.diagnosticTyText(d.ty) }}); - if (src.ty != .slice and src.ty != .slice_mut) return l.fail("E7005", args[1].span, "`slice.copy` reads from `ref src` (a `slice`)", &.{.{ .name = "found", .value = l.diagnosticTyText(src.ty) }}); - if (!d.ty.inner().?.eql(src.ty.inner().?)) return l.fail("E7005", args[1].span, "`slice.copy` copies between slices of the same element type", &.{ .{ .name = "expected", .value = l.diagnosticTyText(d.ty.inner().?) }, .{ .name = "found", .value = l.diagnosticTyText(src.ty.inner().?) } }); + if (d.ty != .slice_mut) return l.fail("E7005", args[0].span, "`slice.copy` writes to `mut dst` (a `slice_mut`)", &.{.{ .name = "found", .value = try l.diagnosticTyText(d.ty) }}); + if (src.ty != .slice and src.ty != .slice_mut) return l.fail("E7005", args[1].span, "`slice.copy` reads from `ref src` (a `slice`)", &.{.{ .name = "found", .value = try l.diagnosticTyText(src.ty) }}); + if (!d.ty.inner().?.eql(src.ty.inner().?)) return l.fail("E7005", args[1].span, "`slice.copy` copies between slices of the same element type", &.{ .{ .name = "expected", .value = try l.diagnosticTyText(d.ty.inner().?) }, .{ .name = "found", .value = try l.diagnosticTyText(src.ty.inner().?) } }); try l.emit(try l.fmt("slice.copy %{s}, %{s}", .{ d.name, src.name }), e.span); try l.endNow(temps.items, e.span); return .{ .name = "", .ty = .void }; @@ -2801,7 +2834,7 @@ const Lowerer = struct { const br = a.kind.borrow; if (br.mutable) return l.fail("E7005", a.span, "atomic operations take `ref` of the cell, never `mut`", &.{}); const b = try l.bindingOf(br.place.*, "an atomic cell"); - if (b.ty != .atomic) return l.fail("E7005", a.span, "an atomic operation takes `ref` of an `atomic`", &.{.{ .name = "found", .value = l.diagnosticTyText(b.ty) }}); + if (b.ty != .atomic) return l.fail("E7005", a.span, "an atomic operation takes `ref` of an `atomic`", &.{.{ .name = "found", .value = try l.diagnosticTyText(b.ty) }}); const r = try l.def(br.place.kind.name, try l.wrap(.ref, b.ty), try l.fmt("borrow.ref %{s}", .{b.value}), a.span); try temps.append(l.arena, r.name); return r; @@ -2809,7 +2842,7 @@ const Lowerer = struct { const b = try l.bindingOf(a, "an atomic cell"); if (b.ty == .atomic) return l.fail("E7005", a.span, "pass the cell as `ref a` (or a `ref` binding of it): atomic operations go through a shared borrow", &.{.{ .name = "suggestion", .value = try l.fmt("ref {s}", .{a.kind.name}) }}); if (b.ty == .ref and b.ty.inner().? == .atomic) return .{ .name = b.value, .ty = b.ty }; - return l.fail("E7005", a.span, "an atomic operation takes a `ref>`", &.{.{ .name = "found", .value = l.diagnosticTyText(b.ty) }}); + return l.fail("E7005", a.span, "an atomic operation takes a `ref>`", &.{.{ .name = "found", .value = try l.diagnosticTyText(b.ty) }}); } fn atomicCall(l: *Lowerer, e: ast.Expr, p: []const u8, args: []const ast.Expr) Error!Value { @@ -2817,13 +2850,13 @@ const Lowerer = struct { if (eq(u8, p, "atomic.new")) { if (args.len != 1) return l.fail("E7005", e.span, "`atomic.new` takes the initial value", &.{}); const v = try l.expr(args[0], null); - if (!atomicScalar(v.ty)) return l.fail("E7005", args[0].span, "atomic needs bool or an integer of at most 64 bits", &.{.{ .name = "found", .value = l.diagnosticTyText(v.ty) }}); + if (!atomicScalar(v.ty)) return l.fail("E7005", args[0].span, "atomic needs bool or an integer of at most 64 bits", &.{.{ .name = "found", .value = try l.diagnosticTyText(v.ty) }}); return l.def("atomic", try l.wrap(.atomic, v.ty), try l.fmt("atomic.new %{s}", .{v.name}), e.span); } if (eq(u8, p, "atomic.take")) { if (args.len != 1) return l.fail("E7005", e.span, "`atomic.take` takes one cell", &.{}); const c = try l.consuming(args[0], null); - if (c.ty != .atomic) return l.fail("E7005", args[0].span, "`atomic.take` takes an `atomic`", &.{.{ .name = "found", .value = l.diagnosticTyText(c.ty) }}); + if (c.ty != .atomic) return l.fail("E7005", args[0].span, "`atomic.take` takes an `atomic`", &.{.{ .name = "found", .value = try l.diagnosticTyText(c.ty) }}); return l.def("v", c.ty.inner().?, try l.fmt("atomic.take %{s}", .{c.name}), e.span); } if (eq(u8, p, "atomic.fence")) { @@ -2852,7 +2885,7 @@ const Lowerer = struct { return .{ .name = "", .ty = .void }; } const op: []const u8 = if (eq(u8, p, "atomic.swap")) "xchg" else p["atomic.".len..]; - if ((eq(u8, op, "add.wrap") or eq(u8, op, "sub.wrap")) and t != .int) return l.fail("E7005", args[1].span, "`atomic.add.wrap` and `atomic.sub.wrap` need an integer cell", &.{.{ .name = "found", .value = l.diagnosticTyText(t) }}); + if ((eq(u8, op, "add.wrap") or eq(u8, op, "sub.wrap")) and t != .int) return l.fail("E7005", args[1].span, "`atomic.add.wrap` and `atomic.sub.wrap` need an integer cell", &.{.{ .name = "found", .value = try l.diagnosticTyText(t) }}); const v = try l.def("old", t, try l.fmt("atomic.{s}.{s} %{s}, %{s}", .{ op, ord, c.name, operand.name }), e.span); try l.endNow(temps.items, e.span); return v; @@ -2898,7 +2931,7 @@ const Lowerer = struct { return v; } if ((b.ty == .mut or (b.ty == .ref and !mutable)) and std.meta.activeTag(b.ty.inner().?) == tag) return .{ .name = b.value, .ty = b.ty }; - return l.fail("E7005", a.span, try l.fmt("{s} is expected here", .{what}), &.{.{ .name = "found", .value = l.diagnosticTyText(b.ty) }}); + return l.fail("E7005", a.span, try l.fmt("{s} is expected here", .{what}), &.{.{ .name = "found", .value = try l.diagnosticTyText(b.ty) }}); } /// The task and channel operations that are plain calls; null for any @@ -2912,7 +2945,7 @@ const Lowerer = struct { if (eq(p, "task.spawn")) { if (args.len < 2) return l.fail("E7005", e.span, "`task.spawn` takes a scope, a function and its arguments", &.{}); const sb = try l.bindingOf(args[0], "a task scope"); - if (sb.ty != .scope) return l.fail("E7005", args[0].span, "`task.spawn` spawns into a scope: `scope s { … task.spawn(s, f, …) … }`", &.{.{ .name = "found", .value = l.diagnosticTyText(sb.ty) }}); + if (sb.ty != .scope) return l.fail("E7005", args[0].span, "`task.spawn` spawns into a scope: `scope s { … task.spawn(s, f, …) … }`", &.{.{ .name = "found", .value = try l.diagnosticTyText(sb.ty) }}); const scope_name = sb.value; const fname = try expressionPath(l.arena, args[1]) orelse return l.fail("E7005", args[1].span, "the function to spawn is named", &.{}); const sig = l.functionSig(fname, args[1].span) orelse return l.unknown(args[1].span, fname); @@ -2933,7 +2966,7 @@ const Lowerer = struct { if (eq(p, "task.join")) { if (args.len != 1) return l.fail("E7005", e.span, "`task.join` takes one task", &.{}); const t = try l.consuming(args[0], null); - if (t.ty != .task) return l.fail("E7005", args[0].span, "`task.join` takes a `task`", &.{.{ .name = "found", .value = l.diagnosticTyText(t.ty) }}); + if (t.ty != .task) return l.fail("E7005", args[0].span, "`task.join` takes a `task`", &.{.{ .name = "found", .value = try l.diagnosticTyText(t.ty) }}); const rt = t.ty.task.*; if (rt == .void) { try l.emit(try l.fmt("task.join %{s}", .{t.name}), e.span); @@ -2944,7 +2977,7 @@ const Lowerer = struct { if (eq(p, "task.cancel")) { if (args.len != 1) return l.fail("E7005", e.span, "`task.cancel` takes one task, by name", &.{}); const b = try l.bindingOf(args[0], "a task"); - if (b.ty != .task) return l.fail("E7005", args[0].span, "`task.cancel` takes a `task`", &.{.{ .name = "found", .value = l.diagnosticTyText(b.ty) }}); + if (b.ty != .task) return l.fail("E7005", args[0].span, "`task.cancel` takes a `task`", &.{.{ .name = "found", .value = try l.diagnosticTyText(b.ty) }}); try l.emit(try l.fmt("task.cancel %{s}", .{b.value}), e.span); return .{ .name = "", .ty = .void }; } @@ -2970,7 +3003,7 @@ const Lowerer = struct { if (args.len != 1) return l.fail("E7005", e.span, "this operation takes one graph owner", &.{}); const o = try l.consuming(args[0], null); const want: std.meta.Tag(Ty) = if (eq(p, "island.freeze")) .island else .frozen; - if (std.meta.activeTag(o.ty) != want) return l.fail("E7005", args[0].span, if (want == .island) "`island.freeze` takes an `island`" else "`arc.from_frozen` takes a `frozen`", &.{.{ .name = "found", .value = l.diagnosticTyText(o.ty) }}); + if (std.meta.activeTag(o.ty) != want) return l.fail("E7005", args[0].span, if (want == .island) "`island.freeze` takes an `island`" else "`arc.from_frozen` takes a `frozen`", &.{.{ .name = "found", .value = try l.diagnosticTyText(o.ty) }}); const out = if (want == .island) try l.wrap(.frozen, o.ty.inner().?) else try l.wrap(.arc, o.ty.inner().?); return try l.def(if (want == .island) "frozen" else "arc", out, try l.fmt("{s} %{s}", .{ p, o.name }), e.span); } @@ -2978,7 +3011,7 @@ const Lowerer = struct { if (args.len != 1) return l.fail("E7005", e.span, "this operation takes one graph owner", &.{}); const o = try l.consuming(args[0], null); const want: std.meta.Tag(Ty) = if (eq(p, "island.destroy")) .island else if (eq(p, "frozen.release")) .frozen else .arc; - if (std.meta.activeTag(o.ty) != want) return l.fail("E7005", args[0].span, "this operation takes another graph owner", &.{ .{ .name = "operation", .value = p }, .{ .name = "found", .value = l.diagnosticTyText(o.ty) } }); + if (std.meta.activeTag(o.ty) != want) return l.fail("E7005", args[0].span, "this operation takes another graph owner", &.{ .{ .name = "operation", .value = p }, .{ .name = "found", .value = try l.diagnosticTyText(o.ty) } }); try l.emit(try l.fmt("{s} %{s}", .{ p, o.name }), e.span); return .{ .name = "", .ty = .void }; } @@ -2992,7 +3025,7 @@ const Lowerer = struct { return v; } if (b.ty == .ref and b.ty.inner().? == .arc) return try l.def("arc", b.ty.inner().?, try l.fmt("arc.clone %{s}", .{b.value}), e.span); - return l.fail("E7005", args[0].span, "`arc.clone` takes an `arc`", &.{.{ .name = "found", .value = l.diagnosticTyText(b.ty) }}); + return l.fail("E7005", args[0].span, "`arc.clone` takes an `arc`", &.{.{ .name = "found", .value = try l.diagnosticTyText(b.ty) }}); } if (eq(p, "island.at") or eq(p, "frozen.at") or eq(p, "arc.at")) return l.invalid(.invalid_borrow, e.span, "a graph access is a borrow: bind it with `ref x = island.at(g, r);` or `mut x = island.at(g, r);`", &.{}); @@ -3005,13 +3038,13 @@ const Lowerer = struct { if (eq(p, "mutex.take")) { if (args.len != 1) return l.fail("E7005", e.span, "`mutex.take` takes one mutex", &.{}); const m = try l.consuming(args[0], null); - if (m.ty != .mutex) return l.fail("E7005", args[0].span, "`mutex.take` takes a `mutex`", &.{.{ .name = "found", .value = l.diagnosticTyText(m.ty) }}); + if (m.ty != .mutex) return l.fail("E7005", args[0].span, "`mutex.take` takes a `mutex`", &.{.{ .name = "found", .value = try l.diagnosticTyText(m.ty) }}); return try l.def("v", m.ty.mutex.*, try l.fmt("mutex.take %{s}", .{m.name}), e.span); } if (eq(p, "channel.close_sender")) { if (args.len != 1) return l.fail("E7005", e.span, "`channel.close_sender` takes one sender", &.{}); const tx = try l.consuming(args[0], null); - if (tx.ty != .sender) return l.fail("E7005", args[0].span, "`channel.close_sender` takes a `sender`", &.{.{ .name = "found", .value = l.diagnosticTyText(tx.ty) }}); + if (tx.ty != .sender) return l.fail("E7005", args[0].span, "`channel.close_sender` takes a `sender`", &.{.{ .name = "found", .value = try l.diagnosticTyText(tx.ty) }}); try l.emit(try l.fmt("channel.close_sender %{s}", .{tx.name}), e.span); return .{ .name = "", .ty = .void }; } @@ -3033,8 +3066,8 @@ const Lowerer = struct { try temps.append(l.arena, v.name); break :blk v; }, - .ref => if (b.ty.ref.* == .mutex) .{ .name = b.value, .ty = b.ty } else return l.fail("E7005", place.span, "`lock` needs a mutex", &.{.{ .name = "found", .value = l.diagnosticTyText(b.ty) }}), - else => return l.fail("E7005", place.span, "`lock` needs a mutex", &.{.{ .name = "found", .value = l.diagnosticTyText(b.ty) }}), + .ref => if (b.ty.ref.* == .mutex) .{ .name = b.value, .ty = b.ty } else return l.fail("E7005", place.span, "`lock` needs a mutex", &.{.{ .name = "found", .value = try l.diagnosticTyText(b.ty) }}), + else => return l.fail("E7005", place.span, "`lock` needs a mutex", &.{.{ .name = "found", .value = try l.diagnosticTyText(b.ty) }}), }; const elem = mr.ty.ref.mutex.*; const depth = l.bindings.items.len; @@ -3093,7 +3126,7 @@ const Lowerer = struct { // without emitting a borrow or evaluating another input. const endpoint_ty: Ty = if (l.lookup(a.endpoint)) |b| b.ty else .void; const channel_ty = if (endpoint_ty.isBorrow()) endpoint_ty.inner().? else endpoint_ty; - return l.noOperandValue(ve.span, if (channel_ty == .sender) l.diagnosticTyText(channel_ty.sender.*) else "a channel element"); + return l.noOperandValue(ve.span, if (channel_ty == .sender) try l.diagnosticTyText(channel_ty.sender.*) else "a channel element"); } try values.append(l.arena, .{ .key = key, .v = v }); av.* = values.items.len - 1; @@ -3212,7 +3245,7 @@ const Lowerer = struct { /// scope, task, shield or guard, at any depth. Endpoints inside are the /// reserved `channel_transfer`, left to the verifier (`E0006`). fn elementRule(l: *Lowerer, t: Ty, span: Span, what: []const u8) Error!void { - if (try l.forbiddenIn(t, 0)) |bad| return l.fail("E7005", span, try l.fmt("{s} contains no borrow, scope, task, shield or guard", .{what}), &.{ .{ .name = "type", .value = l.diagnosticTyText(t) }, .{ .name = "found", .value = l.diagnosticTyText(bad) } }); + if (try l.forbiddenIn(t, 0)) |bad| return l.fail("E7005", span, try l.fmt("{s} contains no borrow, scope, task, shield or guard", .{what}), &.{ .{ .name = "type", .value = try l.diagnosticTyText(t) }, .{ .name = "found", .value = try l.diagnosticTyText(bad) } }); } fn forbiddenIn(l: *Lowerer, t: Ty, depth: u32) Error!?Ty { @@ -3244,7 +3277,7 @@ const Lowerer = struct { const tag = std.meta.stringToEnum(std.meta.Tag(Ty), owner).?; if (std.meta.activeTag(b.ty) == tag) return l.fail("E7005", a.span, try l.fmt("this takes a borrow of the {s}, not the owner: bind `{s} g = {s};` in an enclosing block and pass `g`", .{ owner, if (mutable) "mut" else "ref", a.kind.name }), &.{.{ .name = "name", .value = a.kind.name }}); const ok = (b.ty == .ref or (b.ty == .mut and !mutable) or (b.ty == .mut and mutable)) and std.meta.activeTag(b.ty.inner().?) == tag; - if (!ok or (mutable and b.ty != .mut)) return l.fail("E7005", a.span, try l.fmt("a {s} borrow of an `{s}` is expected here", .{ if (mutable) "`mut`" else "`ref` or `mut`", owner }), &.{.{ .name = "found", .value = l.diagnosticTyText(b.ty) }}); + if (!ok or (mutable and b.ty != .mut)) return l.fail("E7005", a.span, try l.fmt("a {s} borrow of an `{s}` is expected here", .{ if (mutable) "`mut`" else "`ref` or `mut`", owner }), &.{.{ .name = "found", .value = try l.diagnosticTyText(b.ty) }}); return .{ .name = b.value, .ty = b.ty }; } @@ -3283,7 +3316,7 @@ const Lowerer = struct { if (ac.args.len != 2) return l.fail("E7005", place.span, "`.at` takes the graph's borrow binding and an `iref`", &.{}); const g = try l.graphBorrow(ac.args[0], owner, mutable); const r = try l.expr(ac.args[1], null); - if (r.ty != .iref) return l.fail("E7005", ac.args[1].span, "an `iref` is expected here", &.{.{ .name = "found", .value = l.diagnosticTyText(r.ty) }}); + if (r.ty != .iref) return l.fail("E7005", ac.args[1].span, "an `iref` is expected here", &.{.{ .name = "found", .value = try l.diagnosticTyText(r.ty) }}); const op = if (std.mem.eql(u8, owner, "island")) "island.borrow" else if (std.mem.eql(u8, owner, "frozen")) "frozen.borrow" else "arc.borrow"; const target = r.ty.inner().?; const v = try l.defBorrow(name, if (mutable) try l.wrap(.mut, target) else try l.wrap(.ref, target), try l.fmt("{s} %{s}, %{s}", .{ op, g.name, r.name }), g.name, s.span); @@ -3313,14 +3346,14 @@ const Lowerer = struct { const want: Ty = if (o == .bytes) try l.wrap(.slice, .{ .int = "u8" }) else try l.wrap(.slice_mut, .{ .int = "u8" }); if (o == .buffer and a.kind == .bytes) return l.fail("E7005", a.span, "this operand is a buffer the operation writes: pass `mut buf`", &.{}); const v = try l.argument(a, want, temps); - if (!v.ty.eql(want)) return l.fail("E7005", a.span, if (o == .bytes) "bytes are passed as a borrow: `ref buf`, `ref buf[a..b]` or a byte string `b\"…\"`" else "a buffer is passed as `mut buf` or `mut buf[a..b]`", &.{ .{ .name = "expected", .value = l.diagnosticTyText(want) }, .{ .name = "found", .value = l.diagnosticTyText(v.ty) } }); + if (!v.ty.eql(want)) return l.fail("E7005", a.span, if (o == .bytes) "bytes are passed as a borrow: `ref buf`, `ref buf[a..b]` or a byte string `b\"…\"`" else "a buffer is passed as `mut buf` or `mut buf[a..b]`", &.{ .{ .name = "expected", .value = try l.diagnosticTyText(want) }, .{ .name = "found", .value = try l.diagnosticTyText(v.ty) } }); break :blk v; }, .borrowed => |rs| try l.resourceOperand(a, rs, temps), .consumed => |rs| blk: { const v = try l.consuming(a, null); if (v.ty != .resource or std.mem.indexOfScalar(authority.Resource, rs, v.ty.resource) == null) - return l.fail("E7005", a.span, "this operation consumes a resource of another type", &.{ .{ .name = "operation", .value = x.name }, .{ .name = "found", .value = l.diagnosticTyText(v.ty) } }); + return l.fail("E7005", a.span, "this operation consumes a resource of another type", &.{ .{ .name = "operation", .value = x.name }, .{ .name = "found", .value = try l.diagnosticTyText(v.ty) } }); break :blk v; }, }; @@ -3342,7 +3375,7 @@ const Lowerer = struct { else => null, }; if (r == null or std.mem.indexOfScalar(authority.Resource, rs, r.?) == null) - return l.fail("E7005", a.span, "this operation needs a resource of another type", &.{ .{ .name = "expected", .value = expected }, .{ .name = "found", .value = l.diagnosticTyText(b.ty) } }); + return l.fail("E7005", a.span, "this operation needs a resource of another type", &.{ .{ .name = "expected", .value = expected }, .{ .name = "found", .value = try l.diagnosticTyText(b.ty) } }); if (b.ty == .mut) return .{ .name = b.value, .ty = b.ty }; const v = try l.def(a.kind.name, try l.wrap(.mut, b.ty), try l.fmt("borrow.mut %{s}", .{b.value}), a.span); try temps.append(l.arena, v.name); @@ -3357,7 +3390,7 @@ const Lowerer = struct { fn expectCap(l: *Lowerer, a: ast.Expr, kind: []const u8) Error!Value { const c = try l.expr(a, null); - if (c.ty != .cap) return l.fail("E7005", a.span, "a capability is expected here", &.{ .{ .name = "expected", .value = try l.fmt("cap<{s}>", .{kind}) }, .{ .name = "found", .value = l.diagnosticTyText(c.ty) } }); + if (c.ty != .cap) return l.fail("E7005", a.span, "a capability is expected here", &.{ .{ .name = "expected", .value = try l.fmt("cap<{s}>", .{kind}) }, .{ .name = "found", .value = try l.diagnosticTyText(c.ty) } }); return c; } @@ -3390,7 +3423,7 @@ const Lowerer = struct { const n = try l.expr(args[0], usize_ty); try l.checkOperandTy(args[0].span, n.ty, usize_ty); const cap = try l.expectCap(args[1], "mem.alloc"); - return .{ .text = try l.fmt("buffer.new {s} %{s}, %{s}", .{ l.tyText(ty), n.name, cap.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{try l.wrap(.buffer, ty)} }, .{ .role = "err", .params = &.{alloc_err} } }) }; + return .{ .text = try l.fmt("buffer.new {s} %{s}, %{s}", .{ try l.tyText(ty), n.name, cap.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{try l.wrap(.buffer, ty)} }, .{ .role = "err", .params = &.{alloc_err} } }) }; } if (std.mem.eql(u8, path, "buffer.free")) { try want(l, e.span, args, 1, path); @@ -3421,7 +3454,7 @@ const Lowerer = struct { if (v.ty.isBorrow()) return l.contentPositionError(args[0].span, v.ty); const c = try l.expectCap(args[1], "mem.alloc"); l.linear_enabled = true; - return .{ .text = try l.fmt("own.pack {s} %{s}, %{s}", .{ l.tyText(v.ty), v.name, c.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{try l.wrap(.own, v.ty)} }, .{ .role = "err", .params = &.{ alloc_err, v.ty } } }) }; + return .{ .text = try l.fmt("own.pack {s} %{s}, %{s}", .{ try l.tyText(v.ty), v.name, c.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{try l.wrap(.own, v.ty)} }, .{ .role = "err", .params = &.{ alloc_err, v.ty } } }) }; } if (std.mem.eql(u8, path, "own.new")) { try want(l, e.span, args, 2, path); @@ -3494,7 +3527,7 @@ const Lowerer = struct { if (std.mem.eql(u8, path, "task.join_cancel")) { try want(l, e.span, args, 1, path); const t = try l.consuming(args[0], null); - if (t.ty != .task) return l.fail("E7005", args[0].span, "`task.join_cancel` takes a `task`", &.{.{ .name = "found", .value = l.diagnosticTyText(t.ty) }}); + if (t.ty != .task) return l.fail("E7005", args[0].span, "`task.join_cancel` takes a `task`", &.{.{ .name = "found", .value = try l.diagnosticTyText(t.ty) }}); const rt = t.ty.task.*; const ok: []const Ty = if (rt == .void) &.{} else &.{rt}; return .{ .text = try l.fmt("task.join.cancel %{s}", .{t.name}), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = ok }, .{ .role = "cancelled", .params = &.{t.ty} } }) }; @@ -3507,7 +3540,7 @@ const Lowerer = struct { const n = try l.expr(args[0], usize_ty); try l.checkOperandTy(args[0].span, n.ty, usize_ty); const c = try l.expectCap(args[1], "mem.alloc"); - return .{ .text = try l.fmt("channel.make {s}, %{s}, %{s}", .{ l.tyText(et), n.name, c.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{ try l.wrap(.sender, et), try l.wrap(.receiver, et) } }, .{ .role = "err", .params = &.{alloc_err} } }) }; + return .{ .text = try l.fmt("channel.make {s}, %{s}, %{s}", .{ try l.tyText(et), n.name, c.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{ try l.wrap(.sender, et), try l.wrap(.receiver, et) } }, .{ .role = "err", .params = &.{alloc_err} } }) }; } if (std.mem.eql(u8, path, "channel.send")) { try want(l, e.span, args, 2, path); @@ -3528,23 +3561,23 @@ const Lowerer = struct { if (std.mem.eql(u8, path, "channel.close_receiver")) { try want(l, e.span, args, 1, path); const rx = try l.consuming(args[0], null); - if (rx.ty != .receiver) return l.fail("E7005", args[0].span, "`channel.close_receiver` takes a `receiver`", &.{.{ .name = "found", .value = l.diagnosticTyText(rx.ty) }}); + if (rx.ty != .receiver) return l.fail("E7005", args[0].span, "`channel.close_receiver` takes a `receiver`", &.{.{ .name = "found", .value = try l.diagnosticTyText(rx.ty) }}); return .{ .text = try l.fmt("channel.close_receiver %{s}", .{rx.name}), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{} }, .{ .role = "pending", .params = &.{rx.ty} } }) }; } if (std.mem.eql(u8, path, "cap.narrow.prefix")) { try want(l, e.span, args, 2, path); const c = try l.expr(args[0], null); - if (c.ty != .cap) return l.fail("E7005", args[0].span, "a capability is expected here", &.{.{ .name = "found", .value = l.diagnosticTyText(c.ty) }}); + if (c.ty != .cap) return l.fail("E7005", args[0].span, "a capability is expected here", &.{.{ .name = "found", .value = try l.diagnosticTyText(c.ty) }}); var temps: std.ArrayList([]const u8) = .empty; const bytes = try l.wrap(.slice, .{ .int = "u8" }); const p = try l.argument(args[1], bytes, &temps); - if (!p.ty.eql(bytes)) return l.fail("E7005", args[1].span, "the path is a byte string or a `ref` borrow of bytes", &.{.{ .name = "found", .value = l.diagnosticTyText(p.ty) }}); + if (!p.ty.eql(bytes)) return l.fail("E7005", args[1].span, "the path is a byte string or a `ref` borrow of bytes", &.{.{ .name = "found", .value = try l.diagnosticTyText(p.ty) }}); return .{ .text = try l.fmt("cap.narrow.prefix %{s}, %{s}", .{ c.name, p.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{c.ty} }, .{ .role = "err", .params = &.{.{ .builtin = .cap_error }} } }), .temps = temps.items }; } if (std.mem.eql(u8, path, "cap.narrow.budget")) { try want(l, e.span, args, 2, path); const c = try l.expr(args[0], null); - if (c.ty != .cap) return l.fail("E7005", args[0].span, "a capability is expected here", &.{.{ .name = "found", .value = l.diagnosticTyText(c.ty) }}); + if (c.ty != .cap) return l.fail("E7005", args[0].span, "a capability is expected here", &.{.{ .name = "found", .value = try l.diagnosticTyText(c.ty) }}); const n = try l.expr(args[1], usize_ty); try l.checkOperandTy(args[1].span, n.ty, usize_ty); return .{ .text = try l.fmt("cap.narrow.budget %{s}, %{s}", .{ c.name, n.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{c.ty} }, .{ .role = "err", .params = &.{.{ .builtin = .cap_error }} } }) }; @@ -4306,7 +4339,7 @@ const ReferenceTypeResolution = struct { .frozen => l.wrap(.frozen, in), .arc => l.wrap(.arc, in), .iref => l.wrap(.iref, in), - .atomic => if (atomicScalar(in)) l.wrap(.atomic, in) else l.fail("E7005", t.span, "atomic needs bool or an integer of at most 64 bits", &.{.{ .name = "found", .value = l.diagnosticTyText(in) }}), + .atomic => if (atomicScalar(in)) l.wrap(.atomic, in) else l.fail("E7005", t.span, "atomic needs bool or an integer of at most 64 bits", &.{.{ .name = "found", .value = try l.diagnosticTyText(in) }}), }; }, .cap => |k| { @@ -4449,3 +4482,173 @@ test "source type resolution allocation errors propagate and arena storage is re if (!failing.has_induced_failure) break; } } + +// Independent pre-repair printer, used only with shallow test types. +const ReferenceTypeText = struct { + fn typeText(l: *Lowerer, t: Ty, source_names: bool) []const u8 { + return switch (t) { + .int => |x| x, + .bool => "bool", + .void => "void", + .never => "never", + .named => |i| if (source_names and l.m.types[i].air_name != null) (l.m.types[i].display_name orelse l.m.types[i].name) else l.typeNames[i], + .array => |a| std.fmt.allocPrint(l.arena, "array<{s}, {d}>", .{ ReferenceTypeText.typeText(l, a.elem, source_names), a.len }) catch "array", + .ref, .mut, .slice, .slice_mut, .own, .own_array, .buffer, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| std.fmt.allocPrint(l.arena, "{s}<{s}>", .{ @tagName(t), ReferenceTypeText.typeText(l, x.*, source_names) }) catch "borrow", + .scope => "scope", + .shield => "shield", + .region => "region", + .cap => |k| std.fmt.allocPrint(l.arena, "cap<{s}>", .{k}) catch "cap", + .builtin => |b| blk: { + if (b == .io_error) l.uses.insert(.resources); + break :blk @tagName(b); + }, + .resource => |r| blk: { + l.uses.insert(.resources); + break :blk r.text(); + }, + }; + } +}; + +fn expectTypeTextMatches(a: Allocator, m: ast.Module, names: []const []const u8, t: Ty) !void { + for ([_]bool{ false, true }) |source_names| { + var old: Lowerer = .{ .arena = a, .m = m, .typeNames = names }; + var current: Lowerer = .{ .arena = a, .m = m, .typeNames = names }; + old.uses.insert(.unsafe); + current.uses.insert(.unsafe); + try std.testing.expectEqualStrings(ReferenceTypeText.typeText(&old, t, source_names), try current.typeText(t, source_names)); + try std.testing.expectEqualDeep(old.uses, current.uses); + } +} + +test "source type text preserves canonical and diagnostic names and resource features" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const span: Span = .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 2 } }; + const declarations = [_]ast.TypeDecl{ + .{ .span = span, .name = "Local", .kind = .{ .@"struct" = &.{} } }, + .{ .span = span, .name = "pkg.Box", .air_name = "__g_box", .display_name = "Box", .kind = .{ .@"struct" = &.{} } }, + .{ .span = span, .name = "pkg.Record", .air_name = "__g_record", .kind = .{ .@"struct" = &.{} } }, + }; + const names = [_][]const u8{ "@Local", "@__g_box", "@__g_record" }; + const m: ast.Module = .{ .name = "printing", .types = &declarations, .functions = &.{} }; + var builder: Lowerer = .{ .arena = a, .m = m, .typeNames = &names }; + var leaves: std.ArrayList(Ty) = .empty; + for (int_types) |n| try leaves.append(a, .{ .int = n }); + try leaves.appendSlice(a, &.{ .bool, .void, .never, .scope, .shield, .region, .{ .named = 0 }, .{ .named = 1 }, .{ .named = 2 } }); + for ([_][]const u8{ "mem.alloc", "io.read", "fs.open", "unknown.kind" }) |k| try leaves.append(a, .{ .cap = k }); + inline for (@typeInfo(authority.Builtin).@"enum".field_names) |name| try leaves.append(a, .{ .builtin = @field(authority.Builtin, name) }); + inline for (@typeInfo(authority.Resource).@"enum".field_names) |name| try leaves.append(a, .{ .resource = @field(authority.Resource, name) }); + var comparisons: usize = 0; + for (leaves.items) |leaf| { + try expectTypeTextMatches(a, m, &names, leaf); + comparisons += 2; + for ([_]u64{ 0, 1, @as(u64, 1) << 32, std.math.maxInt(u64) }) |length| { + try expectTypeTextMatches(a, m, &names, try builder.arrayOf(leaf, length)); + comparisons += 2; + } + inline for (@typeInfo(Ty).@"union".field_names, @typeInfo(Ty).@"union".field_types) |name, FieldType| if (comptime FieldType == *const Ty) { + const wrapped = try builder.wrap(@field(std.meta.Tag(Ty), name), leaf); + try expectTypeTextMatches(a, m, &names, wrapped); + try expectTypeTextMatches(a, m, &names, try builder.arrayOf(wrapped, 123)); + try expectTypeTextMatches(a, m, &names, try builder.wrap(@field(std.meta.Tag(Ty), name), try builder.arrayOf(leaf, 456))); + comparisons += 6; + }; + } + try std.testing.expectEqual(@as(usize, 3696), comparisons); +} + +test "source type text prints deep mixed chains with one growing output" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const m: ast.Module = .{ .name = "printing", .types = &.{}, .functions = &.{} }; + var l: Lowerer = .{ .arena = a, .m = m }; + var ty: Ty = .{ .cap = "mem.alloc" }; + const count = 65_536; + for (0..count) |i| ty = if (i % 2 == 0) try l.arrayOf(ty, i + 1) else try l.wrap(.ref, ty); + var expected: std.ArrayList(u8) = .empty; + var i: usize = count; + while (i != 0) { + i -= 1; + try expected.appendSlice(a, if (i % 2 == 0) "array<" else "ref<"); + } + try expected.appendSlice(a, "cap"); + for (0..count) |j| { + if (j % 2 == 0) { + var digits: [20]u8 = undefined; + try expected.appendSlice(a, ", "); + try expected.appendSlice(a, std.fmt.bufPrint(&digits, "{d}", .{j + 1}) catch unreachable); + } + try expected.append(a, '>'); + } + try std.testing.expectEqualStrings(expected.items, try l.tyText(ty)); + try std.testing.expectEqualStrings(expected.items, try l.diagnosticTyText(ty)); +} + +test "source type text OOM reaches diagnostics and emission without fallback text" { + var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer scratch.deinit(); + const a = scratch.allocator(); + const m: ast.Module = .{ .name = "printing", .types = &.{}, .functions = &.{} }; + var builder: Lowerer = .{ .arena = a, .m = m }; + var deep: Ty = .{ .cap = "mem.alloc" }; + for (0..128) |i| deep = if (i % 2 == 0) try builder.arrayOf(deep, std.math.maxInt(u64)) else try builder.wrap(.own, deep); + for ([_]Ty{ .{ .cap = "mem.alloc" }, deep }) |ty| for ([_]bool{ false, true }) |source_names| { + var fail_index: usize = 0; + while (true) : (fail_index += 1) { + try std.testing.expect(fail_index < 100); + 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 text = l.typeText(ty, source_names); + if (failing.has_induced_failure) { + try std.testing.expectError(error.OutOfMemory, text); + } else { + try std.testing.expectEqualStrings(try builder.typeText(ty, source_names), try text); + } + arena.deinit(); + try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes); + if (!failing.has_induced_failure) break; + } + }; + const span: Span = .{ .start = .{ .line = 2, .col = 3 }, .end = .{ .line = 2, .col = 9 } }; + for ([_]bool{ false, true }) |diagnostic| { + var fail_index: usize = 0; + while (true) : (fail_index += 1) { + try std.testing.expect(fail_index < 100); + var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = fail_index }); + var arena: std.heap.ArenaAllocator = .init(failing.allocator()); + var l: Lowerer = .{ .arena = arena.allocator(), .m = m }; + const result: Error!void = if (diagnostic) l.checkTy(span, deep, .bool) else blk: { + _ = l.storageFor("x", deep, span) catch |err| break :blk err; + break :blk {}; + }; + if (failing.has_induced_failure) { + try std.testing.expectError(error.OutOfMemory, result); + try std.testing.expect(l.problem == null); + try std.testing.expectEqual(@as(usize, 0), l.allocs.items.len); + } else if (diagnostic) { + try std.testing.expectError(error.Lower, result); + try std.testing.expectEqualStrings("E7005", l.problem.?.code); + try std.testing.expectEqualStrings(try builder.diagnosticTyText(deep), l.problem.?.fields[1].value); + } else { + try result; + try std.testing.expectEqual(@as(usize, 1), l.allocs.items.len); + try std.testing.expect(std.mem.endsWith(u8, l.allocs.items[0].text, try builder.tyText(deep))); + } + 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; + } + } + // Constant leaves keep the original allocation-free path. + var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 0 }); + var l: Lowerer = .{ .arena = failing.allocator(), .m = m }; + try std.testing.expectEqualStrings("u8", try l.tyText(.{ .int = "u8" })); + try std.testing.expectEqualStrings("file", try l.diagnosticTyText(.{ .resource = .file_read })); + try std.testing.expect(l.uses.contains(.resources)); + try std.testing.expect(!failing.has_induced_failure); +}