//! 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; 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 fn checkDeclarations(c: *Context) !void { const m = c.module; if (m.declares("linear_aggregates")) { try checkFiniteLayouts(c); if (c.diags.items.len != 0) return; } for (m.types) |d| switch (d.kind) { .@"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 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), inline .array_splat, .array_make, .aggregate_unpack, .own_pack, .buffer_new => |x| try wellFormed(c, inst.span, x.ty, .param, f.name), else => {}, }; } } try checkFiniteLayouts(c); } /// E1003 applies through arrays as well as direct nominal members. pub fn checkFiniteLayouts(c: *Context) !void { const m = c.module; 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) std.mem.Allocator.Error!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| try visitValue(c, state, f.ty), .@"enum" => |vs| for (vs) |v| for (v.payload) |t| try visitValue(c, state, t), } state[i] = .black; } fn visitValue(c: *Context, state: anytype, t: Type) std.mem.Allocator.Error!void { switch (t) { .named => |i| try visitDecl(c, state, i), .array => |a| try visitValue(c, state, a.elem), .own, .own_array, .buffer, .sender, .receiver, .mutex, .ref, .mut, .slice, .slice_mut, .guard, .task, .local => |inner| if (c.module.declares("linear_aggregates")) try visitValue(c, state, inner.*), else => {}, } } pub const Position = enum { member, param, ret, block_param, borrowed }; /// Shared with source annotation checking; no state or diagnostics. pub fn allowedPosition(tag: std.meta.Tag(Type), pos: Position, linear_aggregates: bool) bool { return switch (tag) { .void, .never => pos == .ret, .local => false, .ref, .mut, .slice, .slice_mut => pos != .member and pos != .borrowed, .scope, .task, .shield, .guard => pos != .member, .resource, .own, .own_array, .buffer, .region, .sender, .receiver, .mutex, .island, .frozen, .arc, .atomic => pos != .member or linear_aggregates, else => true, }; } pub fn innerPosition(tag: std.meta.Tag(Type)) Position { return switch (tag) { .ref, .mut, .task, .sender, .receiver, .mutex, .guard => .borrowed, else => .member, }; } /// Where a type may appear (spec 07 §8.3, §8.8): /// - `void`/`never` only as return types; /// - storage (`local`) 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 = allowedPosition(std.meta.activeTag(t), pos, c.module.declares("linear_aggregates")); if (t == .own_array and c.module.declares("linear_aggregates") and c.module.isLinearType(t.own_array.*)) try c.report("E1001", span, "dynamic heap arrays require Copy content", &.{}); // An atomic cell holds an AtomicScalar (spec 04 §23). if (t == .atomic and !isAtomicScalar(t.atomic.*)) try c.report("E1001", span, "atomic needs bool or an integer of at most 64 bits", &.{ .{ .name = "in", .value = .{ .str = owner } }, .{ .name = "found", .value = .{ .str = try c.typeName(t.atomic.*) } }, }); if (!ok) try c.report("E1001", span, "type not allowed in this position", &.{ .{ .name = "in", .value = .{ .str = owner } }, .{ .name = "position", .value = .{ .str = @tagName(pos) } }, .{ .name = "found", .value = .{ .str = try c.typeName(t) } }, }); // A graph holds IslandSafe values only (spec 03 §22–§24): reported once, // as E2111, at the type. if (t.isGraphOwner()) { if (!isIslandSafe(c.module, t.inner().?)) try c.report("E2111", span, "a graph holds only plain data and iref handles", &.{ .{ .name = "in", .value = .{ .str = owner } }, .{ .name = "found", .value = .{ .str = try c.typeName(t.inner().?) } }, }); return; } // The pointee of ref/mut may be a linear value (`mut>`), and // a task may return one; every other compound holds value types only. // Channel elements and mutex contents may be linear (spec 04 §38.1); // their remaining rules are the element rules of `checkElement`. if (t.inner()) |inner| try wellFormed(c, span, inner, innerPosition(std.meta.activeTag(t)), owner); } /// Validate a phantom or used source generic argument by ordinary type rules. pub fn checkTypeArgument(c: *Context, span: air.Span, t: Type) !void { try wellFormed(c, span, t, .param, "generic argument"); try argumentLengths(c, span, t); } fn argumentLengths(c: *Context, span: air.Span, t: Type) !void { if (t == .array and (t.array.len == 0 or t.array.len > (1 << 32))) try c.report("E1001", span, "array length outside format-0 range", &.{}); if (t.inner()) |inner| try argumentLengths(c, span, inner); } /// `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 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) } }, }); } /// A `cap` operand: wrong kind is E3201, not a capability E1001. fn expectAllocCap(fc: *FnCtx, span: air.Span, v: air.ValueId) !void { const t = fc.typeOf(v); if (t != .cap) return fc.kindError(span, v, "cap"); const kind = air.authority.kinds[t.cap].name; if (!std.mem.eql(u8, kind, "mem.alloc")) try fc.c.report("E3201", span, "allocation needs cap", &.{ .{ .name = "function", .value = .{ .str = fc.f.name } }, .{ .name = "expected", .value = .{ .str = "mem.alloc" } }, .{ .name = "found", .value = .{ .str = kind } }, }); } fn expectRegionRef(fc: *FnCtx, span: air.Span, v: air.ValueId) !void { const t = fc.typeOf(v); if (t != .ref or t.ref.* != .region) try fc.kindError(span, v, "ref"); } /// `ok` receives `result`, `err` an `alloc_error` (counts checked by the CFG stage). fn expectOkErr(fc: *FnCtx, span: air.Span, ok: u32, err: u32, result: Type) !void { const p = fc.f.blocks[ok].params[0]; if (!p.ty.eql(result)) try fc.mismatch(span, try fc.c.valueName(fc.f, p.value), result, p.ty); const e = fc.f.blocks[err].params[0]; if (!e.ty.eql(.{ .builtin = .alloc_error })) try fc.mismatch(span, try fc.c.valueName(fc.f, e.value), .{ .builtin = .alloc_error }, e.ty); } 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); } 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); } /// The parameters of `block` have exactly the types `want` (counts were /// checked by the CFG stage). fn expectParams(fc: *FnCtx, span: air.Span, block: u32, want: []const Type) !void { for (fc.f.blocks[block].params, want) |p, t| { if (!p.ty.eql(t)) try fc.mismatch(span, try fc.c.valueName(fc.f, p.value), t, p.ty); } } 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, .error_const => |x| .{ .builtin = x.which }, .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, .slice_len, .buffer_len, .buffer_capacity => .{ .int = .usize }, .task_scope_begin => .scope, .task_cancelled => .bool, .task_shield_begin => .shield, .iref_eq => .bool, .intrinsic => |x| blk: { const reg = air.authority.intrinsics[x.index]; if (reg.fallible or reg.results.len == 0) break :blk .void; break :blk intrinsicResult(reg.results[0]); }, inline .array_splat, .array_make => |x| x.ty, else => null, }; } pub fn intrinsicResult(r: air.authority.ResultType) Type { return switch (r) { .usize => .{ .int = .usize }, .u64 => .{ .int = .u64 }, .resource => |res| .{ .resource = res }, }; } fn operandText(arena: std.mem.Allocator, o: air.authority.Operand) ![]const u8 { return switch (o) { .cap => |k| std.fmt.allocPrint(arena, "cap<{s}>", .{k}), .bytes => "slice", .buffer => "slice_mut", .borrowed => |rs| blk: { var w: std.Io.Writer.Allocating = .init(arena); for (rs, 0..) |r, i| w.writer.print("{s}mut<{s}>", .{ if (i == 0) "" else " or ", r.text() }) catch return error.OutOfMemory; break :blk w.written(); }, .consumed => |rs| blk: { var w: std.Io.Writer.Allocating = .init(arena); for (rs, 0..) |r, i| w.writer.print("{s}{s}", .{ if (i == 0) "" else " or ", r.text() }) catch return error.OutOfMemory; break :blk w.written(); }, }; } fn operandMatches(o: air.authority.Operand, t: Type) bool { return switch (o) { .cap => t == .cap, // the kind is checked separately (E3201) .bytes => t == .slice and t.slice.* == .int and t.slice.int == .u8, .buffer => t == .slice_mut and t.slice_mut.* == .int and t.slice_mut.int == .u8, .borrowed => |rs| t == .mut and t.mut.* == .resource and std.mem.indexOfScalar(air.authority.Resource, rs, t.mut.resource) != null, .consumed => |rs| t == .resource and std.mem.indexOfScalar(air.authority.Resource, rs, t.resource) != null, }; } fn checkIntrinsic(fc: *FnCtx, inst: air.Inst, x: @FieldType(air.Op, "intrinsic")) !void { const f = fc.f; const span = inst.span; const reg = air.authority.intrinsics[x.index]; if (reg.fallible != (x.ok != null)) { return fc.c.report("E1001", span, if (reg.fallible) "intrinsic is fallible: use the `, ok -> @a, err -> @b` form" else "intrinsic is infallible: it has no `ok`/`err` targets", &.{ .{ .name = "function", .value = .{ .str = f.name } }, .{ .name = "intrinsic", .value = .{ .str = reg.name } }, }); } if (x.args.len != reg.operands.len) { return fc.c.report("E1001", span, "wrong number of intrinsic operands", &.{ .{ .name = "function", .value = .{ .str = f.name } }, .{ .name = "intrinsic", .value = .{ .str = reg.name } }, .{ .name = "expected", .value = .{ .int = @intCast(reg.operands.len) } }, .{ .name = "found", .value = .{ .int = @intCast(x.args.len) } }, }); } for (x.args, reg.operands) |a, o| { const t = fc.typeOf(a); if (!operandMatches(o, t)) { try fc.kindError(span, a, try operandText(fc.c.arena, o)); continue; } if (o == .cap and !std.mem.eql(u8, air.authority.kinds[t.cap].name, o.cap)) { try fc.c.report("E3201", span, "capability of the wrong kind for this intrinsic", &.{ .{ .name = "function", .value = .{ .str = f.name } }, .{ .name = "intrinsic", .value = .{ .str = reg.name } }, .{ .name = "expected", .value = .{ .str = o.cap } }, .{ .name = "found", .value = .{ .str = air.authority.kinds[t.cap].name } }, }); } } if (x.ok) |ok| { if (inst.result != null) return fc.c.report("E1001", span, "a fallible intrinsic delivers results to its `ok` block parameters", &.{ .{ .name = "function", .value = .{ .str = f.name } }, }); for (f.blocks[ok].params, reg.results) |p, r| { const want = intrinsicResult(r); if (!p.ty.eql(want)) try fc.mismatch(span, try fc.c.valueName(f, p.value), want, p.ty); } const e = f.blocks[x.err.?].params[0]; if (!e.ty.eql(.{ .builtin = .io_error })) try fc.mismatch(span, try fc.c.valueName(f, e.value), .{ .builtin = .io_error }, e.ty); } else if (inst.result != null and reg.results.len == 0) { try fc.c.report("E1001", span, "intrinsic has no result to bind", &.{ .{ .name = "function", .value = .{ .str = f.name } }, .{ .name = "intrinsic", .value = .{ .str = reg.name } }, }); } } /// Structural Copy query for source constraints; borrows remain second-class. pub fn isCopy(m: air.Module, t: Type) bool { return switch (t) { .int, .bool, .builtin, .cap, .iref => true, .array => |a| isCopy(m, a.elem), .named => |i| aggregateAll(m, i, isCopy), else => false, }; } /// Local is context-bound state, not the complement of Send (spec 15 §15). pub fn isLocalType(m: air.Module, t: Type) bool { return switch (t) { .local, .task, .scope, .shield, .guard => true, .ref, .mut, .slice, .slice_mut, .own, .own_array, .buffer, .mutex => |inner| isLocalType(m, inner.*), .array => |a| isLocalType(m, a.elem), .named => |i| switch (m.types[i].kind) { .@"struct" => |fs| for (fs) |f| { if (isLocalType(m, f.ty)) break true; } else false, .@"enum" => |vs| blk: { for (vs) |v| for (v.payload) |p| if (isLocalType(m, p)) break :blk true; break :blk false; }, }, else => false, }; } /// `Send` (spec 04 §35): may move to another task. pub fn isSend(m: air.Module, t: Type) bool { return switch (t) { .int, .bool, .builtin, .cap, .resource, .region, .sender, .receiver => true, // Graph contents are IslandSafe plain data (spec 03 §22–§24). .island, .frozen, .arc, .iref => true, // Every access to a cell is an atomic operation (spec 04 §23). .atomic => true, .own, .own_array, .buffer, .mutex => |inner| isSend(m, inner.*), .ref, .slice => |inner| isShare(m, inner.*), .mut, .slice_mut => |inner| isSend(m, inner.*), .array => |a| isSend(m, a.elem), .named => |i| aggregateAll(m, i, isSend), .scope, .task, .shield, .guard, .local, .void, .never => false, }; } /// `Share` (spec 04 §35): may be observed concurrently through shared borrows. pub fn isShare(m: air.Module, t: Type) bool { return switch (t) { .int, .bool, .builtin, .cap => true, .frozen, .arc, .iref, .atomic => true, // Its owner may mutate it: freeze to share (spec 04 §35). .island => false, .resource, .region, .mut, .slice_mut, .scope, .task, .shield, .guard, .sender, .receiver, .local, .void, .never => false, .own, .own_array, .buffer, .ref, .slice => |inner| isShare(m, inner.*), // The lock synchronizes access (spec 04 §35, §40). .mutex => |inner| isSend(m, inner.*), .array => |a| isShare(m, a.elem), .named => |i| aggregateAll(m, i, isShare), }; } /// A borrow whose pointee is an atomic cell: reached only atomically. fn atomicPointee(t: Type) bool { return (t == .ref or t == .mut) and t.inner().? == .atomic; } /// `E4202`: an ordinary load or store of an atomic cell (spec 04 §28). fn ordinaryAtomicAccess(fc: *FnCtx, span: air.Span, v: air.ValueId, use: []const u8) !void { try fc.c.report("E4202", span, "an atomic cell is read and written only by atomic operations", &.{ .{ .name = "function", .value = .{ .str = fc.f.name } }, .{ .name = "operand", .value = .{ .str = try fc.c.valueName(fc.f, v) } }, .{ .name = "found", .value = .{ .str = try fc.c.typeName(fc.typeOf(v)) } }, .{ .name = "use", .value = .{ .str = use } }, }); } /// `E4201`: an ordering outside the operation's row (spec 04 §24). fn checkOrdering(fc: *FnCtx, span: air.Span, operation: []const u8, ord: air.Ordering, allowed: []const air.Ordering) !void { if (std.mem.indexOfScalar(air.Ordering, allowed, ord) != null) return; var text: std.Io.Writer.Allocating = .init(fc.c.arena); for (allowed, 0..) |o, i| text.writer.print("{s}{s}", .{ if (i == 0) "" else ", ", @tagName(o) }) catch return error.OutOfMemory; try fc.c.report("E4201", span, "memory ordering not valid for this atomic operation", &.{ .{ .name = "function", .value = .{ .str = fc.f.name } }, .{ .name = "operation", .value = .{ .str = operation } }, .{ .name = "ordering", .value = .{ .str = @tagName(ord) } }, .{ .name = "allowed", .value = .{ .str = text.written() } }, }); } /// AtomicScalar (spec 04 §23): `bool` and integers of at most 64 bits. pub fn isAtomicScalar(t: Type) bool { return switch (t) { .bool => true, .int => |it| it.bits() <= 64, else => false, }; } /// `IslandSafe` (spec 02 §6): plain data and `iref` handles, at any depth. /// `ArcSafe` is the same set in format 0. pub fn isIslandSafe(m: air.Module, t: Type) bool { return switch (t) { .int, .bool, .builtin, .iref => true, .array => |a| isIslandSafe(m, a.elem), .named => |i| aggregateAll(m, i, isIslandSafe), else => false, }; } fn aggregateAll(m: air.Module, i: u32, comptime pred: fn (air.Module, Type) bool) bool { return switch (m.types[i].kind) { .@"struct" => |fs| for (fs) |f| { if (!pred(m, f.ty)) break false; } else true, .@"enum" => |vs| { for (vs) |v| for (v.payload) |p| if (!pred(m, p)) return false; return true; }, }; } /// `task.spawn` (spec 04 §33.2, §35): arguments like a call, Send/Share /// rules per argument, and a borrow-free, Send result. fn checkSpawn(fc: *FnCtx, inst: air.Inst, x: @FieldType(air.Op, "task_spawn")) !void { const m = fc.c.module; const f = fc.f; const span = inst.span; if (fc.typeOf(x.scope) != .scope) try fc.kindError(span, x.scope, "scope"); 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 (x.args.len == tys.len) for (x.args, tys) |a, pt| { const shared = pt == .ref or pt == .slice; const ok = if (shared) isShare(m, pt.inner().?) else isSend(m, pt); if (!ok) try fc.c.report(if (shared) "E4002" else "E4001", span, if (shared) "data lent to a task through a shared borrow must be Share" else "a value moved or exclusively lent to a task must be Send", &.{ .{ .name = "function", .value = .{ .str = f.name } }, .{ .name = "task_function", .value = .{ .str = callee.name } }, .{ .name = "argument", .value = .{ .str = try fc.c.valueName(f, a) } }, .{ .name = "type", .value = .{ .str = try fc.c.typeName(pt) } }, }); }; const r = callee.ret; if (callee.ret_from != null or r.isBorrow()) { try fc.c.report("E0006", span, "construct belongs to a feature the module does not declare", &.{ .{ .name = "reason", .value = .{ .str = "feature_not_declared" } }, .{ .name = "feature", .value = .{ .str = "task_borrow_returns" } }, .{ .name = "construct", .value = .{ .str = "spawned function returning a borrow" } }, }); } else if (r.isTaskBound()) { try fc.c.report("E1001", span, "a task result must not contain a scope or task handle", &.{.{ .name = "function", .value = .{ .str = f.name } }}); } else if (r != .void and r != .never and !isSend(m, r)) { try fc.c.report("E4001", span, "a task result must be Send", &.{ .{ .name = "function", .value = .{ .str = f.name } }, .{ .name = "task_function", .value = .{ .str = callee.name } }, }); } } /// Element rules of channels and mutexes (spec 04 §38.1). fn checkElement(fc: *FnCtx, span: air.Span, t: Type) !void { const m = fc.c.module; if (contains(m, t, .endpoint)) return fc.c.report("E0006", span, "construct belongs to a feature the module does not declare", &.{ .{ .name = "reason", .value = .{ .str = "feature_not_declared" } }, .{ .name = "feature", .value = .{ .str = "channel_transfer" } }, .{ .name = "construct", .value = .{ .str = "channel endpoint inside a channel element or mutex" } }, }); if (contains(m, t, .forbidden)) return fc.c.report("E1001", span, "a channel element or mutex content contains no borrow, scope, task, shield or guard", &.{ .{ .name = "function", .value = .{ .str = fc.f.name } }, .{ .name = "type", .value = .{ .str = try fc.c.typeName(t) } }, }); if (!isSend(m, t)) try fc.c.report("E4001", span, "a channel element or mutex content must be Send", &.{ .{ .name = "function", .value = .{ .str = fc.f.name } }, .{ .name = "type", .value = .{ .str = try fc.c.typeName(t) } }, }); } /// Whether `t` transitively contains an endpoint, or a borrow or /// function-bound value. fn contains(m: air.Module, t: Type, comptime what: enum { endpoint, forbidden }) bool { const here = switch (what) { .endpoint => t.isEndpoint(), .forbidden => t.isBorrow() or t.isTaskBound() or t == .guard, }; if (here) return true; // An `iref` holds no `T`: types may recurse through it (spec 03 §22). if (t == .iref) return false; if (t.inner()) |inner| if (t != .ref and t != .mut and t != .slice and t != .slice_mut) return contains(m, inner, what); return switch (t) { .named => |i| switch (m.types[i].kind) { .@"struct" => |fs| for (fs) |f| { if (contains(m, f.ty, what)) break true; } else false, .@"enum" => |vs| for (vs) |v| { for (v.payload) |p| if (contains(m, p, what)) return true; } else false, }, else => false, }; } /// `select` (spec 04 §39): each arm is a channel operation; each target /// takes its own parameters, then the send values not sent on its edge. fn checkSelect(fc: *FnCtx, inst: air.Inst, x: @FieldType(air.Op, "select")) !void { const f = fc.f; const a = fc.c.arena; const buf = try a.alloc(air.ValueId, x.arms.len); const vs = air.Op.selectValues(x.arms, buf); const v_types = try a.alloc(Type, vs.len); for (vs, v_types) |v, *t| t.* = fc.typeOf(v); for (x.arms) |arm| { const t = fc.typeOf(arm.endpoint); const want: std.meta.Tag(Type) = if (arm.value == null) .receiver else .sender; if (t != .mut or std.meta.activeTag(t.mut.*) != want) { try fc.kindError(arm.span, arm.endpoint, if (arm.value == null) "mut>" else "mut>"); continue; } const e = t.mut.inner().?; var ok_types: std.ArrayList(Type) = .empty; if (arm.value) |v| { try fc.expectValue(arm.span, v, e); for (vs, v_types) |w, wt| if (w != v) try ok_types.append(a, wt); } else { try ok_types.append(a, e); try ok_types.appendSlice(a, v_types); } try fc.expectParams(arm.span, arm.ok, ok_types.items); try fc.expectParams(arm.span, arm.closed, v_types); } try fc.expectParams(inst.span, x.cancelled, v_types); _ = f; } fn bufferElement(fc: *FnCtx, span: air.Span, v: air.ValueId, mutable: bool) !?Type { const t = fc.typeOf(v); if ((t == .mut or (!mutable and t == .ref)) and t.inner().? == .buffer) return t.inner().?.buffer.*; try fc.kindError(span, v, if (mutable) "mut>" else "ref> or mut>"); return null; } pub fn complete(t: Type) bool { return t != .void and t != .never and t != .local and !t.isBorrow() and !t.isTaskBound() and t != .guard; } 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, .buffer_view, .borrow_ref, .borrow_mut, .load, .slice_make => |v| fc.ty[v] orelse return null, .value_swap => |x| fc.ty[x.borrow] 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, .own_take => |v| fc.ty[v] orelse return null, .task_join => |v| fc.ty[v] orelse return null, .task_spawn => |x| return .{ .task = try boxed(a, m.functions[x.callee].ret) }, .channel_dup, .mutex_take, .mutex_borrow => |v| fc.ty[v] orelse return null, .mutex_make => |v| return .{ .mutex = try boxed(a, fc.ty[v] orelse return null) }, .slice_split => |x| fc.ty[x.slice] orelse return null, .island_root, .frozen_root, .arc_root, .island_freeze, .arc_from_frozen, .arc_clone => |v| fc.ty[v] orelse return null, inline .island_borrow, .frozen_borrow, .arc_borrow => |x| fc.ty[x.owner] orelse return null, .atomic_new => |v| return .{ .atomic = try boxed(a, fc.ty[v] orelse return null) }, .atomic_take => |v| fc.ty[v] orelse return null, .atomic_load => |x| fc.ty[x.cell] orelse return null, .atomic_rmw => |x| fc.ty[x.cell] orelse return null, .atomic_cmpxchg => |x| fc.ty[x.cell] orelse return null, else => return null, }; const invalid: Type = .void; return switch (op) { .buffer_view => if ((t == .ref or t == .mut) and t.inner().? == .buffer) (if (t == .mut) .{ .slice_mut = try boxed(a, t.inner().?.buffer.*) } else .{ .slice = try boxed(a, t.inner().?.buffer.*) }) else invalid, .value_swap => if (t == .mut) t.mut.* else invalid, .local_load => if (t == .local) t.local.* else invalid, .borrow_ref => switch (t) { .local, .ref, .mut => .{ .ref = try boxed(a, t.inner().?) }, .named, .array => if (m.isLinearType(t)) .{ .ref = try boxed(a, t) } else invalid, .resource, .region, .task, .scope, .sender, .receiver, .mutex, .buffer, .island, .frozen, .arc, .atomic => .{ .ref = try boxed(a, t) }, .own => |inner| .{ .ref = inner }, .own_array => |inner| .{ .slice = inner }, .slice, .slice_mut => .{ .slice = try boxed(a, t.inner().?) }, else => invalid, }, .borrow_mut => switch (t) { .local, .mut => .{ .mut = try boxed(a, t.inner().?) }, .named, .array => if (m.isLinearType(t)) .{ .mut = try boxed(a, t) } else invalid, .resource, .region, .task, .scope, .sender, .receiver, .buffer, .island => .{ .mut = try boxed(a, t) }, .own => |inner| .{ .mut = inner }, .own_array => |inner| .{ .slice_mut = 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, .own_take => if (t == .own) t.own.* else invalid, .task_join => if (t == .task) t.task.* else invalid, .channel_dup => if (t == .ref and t.ref.* == .sender) t.ref.* else invalid, .mutex_take => if (t == .mutex) t.mutex.* else invalid, .mutex_borrow => if (t == .guard) Type{ .mut = t.guard } else invalid, // Graph roots and handles (spec 03 §22–§24). .island_root => graphRoot(t, .island), .frozen_root => graphRoot(t, .frozen), .arc_root => graphRoot(t, .arc), .island_freeze => if (t == .island) Type{ .frozen = t.island } else invalid, .arc_from_frozen => if (t == .frozen) Type{ .arc = t.frozen } else invalid, .arc_clone => if (t == .ref and t.ref.* == .arc) t.ref.* else invalid, inline .island_borrow, .frozen_borrow, .arc_borrow => |x| blk: { const owner: std.meta.Tag(Type) = switch (op) { .island_borrow => .island, .frozen_borrow => .frozen, else => .arc, }; const r = fc.ty[x.iref] orelse return null; if (r != .iref) break :blk invalid; const target = try boxed(a, r.iref.*); if (t == .ref and std.meta.activeTag(t.ref.*) == owner) break :blk Type{ .ref = target }; if (owner == .island and t == .mut and t.mut.* == .island) break :blk Type{ .mut = target }; break :blk invalid; }, .atomic_take => if (t == .atomic) t.atomic.* else invalid, // Every atomic operation takes `ref>` (spec 04 §23). .atomic_load, .atomic_rmw, .atomic_cmpxchg => if (t == .ref and t.ref.* == .atomic) t.ref.atomic.* else invalid, else => unreachable, }; } /// `iref` of the root of a graph reached through `ref`/`mut` of its owner. fn graphRoot(t: Type, owner: std.meta.Tag(Type)) Type { const inner = switch (t) { .ref, .mut => |x| x.*, else => return .void, }; if (std.meta.activeTag(inner) != owner) return .void; if (t == .mut and owner != .island) return .void; return .{ .iref = switch (inner) { .island, .frozen, .arc => |x| x, 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 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; 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) continue; if (try derivedType(&fc, inst.op)) |t| { fc.ty[r] = t; if (inst.result2) |r2| fc.ty[r2] = if (inst.op == .atomic_cmpxchg) .bool else t; progress = true; } }; } // 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; }; for (f.blocks, 0..) |b, bi| { fc.block = @intCast(bi); for (b.insts, 0..) |inst, ii| { fc.index = @intCast(ii); 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 { const m = fc.c.module; const f = fc.f; const span = inst.span; switch (inst.op) { .@"const", .trap => {}, .error_const => |x| if (x.variant >= x.which.variants().len) try fc.c.report("E1001", span, "invalid built-in error variant", &.{}), .copy => |v| if (!fc.typeOf(v).isValue() or m.isLinearType(fc.typeOf(v))) 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 => |t| if (m.isLinearType(t)) try fc.c.report("E1001", span, "frame storage requires Copy content", &.{}), .slice_len => {}, .local_store => |x| { const t = fc.typeOf(x.local); if (t != .local) return fc.kindError(span, x.local, "local"); 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"); 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"); }, .borrow_ref => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "local, a resource, ref, mut, slice or slice_mut"), .borrow_mut => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "local, a resource, mut or slice_mut"), .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 (atomicPointee(fc.typeOf(v))) return ordinaryAtomicAccess(fc, span, v, "atomic.load"); if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "ref or mut"); if (m.isLinearType(resultOf(fc, inst))) try fc.c.report("E1001", span, "load cannot copy linear content; exchange or unpack", &.{}); }, .store => |x| { const t = fc.typeOf(x.borrow); if (atomicPointee(t)) return ordinaryAtomicAccess(fc, span, x.borrow, "atomic.store"); if (t != .mut) return fc.kindError(span, x.borrow, "mut"); try fc.expectValue(span, x.value, t.mut.*); if (m.isLinearType(t.mut.*)) try fc.c.report("E1001", span, "store cannot overwrite linear content; use value.swap", &.{}); }, .value_swap => |x| { const t = fc.typeOf(x.borrow); if (atomicPointee(t)) return ordinaryAtomicAccess(fc, span, x.borrow, "atomic operations"); if (t != .mut) return fc.kindError(span, x.borrow, "mut"); try fc.expectValue(span, x.value, t.mut.*); if (!complete(t.mut.*)) try fc.kindError(span, x.value, "a complete value"); }, .buffer_new => |x| { try fc.expectValue(span, x.n, .{ .int = .usize }); try fc.expectAllocCap(span, x.cap); if (!complete(x.ty)) return fc.kindError(span, x.n, "complete buffer content"); try fc.expectParams(span, x.ok, &.{.{ .buffer = try boxed(fc.c.arena, x.ty) }}); try fc.expectParams(span, x.err, &.{.{ .builtin = .alloc_error }}); }, .buffer_len, .buffer_capacity, .buffer_view => |v| { _ = try bufferElement(fc, span, v, false); }, .buffer_reserve => |x| { _ = try bufferElement(fc, span, x.borrow, true); try fc.expectValue(span, x.n, .{ .int = .usize }); try fc.expectAllocCap(span, x.cap); try fc.expectParams(span, x.err, &.{.{ .builtin = .alloc_error }}); }, .buffer_push => |x| { const t = try bufferElement(fc, span, x.borrow, true) orelse return; try fc.expectValue(span, x.value, t); try fc.expectParams(span, x.err, &.{t}); }, .buffer_pop => |x| { const t = try bufferElement(fc, span, x.value, true) orelse return; try fc.expectParams(span, x.ok, &.{t}); }, .buffer_free => |x| { const t = fc.typeOf(x.value); if (t != .buffer) return fc.kindError(span, x.value, "buffer"); try fc.expectParams(span, x.err, &.{t}); }, .array_make => |x| { if (x.ty != .array) return fc.c.report("E1001", span, "array.make needs an array type", &.{}); if (x.args.len != x.ty.array.len) return fc.c.report("E1001", span, "array.make requires every element", &.{}); for (x.args) |arg| try fc.expectValue(span, arg, x.ty.array.elem); }, .aggregate_unpack => |x| { try fc.expectValue(span, x.value, x.ty); switch (x.ty) { .array => |a| for (f.blocks[x.next].params) |p| { if (!p.ty.eql(a.elem)) try fc.mismatch(span, try fc.c.valueName(f, p.value), a.elem, p.ty); }, .named => |i| if (m.types[i].kind == .@"struct") { for (f.blocks[x.next].params, m.types[i].kind.@"struct") |p, field| if (!p.ty.eql(field.ty)) try fc.mismatch(span, try fc.c.valueName(f, p.value), field.ty, p.ty); } else try fc.c.report("E1001", span, "unpack requires a struct or array", &.{}), else => try fc.c.report("E1001", span, "unpack requires a struct or array", &.{}), } }, .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); if (m.isLinearType(x.ty.array.elem)) try fc.c.report("E1001", span, "array.splat cannot duplicate linear elements", &.{}); }, .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 and m.isLinearType(d.inner().?)) return fc.c.report("E1001", span, "slice.copy cannot copy linear elements", &.{}); if (d != .slice_mut) return fc.kindError(span, x.dst, "slice_mut"); 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, .assume => |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 }); }, .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 }); if (m.isLinearType(m.types[x.decl].kind.@"struct"[x.field].ty)) try fc.c.report("E1001", span, "linear fields require whole unpack or borrowed exchange", &.{}); }, .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); }, inline .enum_switch, .enum_take => |x| { if (inst.op == .enum_take and x.ty != .named) try fc.c.report("E1001", span, "enum.take requires a declared enum", &.{}); if (inst.op == .enum_switch and m.isLinearType(x.ty)) try fc.c.report("E1001", span, "linear enums require enum.take", &.{}); try fc.expectValue(span, x.value, x.ty); for (x.arms) |arm| { const params = f.blocks[arm.block].params; for (params, m.variantPayload(x.ty, arm.variant)) |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); }, .intrinsic => |x| try checkIntrinsic(fc, inst, x), .own_pack => |x| { try fc.expectAllocCap(span, x.cap); try fc.expectValue(span, x.value, x.ty); if (!complete(x.ty)) return fc.kindError(span, x.value, "a complete value"); try fc.expectParams(span, x.ok, &.{.{ .own = try boxed(fc.c.arena, x.ty) }}); try fc.expectParams(span, x.err, &.{ .{ .builtin = .alloc_error }, x.ty }); }, .own_new => |x| { try fc.expectAllocCap(span, x.cap); const t = fc.typeOf(x.value); if (!t.isValue() or m.isLinearType(t)) return fc.kindError(span, x.value, "a Copy value type"); try fc.expectOkErr(span, x.ok, x.err, .{ .own = try boxed(fc.c.arena, t) }); }, .own_array => |x| { try fc.expectValue(span, x.n, .{ .int = .usize }); try fc.expectAllocCap(span, x.cap); const t = fc.typeOf(x.value); if (!t.isValue() or m.isLinearType(t)) return fc.kindError(span, x.value, "a Copy value type"); try fc.expectOkErr(span, x.ok, x.err, .{ .own_array = try boxed(fc.c.arena, t) }); }, .own_take => |v| if (fc.typeOf(v) != .own) try fc.kindError(span, v, "own"), .own_free => |v| { const t = fc.typeOf(v); if (t != .own and t != .own_array) return fc.kindError(span, v, "own or own_array"); if (m.isLinearType(t.inner().?)) try fc.c.report("E1001", span, "own.free cannot destroy linear content; use own.take", &.{}); }, .region_create => |x| { try fc.expectAllocCap(span, x.cap); try fc.expectOkErr(span, x.ok, x.err, .region); }, .region_new => |x| { try fc.expectRegionRef(span, x.region); const t = fc.typeOf(x.value); if (!t.isValue() or m.isLinearType(t)) return fc.kindError(span, x.value, "a Copy value type"); try fc.expectOkErr(span, x.ok, x.err, .{ .mut = try boxed(fc.c.arena, t) }); }, .region_array => |x| { try fc.expectRegionRef(span, x.region); try fc.expectValue(span, x.n, .{ .int = .usize }); const t = fc.typeOf(x.value); if (!t.isValue() or m.isLinearType(t)) return fc.kindError(span, x.value, "a Copy value type"); try fc.expectOkErr(span, x.ok, x.err, .{ .slice_mut = try boxed(fc.c.arena, t) }); }, .region_reset, .region_destroy => |v| if (fc.typeOf(v) != .region) try fc.kindError(span, v, "region"), .task_scope_begin, .task_cancelled => {}, .task_scope_end => |v| if (fc.typeOf(v) != .scope) try fc.kindError(span, v, "scope"), .task_cancel => |v| if (fc.typeOf(v) != .task) try fc.kindError(span, v, "task"), .task_join => |v| { const t = fc.typeOf(v); if (t != .task) return fc.kindError(span, v, "task"); const r = t.task.*; if (inst.result != null and r == .void) try fc.c.report("E1001", span, "joining a void task must not bind a result", &.{.{ .name = "function", .value = .{ .str = f.name } }}); if (inst.result == null and r != .void and r != .never) try fc.c.report("E1001", span, "the result of task.join must be bound", &.{.{ .name = "function", .value = .{ .str = f.name } }}); }, .task_spawn => |x| try checkSpawn(fc, inst, x), .task_check_cancel, .task_shield_begin => {}, .task_shield_end => |v| if (fc.typeOf(v) != .shield) try fc.kindError(span, v, "shield"), .task_join_cancel => |x| { const t = fc.typeOf(x.task); if (t != .task) return fc.kindError(span, x.task, "task"); try fc.expectParams(span, x.ok, &.{t.task.*}); try fc.expectParams(span, x.cancelled, &.{t}); }, .channel_make => |x| { try fc.expectValue(span, x.cap, .{ .int = .usize }); try fc.expectAllocCap(span, x.mem); try checkElement(fc, span, x.elem); const e = try boxed(fc.c.arena, x.elem); try fc.expectParams(span, x.ok, &.{ .{ .sender = e }, .{ .receiver = e } }); try fc.expectParams(span, x.err, &.{.{ .builtin = .alloc_error }}); }, .channel_dup => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "ref>"), .channel_send => |x| { const t = fc.typeOf(x.sender); if (t != .mut or t.mut.* != .sender) return fc.kindError(span, x.sender, "mut>"); const e = t.mut.sender.*; try fc.expectValue(span, x.value, e); try fc.expectParams(span, x.closed, &.{e}); try fc.expectParams(span, x.cancelled, &.{e}); }, .channel_recv => |x| { const t = fc.typeOf(x.receiver); if (t != .mut or t.mut.* != .receiver) return fc.kindError(span, x.receiver, "mut>"); try fc.expectParams(span, x.ok, &.{t.mut.receiver.*}); }, .channel_close_sender => |v| if (fc.typeOf(v) != .sender) try fc.kindError(span, v, "sender"), .channel_close_receiver => |x| { const t = fc.typeOf(x.receiver); if (t != .receiver) return fc.kindError(span, x.receiver, "receiver"); try fc.expectParams(span, x.pending, &.{t}); }, .select => |x| try checkSelect(fc, inst, x), .mutex_make => |v| try checkElement(fc, span, fc.typeOf(v)), .mutex_take => |v| if (fc.typeOf(v) != .mutex) try fc.kindError(span, v, "mutex"), .mutex_lock => |x| { const t = fc.typeOf(x.mutex); if (t != .ref or t.ref.* != .mutex) return fc.kindError(span, x.mutex, "ref>"); try fc.expectParams(span, x.ok, &.{.{ .guard = t.ref.mutex }}); }, .mutex_borrow, .mutex_unlock => |v| if (fc.typeOf(v) != .guard) try fc.kindError(span, v, "guard"), inline .island_create, .arc_new => |x| { try fc.expectAllocCap(span, x.cap); const t = fc.typeOf(x.value); // A non-IslandSafe content is reported at the owner type (E2111). if (!isIslandSafe(m, t)) return; const b = try boxed(fc.c.arena, t); try fc.expectOkErr(span, x.ok, x.err, if (inst.op == .arc_new) Type{ .arc = b } else Type{ .island = b }); }, .island_alloc => |x| { const g = fc.typeOf(x.island); if (g != .mut or g.mut.* != .island) return fc.kindError(span, x.island, "mut>"); const t = fc.typeOf(x.value); if (!isIslandSafe(m, t)) return graphContent(fc, span, t, "IslandSafe"); try fc.expectOkErr(span, x.ok, x.err, .{ .iref = try boxed(fc.c.arena, t) }); }, .island_root => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "ref> or mut>"), .frozen_root => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "ref>"), .arc_root => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "ref>"), .island_borrow => |x| if (resultOf(fc, inst) == .void) try fc.kindError(span, x.owner, "ref> or mut>, and an iref"), .frozen_borrow => |x| if (resultOf(fc, inst) == .void) try fc.kindError(span, x.owner, "ref> and an iref"), .arc_borrow => |x| if (resultOf(fc, inst) == .void) try fc.kindError(span, x.owner, "ref> and an iref"), .island_freeze => |v| if (fc.typeOf(v) != .island) try fc.kindError(span, v, "island"), .island_destroy => |v| if (fc.typeOf(v) != .island) try fc.kindError(span, v, "island"), .frozen_release, .arc_from_frozen => |v| if (fc.typeOf(v) != .frozen) try fc.kindError(span, v, "frozen"), .arc_clone => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "ref>"), .arc_release => |v| if (fc.typeOf(v) != .arc) try fc.kindError(span, v, "arc"), .iref_eq => |x| { const a = fc.typeOf(x.a); if (a != .iref) return fc.kindError(span, x.a, "iref"); try fc.expectValue(span, x.b, a); }, // Atomics (spec 04 §23–§25, §42). .atomic_new => |v| if (!isAtomicScalar(fc.typeOf(v))) try fc.kindError(span, v, "bool or an integer of at most 64 bits"), .atomic_take => |v| if (fc.typeOf(v) != .atomic) try fc.kindError(span, v, "atomic"), .atomic_load => |x| { if (resultOf(fc, inst) == .void) return fc.kindError(span, x.cell, "ref>"); try checkOrdering(fc, span, "atomic.load", x.ord, &.{ .relaxed, .acquire, .seq_cst }); }, .atomic_store => |x| { const t = fc.typeOf(x.cell); if (t != .ref or t.ref.* != .atomic) return fc.kindError(span, x.cell, "ref>"); try fc.expectValue(span, x.value, t.ref.atomic.*); try checkOrdering(fc, span, "atomic.store", x.ord, &.{ .relaxed, .release, .seq_cst }); }, .atomic_rmw => |x| { const r = resultOf(fc, inst); if (r == .void) return fc.kindError(span, x.cell, "ref>"); if (r == .bool and (x.op == .add_wrap or x.op == .sub_wrap)) return fc.kindError(span, x.cell, "ref> with an integer T"); try fc.expectValue(span, x.value, r); try checkOrdering(fc, span, try std.fmt.allocPrint(fc.c.arena, "atomic.{s}", .{x.op.text()}), x.ord, &.{ .relaxed, .acquire, .release, .acq_rel, .seq_cst }); }, .atomic_cmpxchg => |x| { const r = resultOf(fc, inst); if (r == .void) return fc.kindError(span, x.cell, "ref>"); try fc.expectValue(span, x.expected, r); try fc.expectValue(span, x.desired, r); try checkOrdering(fc, span, "atomic.cmpxchg", x.success, &.{ .relaxed, .acquire, .release, .acq_rel, .seq_cst }); // A failed compare-exchange is a read, never stronger than the // success ordering (spec 04 §24.1). const failure: []const air.Ordering = switch (x.success) { .relaxed, .release => &.{.relaxed}, .acquire, .acq_rel => &.{ .relaxed, .acquire }, .seq_cst => &.{ .relaxed, .acquire, .seq_cst }, }; try checkOrdering(fc, span, "atomic.cmpxchg failure", x.failure, failure); }, .atomic_fence => |o| try checkOrdering(fc, span, "atomic.fence", o, &.{ .acquire, .release, .acq_rel, .seq_cst }), .cap_narrow => |x| { const t = fc.typeOf(x.cap); if (t != .cap) return fc.kindError(span, x.cap, "cap"); // No form of any kind widens; an unregistered form is reported as // an attempt to widen (spec 05 §10.4). if (!air.authority.hasForm(t.cap, x.form)) try fc.c.report("E3202", span, "narrowing form not defined for this capability kind", &.{ .{ .name = "function", .value = .{ .str = f.name } }, .{ .name = "capability_kind", .value = .{ .str = air.authority.kinds[t.cap].name } }, .{ .name = "form", .value = .{ .str = x.form } }, }); if (std.mem.eql(u8, x.form, "budget")) { if (x.args.len != 1) return fc.c.report("E1001", span, "cap.narrow.budget takes one byte-count operand", &.{.{ .name = "function", .value = .{ .str = f.name } }}); try fc.expectValue(span, x.args[0], .{ .int = .usize }); } if (std.mem.eql(u8, x.form, "prefix")) { if (x.args.len != 1) return fc.c.report("E1001", span, "cap.narrow.prefix takes one path operand", &.{.{ .name = "function", .value = .{ .str = f.name } }}); if (!operandMatches(.bytes, fc.typeOf(x.args[0]))) try fc.kindError(span, x.args[0], "slice"); } const ok = f.blocks[x.ok].params[0]; if (!ok.ty.eql(t)) try fc.mismatch(span, try fc.c.valueName(f, ok.value), t, ok.ty); const err = f.blocks[x.err].params[0]; if (!err.ty.eql(.{ .builtin = .cap_error })) try fc.mismatch(span, try fc.c.valueName(f, err.value), .{ .builtin = .cap_error }, err.ty); }, .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), }, } } /// A graph's content that is not `IslandSafe`/`ArcSafe` (spec 03 §22, §24). fn graphContent(fc: *FnCtx, span: air.Span, t: Type, property: []const u8) !void { try fc.c.report("E2111", span, "a graph holds only plain data and iref handles", &.{ .{ .name = "function", .value = .{ .str = fc.f.name } }, .{ .name = "property", .value = .{ .str = property } }, .{ .name = "found", .value = .{ .str = try fc.c.typeName(t) } }, }); } 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; 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"}); }