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
\\
);
}
+178 -3
View File
@@ -20,13 +20,29 @@ pub const Value = union(enum) {
boolean: bool,
void,
aggregate: Aggregate,
array: []Value,
/// Frame storage (`local<T>`).
local: *Cell,
/// `ref<T>` / `mut<T>`: a place inside frame storage.
place: Place,
/// `slice<T>` / `slice_mut<T>`.
slice: Slice,
pub const Aggregate = struct {
decl: u32,
/// Active variant for enums; 0 for structs.
variant: u32,
fields: []const Value,
fields: []Value,
};
/// Frame storage. `value` is `.void` while uninitialized.
pub const Cell = struct { value: Value, ty: air.Type };
/// Path of field or element indices from the cell's value.
pub const Place = struct { cell: *Cell, path: []const u32 };
/// Range `[start, start + len)` of the array at `place`.
pub const Slice = struct { place: Place, start: u64, len: u64 };
};
pub const Trap = struct {
@@ -71,6 +87,7 @@ const TrapKind = enum {
shift_out_of_range,
cast_out_of_range,
call_depth,
out_of_bounds,
fn code(k: TrapKind) *const diag.Code {
return switch (k) {
@@ -81,6 +98,7 @@ const TrapKind = enum {
.shift_out_of_range => diag.lookup("T0005").?,
.cast_out_of_range => diag.lookup("T0006").?,
.call_depth => diag.lookup("T0007").?,
.out_of_bounds => diag.lookup("T0008").?,
};
}
};
@@ -200,13 +218,13 @@ const Machine = struct {
.struct_make => |x| return bind(vals, inst.result, .{ .aggregate = .{
.decl = x.decl,
.variant = 0,
.fields = try m.gather(vals, x.args),
.fields = try m.gatherMut(vals, x.args),
} }),
.struct_get => |x| return bind(vals, inst.result, vals[x.a].aggregate.fields[x.field]),
.enum_make => |x| return bind(vals, inst.result, .{ .aggregate = .{
.decl = x.decl,
.variant = x.variant,
.fields = try m.gather(vals, x.args),
.fields = try m.gatherMut(vals, x.args),
} }),
.call => |x| {
if (m.depth >= call_depth_limit) return .{ .trap = .call_depth };
@@ -237,6 +255,7 @@ const Machine = struct {
},
.ret => |v| return .{ .ret = if (v) |x| vals[x] else .void },
.trap => return .{ .trap = .explicit },
.local_alloc, .local_store, .local_zero, .local_load, .borrow_ref, .borrow_mut, .borrow_field, .borrow_end, .load, .store, .array_splat, .borrow_index, .slice_make, .slice_len, .slice_sub, .slice_split, .slice_copy, .guard => return m.execMemory(vals, inst),
}
}
@@ -245,7 +264,156 @@ const Machine = struct {
return .next;
}
// ------------------------------------------------------------ memory (spec 07a, features ownership/arrays)
/// Values in storage never share structure with SSA values, so every
/// transfer between the two copies aggregates and arrays.
fn deepCopy(m: *Machine, v: Value) std.mem.Allocator.Error!Value {
return switch (v) {
.aggregate => |a| .{ .aggregate = .{ .decl = a.decl, .variant = a.variant, .fields = try m.copyAll(a.fields) } },
.array => |items| .{ .array = try m.copyAll(items) },
else => v,
};
}
fn copyAll(m: *Machine, items: []const Value) std.mem.Allocator.Error![]Value {
const out = try m.arena.alloc(Value, items.len);
for (items, out) |x, *o| o.* = try m.deepCopy(x);
return out;
}
fn zeroValue(m: *Machine, t: air.Type) std.mem.Allocator.Error!Value {
return switch (t) {
.int => |it| .{ .int = .{ .ty = it, .bits = 0 } },
.bool => .{ .boolean = false },
.array => |a| blk: {
const items = try m.arena.alloc(Value, a.len);
for (items) |*x| x.* = try m.zeroValue(a.elem);
break :blk .{ .array = items };
},
.named => |i| blk: {
const fields = m.module.types[i].kind.@"struct";
const out = try m.arena.alloc(Value, fields.len);
for (fields, out) |fd, *o| o.* = try m.zeroValue(fd.ty);
break :blk .{ .aggregate = .{ .decl = i, .variant = 0, .fields = out } };
},
else => unreachable, // verified zeroable
};
}
fn placePtr(p: Value.Place) *Value {
var v = &p.cell.value;
for (p.path) |i| v = switch (v.*) {
.aggregate => |a| &a.fields[i],
.array => |items| &items[i],
else => unreachable,
};
return v;
}
fn extend(m: *Machine, p: Value.Place, i: u64) !Value.Place {
const path = try m.arena.alloc(u32, p.path.len + 1);
@memcpy(path[0..p.path.len], p.path);
path[p.path.len] = @intCast(i);
return .{ .cell = p.cell, .path = path };
}
fn asPlace(v: Value) Value.Place {
return switch (v) {
.local => |c| .{ .cell = c, .path = &.{} },
.place => |p| p,
else => unreachable,
};
}
fn usize_(v: Value) u64 {
return @truncate(v.int.bits);
}
fn execMemory(m: *Machine, vals: []Value, inst: air.Inst) std.mem.Allocator.Error!Step {
switch (inst.op) {
.local_alloc => |t| {
const cell = try m.arena.create(Value.Cell);
cell.* = .{ .value = .void, .ty = t };
return bind(vals, inst.result, .{ .local = cell });
},
.local_store => |x| {
vals[x.local].local.value = try m.deepCopy(vals[x.value]);
return .next;
},
.local_zero => |v| {
const cell = vals[v].local;
cell.value = try m.zeroValue(cell.ty);
return .next;
},
.local_load => |v| return bind(vals, inst.result, try m.deepCopy(vals[v].local.value)),
.borrow_ref, .borrow_mut => |v| return bind(vals, inst.result, switch (vals[v]) {
.local => |c| .{ .place = .{ .cell = c, .path = &.{} } },
else => |x| x,
}),
.borrow_field => |x| return bind(vals, inst.result, .{ .place = try m.extend(asPlace(vals[x.borrow]), x.field) }),
.borrow_end => return .next,
.load => |v| return bind(vals, inst.result, try m.deepCopy(placePtr(asPlace(vals[v])).*)),
.store => |x| {
placePtr(asPlace(vals[x.borrow])).* = try m.deepCopy(vals[x.value]);
return .next;
},
.array_splat => |x| {
const items = try m.arena.alloc(Value, x.ty.array.len);
for (items) |*it| it.* = try m.deepCopy(vals[x.value]);
return bind(vals, inst.result, .{ .array = items });
},
.borrow_index => |x| {
const i = usize_(vals[x.index]);
const place: Value.Place, const start: u64, const len: u64 = switch (vals[x.borrow]) {
.slice => |s| .{ s.place, s.start, s.len },
else => |b| .{ asPlace(b), 0, placePtr(asPlace(b)).array.len },
};
// `.proven` was verified in bounds; the check is kept as a
// defensive assertion that can never fire on verified AIR.
if (i >= len) return .{ .trap = .out_of_bounds };
return bind(vals, inst.result, .{ .place = try m.extend(place, start + i) });
},
.slice_make => |v| {
const p = asPlace(vals[v]);
return bind(vals, inst.result, .{ .slice = .{ .place = p, .start = 0, .len = placePtr(p).array.len } });
},
.slice_len => |v| return bind(vals, inst.result, .{ .int = .{ .ty = .usize, .bits = vals[v].slice.len } }),
.slice_sub => |x| {
const s = vals[x.slice].slice;
const start = usize_(vals[x.start]);
const len = usize_(vals[x.len]);
if (start > s.len or len > s.len - start) return .{ .trap = .out_of_bounds };
return bind(vals, inst.result, .{ .slice = .{ .place = s.place, .start = s.start + start, .len = len } });
},
.slice_split => |x| {
const s = vals[x.slice].slice;
const at = usize_(vals[x.at]);
if (at > s.len) return .{ .trap = .out_of_bounds };
vals[inst.result.?] = .{ .slice = .{ .place = s.place, .start = s.start, .len = at } };
vals[inst.result2.?] = .{ .slice = .{ .place = s.place, .start = s.start + at, .len = s.len - at } };
return .next;
},
.slice_copy => |x| {
const d = vals[x.dst].slice;
const s = vals[x.src].slice;
if (d.len < s.len) return .{ .trap = .out_of_bounds };
const dst = placePtr(d.place).array;
const src = placePtr(s.place).array;
// Operands never overlap (spec 08 §11.2), so a forward copy is exact.
for (0..s.len) |k| dst[d.start + k] = try m.deepCopy(src[s.start + k]);
return .next;
},
.guard => |v| return if (vals[v].boolean) .next else .{ .trap = .assert },
else => unreachable,
}
}
fn gather(m: *Machine, vals: []const Value, ids: []const air.ValueId) ![]const Value {
return m.gatherMut(vals, ids);
}
fn gatherMut(m: *Machine, vals: []const Value, ids: []const air.ValueId) ![]Value {
const out = try m.arena.alloc(Value, ids.len);
for (ids, out) |id, *o| o.* = vals[id];
return out;
@@ -374,6 +542,13 @@ pub fn writeValue(module: air.Module, v: Value, s: *std.json.Stringify) std.Io.W
},
.boolean => |b| try s.write(b),
.void => try s.write(null),
.array => |items| {
try s.beginArray();
for (items) |x| try writeValue(module, x, s);
try s.endArray();
},
// Storage and borrows cannot be returned from `@main` (spec 08 §11.3).
.local, .place, .slice => try s.write(null),
.aggregate => |agg| {
const d = module.types[agg.decl];
switch (d.kind) {
+1 -1
View File
@@ -8,7 +8,7 @@ pub const version = "0.0.0-dev";
/// Highest plan phase (docs/plan/README.md) whose features are implemented.
/// Conformance tests for later phases are reported as PENDING.
pub const implemented_phase: u8 = 0;
pub const implemented_phase: u8 = 1;
pub const diag = @import("diag.zig");
pub const air = @import("air.zig");
+10 -1
View File
@@ -16,6 +16,9 @@ pub const budget = @import("verifier/budget.zig");
pub const cfg = @import("verifier/cfg.zig");
pub const ssa = @import("verifier/ssa.zig");
pub const types = @import("verifier/types.zig");
pub const init = @import("verifier/init.zig");
pub const borrow = @import("verifier/borrow.zig");
pub const bounds = @import("verifier/bounds.zig");
/// Shared state for one verification run.
pub const Context = struct {
@@ -23,6 +26,9 @@ pub const Context = struct {
file: []const u8,
module: air.Module,
diags: std.ArrayList(diag.Diagnostic) = .empty,
/// Type of every value, per function; filled by the types stage and
/// available to all later stages.
value_types: []const []const air.Type = &.{},
pub fn report(
c: *Context,
@@ -54,7 +60,7 @@ pub const Context = struct {
/// stage, or an empty slice if the module verifies.
pub fn verify(arena: std.mem.Allocator, file: []const u8, module: air.Module) std.mem.Allocator.Error![]const diag.Diagnostic {
var c: Context = .{ .arena = arena, .file = file, .module = module };
const stages = .{ budget.check, cfg.check, ssa.check, types.check };
const stages = .{ budget.check, cfg.check, ssa.check, types.check, init.check, borrow.check, bounds.check };
inline for (stages) |stage| {
try stage(&c);
if (c.diags.items.len != 0) {
@@ -78,6 +84,9 @@ test {
_ = cfg;
_ = ssa;
_ = types;
_ = init;
_ = borrow;
_ = bounds;
}
/// Test helper: parses `src` and verifies it, expecting exactly `codes`.
+418
View File
@@ -0,0 +1,418 @@
//! Borrow verification for frame storage (spec 08 §11).
//! Reports E2101, E2102, E2105, E2106, E2107, E2108.
//!
//! Every borrow value has static provenance fixed at its definition (root,
//! path, mode, parent). The only flow-sensitive state is the set of live
//! owned borrows. It must be identical on every edge into a block (§11.4),
//! so one walk over the reverse postorder decides each function. The walk
//! covers blocks reachable from the entry block; other blocks never execute.
const std = @import("std");
const air = @import("../air.zig");
const verifier = @import("../verifier.zig");
const ssa = @import("ssa.zig");
const Context = verifier.Context;
const ValueId = air.ValueId;
/// One step of a path from a root (§11.2).
const Seg = union(enum) {
field: u32,
/// One side of a `slice.split`, keyed by the split's left result.
split: struct { key: ValueId, side: u1 },
/// An element or sub-range; overlaps every sibling.
elem,
};
const Mode = enum { shared, exclusive };
const Info = struct {
/// Owned borrows are created in this function; lent ones are parameters.
owned: bool,
mode: Mode,
/// A local (`local.alloc` result) or a lent parameter.
root: ValueId,
path: []const Seg,
/// Owned borrow or lent parameter this borrow was derived from.
parent: ?ValueId,
};
pub fn check(c: *Context) !void {
// Signatures first: a borrow return needs `from` (§11.3).
for (c.module.functions) |f| {
if (f.ret.isBorrow() and f.ret_from == null) {
try c.report("E2102", f.span, "a function returning a borrow must name its source with `from`", &.{
.{ .name = "function", .value = .{ .str = f.name } },
});
}
}
if (c.diags.items.len != 0) return;
for (c.module.functions, c.value_types) |f, types| try checkFunction(c, f, types);
}
const Walker = struct {
c: *Context,
f: air.Function,
types: []const air.Type,
info: []?Info,
/// Live owned borrows in the current block.
live: []bool,
block: u32 = 0,
index: u32 = 0,
span: air.Span = .{ .line = 0, .col = 0 },
fn name(w: *Walker, v: ValueId) ![]const u8 {
return w.c.valueName(w.f, v);
}
fn report(w: *Walker, code: []const u8, message: []const u8, borrow: ValueId, extra: ?struct { []const u8, ValueId }) !void {
if (extra) |e| {
try w.c.report(code, w.span, message, &.{
.{ .name = "function", .value = .{ .str = w.f.name } },
.{ .name = "block", .value = .{ .str = w.f.blocks[w.block].name } },
.{ .name = "inst", .value = .{ .int = w.index } },
.{ .name = "borrow", .value = .{ .str = try w.name(borrow) } },
.{ .name = e[0], .value = .{ .str = try w.name(e[1]) } },
});
} else {
try w.c.report(code, w.span, message, &.{
.{ .name = "function", .value = .{ .str = w.f.name } },
.{ .name = "block", .value = .{ .str = w.f.blocks[w.block].name } },
.{ .name = "inst", .value = .{ .int = w.index } },
.{ .name = "borrow", .value = .{ .str = try w.name(borrow) } },
});
}
}
fn isAncestor(w: *Walker, anc: ValueId, of: ValueId) bool {
var x: ?ValueId = of;
while (x) |v| {
if (v == anc) return true;
x = if (w.info[v]) |i| i.parent else null;
}
return false;
}
/// Checks that `v`, used as a borrow, has not been ended (E2106).
fn usable(w: *Walker, v: ValueId) !bool {
const i = w.info[v].?;
if (!i.owned or w.live[v]) return true;
try w.report("E2106", "borrow used after it was ended", v, null);
return false;
}
/// An access to `path` under `root` with `mode`, performed through
/// `through` (a borrow whose ancestors do not conflict) or directly on a
/// local (`through == null`). Reports the first conflict (E2101).
fn access(w: *Walker, root: ValueId, path: []const Seg, mode: Mode, via: ?ValueId, who: ValueId) !void {
for (w.live, 0..) |is_live, cv| {
if (!is_live) continue;
const ci = w.info[cv].?;
if (ci.root != root) continue;
if (via) |t| if (w.isAncestor(@intCast(cv), t)) continue;
if (mode == .shared and ci.mode == .shared) continue;
if (!overlap(path, ci.path)) continue;
try w.report("E2101", "conflicting borrow or access", who, .{ "conflicts_with", @intCast(cv) });
return;
}
}
/// Records a new owned borrow and checks it against live borrows.
fn create(w: *Walker, v: ValueId, parent: ?ValueId, root: ValueId, path: []const Seg) !void {
const mode: Mode = if (w.types[v].isMutBorrow()) .exclusive else .shared;
w.info[v] = .{ .owned = true, .mode = mode, .root = root, .path = path, .parent = parent };
try w.access(root, path, mode, parent, v);
w.live[v] = true;
}
/// Creates a borrow derived from borrow `p` with an extra path step.
fn derive(w: *Walker, v: ValueId, p: ValueId, seg: ?Seg) !void {
if (!try w.usable(p)) return w.poison(v, p);
const pi = w.info[p].?;
try w.create(v, p, pi.root, try w.extend(pi.path, seg));
}
/// After an error, give `v` provenance so later uses do not cascade.
fn poison(w: *Walker, v: ValueId, p: ValueId) void {
const pi = w.info[p].?;
w.info[v] = .{ .owned = true, .mode = .shared, .root = pi.root, .path = pi.path, .parent = p };
w.live[v] = true;
}
fn extend(w: *Walker, path: []const Seg, seg: ?Seg) ![]const Seg {
const s = seg orelse return path;
const out = try w.c.arena.alloc(Seg, path.len + 1);
@memcpy(out[0..path.len], path);
out[path.len] = s;
return out;
}
/// Read or write through borrow `b` (load, store, slice.copy).
fn useThrough(w: *Walker, b: ValueId, mode: Mode) !void {
if (!try w.usable(b)) return;
const bi = w.info[b].?;
try w.access(bi.root, bi.path, mode, b, b);
}
fn isLocal(w: *Walker, v: ValueId) bool {
return w.types[v] == .local;
}
};
pub fn overlap(a: []const Seg, b: []const Seg) bool {
for (a[0..@min(a.len, b.len)], b[0..@min(a.len, b.len)]) |x, y| {
switch (x) {
.field => |fx| if (y == .field) {
if (fx != y.field) return false;
continue;
},
.split => |sx| if (y == .split and sx.key == y.split.key) {
if (sx.side != y.split.side) return false;
continue;
},
.elem => {},
}
return true;
}
return true; // one path is a prefix of the other
}
fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void {
var w: Walker = .{
.c = c,
.f = f,
.types = types,
.info = try c.arena.alloc(?Info, f.values.len),
.live = try c.arena.alloc(bool, f.values.len),
};
@memset(w.info, null);
@memset(w.live, false);
for (f.params) |p| if (p.ty.isBorrow()) {
w.info[p.value] = .{
.owned = false,
.mode = if (p.ty.isMutBorrow()) .exclusive else .shared,
.root = p.value,
.path = &.{},
.parent = null,
};
};
const dom = try ssa.dominators(c.arena, f);
const entry_state = try c.arena.alloc(?[]bool, f.blocks.len);
@memset(entry_state, null);
entry_state[0] = try c.arena.dupe(bool, w.live);
var reported_join = try c.arena.alloc(bool, f.blocks.len);
@memset(reported_join, false);
var succ: std.ArrayList(u32) = .empty;
for (dom.rpo) |b| {
@memcpy(w.live, entry_state[b].?);
w.block = b;
const blk = f.blocks[b];
for (blk.insts, 0..) |inst, ii| {
w.index = @intCast(ii);
w.span = inst.span;
try step(&w, inst);
}
// Propagate the exit state along every edge (§11.4).
succ.clearRetainingCapacity();
try air.successors(blk.insts[blk.insts.len - 1].op, &succ, c.arena);
for (succ.items) |s| {
if (entry_state[s]) |expected| {
if (!std.mem.eql(bool, expected, w.live) and !reported_join[s]) {
reported_join[s] = true;
for (expected, w.live, 0..) |a, x, v| if (a != x) {
try c.report("E2105", f.blocks[s].span, "borrow state differs between edges into this block", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "block", .value = .{ .str = f.blocks[s].name } },
.{ .name = "borrow", .value = .{ .str = try c.valueName(f, @intCast(v)) } },
});
break;
};
}
} else entry_state[s] = try c.arena.dupe(bool, w.live);
}
}
}
fn step(w: *Walker, inst: air.Inst) !void {
const f = w.f;
switch (inst.op) {
.local_store => |x| try w.access(x.local, &.{}, .exclusive, null, x.local),
.local_zero => |v| try w.access(v, &.{}, .exclusive, null, v),
.local_load => |v| try w.access(v, &.{}, .shared, null, v),
.borrow_ref, .borrow_mut => |x| {
const r = inst.result.?;
if (w.isLocal(x)) {
try w.create(r, null, x, &.{});
} else try w.derive(r, x, null);
},
.borrow_field => |x| try w.derive(inst.result.?, x.borrow, .{ .field = x.field }),
.borrow_index => |x| try w.derive(inst.result.?, x.borrow, .elem),
.slice_make => |v| try w.derive(inst.result.?, v, null),
.slice_sub => |x| try w.derive(inst.result.?, x.slice, .elem),
.slice_split => |x| {
const l = inst.result.?;
try w.derive(l, x.slice, .{ .split = .{ .key = l, .side = 0 } });
try w.derive(inst.result2.?, x.slice, .{ .split = .{ .key = l, .side = 1 } });
},
.slice_len => |v| _ = try w.usable(v), // metadata: no access to elements
.load => |v| try w.useThrough(v, .shared),
.store => |x| try w.useThrough(x.borrow, .exclusive),
.slice_copy => |x| {
try w.useThrough(x.src, .shared);
try w.useThrough(x.dst, .exclusive);
},
.borrow_end => |v| {
const i = w.info[v].?;
if (!i.owned) return w.report("E2107", "a borrow parameter is lent by the caller and cannot be ended", v, null);
if (!w.live[v]) return w.report("E2106", "borrow ended twice", v, null);
// Ended even when rejected, so one mistake yields one diagnostic.
defer w.live[v] = false;
for (w.live, 0..) |is_live, cv| {
if (is_live and w.info[cv].?.parent == v) {
return w.report("E2102", "borrow ended while a borrow derived from it is live", v, .{ "child", @intCast(cv) });
}
}
},
.call => |x| try callStep(w, inst, x.callee, x.args),
.ret => |v| try retStep(w, v),
// Values of these instructions are not borrows; any borrow operand
// here was already rejected by the type stage.
else => {},
}
_ = f;
}
fn callStep(w: *Walker, inst: air.Inst, callee_index: u32, args: []const ValueId) !void {
const callee = w.c.module.functions[callee_index];
// Arguments already reported; a conflict involving one of them is the
// same mistake and is not reported again.
const reported = try w.c.arena.alloc(bool, args.len);
@memset(reported, false);
for (args, 0..) |a, i| {
if (!w.types[a].isBorrow()) continue;
if (!try w.usable(a)) continue;
const ai = w.info[a].?;
// The argument is lent for the call: checked like a use of `a`.
const before = w.c.diags.items.len;
try w.access(ai.root, ai.path, ai.mode, a, a);
if (w.c.diags.items.len != before) {
reported[i] = true;
continue;
}
// Arguments must not alias each other if either is exclusive (§11.2).
for (args[0..i], 0..) |b, j| {
if (reported[j]) continue;
if (!w.types[b].isBorrow()) continue;
const bi = w.info[b].?;
if (bi.root != ai.root) continue;
if (ai.mode == .shared and bi.mode == .shared) continue;
if (overlap(ai.path, bi.path)) {
try w.report("E2101", "call arguments alias and one of them is exclusive", a, .{ "conflicts_with", b });
break;
}
}
}
if (callee.ret_from) |p| {
// The result borrows from the argument passed for `from` (§11.3).
const a = args[p];
if (!w.types[a].isBorrow() or w.info[a] == null) return;
try w.derive(inst.result.?, a, .elem);
}
}
fn retStep(w: *Walker, value: ?ValueId) !void {
const f = w.f;
var transferred: ?ValueId = null;
if (f.ret_from) |p| {
const pv = f.params[p].value;
const b = value.?;
if (!try w.usable(b)) return;
const bi = w.info[b].?;
if (bi.root != pv) {
if (w.isLocal(bi.root)) {
return w.report("E2108", "borrow of frame storage escapes its function", b, .{ "local", bi.root });
}
return w.report("E2102", "returned borrow does not derive from the `from` parameter", b, .{ "from", pv });
}
transferred = b;
}
// Only the returned borrow and its owned ancestors may remain live.
for (w.live, 0..) |is_live, v| {
if (!is_live) continue;
if (transferred) |t| if (w.isAncestor(@intCast(v), t)) continue;
try w.report("E2105", "borrow not ended before return", @intCast(v), null);
}
}
// ---------------------------------------------------------------- tests
const h = "module t\nair 0\nlang 0.1\nfeatures [arrays, ownership]\n";
fn fun(comptime sig: []const u8, comptime body: []const u8) []const u8 {
return h ++ "fn @f" ++ sig ++ "\neffects []\nentry:\n" ++ body;
}
const local_x = " %x = local.alloc u8\n local.zero %x\n";
test "exclusive XOR shared" {
try verifier.expectCodes(comptime fun("() -> void", local_x ++ " %a = borrow.mut %x\n %b = borrow.ref %x\n borrow.end %b\n borrow.end %a\n ret\n"), &.{"E2101"});
try verifier.expectCodes(comptime fun("() -> void", local_x ++ " %a = borrow.ref %x\n %b = borrow.ref %x\n borrow.end %b\n borrow.end %a\n ret\n"), &.{});
try verifier.expectCodes(comptime fun("() -> void", local_x ++ " %a = borrow.ref %x\n %one = const.u8 1\n local.store %x, %one\n borrow.end %a\n ret\n"), &.{"E2101"});
try verifier.expectCodes(comptime fun("() -> u8", local_x ++ " %a = borrow.ref %x\n %v = local.load %x\n borrow.end %a\n ret %v\n"), &.{});
try verifier.expectCodes(comptime fun("() -> u8", local_x ++ " %a = borrow.mut %x\n %v = local.load %x\n borrow.end %a\n ret %v\n"), &.{"E2101"});
}
test "reborrow freezes the parent" {
// Reading through a mut borrow while a shared child is live is fine;
// writing is not.
try verifier.expectCodes(comptime fun("() -> u8", local_x ++ " %m = borrow.mut %x\n %r = borrow.ref %m\n %v = load %m\n borrow.end %r\n borrow.end %m\n ret %v\n"), &.{});
try verifier.expectCodes(comptime fun("() -> void", local_x ++ " %m = borrow.mut %x\n %r = borrow.ref %m\n %z = const.u8 0\n store %m, %z\n borrow.end %r\n borrow.end %m\n ret\n"), &.{"E2101"});
try verifier.expectCodes(comptime fun("() -> void", local_x ++ " %m = borrow.mut %x\n %r = borrow.ref %m\n borrow.end %m\n borrow.end %r\n ret\n"), &.{"E2102"});
}
test "fields and split halves are disjoint" {
const s = h ++ "type @P = struct { a: u8, b: u8 }\n";
try verifier.expectCodes(s ++ "fn @f() -> void\neffects []\nentry:\n %x = local.alloc @P\n local.zero %x\n %m = borrow.mut %x\n %fa = borrow.field @P.a, %m\n %fb = borrow.field @P.b, %m\n borrow.end %fa\n borrow.end %fb\n borrow.end %m\n ret\n", &.{});
try verifier.expectCodes(s ++ "fn @f() -> void\neffects []\nentry:\n %x = local.alloc @P\n local.zero %x\n %m = borrow.mut %x\n %fa = borrow.field @P.a, %m\n %fb = borrow.field @P.a, %m\n borrow.end %fa\n borrow.end %fb\n borrow.end %m\n ret\n", &.{"E2101"});
const arr = " %x = local.alloc array<u8, 8>\n local.zero %x\n %m = borrow.mut %x\n %s = slice.make %m\n %k = const.usize 4\n %l, %r = slice.split %s, %k\n";
const ends = " borrow.end %l\n borrow.end %r\n borrow.end %s\n borrow.end %m\n ret\n";
try verifier.expectCodes(comptime fun("() -> void", arr ++ " %lr = borrow.ref %l\n slice.copy %r, %lr\n borrow.end %lr\n" ++ ends), &.{});
// Two element borrows of the same parent overlap.
try verifier.expectCodes(comptime fun("() -> void", arr ++ " %z = const.usize 0\n %e1 = borrow.index %l, %z\n %e2 = borrow.index %l, %z\n borrow.end %e1\n borrow.end %e2\n" ++ ends), &.{"E2101"});
// slice.copy within one slice: source and destination overlap.
try verifier.expectCodes(comptime fun("() -> void", arr ++ " %lr = borrow.ref %l\n slice.copy %l, %lr\n borrow.end %lr\n" ++ ends), &.{"E2101"});
}
test "path linearity" {
try verifier.expectCodes(comptime fun("(%c: bool) -> void", local_x ++ " %a = borrow.ref %x\n cbr %c, @p(), @q()\np:\n borrow.end %a\n ret\nq:\n borrow.end %a\n ret\n"), &.{});
try verifier.expectCodes(comptime fun("(%c: bool) -> void", local_x ++ " %a = borrow.ref %x\n cbr %c, @p(), @q()\np:\n borrow.end %a\n ret\nq:\n ret\n"), &.{"E2105"});
try verifier.expectCodes(comptime fun("(%c: bool) -> void", local_x ++ " %a = borrow.ref %x\n cbr %c, @p(), @q()\np:\n borrow.end %a\n br @j()\nq:\n br @j()\nj:\n ret\n"), &.{ "E2105", "E2105" });
try verifier.expectCodes(comptime fun("() -> void", local_x ++ " %a = borrow.ref %x\n borrow.end %a\n borrow.end %a\n ret\n"), &.{"E2106"});
try verifier.expectCodes(comptime fun("() -> u8", local_x ++ " %a = borrow.ref %x\n borrow.end %a\n %v = load %a\n ret %v\n"), &.{"E2106"});
// trap paths carry no obligation.
try verifier.expectCodes(comptime fun("() -> void", local_x ++ " %a = borrow.ref %x\n trap\n"), &.{});
}
test "loops end their borrows before the back edge" {
try verifier.expectCodes(comptime fun("(%c: bool) -> void", local_x ++ " br @loop()\nloop:\n %a = borrow.ref %x\n borrow.end %a\n cbr %c, @loop(), @out()\nout:\n ret\n"), &.{});
try verifier.expectCodes(comptime fun("(%c: bool) -> void", local_x ++ " br @loop()\nloop:\n %a = borrow.ref %x\n cbr %c, @loop(), @out()\nout:\n borrow.end %a\n ret\n"), &.{"E2105"});
}
test "returning borrows" {
try verifier.expectCodes(h ++ "fn @first(%s: slice<u8>) -> ref<u8> from %s\neffects []\nentry:\n %z = const.usize 0\n %e = borrow.index %s, %z\n ret %e\n", &.{});
try verifier.expectCodes(h ++ "fn @f(%s: slice<u8>) -> ref<u8>\neffects []\nentry:\n %z = const.usize 0\n %e = borrow.index %s, %z\n ret %e\n", &.{"E2102"});
try verifier.expectCodes(h ++ "fn @f(%p: ref<u8>) -> ref<u8> from %p\neffects []\nentry:\n" ++ local_x ++ " %b = borrow.ref %x\n ret %b\n", &.{"E2108"});
try verifier.expectCodes(h ++ "fn @f(%p: ref<u8>, %q: ref<u8>) -> ref<u8> from %p\neffects []\nentry:\n %b = borrow.ref %q\n ret %b\n", &.{"E2102"});
try verifier.expectCodes(h ++ "fn @f(%p: ref<u8>) -> void\neffects []\nentry:\n borrow.end %p\n ret\n", &.{"E2107"});
}
test "call results keep their source alive; mut arguments do not alias" {
const first = "fn @first(%s: slice<u8>) -> ref<u8> from %s\neffects []\nentry:\n %z = const.usize 0\n %e = borrow.index %s, %z\n ret %e\n";
const caller = "fn @f() -> u8\neffects []\nentry:\n %x = local.alloc array<u8, 4>\n local.zero %x\n %r = borrow.ref %x\n %s = slice.make %r\n %e = call @first(%s)\n";
try verifier.expectCodes(h ++ caller ++ " %v = load %e\n borrow.end %e\n borrow.end %s\n borrow.end %r\n ret %v\n" ++ first, &.{});
try verifier.expectCodes(h ++ caller ++ " borrow.end %s\n %v = load %e\n borrow.end %e\n borrow.end %r\n ret %v\n" ++ first, &.{"E2102"});
const two = "fn @g(%a: mut<u8>, %b: ref<u8>) -> void\neffects []\nentry:\n ret\n";
try verifier.expectCodes(h ++ "fn @f() -> void\neffects []\nentry:\n" ++ local_x ++ " %m = borrow.mut %x\n %r = borrow.ref %m\n call @g(%m, %r)\n borrow.end %r\n borrow.end %m\n ret\n" ++ two, &.{"E2101"});
}
+180
View File
@@ -0,0 +1,180 @@
//! Bounds facts for `borrow.index.proven` (spec 08 §12). Reports E2103.
//!
//! The analysis is exactly the fact table of the spec: no arithmetic, no
//! other comparisons, no other types. Accepting more or fewer programs would
//! be a conformance bug.
const std = @import("std");
const air = @import("../air.zig");
const verifier = @import("../verifier.zig");
const ssa = @import("ssa.zig");
const init = @import("init.zig");
const Context = verifier.Context;
const Fact = struct { i: air.ValueId, n: air.ValueId };
pub fn check(c: *Context) !void {
for (c.module.functions, c.value_types) |f, types| {
var any = false;
for (f.blocks) |b| for (b.insts) |inst| {
if (inst.op == .borrow_index and inst.op.borrow_index.proven) any = true;
};
if (any) try checkFunction(c, f, types);
}
}
fn defOf(f: air.Function, v: air.ValueId) ?air.Inst {
return switch (f.values[v].def) {
.inst => |d| f.blocks[d.block].insts[d.index],
else => null,
};
}
/// Fact established when `cond` is known to be `truth` (spec 08 §12 table).
fn factFrom(f: air.Function, cond: air.ValueId, truth: bool) ?Fact {
const inst = defOf(f, cond) orelse return null;
if (inst.op != .cmp) return null;
const x = inst.op.cmp;
if (x.ty != .int or x.ty.int != .usize) return null;
if (truth) return switch (x.op) {
.lt => .{ .i = x.a, .n = x.b },
.gt => .{ .i = x.b, .n = x.a },
else => null,
};
return switch (x.op) {
.ge => .{ .i = x.a, .n = x.b },
.le => .{ .i = x.b, .n = x.a },
else => null,
};
}
fn constUsize(f: air.Function, v: air.ValueId) ?u128 {
const inst = defOf(f, v) orelse return null;
if (inst.op != .@"const") return null;
const k = inst.op.@"const";
if (k.ty != .int or k.ty.int != .usize) return null;
return k.bits;
}
fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void {
const dom = try ssa.dominators(c.arena, f);
const preds = try init.predecessors(c.arena, f);
var facts: std.ArrayList(Fact) = .empty;
for (dom.rpo) |b| {
// Facts from cbr edges into b and its dominators.
facts.clearRetainingCapacity();
var d = b;
while (true) {
if (d != 0 and preds[d].len == 1) if (edgeFact(f, preds[d][0], d)) |fact| try facts.append(c.arena, fact);
// Guards anywhere in a strict dominator have executed before b.
if (d != b) for (f.blocks[d].insts) |inst| if (inst.op == .guard) {
if (factFrom(f, inst.op.guard, true)) |fact| try facts.append(c.arena, fact);
};
if (d == 0) break;
d = dom.idom[d];
}
for (f.blocks[b].insts, 0..) |inst, ii| {
switch (inst.op) {
.guard => |g| if (factFrom(f, g, true)) |fact| try facts.append(c.arena, fact),
.borrow_index => |x| if (x.proven and !proven(f, types, facts.items, x.borrow, x.index)) {
try c.report("E2103", inst.span, "element access not proven in bounds", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "block", .value = .{ .str = f.blocks[b].name } },
.{ .name = "inst", .value = .{ .int = @intCast(ii) } },
.{ .name = "borrow", .value = .{ .str = try c.valueName(f, x.borrow) } },
.{ .name = "index", .value = .{ .str = try c.valueName(f, x.index) } },
});
},
else => {},
}
}
}
}
/// Fact from the edge `from -> to`, if it is the only edge into `to`.
fn edgeFact(f: air.Function, from: u32, to: u32) ?Fact {
const term = f.blocks[from].insts[f.blocks[from].insts.len - 1].op;
if (term != .cbr) return null;
const x = term.cbr;
if (x.then.block == x.@"else".block) return null; // two edges into `to`
return factFrom(f, x.cond, x.then.block == to);
}
fn proven(f: air.Function, types: []const air.Type, facts: []const Fact, b: air.ValueId, i: air.ValueId) bool {
// Static length N when `b` borrows an `array<T, N>`.
const len: ?u64 = switch (types[b]) {
.ref, .mut => |inner| if (inner.* == .array) inner.array.len else null,
else => null,
};
if (len) |n| if (constUsize(f, i)) |k| if (k < n) return true;
for (facts) |fact| {
if (fact.i != i) continue;
if (defOf(f, fact.n)) |nd| if (nd.op == .slice_len and nd.op.slice_len == b) return true;
if (len) |n| if (constUsize(f, fact.n)) |k| if (k <= n) return true;
}
return false;
}
const h = "module t\nair 0\nlang 0.1\nfeatures [arrays, ownership]\n";
fn withSlice(comptime body: []const u8) []const u8 {
return h ++ "fn @f(%s: slice<u8>, %i: usize) -> u8\neffects []\nentry:\n %n = slice.len %s\n" ++ body;
}
const use = " %e = borrow.index.proven %s, %i\n %v = load %e\n borrow.end %e\n ret %v\n";
const out = "out:\n trap\n";
test "fact table: each established fact proves the access" {
try verifier.expectCodes(comptime withSlice(" %c = lt.usize %i, %n\n cbr %c, @in(), @out()\nin:\n" ++ use ++ out), &.{});
try verifier.expectCodes(comptime withSlice(" %c = gt.usize %n, %i\n cbr %c, @in(), @out()\nin:\n" ++ use ++ out), &.{});
try verifier.expectCodes(comptime withSlice(" %c = ge.usize %i, %n\n cbr %c, @out(), @in()\nin:\n" ++ use ++ out), &.{});
try verifier.expectCodes(comptime withSlice(" %c = le.usize %n, %i\n cbr %c, @out(), @in()\nin:\n" ++ use ++ out), &.{});
try verifier.expectCodes(comptime withSlice(" %c = lt.usize %i, %n\n guard %c\n" ++ use), &.{});
}
test "non-facts do not prove the access" {
// i <= n allows i == n.
try verifier.expectCodes(comptime withSlice(" %c = le.usize %i, %n\n cbr %c, @in(), @out()\nin:\n" ++ use ++ out), &.{"E2103"});
try verifier.expectCodes(comptime withSlice(" %c = ge.usize %n, %i\n cbr %c, @in(), @out()\nin:\n" ++ use ++ out), &.{"E2103"});
// Wrong edge.
try verifier.expectCodes(comptime withSlice(" %c = lt.usize %i, %n\n cbr %c, @out(), @in()\nin:\n" ++ use ++ out), &.{"E2103"});
// No fact at all.
try verifier.expectCodes(comptime withSlice(use), &.{"E2103"});
// Guard on a false-edge comparison establishes nothing.
try verifier.expectCodes(comptime withSlice(" %c = ge.usize %i, %n\n guard %c\n" ++ use), &.{"E2103"});
}
test "fact applies only to the same slice value" {
try verifier.expectCodes(h ++
\\fn @f(%s: slice<u8>, %t: slice<u8>, %i: usize) -> u8
\\effects []
\\entry:
\\ %n = slice.len %t
\\ %c = lt.usize %i, %n
\\ cbr %c, @in(), @out()
\\in:
\\ %e = borrow.index.proven %s, %i
\\ %v = load %e
\\ borrow.end %e
\\ ret %v
\\out:
\\ trap
\\
, &.{"E2103"});
}
test "constant cases on static arrays" {
const arr = h ++ "fn @f(%a: ref<array<u8, 4>>, %i: usize) -> u8\neffects []\nentry:\n";
const use_a = " %e = borrow.index.proven %a, %i\n %v = load %e\n borrow.end %e\n ret %v\n";
try verifier.expectCodes(arr ++ " %k = const.usize 3\n %e = borrow.index.proven %a, %k\n %v = load %e\n borrow.end %e\n ret %v\n", &.{});
try verifier.expectCodes(arr ++ " %k = const.usize 4\n %e = borrow.index.proven %a, %k\n %v = load %e\n borrow.end %e\n ret %v\n", &.{"E2103"});
try verifier.expectCodes(arr ++ " %k = const.usize 4\n %c = lt.usize %i, %k\n cbr %c, @in(), @out()\nin:\n" ++ use_a ++ out, &.{});
try verifier.expectCodes(arr ++ " %k = const.usize 5\n %c = lt.usize %i, %k\n cbr %c, @in(), @out()\nin:\n" ++ use_a ++ out, &.{"E2103"});
}
test "a cbr edge proves nothing when the target has other predecessors" {
try verifier.expectCodes(comptime withSlice(" %c = lt.usize %i, %n\n cbr %c, @in(), @other()\nother:\n br @in()\nin:\n" ++ use), &.{"E2103"});
}
+49 -1
View File
@@ -15,8 +15,37 @@ pub const Limits = struct {
pub const blocks = 16_384;
pub const insts = 262_144;
pub const cases = 4_096;
pub const local_frame = 1_048_576; // bytes, spec 08 §11.5
};
/// Accounted size in bytes (spec 08 §11.5). A counting rule, not a layout.
/// Recursive aggregates are reported later (E1003); they count as 0 here.
pub fn accountedSize(m: air.Module, t: air.Type, depth: usize) u64 {
if (depth > m.types.len + 1) return 0;
return switch (t) {
.int => |it| it.bits() / 8,
.bool => 1,
.array => |a| std.math.mul(u64, a.len, accountedSize(m, a.elem, depth + 1)) catch std.math.maxInt(u64),
.named => |i| switch (m.types[i].kind) {
.@"struct" => |fs| blk: {
var sum: u64 = 0;
for (fs) |f| sum +|= accountedSize(m, f.ty, depth + 1);
break :blk sum;
},
.@"enum" => |vs| blk: {
var max: u64 = 0;
for (vs) |v| {
var sum: u64 = 0;
for (v.payload) |p| sum +|= accountedSize(m, p, depth + 1);
max = @max(max, sum);
}
break :blk 4 +| max;
},
},
else => 0,
};
}
pub fn check(c: *verifier.Context) !void {
const m = c.module;
const origin: air.Span = .{ .line = 1, .col = 1 };
@@ -45,10 +74,15 @@ pub fn check(c: *verifier.Context) !void {
};
}
try limit(c, f.span, "instructions per function", Limits.insts, n);
var frame: u64 = 0;
for (f.blocks) |b| for (b.insts) |inst| if (inst.op == .local_alloc) {
frame +|= accountedSize(m, inst.op.local_alloc, 0);
};
try limit(c, f.span, "local frame bytes", Limits.local_frame, frame);
}
}
fn limit(c: *verifier.Context, span: air.Span, name: []const u8, max: usize, found: usize) !void {
fn limit(c: *verifier.Context, span: air.Span, name: []const u8, max: u64, found: u64) !void {
if (found <= max) return;
try c.report("E5101", span, "deterministic verifier resource limit exceeded", &.{
.{ .name = "limit", .value = .{ .str = name } },
@@ -65,3 +99,17 @@ test "too many parameters" {
try src.appendSlice(std.testing.allocator, ") -> void\neffects []\nentry:\n ret\n");
try verifier.expectCodes(src.items, &.{"E5101"});
}
test "local frame limit" {
const h = "module t\nair 0\nlang 0.1\nfeatures [arrays, ownership]\n";
try verifier.expectCodes(h ++ "fn @f() -> void\neffects []\nentry:\n %a = local.alloc array<u8, 1048576>\n ret\n", &.{});
try verifier.expectCodes(h ++ "fn @f() -> void\neffects []\nentry:\n %a = local.alloc array<u8, 1048576>\n %b = local.alloc u8\n ret\n", &.{"E5101"});
try verifier.expectCodes(h ++ "fn @f() -> void\neffects []\nentry:\n %a = local.alloc array<usize, 131073>\n ret\n", &.{"E5101"});
}
test "accounted sizes" {
const m: air.Module = .{ .name = "t", .format_version = 0, .lang = .{ 0, 1 }, .features = &.{}, .types = &.{}, .functions = &.{} };
try std.testing.expectEqual(@as(u64, 8), accountedSize(m, .{ .int = .isize }, 0));
try std.testing.expectEqual(@as(u64, 16), accountedSize(m, .{ .int = .u128 }, 0));
try std.testing.expectEqual(@as(u64, 1), accountedSize(m, .bool, 0));
}
+11
View File
@@ -14,6 +14,11 @@ fn checkFunction(c: *Context, f: air.Function) !void {
if (f.blocks.len == 0) return invalid(c, f, f.span, "function has no blocks", null);
if (f.blocks[0].params.len != 0) try invalid(c, f, f.blocks[0].span, "entry block must not declare parameters", f.blocks[0].name);
for (f.blocks[1..]) |b| for (b.insts) |inst| if (inst.op == .local_alloc) {
// Frame storage is static: allocated once per call (spec 08 §11.5).
try invalid(c, f, inst.span, "local.alloc outside the entry block", b.name);
};
for (f.blocks) |b| {
if (b.insts.len == 0) {
try invalid(c, f, b.span, "block has no terminator", b.name);
@@ -124,3 +129,9 @@ test "switch shapes" {
try verifier.expectCodes(e ++ "fn @f(%e: @E) -> void\neffects []\nentry:\n enum.switch @E %e, A -> @x, B -> @y\nx:\n ret\ny(%v: u8):\n ret\n", &.{});
try verifier.expectCodes(e ++ "fn @f(%e: @E) -> void\neffects []\nentry:\n enum.switch @E %e, A -> @x, default -> @x()\nx:\n ret\n", &.{});
}
test "local.alloc only in the entry block" {
const o = "module t\nair 0\nlang 0.1\nfeatures [ownership]\n";
try verifier.expectCodes(o ++ "fn @f() -> void\neffects []\nentry:\n %x = local.alloc u8\n br @next()\nnext:\n ret\n", &.{});
try verifier.expectCodes(o ++ "fn @f() -> void\neffects []\nentry:\n br @next()\nnext:\n %x = local.alloc u8\n ret\n", &.{"E5002"});
}
+173
View File
@@ -0,0 +1,173 @@
//! Initialization of frame storage (spec 08 §13). Reports E1010.
//!
//! Must-initialized dataflow over reachable blocks: a local is initialized
//! at a point if `local.store` or `local.zero` executed on every path to it.
const std = @import("std");
const air = @import("../air.zig");
const verifier = @import("../verifier.zig");
const ssa = @import("ssa.zig");
const Context = verifier.Context;
pub fn check(c: *Context) !void {
for (c.module.functions) |f| try checkFunction(c, f);
}
fn checkFunction(c: *Context, f: air.Function) !void {
// Number the locals of the function.
const slot = try c.arena.alloc(?u32, f.values.len);
@memset(slot, null);
var n: u32 = 0;
for (f.blocks) |b| for (b.insts) |inst| if (inst.op == .local_alloc) {
slot[inst.result.?] = n;
n += 1;
};
if (n == 0) return;
const dom = try ssa.dominators(c.arena, f);
const preds = try predecessors(c.arena, f);
// in[b]: locals initialized at entry of b; null until computed.
const in = try c.arena.alloc(?[]bool, f.blocks.len);
@memset(in, null);
const out = try c.arena.alloc([]bool, f.blocks.len);
for (out) |*o| {
o.* = try c.arena.alloc(bool, n);
@memset(o.*, true); // top element for the intersection
}
// Iterate to a fixpoint; the lattice is finite and transfer is monotone.
var changed = true;
while (changed) {
changed = false;
for (dom.rpo) |b| {
const state = try c.arena.alloc(bool, n);
if (b == 0) {
@memset(state, false);
} else {
@memset(state, true);
for (preds[b]) |p| if (dom.reachable(p)) {
for (state, out[p]) |*s, o| s.* = s.* and o;
};
}
in[b] = state;
const new = try c.arena.dupe(bool, state);
for (f.blocks[b].insts) |inst| transfer(inst.op, slot, new);
if (!std.mem.eql(bool, new, out[b])) {
out[b] = new;
changed = true;
}
}
}
// Report reads of locals that are not definitely initialized.
for (dom.rpo) |b| {
const state = try c.arena.dupe(bool, in[b].?);
for (f.blocks[b].insts, 0..) |inst, ii| {
const read: ?air.ValueId = switch (inst.op) {
.local_load, .borrow_ref, .borrow_mut => |v| v,
else => null,
};
if (read) |v| if (slot[v]) |s| if (!state[s]) {
try c.report("E1010", inst.span, "local read or borrowed before it is initialized on every path", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "block", .value = .{ .str = f.blocks[b].name } },
.{ .name = "inst", .value = .{ .int = @intCast(ii) } },
.{ .name = "local", .value = .{ .str = try c.valueName(f, v) } },
});
};
transfer(inst.op, slot, state);
}
}
}
fn transfer(op: air.Op, slot: []const ?u32, state: []bool) void {
switch (op) {
.local_store => |x| if (slot[x.local]) |s| {
state[s] = true;
},
.local_zero => |v| if (slot[v]) |s| {
state[s] = true;
},
else => {},
}
}
pub fn predecessors(arena: std.mem.Allocator, f: air.Function) ![]const []const u32 {
var lists = try arena.alloc(std.ArrayList(u32), f.blocks.len);
for (lists) |*l| l.* = .empty;
var succ: std.ArrayList(u32) = .empty;
for (f.blocks, 0..) |b, i| {
succ.clearRetainingCapacity();
try air.successors(b.insts[b.insts.len - 1].op, &succ, arena);
for (succ.items) |s| {
// A block reached twice from the same terminator has one predecessor.
if (std.mem.indexOfScalar(u32, lists[s].items, @intCast(i)) == null) try lists[s].append(arena, @intCast(i));
}
}
const out = try arena.alloc([]const u32, f.blocks.len);
for (lists, out) |l, *o| o.* = l.items;
return out;
}
const h = "module t\nair 0\nlang 0.1\nfeatures [ownership]\n";
test "initialization" {
try verifier.expectCodes(h ++ "fn @f() -> u8\neffects []\nentry:\n %x = local.alloc u8\n %v = local.load %x\n ret %v\n", &.{"E1010"});
try verifier.expectCodes(h ++ "fn @f() -> u8\neffects []\nentry:\n %x = local.alloc u8\n local.zero %x\n %v = local.load %x\n ret %v\n", &.{});
// Initialized on one path only.
try verifier.expectCodes(h ++
\\fn @f(%c: bool) -> u8
\\effects []
\\entry:
\\ %x = local.alloc u8
\\ cbr %c, @a(), @b()
\\a:
\\ %one = const.u8 1
\\ local.store %x, %one
\\ br @join()
\\b:
\\ br @join()
\\join:
\\ %v = local.load %x
\\ ret %v
\\
, &.{"E1010"});
// Initialized on both paths.
try verifier.expectCodes(h ++
\\fn @f(%c: bool) -> u8
\\effects []
\\entry:
\\ %x = local.alloc u8
\\ cbr %c, @a(), @b()
\\a:
\\ %one = const.u8 1
\\ local.store %x, %one
\\ br @join()
\\b:
\\ local.zero %x
\\ br @join()
\\join:
\\ %r = borrow.ref %x
\\ %v = load %r
\\ borrow.end %r
\\ ret %v
\\
, &.{});
// Initialization inside a loop body does not reach the loop header.
try verifier.expectCodes(h ++
\\fn @f(%c: bool) -> u8
\\effects []
\\entry:
\\ %x = local.alloc u8
\\ br @loop()
\\loop:
\\ %v = local.load %x
\\ local.zero %x
\\ cbr %c, @loop(), @out()
\\out:
\\ ret %v
\\
, &.{"E1010"});
}
+209 -16
View File
@@ -14,7 +14,9 @@ const Type = air.Type;
pub fn check(c: *Context) !void {
try checkDeclarations(c);
if (c.diags.items.len != 0) return;
for (c.module.functions) |f| try checkFunction(c, f);
const all = try c.arena.alloc([]const Type, c.module.functions.len);
for (c.module.functions, all) |f, *out| out.* = try checkFunction(c, f);
c.value_types = all;
}
// ---------------------------------------------------------------- declarations
@@ -22,12 +24,30 @@ pub fn check(c: *Context) !void {
fn checkDeclarations(c: *Context) !void {
const m = c.module;
for (m.types) |d| switch (d.kind) {
.@"struct" => |fs| for (fs) |fld| try valueType(c, d.span, fld.ty, d.name),
.@"enum" => |vs| for (vs) |v| for (v.payload) |t| try valueType(c, d.span, t, d.name),
.@"struct" => |fs| for (fs) |fld| try wellFormed(c, d.span, fld.ty, .member, d.name),
.@"enum" => |vs| for (vs) |v| for (v.payload) |t| try wellFormed(c, d.span, t, .member, d.name),
};
for (m.functions) |f| {
for (f.params) |p| try valueType(c, f.span, p.ty, f.name);
for (f.blocks) |b| for (b.params) |p| try valueType(c, b.span, p.ty, f.name);
for (f.params) |p| try wellFormed(c, f.span, p.ty, .param, f.name);
try wellFormed(c, f.span, f.ret, .ret, f.name);
if (f.ret_from) |i| {
const p = f.params[i].ty;
if (!f.ret.isBorrow() or !p.isBorrow() or (f.ret.isMutBorrow() and !p.isMutBorrow())) {
try c.report("E1001", f.span, "`from` requires a borrow return and a borrow parameter whose mode allows the result mode", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "ret", .value = .{ .str = try c.typeName(f.ret) } },
.{ .name = "from", .value = .{ .str = try c.typeName(p) } },
});
}
}
for (f.blocks) |b| {
for (b.params) |p| try wellFormed(c, b.span, p.ty, .block_param, f.name);
for (b.insts) |inst| switch (inst.op) {
.local_alloc => |t| try wellFormed(c, inst.span, t, .member, f.name),
.array_splat => |x| try wellFormed(c, inst.span, x.ty, .member, f.name),
else => {},
};
}
}
// E1003: an aggregate that contains itself by value has no finite size.
@@ -52,13 +72,42 @@ fn visitDecl(c: *Context, state: anytype, i: u32) !void {
state[i] = .black;
}
/// `void` and `never` are only valid as function return types (spec 07 §8.3).
fn valueType(c: *Context, span: air.Span, t: Type, owner: []const u8) !void {
if (t != .void and t != .never) return;
try c.report("E1001", span, "`void` and `never` are only valid as function return types", &.{
const Position = enum { member, param, ret, block_param };
/// Where a type may appear (spec 07 §8.3, §8.8):
/// - `void`/`never` only as return types;
/// - storage (`local<T>`) only as the result of `local.alloc`;
/// - borrows only as parameters, returns and (gated) block parameters,
/// never as members (fields, payloads, elements, locals);
/// - the inner type of every compound type is a value type.
fn wellFormed(c: *Context, span: air.Span, t: Type, pos: Position, owner: []const u8) !void {
const ok = switch (t) {
.void, .never => pos == .ret,
.local => false,
.ref, .mut, .slice, .slice_mut => pos != .member,
else => true,
};
if (!ok) try c.report("E1001", span, "type not allowed in this position", &.{
.{ .name = "in", .value = .{ .str = owner } },
.{ .name = "found", .value = .{ .str = @tagName(t) } },
.{ .name = "position", .value = .{ .str = @tagName(pos) } },
.{ .name = "found", .value = .{ .str = try c.typeName(t) } },
});
if (t.inner()) |inner| try wellFormed(c, span, inner, .member, owner);
}
/// `local.alloc` results are checked separately: their own type is storage.
fn zeroable(m: air.Module, t: Type) bool {
return switch (t) {
.int, .bool => true,
.array => |a| zeroable(m, a.elem),
.named => |i| switch (m.types[i].kind) {
.@"struct" => |fs| for (fs) |f| {
if (!zeroable(m, f.ty)) break false;
} else true,
.@"enum" => false,
},
else => false,
};
}
// ---------------------------------------------------------------- functions
@@ -86,6 +135,17 @@ const FnCtx = struct {
});
}
fn kindError(fc: *FnCtx, span: air.Span, v: air.ValueId, expected: []const u8) !void {
try fc.c.report("E1001", span, "operand has the wrong kind of type", &.{
.{ .name = "function", .value = .{ .str = fc.f.name } },
.{ .name = "block", .value = .{ .str = fc.f.blocks[fc.block].name } },
.{ .name = "inst", .value = .{ .int = fc.index } },
.{ .name = "operand", .value = .{ .str = try fc.c.valueName(fc.f, v) } },
.{ .name = "expected", .value = .{ .str = expected } },
.{ .name = "found", .value = .{ .str = try fc.c.typeName(fc.typeOf(v)) } },
});
}
fn expectValue(fc: *FnCtx, span: air.Span, v: air.ValueId, expected: Type) !void {
const found = fc.typeOf(v);
if (!found.eql(expected)) try fc.mismatch(span, try fc.c.valueName(fc.f, v), expected, found);
@@ -121,16 +181,84 @@ fn resultType(m: air.Module, op: air.Op) ?Type {
.struct_get => |x| m.types[x.decl].kind.@"struct"[x.field].ty,
.enum_make => |x| .{ .named = x.decl },
.call => |x| m.functions[x.callee].ret,
.slice_len => .{ .int = .usize },
.array_splat => |x| x.ty,
else => null,
};
}
fn checkFunction(c: *Context, f: air.Function) !void {
fn boxed(arena: std.mem.Allocator, t: Type) !*const Type {
const b = try arena.create(Type);
b.* = t;
return b;
}
/// Result type of an instruction whose result depends on operand types.
/// Returns null while an operand is unresolved, and `.void` (which no later
/// check accepts) if the operand has the wrong kind; `checkInst` reports that.
fn derivedType(fc: *FnCtx, op: air.Op) !?Type {
const a = fc.c.arena;
const m = fc.c.module;
const t = switch (op) {
.copy => |v| return fc.ty[v],
.local_alloc => |inner| return .{ .local = try boxed(a, inner) },
.local_load => |v| fc.ty[v] orelse return null,
.borrow_ref, .borrow_mut, .load, .slice_make => |v| fc.ty[v] orelse return null,
.borrow_field => |x| fc.ty[x.borrow] orelse return null,
.borrow_index => |x| fc.ty[x.borrow] orelse return null,
.slice_sub => |x| fc.ty[x.slice] orelse return null,
.slice_split => |x| fc.ty[x.slice] orelse return null,
else => return null,
};
const invalid: Type = .void;
return switch (op) {
.local_load => if (t == .local) t.local.* else invalid,
.borrow_ref => switch (t) {
.local, .ref, .mut => .{ .ref = try boxed(a, t.inner().?) },
.slice, .slice_mut => .{ .slice = try boxed(a, t.inner().?) },
else => invalid,
},
.borrow_mut => switch (t) {
.local, .mut => .{ .mut = try boxed(a, t.inner().?) },
.slice_mut => .{ .slice_mut = try boxed(a, t.inner().?) },
else => invalid,
},
.borrow_field => |x| switch (t) {
.ref, .mut => |inner| if (inner.* == .named and inner.named == x.decl) blk: {
const fty = try boxed(a, m.types[x.decl].kind.@"struct"[x.field].ty);
break :blk if (t == .ref) Type{ .ref = fty } else Type{ .mut = fty };
} else invalid,
else => invalid,
},
.load => if (t == .ref or t == .mut) t.inner().? else invalid,
.borrow_index => switch (t) {
.ref, .mut => |inner| if (inner.* == .array) blk: {
const e = try boxed(a, inner.array.elem);
break :blk if (t == .ref) Type{ .ref = e } else Type{ .mut = e };
} else invalid,
.slice => |e| .{ .ref = e },
.slice_mut => |e| .{ .mut = e },
else => invalid,
},
.slice_make => switch (t) {
.ref, .mut => |inner| if (inner.* == .array) blk: {
const e = try boxed(a, inner.array.elem);
break :blk if (t == .ref) Type{ .slice = e } else Type{ .slice_mut = e };
} else invalid,
else => invalid,
},
.slice_sub, .slice_split => if (t.isSlice()) t else invalid,
else => unreachable,
};
}
fn checkFunction(c: *Context, f: air.Function) ![]const Type {
const m = c.module;
var fc: FnCtx = .{ .c = c, .f = f, .ty = try c.arena.alloc(?Type, f.values.len) };
@memset(fc.ty, null);
// Seed types from declarations and opcodes, then resolve `copy` chains.
// Seed types from declarations and opcodes, then resolve types that
// depend on operand types (`copy`, borrows, slices) to a fixpoint.
for (f.params) |p| fc.ty[p.value] = p.ty;
for (f.blocks) |b| {
for (b.params) |p| fc.ty[p.value] = p.ty;
@@ -143,14 +271,15 @@ fn checkFunction(c: *Context, f: air.Function) !void {
progress = false;
for (f.blocks) |b| for (b.insts) |inst| {
const r = inst.result orelse continue;
if (fc.ty[r] != null or inst.op != .copy) continue;
if (fc.ty[inst.op.copy]) |t| {
if (fc.ty[r] != null) continue;
if (try derivedType(&fc, inst.op)) |t| {
fc.ty[r] = t;
if (inst.result2) |r2| fc.ty[r2] = t;
progress = true;
}
};
}
// A `copy` cycle can only occur in unreachable code; give it a type that
// A cycle can only occur in unreachable code; give it a type that
// cannot satisfy any later check rather than leaving it unresolved.
for (fc.ty) |*t| if (t.* == null) {
t.* = .void;
@@ -163,6 +292,9 @@ fn checkFunction(c: *Context, f: air.Function) !void {
try checkInst(&fc, inst);
}
}
const out = try c.arena.alloc(Type, f.values.len);
for (fc.ty, out) |t, *o| o.* = t.?;
return out;
}
fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
@@ -170,7 +302,64 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
const f = fc.f;
const span = inst.span;
switch (inst.op) {
.@"const", .copy, .trap => {},
.@"const", .trap => {},
.copy => |v| if (!fc.typeOf(v).isValue()) try fc.c.report("E1001", span, "only value types can be copied", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "found", .value = .{ .str = try fc.c.typeName(fc.typeOf(v)) } },
}),
.local_alloc, .slice_len => {},
.local_store => |x| {
const t = fc.typeOf(x.local);
if (t != .local) return fc.kindError(span, x.local, "local<T>");
try fc.expectValue(span, x.value, t.local.*);
},
.local_zero => |v| {
const t = fc.typeOf(v);
if (t != .local) return fc.kindError(span, v, "local<T>");
if (!zeroable(m, t.local.*)) try fc.c.report("E1001", span, "type is not zeroable", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "found", .value = .{ .str = try fc.c.typeName(t.local.*) } },
});
},
.local_load => |v| if (fc.typeOf(v) != .local) try fc.kindError(span, v, "local<T>"),
.borrow_ref => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "local<T>, ref<T>, mut<T>, slice<T> or slice_mut<T>"),
.borrow_mut => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "local<T>, mut<T> or slice_mut<T>"),
.borrow_field => |x| if (resultOf(fc, inst) == .void) try fc.kindError(span, x.borrow, "ref or mut of the named struct"),
.borrow_end => |v| if (!fc.typeOf(v).isBorrow()) try fc.kindError(span, v, "a borrow"),
.load => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "ref<T> or mut<T>"),
.store => |x| {
const t = fc.typeOf(x.borrow);
if (t != .mut) return fc.kindError(span, x.borrow, "mut<T>");
try fc.expectValue(span, x.value, t.mut.*);
},
.array_splat => |x| {
if (x.ty != .array) return fc.c.report("E1001", span, "array.splat needs an array type", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "found", .value = .{ .str = try fc.c.typeName(x.ty) } },
});
try fc.expectValue(span, x.value, x.ty.array.elem);
},
.borrow_index => |x| {
if (resultOf(fc, inst) == .void) return fc.kindError(span, x.borrow, "a borrow of an array, or a slice");
try fc.expectValue(span, x.index, .{ .int = .usize });
},
.slice_make => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "ref or mut of an array"),
.slice_sub => |x| {
if (!fc.typeOf(x.slice).isSlice()) return fc.kindError(span, x.slice, "a slice");
try fc.expectValue(span, x.start, .{ .int = .usize });
try fc.expectValue(span, x.len, .{ .int = .usize });
},
.slice_split => |x| {
if (!fc.typeOf(x.slice).isSlice()) return fc.kindError(span, x.slice, "a slice");
try fc.expectValue(span, x.at, .{ .int = .usize });
},
.slice_copy => |x| {
const d = fc.typeOf(x.dst);
if (d != .slice_mut) return fc.kindError(span, x.dst, "slice_mut<T>");
const s = fc.typeOf(x.src);
if (!s.isSlice() or !s.inner().?.eql(d.inner().?)) return fc.kindError(span, x.src, try std.fmt.allocPrint(fc.c.arena, "slice<{s}> or slice_mut<{s}>", .{ try fc.c.typeName(d.inner().?), try fc.c.typeName(d.inner().?) }));
},
.guard => |v| try fc.expectValue(span, v, .bool),
.arith => |x| {
try fc.expectValue(span, x.a, .{ .int = x.ty });
try fc.expectValue(span, x.b, .{ .int = x.ty });
@@ -251,6 +440,10 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
}
}
fn resultOf(fc: *FnCtx, inst: air.Inst) Type {
return fc.typeOf(inst.result.?);
}
/// Every value of `from` is representable in `to` (spec 02 §2.1).
pub fn lossless(from: air.IntType, to: air.IntType) bool {
if (from.pointerSized() or to.pointerSized()) return false;