verifier: resource limits, CFG, SSA dominance and types (P0-7..P0-10)

- verifier.zig: staged pipeline per spec 07 §8.6, deterministic order
- budget.zig: fixed limits from spec 08 §7 (E5101)
- cfg.zig: terminators, branch arity, switch/enum.switch shape (E5002)
- ssa.zig: Cooper-Harvey-Kennedy dominators, use dominance (E5001)
- types.zig: operand/result types, casts, calls, returns, recursive
  aggregates (E1001, E1002, E1003)
- check.zig runs parse -> verify; seed conformance tests get module
  headers; tests for unimplemented phases report PENDING
This commit is contained in:
dev committed 2026-10-04 12:24:41 +03:00
1 parent ef6a2c5475
commit 50bf990355
14 files changed
+892 -11

No files matched your search

+11 -6
View File
@@ -1,8 +1,10 @@
//! Front door used by the CLI, the conformance runner and (later) `ajid`:
//! parse → verify, collecting diagnostics.
//! parse → verify, collecting diagnostics (spec 07 §8.6).
const std = @import("std");
const air = @import("air.zig");
const diag = @import("diag.zig");
const verifier = @import("verifier.zig");
pub const Status = enum {
/// Module verified; no error diagnostics.
@@ -16,15 +18,18 @@ pub const Status = enum {
pub const Report = struct {
status: Status,
diagnostics: []const diag.Diagnostic,
/// Present when `status == .accepted`.
module: ?air.Module = null,
/// Pipeline stage that is missing when `status == .unimplemented`.
missing_stage: []const u8 = "",
};
/// Checks a text AIR module. All allocations go into `arena`.
pub fn checkAir(arena: std.mem.Allocator, file_name: []const u8, source: []const u8) !Report {
_ = arena;
_ = file_name;
_ = source;
// TODO(phase-0): air.parse → verifier.verify.
return .{ .status = .unimplemented, .diagnostics = &.{}, .missing_stage = "air.parse" };
const parsed = try air.parse.parse(arena, file_name, source);
if (parsed.diagnostics.len != 0) return .{ .status = .rejected, .diagnostics = parsed.diagnostics };
const module = parsed.module.?;
const ds = try verifier.verify(arena, file_name, module);
if (ds.len != 0) return .{ .status = .rejected, .diagnostics = ds };
return .{ .status = .accepted, .diagnostics = &.{}, .module = module };
}
+4
View File
@@ -6,6 +6,10 @@
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 diag = @import("diag.zig");
pub const air = @import("air.zig");
pub const verifier = @import("verifier.zig");
+98 -5
View File
@@ -1,8 +1,101 @@
//! AIR verifier (spec 08). Part of the language semantics, not a lint.
//!
//! Passes are added in plan order (docs/plan/README.md). Each normative rejection MUST map to a
//! code in `diag.registry` and MUST have positive and negative conformance
//! tests under tests/conformance/.
//! Passes are added in plan order (docs/plan/README.md). Each normative
//! rejection maps to a code in `diag.registry` and has accept and reject
//! conformance tests under tests/conformance/.
//!
//! Phase 0: SSA/dominance (E5001), CFG/terminators (E5002), types (E1001),
//! deterministic resource budget (E5101).
//! Stages run in the order of spec 07 §8.6 and verification stops after the
//! first stage that reports an error, so later stages may assume the
//! invariants established by earlier ones.
const std = @import("std");
const air = @import("air.zig");
const diag = @import("diag.zig");
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");
/// Shared state for one verification run.
pub const Context = struct {
arena: std.mem.Allocator,
file: []const u8,
module: air.Module,
diags: std.ArrayList(diag.Diagnostic) = .empty,
pub fn report(
c: *Context,
id: []const u8,
span: air.Span,
message: []const u8,
fields: []const diag.Field,
) std.mem.Allocator.Error!void {
try c.diags.append(c.arena, .{
.code = diag.lookup(id).?,
.span = .{ .file = c.file, .line = span.line, .col = span.col },
.message = message,
.fields = try c.arena.dupe(diag.Field, fields),
});
}
pub fn valueName(c: *Context, f: air.Function, v: air.ValueId) std.mem.Allocator.Error![]const u8 {
return std.fmt.allocPrint(c.arena, "%{s}", .{f.values[v].name});
}
pub fn typeName(c: *Context, t: air.Type) std.mem.Allocator.Error![]const u8 {
var w: std.Io.Writer.Allocating = .init(c.arena);
air.print.printType(c.module, t, &w.writer) catch return error.OutOfMemory;
return w.written();
}
};
/// Runs all verifier stages. Returns the diagnostics of the first failing
/// 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 };
inline for (stages) |stage| {
try stage(&c);
if (c.diags.items.len != 0) {
std.mem.sort(diag.Diagnostic, c.diags.items, {}, bySpan);
return c.diags.items;
}
}
return &.{};
}
fn bySpan(_: void, a: diag.Diagnostic, b: diag.Diagnostic) bool {
const sa = a.span.?;
const sb = b.span.?;
if (sa.line != sb.line) return sa.line < sb.line;
if (sa.col != sb.col) return sa.col < sb.col;
return std.mem.lessThan(u8, a.code.id, b.code.id);
}
test {
_ = budget;
_ = cfg;
_ = ssa;
_ = types;
}
/// Test helper: parses `src` and verifies it, expecting exactly `codes`.
pub fn expectCodes(src: []const u8, codes: []const []const u8) !void {
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
const r = try air.parse.parse(arena, "t.air", src);
if (r.diagnostics.len != 0) {
for (r.diagnostics) |d| std.debug.print("parse: {s} {s}\n", .{ d.code.id, d.message });
return error.ParseFailed;
}
const ds = try verify(arena, "t.air", r.module.?);
if (ds.len != codes.len) {
for (ds) |d| std.debug.print("got {s} {s} at {d}:{d}\n", .{ d.code.id, d.message, d.span.?.line, d.span.?.col });
return error.TestExpectedEqual;
}
for (codes, ds) |c, d| try std.testing.expectEqualStrings(c, d.code.id);
}
pub const test_header = "module t\nair 0\nlang 0.1\nfeatures []\n";
+67
View File
@@ -0,0 +1,67 @@
//! Deterministic verifier resource limits (spec 08 §7, E5101).
//!
//! Limits are fixed by the spec so that no flag can change which programs
//! are accepted.
const std = @import("std");
const air = @import("../air.zig");
const verifier = @import("../verifier.zig");
pub const Limits = struct {
pub const functions = 65_536;
pub const types = 65_536;
pub const members = 256; // fields, variants, payload values
pub const params = 64; // per function or block; arguments per call or branch
pub const blocks = 16_384;
pub const insts = 262_144;
pub const cases = 4_096;
};
pub fn check(c: *verifier.Context) !void {
const m = c.module;
const origin: air.Span = .{ .line = 1, .col = 1 };
try limit(c, origin, "functions per module", Limits.functions, m.functions.len);
try limit(c, origin, "type declarations per module", Limits.types, m.types.len);
for (m.types) |d| switch (d.kind) {
.@"struct" => |fs| try limit(c, d.span, "fields per struct", Limits.members, fs.len),
.@"enum" => |vs| {
try limit(c, d.span, "variants per enum", Limits.members, vs.len);
for (vs) |v| try limit(c, d.span, "payload values per variant", Limits.members, v.payload.len);
},
};
for (m.functions) |f| {
try limit(c, f.span, "parameters per function", Limits.params, f.params.len);
try limit(c, f.span, "blocks per function", Limits.blocks, f.blocks.len);
var n: usize = 0;
for (f.blocks) |b| {
n += b.insts.len;
try limit(c, b.span, "parameters per block", Limits.params, b.params.len);
for (b.insts) |inst| switch (inst.op) {
.call => |x| try limit(c, inst.span, "arguments per call", Limits.params, x.args.len),
.struct_make => |x| try limit(c, inst.span, "arguments per call", Limits.params, x.args.len),
.enum_make => |x| try limit(c, inst.span, "arguments per call", Limits.params, x.args.len),
.@"switch" => |x| try limit(c, inst.span, "cases per switch", Limits.cases, x.cases.len),
else => {},
};
}
try limit(c, f.span, "instructions per function", Limits.insts, n);
}
}
fn limit(c: *verifier.Context, span: air.Span, name: []const u8, max: usize, found: usize) !void {
if (found <= max) return;
try c.report("E5101", span, "deterministic verifier resource limit exceeded", &.{
.{ .name = "limit", .value = .{ .str = name } },
.{ .name = "max", .value = .{ .int = @intCast(max) } },
.{ .name = "found", .value = .{ .int = @intCast(found) } },
});
}
test "too many parameters" {
var src: std.ArrayList(u8) = .empty;
defer src.deinit(std.testing.allocator);
try src.appendSlice(std.testing.allocator, verifier.test_header ++ "fn @f(");
for (0..65) |i| try src.print(std.testing.allocator, "{s}%p{d}: u8", .{ if (i == 0) "" else ", ", i });
try src.appendSlice(std.testing.allocator, ") -> void\neffects []\nentry:\n ret\n");
try verifier.expectCodes(src.items, &.{"E5101"});
}
+126
View File
@@ -0,0 +1,126 @@
//! CFG structure (spec 07 §8.2, spec 07a terminators). Reports E5002.
const std = @import("std");
const air = @import("../air.zig");
const verifier = @import("../verifier.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 {
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) |b| {
if (b.insts.len == 0) {
try invalid(c, f, b.span, "block has no terminator", b.name);
continue;
}
for (b.insts[0 .. b.insts.len - 1]) |inst| {
if (inst.op.isTerminator()) try invalid(c, f, inst.span, "terminator before the end of the block", b.name);
}
const last = b.insts[b.insts.len - 1];
if (!last.op.isTerminator()) {
try invalid(c, f, last.span, "block does not end with a terminator", b.name);
continue;
}
try checkTerminator(c, f, last);
}
}
fn checkTerminator(c: *Context, f: air.Function, inst: air.Inst) !void {
switch (inst.op) {
.br => |t| try arity(c, f, inst.span, t),
.cbr => |x| {
try arity(c, f, inst.span, x.then);
try arity(c, f, inst.span, x.@"else");
},
.@"switch" => |x| {
for (x.cases, 0..) |case, i| {
try arity(c, f, case.span, case.target);
for (x.cases[0..i]) |prev| if (prev.bits == case.bits)
try invalid(c, f, case.span, "duplicate switch case", null);
}
try arity(c, f, inst.span, x.default);
},
.enum_switch => |x| {
const variants = c.module.types[x.decl].kind.@"enum";
for (x.arms, 0..) |arm, i| {
for (x.arms[0..i]) |prev| if (prev.variant == arm.variant)
try invalid(c, f, arm.span, "duplicate enum.switch arm", null);
const blk = f.blocks[arm.block];
if (blk.params.len != variants[arm.variant].payload.len) {
try c.report("E5002", arm.span, "arm target parameters do not match the variant payload", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "block", .value = .{ .str = blk.name } },
.{ .name = "expected", .value = .{ .int = @intCast(variants[arm.variant].payload.len) } },
.{ .name = "found", .value = .{ .int = @intCast(blk.params.len) } },
});
}
}
if (x.default) |d| {
try arity(c, f, inst.span, d);
} else {
for (variants, 0..) |v, vi| {
const covered = for (x.arms) |arm| {
if (arm.variant == vi) break true;
} else false;
if (!covered) try c.report("E5002", inst.span, "enum.switch is not exhaustive and has no default", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "missing_variant", .value = .{ .str = v.name } },
});
}
}
},
.ret, .trap => {},
else => unreachable,
}
}
fn arity(c: *Context, f: air.Function, span: air.Span, t: air.Target) !void {
const blk = f.blocks[t.block];
if (blk.params.len == t.args.len) return;
try c.report("E5002", span, "branch argument count does not match block parameters", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "block", .value = .{ .str = blk.name } },
.{ .name = "expected", .value = .{ .int = @intCast(blk.params.len) } },
.{ .name = "found", .value = .{ .int = @intCast(t.args.len) } },
});
}
fn invalid(c: *Context, f: air.Function, span: air.Span, message: []const u8, block: ?[]const u8) !void {
if (block) |b| {
try c.report("E5002", span, message, &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "block", .value = .{ .str = b } },
});
} else {
try c.report("E5002", span, message, &.{.{ .name = "function", .value = .{ .str = f.name } }});
}
}
const h = verifier.test_header;
test "terminators" {
try verifier.expectCodes(h ++ "fn @f() -> void\neffects []\nentry:\n ret\n", &.{});
try verifier.expectCodes(h ++ "fn @f(%a: u8) -> u8\neffects []\nentry:\n %b = copy %a\n", &.{"E5002"});
try verifier.expectCodes(h ++ "fn @f() -> void\neffects []\nentry:\n ret\n ret\n", &.{"E5002"});
try verifier.expectCodes(h ++ "fn @f() -> void\neffects []\nentry:\nnext:\n ret\n", &.{"E5002"});
}
test "branch arity and entry block" {
try verifier.expectCodes(h ++ "fn @f(%a: u8) -> u8\neffects []\nentry:\n br @b(%a, %a)\nb(%x: u8):\n ret %x\n", &.{"E5002"});
try verifier.expectCodes(h ++ "fn @f() -> void\neffects []\nentry(%x: u8):\n ret\n", &.{"E5002"});
}
test "switch shapes" {
try verifier.expectCodes(h ++ "fn @f(%a: u8) -> void\neffects []\nentry:\n switch.u8 %a, 1 -> @x(), 1 -> @x(), default -> @x()\nx:\n ret\n", &.{"E5002"});
const e = h ++ "type @E = enum { A, B(u8) }\n";
try verifier.expectCodes(e ++ "fn @f(%e: @E) -> void\neffects []\nentry:\n enum.switch @E %e, A -> @x\nx:\n ret\n", &.{"E5002"});
try verifier.expectCodes(e ++ "fn @f(%e: @E) -> void\neffects []\nentry:\n enum.switch @E %e, A -> @x, B -> @x\nx:\n ret\n", &.{"E5002"});
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", &.{});
}
+234
View File
@@ -0,0 +1,234 @@
//! SSA dominance (spec 07 §8.2). Reports E5001.
//!
//! Undefined and doubly defined values are already rejected during parsing;
//! this pass checks that every use is dominated by its definition.
//! Dominators use the iterative algorithm of Cooper, Harvey and Kennedy over
//! a reverse postorder, which is deterministic for a given CFG.
const std = @import("std");
const air = @import("../air.zig");
const verifier = @import("../verifier.zig");
const Context = verifier.Context;
const none = std.math.maxInt(u32);
pub const Dominators = struct {
/// Immediate dominator per block; `none` for unreachable blocks.
/// The entry block is its own immediate dominator.
idom: []u32,
/// Reverse postorder of reachable blocks.
rpo: []u32,
/// Position of each block in `rpo`; `none` for unreachable blocks.
order: []u32,
pub fn reachable(d: Dominators, b: u32) bool {
return d.order[b] != none;
}
/// Whether `a` dominates `b`. Both must be reachable.
pub fn dominates(d: Dominators, a: u32, b: u32) bool {
var x = b;
while (true) {
if (x == a) return true;
if (x == 0) return false;
x = d.idom[x];
}
}
};
pub fn dominators(arena: std.mem.Allocator, f: air.Function) !Dominators {
const n: u32 = @intCast(f.blocks.len);
const order = try arena.alloc(u32, n);
@memset(order, none);
const idom = try arena.alloc(u32, n);
@memset(idom, none);
// Successor lists.
const succs = try arena.alloc([]const u32, n);
var preds = try arena.alloc(std.ArrayList(u32), n);
for (preds) |*p| p.* = .empty;
for (f.blocks, 0..) |b, i| {
var list: std.ArrayList(u32) = .empty;
if (b.insts.len != 0) try air.successors(b.insts[b.insts.len - 1].op, &list, arena);
succs[i] = list.items;
for (list.items) |s| try preds[s].append(arena, @intCast(i));
}
// Iterative DFS postorder from the entry block.
var post: std.ArrayList(u32) = .empty;
const visited = try arena.alloc(bool, n);
@memset(visited, false);
const Frame = struct { block: u32, next: u32 };
var stack: std.ArrayList(Frame) = .empty;
try stack.append(arena, .{ .block = 0, .next = 0 });
visited[0] = true;
while (stack.items.len != 0) {
const top = &stack.items[stack.items.len - 1];
const ss = succs[top.block];
if (top.next < ss.len) {
const s = ss[top.next];
top.next += 1;
if (!visited[s]) {
visited[s] = true;
try stack.append(arena, .{ .block = s, .next = 0 });
}
} else {
try post.append(arena, top.block);
_ = stack.pop();
}
}
const rpo = post.items;
std.mem.reverse(u32, rpo);
for (rpo, 0..) |b, i| order[b] = @intCast(i);
idom[0] = 0;
var changed = true;
while (changed) {
changed = false;
for (rpo[1..]) |b| {
var new: u32 = none;
for (preds[b].items) |p| {
if (idom[p] == none) continue;
new = if (new == none) p else intersect(idom, order, p, new);
}
if (idom[b] != new) {
idom[b] = new;
changed = true;
}
}
}
return .{ .idom = idom, .rpo = rpo, .order = order };
}
fn intersect(idom: []const u32, order: []const u32, a0: u32, b0: u32) u32 {
var a = a0;
var b = b0;
while (a != b) {
while (order[a] > order[b]) a = idom[a];
while (order[b] > order[a]) b = idom[b];
}
return a;
}
pub fn check(c: *Context) !void {
for (c.module.functions) |f| try checkFunction(c, f);
}
const UseCtx = struct {
c: *Context,
f: air.Function,
dom: Dominators,
block: u32,
index: u32,
span: air.Span,
err: ?std.mem.Allocator.Error = null,
fn visit(u: *UseCtx, v: air.ValueId) void {
if (u.err != null) return;
u.checkUse(v) catch |e| {
u.err = e;
};
}
fn checkUse(u: *UseCtx, v: air.ValueId) !void {
const reachable = u.dom.reachable(u.block);
const ok = switch (u.f.values[v].def) {
.none => unreachable, // rejected by the parser
.param => true,
.block_param => |d| if (d.block == u.block) true else reachable and u.dom.reachable(d.block) and u.dom.dominates(d.block, u.block),
.inst => |d| if (d.block == u.block) d.index < u.index else reachable and u.dom.reachable(d.block) and u.dom.dominates(d.block, u.block),
};
// Uses in unreachable blocks are only checked against definitions in
// the same block (spec 07 §8.2).
const same_block = switch (u.f.values[v].def) {
.block_param => |d| d.block == u.block,
.inst => |d| d.block == u.block,
else => true,
};
if (ok or (!reachable and !same_block)) return;
try u.c.report("E5001", u.span, "use is not dominated by its definition", &.{
.{ .name = "function", .value = .{ .str = u.f.name } },
.{ .name = "value", .value = .{ .str = try u.c.valueName(u.f, v) } },
.{ .name = "block", .value = .{ .str = u.f.blocks[u.block].name } },
});
}
};
fn checkFunction(c: *Context, f: air.Function) !void {
const dom = try dominators(c.arena, f);
for (f.blocks, 0..) |b, bi| {
for (b.insts, 0..) |inst, ii| {
var u: UseCtx = .{ .c = c, .f = f, .dom = dom, .block = @intCast(bi), .index = @intCast(ii), .span = inst.span };
air.forEachUse(inst.op, &u, UseCtx.visit);
if (u.err) |e| return e;
}
}
}
const h = verifier.test_header;
test "use not dominated by definition" {
// %x is defined only on the `a` path but used after the join.
try verifier.expectCodes(h ++
\\fn @f(%c: bool) -> u8
\\effects []
\\entry:
\\ cbr %c, @a(), @b()
\\a:
\\ %x = const.u8 1
\\ br @join()
\\b:
\\ br @join()
\\join:
\\ ret %x
\\
, &.{"E5001"});
}
test "use before definition in the same block" {
try verifier.expectCodes(h ++
\\fn @f() -> u8
\\effects []
\\entry:
\\ %y = copy %x
\\ %x = const.u8 1
\\ ret %y
\\
, &.{"E5001"});
}
test "loop-carried values through block parameters verify" {
try verifier.expectCodes(h ++
\\fn @f(%n: u64) -> u64
\\effects []
\\entry:
\\ %z = const.u64 0
\\ br @loop(%z)
\\loop(%i: u64):
\\ %d = ge.u64 %i, %n
\\ cbr %d, @exit(), @body()
\\body:
\\ %one = const.u64 1
\\ %next = add.checked.u64 %i, %one
\\ br @loop(%next)
\\exit:
\\ ret %i
\\
, &.{});
}
test "unreachable blocks only check same-block order" {
try verifier.expectCodes(h ++
\\fn @f() -> u8
\\effects []
\\entry:
\\ %a = const.u8 1
\\ ret %a
\\dead:
\\ ret %b
\\dead2:
\\ %b = const.u8 2
\\ ret %b
\\
, &.{});
}
+319
View File
@@ -0,0 +1,319 @@
//! Type verification for format version 0 (spec 07 §8.3, spec 07a).
//! Reports E1001, E1002 and E1003.
//!
//! Runs after CFG and SSA verification, so block shapes and branch arities
//! are known to be valid and every use has a dominating definition.
const std = @import("std");
const air = @import("../air.zig");
const verifier = @import("../verifier.zig");
const Context = verifier.Context;
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);
}
// ---------------------------------------------------------------- declarations
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),
};
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);
}
// E1003: an aggregate that contains itself by value has no finite size.
const state = try c.arena.alloc(enum { white, grey, black }, m.types.len);
@memset(state, .white);
for (0..m.types.len) |i| try visitDecl(c, state, @intCast(i));
}
fn visitDecl(c: *Context, state: anytype, i: u32) !void {
if (state[i] == .black) return;
if (state[i] == .grey) {
const d = c.module.types[i];
try c.report("E1003", d.span, "aggregate type contains itself by value", &.{.{ .name = "type", .value = .{ .str = d.name } }});
state[i] = .black;
return;
}
state[i] = .grey;
switch (c.module.types[i].kind) {
.@"struct" => |fs| for (fs) |f| if (f.ty == .named) try visitDecl(c, state, f.ty.named),
.@"enum" => |vs| for (vs) |v| for (v.payload) |t| if (t == .named) try visitDecl(c, state, t.named),
}
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", &.{
.{ .name = "in", .value = .{ .str = owner } },
.{ .name = "found", .value = .{ .str = @tagName(t) } },
});
}
// ---------------------------------------------------------------- functions
const FnCtx = struct {
c: *Context,
f: air.Function,
/// Type of each value; null while unresolved.
ty: []?Type,
block: u32 = 0,
index: u32 = 0,
fn typeOf(fc: *FnCtx, v: air.ValueId) Type {
return fc.ty[v].?;
}
fn mismatch(fc: *FnCtx, span: air.Span, what: []const u8, expected: Type, found: Type) !void {
try fc.c.report("E1001", span, "type mismatch", &.{
.{ .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 = what } },
.{ .name = "expected", .value = .{ .str = try fc.c.typeName(expected) } },
.{ .name = "found", .value = .{ .str = try fc.c.typeName(found) } },
});
}
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);
}
fn expectArgs(fc: *FnCtx, span: air.Span, args: []const air.ValueId, params: []const Type) !void {
if (args.len != params.len) {
try fc.c.report("E1001", span, "wrong number of operands", &.{
.{ .name = "function", .value = .{ .str = fc.f.name } },
.{ .name = "expected", .value = .{ .int = @intCast(params.len) } },
.{ .name = "found", .value = .{ .int = @intCast(args.len) } },
});
return;
}
for (args, params) |a, p| try fc.expectValue(span, a, p);
}
fn expectTarget(fc: *FnCtx, span: air.Span, t: air.Target) !void {
const params = fc.f.blocks[t.block].params;
for (t.args, params) |a, p| try fc.expectValue(span, a, p.ty);
}
};
/// Result type of a value-producing instruction. `copy` is resolved by the caller.
fn resultType(m: air.Module, op: air.Op) ?Type {
return switch (op) {
.@"const" => |x| x.ty,
.arith => |x| .{ .int = x.ty },
.bit => |x| x.ty,
.cmp => .bool,
.cast => |x| .{ .int = x.to },
.struct_make => |x| .{ .named = x.decl },
.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,
else => null,
};
}
fn checkFunction(c: *Context, f: air.Function) !void {
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.
for (f.params) |p| fc.ty[p.value] = p.ty;
for (f.blocks) |b| {
for (b.params) |p| fc.ty[p.value] = p.ty;
for (b.insts) |inst| if (inst.result) |r| {
fc.ty[r] = resultType(m, inst.op);
};
}
var progress = true;
while (progress) {
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| {
fc.ty[r] = t;
progress = true;
}
};
}
// A `copy` 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;
};
for (f.blocks, 0..) |b, bi| {
fc.block = @intCast(bi);
for (b.insts, 0..) |inst, ii| {
fc.index = @intCast(ii);
try checkInst(&fc, inst);
}
}
}
fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
const m = fc.c.module;
const f = fc.f;
const span = inst.span;
switch (inst.op) {
.@"const", .copy, .trap => {},
.arith => |x| {
try fc.expectValue(span, x.a, .{ .int = x.ty });
try fc.expectValue(span, x.b, .{ .int = x.ty });
},
.bit => |x| {
try fc.expectValue(span, x.a, x.ty);
try fc.expectValue(span, x.b, x.ty);
},
.cmp => |x| {
try fc.expectValue(span, x.a, x.ty);
try fc.expectValue(span, x.b, x.ty);
},
.assert => |v| try fc.expectValue(span, v, .bool),
.cast => |x| {
const from = fc.typeOf(x.a);
if (from != .int) {
try invalidCast(fc, span, from, x.to, "operand is not an integer");
} else if (x.mode == .widen and !lossless(from.int, x.to)) {
try invalidCast(fc, span, from, x.to, "widen is not lossless for every value");
}
},
.struct_make => |x| {
const fields = m.types[x.decl].kind.@"struct";
const tys = try fc.c.arena.alloc(Type, fields.len);
for (fields, tys) |fld, *t| t.* = fld.ty;
try fc.expectArgs(span, x.args, tys);
},
.struct_get => |x| try fc.expectValue(span, x.a, .{ .named = x.decl }),
.enum_make => |x| try fc.expectArgs(span, x.args, m.types[x.decl].kind.@"enum"[x.variant].payload),
.call => |x| {
const callee = m.functions[x.callee];
const tys = try fc.c.arena.alloc(Type, callee.params.len);
for (callee.params, tys) |p, *t| t.* = p.ty;
try fc.expectArgs(span, x.args, tys);
if (inst.result != null and callee.ret == .void) {
try fc.c.report("E1001", span, "call to a void function must not bind a result", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "callee", .value = .{ .str = callee.name } },
});
} else if (inst.result == null and callee.ret != .void and callee.ret != .never) {
try fc.c.report("E1001", span, "call result must be bound", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "callee", .value = .{ .str = callee.name } },
});
}
},
.br => |t| try fc.expectTarget(span, t),
.cbr => |x| {
try fc.expectValue(span, x.cond, .bool);
try fc.expectTarget(span, x.then);
try fc.expectTarget(span, x.@"else");
},
.@"switch" => |x| {
try fc.expectValue(span, x.value, .{ .int = x.ty });
for (x.cases) |case| try fc.expectTarget(case.span, case.target);
try fc.expectTarget(span, x.default);
},
.enum_switch => |x| {
try fc.expectValue(span, x.value, .{ .named = x.decl });
const variants = m.types[x.decl].kind.@"enum";
for (x.arms) |arm| {
const params = f.blocks[arm.block].params;
for (params, variants[arm.variant].payload) |p, t| {
if (!p.ty.eql(t)) try fc.mismatch(arm.span, try fc.c.valueName(f, p.value), t, p.ty);
}
}
if (x.default) |d| try fc.expectTarget(span, d);
},
.ret => |v| switch (f.ret) {
.never => try fc.c.report("E1001", span, "`ret` in a function returning never", &.{
.{ .name = "function", .value = .{ .str = f.name } },
}),
.void => if (v) |x| try fc.mismatch(span, try fc.c.valueName(f, x), .void, fc.typeOf(x)),
else => if (v) |x| {
try fc.expectValue(span, x, f.ret);
} else try fc.mismatch(span, "return value", f.ret, .void),
},
}
}
/// 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;
if (from.signed() and !to.signed()) return false;
if (!from.signed() and to.signed()) return to.bits() > from.bits();
return to.bits() >= from.bits();
}
fn invalidCast(fc: *FnCtx, span: air.Span, from: Type, to: air.IntType, message: []const u8) !void {
try fc.c.report("E1002", span, message, &.{
.{ .name = "function", .value = .{ .str = fc.f.name } },
.{ .name = "from", .value = .{ .str = try fc.c.typeName(from) } },
.{ .name = "to", .value = .{ .str = @tagName(to) } },
});
}
// ---------------------------------------------------------------- tests
const h = verifier.test_header;
inline fn body(comptime sig: []const u8, comptime insts: []const u8) []const u8 {
return comptime h ++ "fn @f" ++ sig ++ "\neffects []\nentry:\n" ++ insts;
}
test "arithmetic operand types" {
try verifier.expectCodes(body("(%a: u64, %b: u64) -> u64", " %c = add.checked.u64 %a, %b\n ret %c\n"), &.{});
try verifier.expectCodes(body("(%a: u64, %b: u32) -> u64", " %c = add.checked.u64 %a, %b\n ret %c\n"), &.{"E1001"});
try verifier.expectCodes(body("(%a: u64) -> u32", " ret %a\n"), &.{"E1001"});
try verifier.expectCodes(body("(%a: usize, %b: u64) -> bool", " %c = eq.u64 %a, %b\n ret %c\n"), &.{"E1001"});
try verifier.expectCodes(body("(%a: u8) -> void", " cbr %a, @x(), @x()\nx:\n ret\n"), &.{"E1001"});
try verifier.expectCodes(body("(%a: u8) -> void", " assert %a\n ret\n"), &.{"E1001"});
}
test "casts" {
try verifier.expectCodes(body("(%a: u8) -> i16", " %b = cast.widen.i16 %a\n ret %b\n"), &.{});
try verifier.expectCodes(body("(%a: u8) -> i8", " %b = cast.widen.i8 %a\n ret %b\n"), &.{"E1002"});
try verifier.expectCodes(body("(%a: i8) -> u64", " %b = cast.widen.u64 %a\n ret %b\n"), &.{"E1002"});
try verifier.expectCodes(body("(%a: u32) -> usize", " %b = cast.widen.usize %a\n ret %b\n"), &.{"E1002"});
try verifier.expectCodes(body("(%a: u32) -> usize", " %b = cast.checked.usize %a\n ret %b\n"), &.{});
try verifier.expectCodes(body("(%a: bool) -> u8", " %b = cast.wrap.u8 %a\n ret %b\n"), &.{"E1002"});
}
test "returns and calls" {
try verifier.expectCodes(body("() -> void", " ret\n"), &.{});
try verifier.expectCodes(body("() -> u8", " ret\n"), &.{"E1001"});
try verifier.expectCodes(body("() -> never", " ret\n"), &.{"E1001"});
try verifier.expectCodes(body("() -> never", " trap\n"), &.{});
const g = "fn @g(%x: u8) -> void\neffects []\nentry:\n ret\n";
try verifier.expectCodes(body("(%a: u8) -> void", " call @g(%a)\n ret\n") ++ g, &.{});
try verifier.expectCodes(body("(%a: u8) -> void", " %r = call @g(%a)\n ret\n") ++ g, &.{"E1001"});
try verifier.expectCodes(body("(%a: u16) -> void", " call @g(%a)\n ret\n") ++ g, &.{"E1001"});
try verifier.expectCodes(body("(%a: u8) -> void", " call @g(%a, %a)\n ret\n") ++ g, &.{"E1001"});
const k = "fn @k() -> u8\neffects []\nentry:\n %z = const.u8 0\n ret %z\n";
try verifier.expectCodes(body("() -> void", " call @k()\n ret\n") ++ k, &.{"E1001"});
}
test "aggregates and declarations" {
const s = h ++ "type @P = struct { x: u8, y: bool }\ntype @E = enum { A, B(u8) }\n";
try verifier.expectCodes(s ++ "fn @f(%a: u8, %t: bool) -> u8\neffects []\nentry:\n %p = struct.make @P(%a, %t)\n %x = struct.get @P.x, %p\n ret %x\n", &.{});
try verifier.expectCodes(s ++ "fn @f(%a: u8) -> void\neffects []\nentry:\n %p = struct.make @P(%a, %a)\n ret\n", &.{"E1001"});
try verifier.expectCodes(s ++ "fn @f(%a: u8) -> void\neffects []\nentry:\n %p = struct.make @P(%a)\n ret\n", &.{"E1001"});
try verifier.expectCodes(s ++ "fn @f(%e: @E) -> void\neffects []\nentry:\n enum.switch @E %e, A -> @x, B -> @y\nx:\n ret\ny(%v: u16):\n ret\n", &.{"E1001"});
try verifier.expectCodes(h ++ "type @R = struct { next: @R }\nfn @f() -> void\neffects []\nentry:\n ret\n", &.{"E1003"});
try verifier.expectCodes(h ++ "type @A = struct { b: @B }\ntype @B = enum { X(@A) }\nfn @f() -> void\neffects []\nentry:\n ret\n", &.{"E1003"});
try verifier.expectCodes(h ++ "fn @f(%v: void) -> void\neffects []\nentry:\n ret\n", &.{"E1001"});
}
@@ -2,6 +2,11 @@
; expect: accept
; phase: 0
; spec: docs/spec/07-air.md
module test.loop_block_params
air 0
lang 0.1
features []
fn @count(%n: u64) -> u64
effects []
+5
View File
@@ -2,6 +2,11 @@
; expect: accept
; phase: 0
; spec: docs/spec/07-air.md
module test.sum
air 0
lang 0.1
features []
fn @sum(%a: u64, %b: u64) -> u64
effects []
@@ -2,6 +2,11 @@
; expect: reject E5002
; phase: 0
; spec: docs/spec/07-air.md
module test.missing_terminator
air 0
lang 0.1
features []
fn @f(%a: u64) -> u64
effects []
@@ -2,6 +2,11 @@
; expect: reject E1001
; phase: 0
; spec: docs/spec/02-types-and-values.md
module test.operand_type_mismatch
air 0
lang 0.1
features []
fn @f(%a: u64, %b: u32) -> u64
effects []
@@ -2,6 +2,11 @@
; expect: reject E5001
; phase: 0
; spec: docs/spec/07-air.md
module test.undefined_value
air 0
lang 0.1
features []
fn @f(%a: u64) -> u64
effects []
@@ -2,6 +2,11 @@
; expect: reject E2001
; phase: 1
; spec: docs/spec/03-memory-model.md
module test.use_after_move
air 0
lang 0.1
features []
fn @f(%p: Own<u64>) -> Own<u64>
effects []
+3
View File
@@ -107,6 +107,9 @@ fn runOne(arena: std.mem.Allocator, path: []const u8, source: []const u8) !Resul
const header = parseHeader(arena, source) catch |err|
return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "bad header: {t}", .{err}) };
if (header.phase > aji.implemented_phase)
return .{ .outcome = .pending, .detail = try std.fmt.allocPrint(arena, "phase {d} not implemented", .{header.phase}) };
// Blank header lines (keeping newlines) so spans in diagnostics stay accurate
// and the AIR grammar does not have to know about test metadata.
const body = try arena.dupe(u8, source);