Phase 1: frame storage, second-class borrows, arrays (P1-3..P1-10)

- air: types local/ref/mut/array/slice/slice_mut, from-returns,
  multi-result binding, 18 new instructions; feature gating reports
  E0006 feature_not_declared; borrow-typed block parameters gated by
  borrow_joins; printer and round-trip tests for all new forms
- verifier: second-class and zeroable type rules (E1001); local.alloc
  only in entry (E5002); frame size accounting (E5101); stages init
  (E1010), borrow (E2101, E2102, E2105-E2108) and bounds facts (E2103);
  value types shared between stages
- interp: frame cells, places, slices, deep copies between storage and
  SSA values, T0008 bounds traps
- features arrays and ownership supported; implemented_phase = 1
- conformance: 5 accept, 18 reject, 11 run tests for Phase 1, including
  the file-copy core exit program; 6000 mutants without a crash
This commit is contained in:
dev committed 2026-10-04 13:24:09 +03:00
1 parent be9dd0e1ed
commit 1ae6b485d8
50 files changed
+2376 -37

No files matched your search

+2 -2
View File
@@ -36,8 +36,8 @@ pub const registry = [_]Feature{
.{ .name = "tasks", .depends = &.{"ownership"}, .status = .reserved, .phase = 3 },
};
/// Features implemented by this toolchain, sorted. Empty: Phase 0 baseline.
pub const supported = [_][]const u8{};
/// Features implemented by this toolchain, sorted.
pub const supported = [_][]const u8{ "arrays", "ownership" };
pub const Reason = enum {
unknown_feature,
+104 -3
View File
@@ -64,12 +64,58 @@ pub const Type = union(enum) {
never,
/// Index into `Module.types`.
named: u32,
// Feature `ownership` (spec 07 §8.8).
local: *const Type,
ref: *const Type,
mut: *const Type,
// Feature `arrays`.
array: *const Array,
slice: *const Type,
slice_mut: *const Type,
pub const Array = struct { elem: Type, len: u64 };
pub fn eql(a: Type, b: Type) bool {
if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false;
return switch (a) {
.int => |x| b == .int and b.int == x,
.named => |x| b == .named and b.named == x,
else => std.meta.activeTag(a) == std.meta.activeTag(b),
.int => |x| b.int == x,
.named => |x| b.named == x,
.local, .ref, .mut, .slice, .slice_mut => |x| x.eql(b.inner().?),
.array => |x| x.len == b.array.len and x.elem.eql(b.array.elem),
.bool, .void, .never => true,
};
}
/// Element or pointee type of storage, borrow and slice types.
pub fn inner(t: Type) ?Type {
return switch (t) {
.local, .ref, .mut, .slice, .slice_mut => |x| x.*,
.array => |a| a.elem,
else => null,
};
}
/// Borrow class (spec 07 §8.8): second-class, linear when owned.
pub fn isBorrow(t: Type) bool {
return switch (t) {
.ref, .mut, .slice, .slice_mut => true,
else => false,
};
}
pub fn isMutBorrow(t: Type) bool {
return t == .mut or t == .slice_mut;
}
pub fn isSlice(t: Type) bool {
return t == .slice or t == .slice_mut;
}
/// Value types may be stored in fields, payloads, elements and locals.
pub fn isValue(t: Type) bool {
return switch (t) {
.void, .never, .local, .ref, .mut, .slice, .slice_mut => false,
else => true,
};
}
};
@@ -137,6 +183,28 @@ pub const CmpOp = enum { eq, ne, lt, le, gt, ge };
pub const CastMode = enum { checked, wrap, widen };
pub const Op = union(enum) {
// Feature `ownership` (spec 07a).
local_alloc: Type,
local_store: struct { local: ValueId, value: ValueId },
local_zero: ValueId,
local_load: ValueId,
borrow_ref: ValueId,
borrow_mut: ValueId,
borrow_field: struct { decl: u32, field: u32, borrow: ValueId },
borrow_end: ValueId,
load: ValueId,
store: struct { borrow: ValueId, value: ValueId },
// Feature `arrays`.
array_splat: struct { ty: Type, value: ValueId },
borrow_index: struct { borrow: ValueId, index: ValueId, proven: bool },
slice_make: ValueId,
slice_len: ValueId,
slice_sub: struct { slice: ValueId, start: ValueId, len: ValueId },
/// Two results: `Inst.result` (left) and `Inst.result2` (right).
slice_split: struct { slice: ValueId, at: ValueId },
slice_copy: struct { dst: ValueId, src: ValueId },
guard: ValueId,
@"const": struct { ty: Type, bits: u128 },
copy: ValueId,
arith: struct { op: ArithOp, mode: ArithMode, ty: IntType, a: ValueId, b: ValueId },
@@ -169,6 +237,8 @@ pub const Op = union(enum) {
pub const Inst = struct {
result: ?ValueId,
/// Second result of `slice.split`.
result2: ?ValueId = null,
op: Op,
span: Span,
};
@@ -185,6 +255,8 @@ pub const Function = struct {
span: Span,
params: []const Param,
ret: Type,
/// Index into `params` of the `from` parameter of a borrow return.
ret_from: ?u32 = null,
effects: []const []const u8,
blocks: []const Block,
values: []const ValueInfo,
@@ -243,6 +315,35 @@ pub fn forEachUse(op: Op, ctx: anytype, comptime f: fn (@TypeOf(ctx), ValueId) v
if (x.default) |d| for (d.args) |v| f(ctx, v);
},
.ret => |v| if (v) |x| f(ctx, x),
.local_alloc => {},
.local_store => |x| {
f(ctx, x.local);
f(ctx, x.value);
},
.local_zero, .local_load, .borrow_ref, .borrow_mut, .borrow_end, .load, .slice_make, .slice_len, .guard => |v| f(ctx, v),
.borrow_field => |x| f(ctx, x.borrow),
.store => |x| {
f(ctx, x.borrow);
f(ctx, x.value);
},
.array_splat => |x| f(ctx, x.value),
.borrow_index => |x| {
f(ctx, x.borrow);
f(ctx, x.index);
},
.slice_sub => |x| {
f(ctx, x.slice);
f(ctx, x.start);
f(ctx, x.len);
},
.slice_split => |x| {
f(ctx, x.slice);
f(ctx, x.at);
},
.slice_copy => |x| {
f(ctx, x.dst);
f(ctx, x.src);
},
}
}
+177 -3
View File
@@ -49,6 +49,8 @@ const Tag = enum {
r_bracket,
l_brace,
r_brace,
lt,
gt,
/// Identifier, possibly dotted: opcodes, keywords, types, paths.
word,
/// `%name`; text excludes the sigil.
@@ -104,6 +106,14 @@ fn tokenize(arena: Allocator, src: []const u8) Allocator.Error![]const Token {
i += 1;
tag = .comma;
},
'<' => {
i += 1;
tag = .lt;
},
'>' => {
i += 1;
tag = .gt;
},
':' => {
i += 1;
tag = .colon;
@@ -185,6 +195,8 @@ const Parser = struct {
type_names: std.ArrayList([]const u8) = .empty,
fn_names: std.ArrayList([]const u8) = .empty,
types: []air.TypeDecl = &.{},
/// Features declared in the module header, sorted.
declared: []const []const u8 = &.{},
// Function-level state.
fn_name: []const u8 = "",
@@ -296,6 +308,7 @@ const Parser = struct {
}
if (problems.len != 0) return error.SyntaxError;
features_mod.sort(features);
p.declared = features;
try p.prescanDeclarations();
@@ -457,6 +470,7 @@ const Parser = struct {
return .void;
},
.word => {
if (p.peek().tag == .lt) return p.parseCompoundType(t);
if (std.meta.stringToEnum(air.IntType, t.text)) |it| return .{ .int = it };
if (std.mem.eql(u8, t.text, "bool")) return .bool;
if (std.mem.eql(u8, t.text, "void")) return .void;
@@ -475,6 +489,54 @@ const Parser = struct {
}
}
/// `local<T>`, `ref<T>`, `mut<T>`, `slice<T>`, `slice_mut<T>`, `array<T, N>` (spec 07 §8.8).
fn parseCompoundType(p: *Parser, t: Token) Error!air.Type {
const Kind = enum { local, ref, mut, slice, slice_mut, array };
const kind = std.meta.stringToEnum(Kind, t.text) orelse {
try p.report("E0004", t.span, "unknown type", &.{.{ .name = "name", .value = .{ .str = t.text } }});
return error.SyntaxError;
};
try p.requireFeature(switch (kind) {
.local, .ref, .mut => "ownership",
.slice, .slice_mut, .array => "arrays",
}, t.span, t.text);
_ = try p.expect(.lt, "`<`");
const inner = try p.parseType();
if (kind == .array) {
_ = try p.expect(.comma, "`,`");
const n_tok = try p.expect(.number, "array length");
const n = std.fmt.parseInt(u64, n_tok.text, 0) catch 0;
if (n == 0 or n > (@as(u64, 1) << 32)) {
try p.report("E0002", n_tok.span, "array length must be between 1 and 2^32", &.{.{ .name = "literal", .value = .{ .str = n_tok.text } }});
}
_ = try p.expect(.gt, "`>`");
const arr = try p.arena.create(air.Type.Array);
arr.* = .{ .elem = inner, .len = @max(n, 1) };
return .{ .array = arr };
}
_ = try p.expect(.gt, "`>`");
const boxed = try p.arena.create(air.Type);
boxed.* = inner;
return switch (kind) {
.local => .{ .local = boxed },
.ref => .{ .ref = boxed },
.mut => .{ .mut = boxed },
.slice => .{ .slice = boxed },
.slice_mut => .{ .slice_mut = boxed },
.array => unreachable,
};
}
/// Reports `E0006 feature_not_declared` if `feature` is not in the header (spec 07 §8.1).
fn requireFeature(p: *Parser, feature: []const u8, span: Span, construct: []const u8) Error!void {
for (p.declared) |d| if (eql(d, feature)) return;
try p.report("E0006", span, "construct belongs to a feature the module does not declare", &.{
.{ .name = "reason", .value = .{ .str = "feature_not_declared" } },
.{ .name = "feature", .value = .{ .str = feature } },
.{ .name = "construct", .value = .{ .str = construct } },
});
}
// ------------------------------------------------------------ functions
fn parseFunction(p: *Parser) Error!air.Function {
@@ -499,6 +561,16 @@ const Parser = struct {
_ = try p.expect(.r_paren, "`)`");
_ = try p.expect(.arrow, "`->`");
const ret = try p.parseType();
var ret_from: ?u32 = null;
if (p.atWord("from")) {
const from_tok = p.next();
try p.requireFeature("ownership", from_tok.span, "from");
const v = try p.expect(.local, "parameter after `from`");
for (params.items, 0..) |prm, i| {
if (eql(p.values.items[prm.value].name, v.text)) ret_from = @intCast(i);
}
if (ret_from == null) try p.report("E0004", v.span, "`from` must name a parameter", &.{.{ .name = "name", .value = .{ .str = v.text } }});
}
_ = try p.expect(.nl, "end of line");
p.skipNewlines();
_ = try p.expectWord("effects");
@@ -526,6 +598,7 @@ const Parser = struct {
.span = name.span,
.params = params.items,
.ret = ret,
.ret_from = ret_from,
.effects = effects,
.blocks = blocks.items,
.values = p.values.items,
@@ -597,7 +670,11 @@ const Parser = struct {
while (p.peek().tag != .r_paren) {
const v = try p.expect(.local, "block parameter");
_ = try p.expect(.colon, "`:`");
const ty_span = p.peek().span;
const ty = try p.parseType();
// Borrow-typed block parameters belong to the reserved feature
// `borrow_joins` (spec 08 §11.6).
if (ty.isBorrow()) try p.requireFeature("borrow_joins", ty_span, "borrow-typed block parameter");
const id = try p.defineValue(v, .{ .block_param = .{ .block = index, .index = @intCast(params.items.len) } });
try params.append(p.arena, .{ .value = id, .ty = ty });
if (p.peek().tag != .comma) break;
@@ -624,9 +701,15 @@ const Parser = struct {
/// Returns null if the line was skipped after an unknown-opcode error.
fn parseInst(p: *Parser, block: u32, index: u32) Error!?air.Inst {
var result_tok: ?Token = null;
var result2_tok: ?Token = null;
if (p.peek().tag == .local and p.peekAt(1).tag == .equals) {
result_tok = p.next();
_ = p.next();
} else if (p.peek().tag == .local and p.peekAt(1).tag == .comma and p.peekAt(2).tag == .local and p.peekAt(3).tag == .equals) {
result_tok = p.next();
_ = p.next();
result2_tok = p.next();
_ = p.next();
}
const op_tok = try p.expect(.word, "opcode");
var parts_buf: [4][]const u8 = undefined;
@@ -750,12 +833,15 @@ const Parser = struct {
break :op .{ .ret = if (p.peek().tag == .local) try p.useValue() else null };
}
if (eql(op_tok.text, "trap")) break :op .trap;
if (try p.parseMemoryOp(op_tok)) |mop| break :op mop;
return p.unknownOpcode(op_tok);
};
_ = try p.expect(.nl, "end of line");
const produces_value = switch (op) {
.@"const", .copy, .arith, .bit, .cmp, .cast, .struct_make, .struct_get, .enum_make => true,
.local_alloc, .local_load, .borrow_ref, .borrow_mut, .borrow_field, .load => true,
.array_splat, .borrow_index, .slice_make, .slice_len, .slice_sub, .slice_split => true,
else => false,
};
const may_bind = produces_value or op == .call;
@@ -764,8 +850,96 @@ const Parser = struct {
} else if (produces_value) {
return p.fail(op_tok, "result binding `%name =`");
}
const result = if (result_tok) |rt| try p.defineValue(rt, .{ .inst = .{ .block = block, .index = index } }) else null;
return .{ .result = result, .op = op, .span = if (result_tok) |rt| rt.span else op_tok.span };
if ((op == .slice_split) != (result2_tok != null)) {
return p.fail(result_tok orelse op_tok, if (op == .slice_split) "two results `%left, %right =`" else "a single result");
}
const def: air.ValueInfo.Def = .{ .inst = .{ .block = block, .index = index } };
const result = if (result_tok) |rt| try p.defineValue(rt, def) else null;
const result2 = if (result2_tok) |rt| try p.defineValue(rt, def) else null;
return .{ .result = result, .result2 = result2, .op = op, .span = if (result_tok) |rt| rt.span else op_tok.span };
}
/// Instructions of the features `ownership` and `arrays` (spec 07a).
fn parseMemoryOp(p: *Parser, op_tok: Token) Error!?air.Op {
const Name = enum {
@"local.alloc",
@"local.store",
@"local.zero",
@"local.load",
@"borrow.ref",
@"borrow.mut",
@"borrow.field",
@"borrow.end",
load,
store,
@"array.splat",
@"borrow.index",
@"borrow.index.proven",
@"slice.make",
@"slice.len",
@"slice.sub",
@"slice.split",
@"slice.copy",
guard,
};
const name = std.meta.stringToEnum(Name, op_tok.text) orelse return null;
const feature: []const u8 = switch (name) {
.@"local.alloc", .@"local.store", .@"local.zero", .@"local.load", .@"borrow.ref", .@"borrow.mut", .@"borrow.field", .@"borrow.end", .load, .store => "ownership",
else => "arrays",
};
try p.requireFeature(feature, op_tok.span, op_tok.text);
return switch (name) {
.@"local.alloc" => .{ .local_alloc = try p.parseType() },
.@"local.store" => blk: {
const s, const v = try p.twoOperands();
break :blk .{ .local_store = .{ .local = s, .value = v } };
},
.@"local.zero" => .{ .local_zero = try p.useValue() },
.@"local.load" => .{ .local_load = try p.useValue() },
.@"borrow.ref" => .{ .borrow_ref = try p.useValue() },
.@"borrow.mut" => .{ .borrow_mut = try p.useValue() },
.@"borrow.field" => blk: {
const decl = try p.typeRef(.@"struct");
_ = try p.expect(.dot, "`.`");
const field_tok = try p.expect(.word, "field name");
const field = p.types[decl].fieldIndex(field_tok.text) orelse f: {
try p.report("E0004", field_tok.span, "unknown field", &.{.{ .name = "name", .value = .{ .str = field_tok.text } }});
break :f 0;
};
_ = try p.expect(.comma, "`,`");
break :blk .{ .borrow_field = .{ .decl = decl, .field = field, .borrow = try p.useValue() } };
},
.@"borrow.end" => .{ .borrow_end = try p.useValue() },
.load => .{ .load = try p.useValue() },
.store => blk: {
const b, const v = try p.twoOperands();
break :blk .{ .store = .{ .borrow = b, .value = v } };
},
.@"array.splat" => blk: {
const ty = try p.parseType();
break :blk .{ .array_splat = .{ .ty = ty, .value = try p.useValue() } };
},
.@"borrow.index", .@"borrow.index.proven" => blk: {
const b, const i = try p.twoOperands();
break :blk .{ .borrow_index = .{ .borrow = b, .index = i, .proven = name == .@"borrow.index.proven" } };
},
.@"slice.make" => .{ .slice_make = try p.useValue() },
.@"slice.len" => .{ .slice_len = try p.useValue() },
.@"slice.sub" => blk: {
const s, const start = try p.twoOperands();
_ = try p.expect(.comma, "`,`");
break :blk .{ .slice_sub = .{ .slice = s, .start = start, .len = try p.useValue() } };
},
.@"slice.split" => blk: {
const s, const at = try p.twoOperands();
break :blk .{ .slice_split = .{ .slice = s, .at = at } };
},
.@"slice.copy" => blk: {
const d, const s = try p.twoOperands();
break :blk .{ .slice_copy = .{ .dst = d, .src = s } };
},
.guard => .{ .guard = try p.useValue() },
};
}
fn unknownOpcode(p: *Parser, t: Token) Error!?air.Inst {
@@ -988,7 +1162,7 @@ test "resolution diagnostics" {
try expectCodes(header ++ "fn @f() -> f32\neffects []\nentry:\n trap\n", &.{"E0006"});
try expectCodes(header ++ "fn @f() -> u8\neffects []\nentry:\n trap\nfn @f() -> u8\neffects []\nentry:\n trap\n", &.{"E0003"});
try expectCodes("module t\nair 1\nlang 0.1\nfeatures []\n", &.{"E0005"});
try expectCodes("module t\nair 0\nlang 0.1\nfeatures [magic, ownership, ownership]\nfn @f( -> broken\n", &.{ "E0006", "E0006", "E0006" });
try expectCodes("module t\nair 0\nlang 0.1\nfeatures [heap, magic, ownership, ownership]\nfn @f( -> broken\n", &.{ "E0006", "E0006", "E0006" });
try expectCodes(header ++ "fn @f( -> u8\n", &.{"E0001"});
try expectCodes(header ++ "type\n", &.{"E0001"}); // found by fuzzing
}
+112 -2
View File
@@ -47,6 +47,7 @@ pub fn print(m: air.Module, w: *Writer) Writer.Error!void {
try params(m, f, f.params, w);
try w.writeAll(") -> ");
try printType(m, f.ret, w);
if (f.ret_from) |i| try w.print(" from %{s}", .{f.values[f.params[i].value].name});
try w.writeAll("\neffects [");
try list(w, f.effects);
try w.writeAll("]\n");
@@ -60,7 +61,11 @@ pub fn print(m: air.Module, w: *Writer) Writer.Error!void {
try w.writeAll(":\n");
for (b.insts) |inst| {
try w.writeAll(" ");
if (inst.result) |r| try w.print("%{s} = ", .{f.values[r].name});
if (inst.result) |r| {
try w.print("%{s}", .{f.values[r].name});
if (inst.result2) |r2| try w.print(", %{s}", .{f.values[r2].name});
try w.writeAll(" = ");
}
try printOp(m, f, inst.op, w);
try w.writeByte('\n');
}
@@ -87,7 +92,17 @@ pub fn printType(m: air.Module, t: air.Type, w: *Writer) Writer.Error!void {
switch (t) {
.int => |it| try w.writeAll(@tagName(it)),
.named => |i| try w.print("@{s}", .{m.types[i].name}),
else => try w.writeAll(@tagName(t)),
.local, .ref, .mut, .slice, .slice_mut => |inner| {
try w.print("{s}<", .{@tagName(t)});
try printType(m, inner.*, w);
try w.writeByte('>');
},
.array => |a| {
try w.writeAll("array<");
try printType(m, a.elem, w);
try w.print(", {d}>", .{a.len});
},
.bool, .void, .never => try w.writeAll(@tagName(t)),
}
}
@@ -228,9 +243,54 @@ fn printOp(m: air.Module, f: air.Function, op: air.Op, w: *Writer) Writer.Error!
}
},
.trap => try w.writeAll("trap"),
.local_alloc => |t| {
try w.writeAll("local.alloc ");
try printType(m, t, w);
},
.local_store => |x| try two(f, w, "local.store", x.local, x.value),
.local_zero => |v| try one(f, w, "local.zero", v),
.local_load => |v| try one(f, w, "local.load", v),
.borrow_ref => |v| try one(f, w, "borrow.ref", v),
.borrow_mut => |v| try one(f, w, "borrow.mut", v),
.borrow_field => |x| {
const d = m.types[x.decl];
try w.print("borrow.field @{s}.{s}, ", .{ d.name, d.kind.@"struct"[x.field].name });
try value(f, x.borrow, w);
},
.borrow_end => |v| try one(f, w, "borrow.end", v),
.load => |v| try one(f, w, "load", v),
.store => |x| try two(f, w, "store", x.borrow, x.value),
.array_splat => |x| {
try w.writeAll("array.splat ");
try printType(m, x.ty, w);
try w.writeByte(' ');
try value(f, x.value, w);
},
.borrow_index => |x| try two(f, w, if (x.proven) "borrow.index.proven" else "borrow.index", x.borrow, x.index),
.slice_make => |v| try one(f, w, "slice.make", v),
.slice_len => |v| try one(f, w, "slice.len", v),
.slice_sub => |x| {
try two(f, w, "slice.sub", x.slice, x.start);
try w.writeAll(", ");
try value(f, x.len, w);
},
.slice_split => |x| try two(f, w, "slice.split", x.slice, x.at),
.slice_copy => |x| try two(f, w, "slice.copy", x.dst, x.src),
.guard => |v| try one(f, w, "guard", v),
}
}
fn one(f: air.Function, w: *Writer, op: []const u8, a: air.ValueId) Writer.Error!void {
try w.print("{s} ", .{op});
try value(f, a, w);
}
fn two(f: air.Function, w: *Writer, op: []const u8, a: air.ValueId, b: air.ValueId) Writer.Error!void {
try one(f, w, op, a);
try w.writeAll(", ");
try value(f, b, w);
}
// ---------------------------------------------------------------- tests
const parse = @import("parse.zig").parse;
@@ -340,3 +400,53 @@ test "round-trip fuzz over generated arithmetic modules" {
try roundTrip(w.buffered());
}
}
test "round-trip of ownership and arrays forms" {
try roundTrip(
\\module t
\\air 0
\\lang 0.1
\\features [ownership, arrays]
\\type @P = struct { a: u8, b: array<u16, 3> }
\\fn @first(%s: slice<u8>) -> ref<u8> from %s
\\effects []
\\entry:
\\ %z = const.usize 0
\\ %e = borrow.index.proven %s, %z
\\ ret %e
\\fn @main(%d: slice_mut<u8>) -> void
\\effects []
\\entry:
\\ %x = local.alloc @P
\\ local.zero %x
\\ %m = borrow.mut %x
\\ %f = borrow.field @P.b, %m
\\ %s = slice.make %f
\\ %n = slice.len %s
\\ %k = const.usize 1
\\ %l, %r = slice.split %s, %k
\\ %t = slice.sub %r, %k, %k
\\ %c = lt.usize %k, %n
\\ guard %c
\\ %rr = borrow.ref %l
\\ slice.copy %t, %rr
\\ %v = const.u16 7
\\ %a = array.splat array<u16, 3> %v
\\ %e = borrow.index %l, %k
\\ store %e, %v
\\ %w = load %e
\\ borrow.end %e
\\ borrow.end %rr
\\ borrow.end %t
\\ borrow.end %l
\\ borrow.end %r
\\ borrow.end %s
\\ borrow.end %f
\\ borrow.end %m
\\ %y = local.alloc array<u16, 3>
\\ local.store %y, %a
\\ %q = local.load %y
\\ ret
\\
);
}