Files
aji/src/frontend/lower.zig
T

5834 lines
329 KiB
Zig
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Lowering of `.aji` source 0.1 to canonical text AIR (spec 15).
//!
//! The frontend is a thin layer: it resolves names and source types only as
//! far as needed to choose AIR instructions, and writes canonical AIR text
//! together with a line map (AIR line → source span). Every semantic
//! judgement — ownership, borrows, resources, effects, concurrency — is left
//! to the AIR verifier, which reports at the mapped source location.
//!
//! The frontend never repairs a program: it does not add `move`, effects,
//! closes or error handling. It generates only representation mechanics
//! (SSA, blocks, block parameters, the `features` header).
//!
//! Layers implemented here (spec 15 is implemented layer by layer; a
//! construct of a later layer is reported as not yet implemented):
//! 1. scalars, expressions, functions, control flow;
//! 2. structs, enums, exhaustive `match`;
//! 3–4. addressable values (frame storage chosen by lowering), lexical
//! borrows, places, arrays, slices, byte strings;
//! 5. linear values with explicit `move`, `own`, regions, `cap<mem.alloc>`,
//! outcome matches and `or trap`;
//! 6. intrinsics (I/O, files, TCP, clock, random), resources, capability
//! narrowing, unsafe operations;
//! 7. task scopes, spawn and join, channels;
//! 8. `lock` and mutexes, `select`, cancellation points, shields;
//! 9. islands, frozen graphs, arcs and `iref` handles (spec 03 §22–§24).
const std = @import("std");
const ast = @import("ast.zig");
const parse_mod = @import("parse.zig");
const authority = @import("../air/authority.zig");
const features_mod = @import("../air/features.zig");
const air_module = @import("../air/module.zig");
const properties = @import("../air/properties.zig");
const verifier_types = @import("../verifier/types.zig");
const type_positions = @import("type_positions.zig");
const type_properties = @import("type_properties.zig");
const Allocator = std.mem.Allocator;
const Span = ast.Span;
/// A source-level type: the subset of AIR types the implemented layers use.
pub const Ty = union(enum) {
int: []const u8,
bool,
void,
never,
/// A declared struct or enum: index into the module's type declarations.
named: u32,
array: *const Arr,
ref: *const Ty,
mut: *const Ty,
slice: *const Ty,
slice_mut: *const Ty,
own: *const Ty,
own_array: *const Ty,
buffer: *const Ty,
region,
/// `cap<K>`: the kind.
cap: []const u8,
/// A built-in enum (`alloc_error`, `cap_error`, `io_error`).
builtin: authority.Builtin,
/// `file<read|write|append>`, `stream`, `listener`.
resource: authority.Resource,
/// `task<T>`, `sender<T>`, `receiver<T>`: the element or result type.
task: *const Ty,
sender: *const Ty,
receiver: *const Ty,
/// A task scope (bound by `scope s { … }`, never written as a type).
scope,
/// `mutex<T>`; `guard<T>` is never a source value (the `lock` block).
mutex: *const Ty,
guard: *const Ty,
/// A shield (`shield { … }`, never a source value).
shield,
/// Graph owners and handles (spec 03 §22–§24).
island: *const Ty,
frozen: *const Ty,
arc: *const Ty,
iref: *const Ty,
/// `atomic<T>` (spec 04 §23; layer 10): a linear cell.
atomic: *const Ty,
pub const Arr = struct { elem: Ty, len: u64 };
/// Linear: consumed exactly once, by `move` (spec 15 §5).
fn isLinear(t: Ty) bool {
return switch (t) {
.own, .own_array, .buffer, .region, .resource, .task, .sender, .receiver, .scope, .mutex, .guard, .shield, .island, .frozen, .arc, .atomic => true,
else => false,
};
}
fn eql(initial_a: Ty, initial_b: Ty) bool {
var a = initial_a;
var b = initial_b;
while (true) {
if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false;
switch (a) {
.int => |x| return std.mem.eql(u8, x, b.int),
.named => |i| return i == b.named,
.array => |x| {
if (x.len != b.array.len) return false;
a = x.elem;
b = b.array.elem;
},
.ref, .mut, .slice, .slice_mut, .own, .own_array, .buffer, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| {
a = x.*;
b = inner(b).?;
},
.cap => |k| return std.mem.eql(u8, k, b.cap),
.builtin => |e| return e == b.builtin,
.resource => |r| return r == b.resource,
.bool, .void, .never, .region, .scope, .shield => return true,
}
}
}
fn inner(t: Ty) ?Ty {
return switch (t) {
.ref, .mut, .slice, .slice_mut, .own, .own_array, .buffer, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| x.*,
.array => |a| a.elem,
else => null,
};
}
fn isBorrow(t: Ty) bool {
return t == .ref or t == .mut or t == .slice or t == .slice_mut;
}
fn isMutBorrow(t: Ty) bool {
return t == .mut or t == .slice_mut;
}
};
const int_types = [_][]const u8{ "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize" };
/// AtomicScalar (spec 04 §23): `bool` and integers of at most 64 bits.
fn atomicScalar(t: Ty) bool {
return t == .bool or (t == .int and intBits(t.int) <= 64);
}
fn isIntName(n: []const u8) bool {
for (int_types) |t| if (std.mem.eql(u8, t, n)) return true;
return false;
}
fn isSigned(n: []const u8) bool {
return n[0] == 'i';
}
fn intBits(n: []const u8) u16 {
if (std.mem.endsWith(u8, n, "size")) return 64;
return std.fmt.parseInt(u16, n[1..], 10) catch 64;
}
pub const InvalidReason = @import("../diag.zig").SourceInvalidReason;
pub const Problem = struct {
reason: ?InvalidReason = null,
code: []const u8,
span: Span,
message: []const u8,
fields: []const Field = &.{},
repair_candidates: []const @import("../diag.zig").RepairCandidate = &.{},
pub const Field = struct { name: []const u8, value: []const u8 };
};
pub const Output = struct {
air: []const u8,
/// `lines[i]` is the source span of AIR line `i + 1`, if any.
lines: []const ?Span,
/// The same AIR with `; line:col-line:col` comments before each
/// instruction and block label (not canonical; `aji lower --annotate`).
annotated: []const u8,
/// Byte-string materializations, for the normalized size metric
/// (spec 15 §11): `constant_of[i]` is 0, or `k` when AIR line `i + 1`
/// belongs to the materialization of `constants[k - 1]`.
constant_of: []const u32,
constants: []const Constant,
pub const Constant = struct { storage: []const u8, bytes: []const u8 };
};
pub const Result = union(enum) {
ok: Output,
/// A source problem (`E7xxx`).
err: Problem,
errors: []const Problem,
/// A construct of a layer that is not implemented yet.
unimplemented: struct { span: Span, construct: []const u8 },
};
const Error = error{ Lower, Unimplemented, OutOfMemory };
pub fn lower(arena: Allocator, m: ast.Module) Allocator.Error!Result {
var l: Lowerer = .{ .arena = arena, .m = m };
l.run() catch |e| switch (e) {
error.Lower => return if (l.problems.items.len > 1) .{ .errors = l.problems.items } else .{ .err = if (l.problems.items.len == 1) l.problems.items[0] else l.problem.? },
error.Unimplemented => return .{ .unimplemented = l.unimpl.? },
error.OutOfMemory => return error.OutOfMemory,
};
return .{ .ok = .{ .air = l.out.items, .lines = l.lines.items, .annotated = l.annotated.items, .constant_of = l.constant_of.items, .constants = l.constants.items } };
}
/// `constant`: 0, or the 1-based index of the byte-string constant whose
/// materialization the instruction belongs to.
const Inst = struct { text: []const u8, span: ?Span, constant: u32 = 0 };
const Block = struct {
name: []const u8,
/// The source construct that creates this block (including joins).
span: Span,
params: std.ArrayList(Param) = .empty,
insts: std.ArrayList(Inst) = .empty,
terminated: bool = false,
};
const Param = struct { name: []const u8, ty: Ty };
const Binding = struct {
name: []const u8,
/// Assignable (`var`).
mutable: bool,
/// For `ssa`: the SSA value. For `storage`: the `local<T>` value. For
/// `borrow`: the borrow value.
value: []const u8,
/// For `storage`: the stored type `T`.
ty: Ty,
kind: Kind = .ssa,
const Kind = enum { ssa, storage, borrow };
};
/// A borrow to end with `borrow.end` when its scope ends (spec 15 §9).
/// Something ended at every normal exit of a lexical scope, innermost
/// first: a borrow (`borrow.end`) or a task scope (`task.scope.end`).
const BorrowEnd = struct { name: []const u8, span: Span, op: []const u8 = "borrow.end" };
/// A bounds fact the verifier can prove (spec 08 §12, "fact on the same
/// slice"): inside the true branch of `if i < s.len`, with `i` and `s`
/// still the same SSA values.
const Fact = struct { index: []const u8, slice: []const u8 };
/// A borrowed place: the final borrow and the chain of borrows created for
/// it, to be ended in reverse order.
const Placed = struct { v: Value, ends: []const []const u8 };
const Loop = struct {
/// Target of `continue`.
@"continue": usize,
exit: usize,
/// Number of bindings visible when the loop started; the variables among
/// them are the loop's carried state.
depth: usize,
/// Number of borrow scopes open when the loop started: `break` and
/// `continue` end the borrows of every scope above it.
scope_depth: usize,
/// Variables carried to the loop's header (and `continue` target) and
/// to its exit.
header_vars: []const usize = &.{},
exit_vars: []const usize = &.{},
};
const FnOut = struct {
header: []const u8,
effects: []const u8,
span: Span,
blocks: []const Block,
};
const Value = struct { name: []const u8, ty: Ty };
/// What remains to be lowered in an enclosing block: the statements after
/// the current one, the tail, the current statement itself, and, for a loop
/// body, the loop (whose next iteration also follows).
const Rest = struct {
stmts: []const ast.Stmt,
tail: ?*const ast.Expr,
current: ?ast.Stmt = null,
/// The tail expression, while it is being lowered.
current_expr: ?*const ast.Expr = null,
loop: ?LoopAst = null,
};
const LoopAst = struct { cond: ?ast.Expr, body: ast.Block, step: ?[]const u8 };
const FnSig = struct { params: []const Ty, ret: Ty, from: ?usize = null, air_name: []const u8, display_name: []const u8 };
const Lowerer = struct {
arena: Allocator,
m: ast.Module,
out: std.ArrayList(u8) = .empty,
annotated: std.ArrayList(u8) = .empty,
lines: std.ArrayList(?Span) = .empty,
constant_of: std.ArrayList(u32) = .empty,
constants: std.ArrayList(Output.Constant) = .empty,
/// Set while a byte string is materialized: the tag for its instructions.
in_constant: u32 = 0,
problem: ?Problem = null,
problems: std.ArrayList(Problem) = .empty,
unimpl: ?@FieldType(Result, "unimplemented") = null,
sigs: std.StringHashMapUnmanaged(FnSig) = .empty,
/// `@Name` of each declared type.
typeNames: []const []const u8 = &.{},
// Per function.
blocks: std.ArrayList(Block) = .empty,
cur: ?usize = null,
bindings: std.ArrayList(Binding) = .empty,
loops: std.ArrayList(Loop) = .empty,
counter: u32 = 0,
/// Features found while lowering rather than by scanning the text.
uses: std.EnumSet(UseFeature) = .empty,
/// Set while lowering a `ref unchecked …` place: its index is unchecked.
unchecked: bool = false,
/// The current function's parameter names, which generated names avoid.
params: []const ast.Param = &.{},
ret: Ty = .void,
/// Mechanical ancestry for transferring lexical ends; AIR verifies provenance.
borrow_parents: std.StringHashMapUnmanaged([]const u8) = .empty,
/// Statements still to be lowered in each enclosing block (innermost
/// last), for inferring the type of an untyped `let` from its uses.
rest: std.ArrayList(Rest) = .empty,
/// Set by a loop just before lowering its body: the body's `Rest` frame.
pending_loop: ?LoopAst = null,
/// Set by `scope`, `shield` and `lock` just before lowering a body:
/// bindings and ends that belong to the body's own lexical scope (ends
/// in creation order; they run innermost first at every normal exit).
pending_bindings: std.ArrayList(Binding) = .empty,
pending_ends: std.ArrayList(BorrowEnd) = .empty,
/// Borrows to end at the end of each open lexical scope (innermost last).
scopes: std.ArrayList(std.ArrayList(BorrowEnd)) = .empty,
/// `local.alloc` instructions; they go first in the entry block.
allocs: std.ArrayList(Inst) = .empty,
/// Names whose variables need frame storage (borrowed or indexed).
addressable: std.StringHashMapUnmanaged(void) = .empty,
facts: std.ArrayList(Fact) = .empty,
/// Index of the first binding of the innermost scope (for the no-shadowing rule).
scope_binding_start: usize = 0,
fns: std.ArrayList(FnOut) = .empty,
linear_enabled: bool = false,
/// Complete declaration snapshot, with finite layouts checked before bodies.
property_module: ?air_module.Module = null,
/// Count witness visits in unit tests, never used to accept/reject source.
property_visits: usize = 0,
fn needsLinearType(l: *Lowerer, initial: Ty, initial_depth: usize) bool {
var t = initial;
var depth = initial_depth;
while (true) {
if (depth > l.m.types.len + 32) return false;
if (t == .named) return l.isLinear(t);
const inner = t.inner() orelse return false;
if ((t == .array or t == .own or t == .own_array or t == .slice or t == .slice_mut) and l.isLinear(inner)) return true;
t = inner;
depth += 1;
}
}
fn isLinear(l: *Lowerer, initial: Ty) bool {
// Signatures/declarations resolve before checkRequirements; all
// structural ownership queries run after its immutable snapshot.
var t = initial;
while (true) {
if (t.isLinear()) return true;
switch (t) {
.array => |a| t = a.elem,
.named => |i| return l.property_module.?.nominal_properties.?[i].linear,
else => return false,
}
}
}
fn fail(l: *Lowerer, comptime code: []const u8, span: Span, message: []const u8, fields: []const Problem.Field) Error {
if (comptime std.mem.eql(u8, code, "E7006")) @compileError("E7006 requires an explicit reason via invalid()");
// `fields` usually points at a temporary array: keep a copy.
l.problem = .{ .code = code, .span = span, .message = message, .fields = try l.arena.dupe(Problem.Field, fields) };
return error.Lower;
}
fn invalid(l: *Lowerer, reason: InvalidReason, span: Span, message: []const u8, fields: []const Problem.Field) Error {
l.problem = .{ .code = "E7006", .reason = reason, .span = span, .message = message, .fields = try l.arena.dupe(Problem.Field, fields) };
return error.Lower;
}
fn invalidWidening(l: *Lowerer, span: Span, fields: []const Problem.Field) Error {
l.problem = .{
.code = "E7005",
.span = span,
.message = "`as` only widens without loss; use `as!` (checked, traps T0006 when the value does not fit) or `as%` (wrapping)",
.fields = try l.arena.dupe(Problem.Field, fields),
.repair_candidates = @import("../diag.zig").SourceRepairKind.one(.numeric_cast_modes),
};
return error.Lower;
}
fn notYet(l: *Lowerer, span: Span, construct: []const u8) Error {
l.unimpl = .{ .span = span, .construct = construct };
return error.Unimplemented;
}
fn tyText(l: *Lowerer, t: Ty) Allocator.Error![]const u8 {
return l.typeText(t, false);
}
fn diagnosticTyText(l: *Lowerer, t: Ty) Allocator.Error![]const u8 {
return l.typeText(t, true);
}
fn typeText(l: *Lowerer, annotation: Ty, source_names: bool) Allocator.Error![]const u8 {
var pending: std.ArrayList(Ty) = .empty;
defer pending.deinit(l.arena);
var out: std.ArrayList(u8) = .empty;
defer out.deinit(l.arena);
var t = annotation;
while (t.inner()) |inner| {
try pending.append(l.arena, t);
if (t == .array) {
try out.appendSlice(l.arena, "array<");
} else {
try out.appendSlice(l.arena, @tagName(t));
try out.append(l.arena, '<');
}
t = inner;
}
const leaf: ?[]const u8 = switch (t) {
.int => |x| x,
.bool => "bool",
.void => "void",
.never => "never",
.named => |i| if (source_names and l.m.types[i].air_name != null) (l.m.types[i].display_name orelse l.m.types[i].name) else l.typeNames[i],
.scope => "scope",
.shield => "shield",
.region => "region",
.cap => |k| leaf: {
try out.appendSlice(l.arena, "cap<");
try out.appendSlice(l.arena, k);
try out.append(l.arena, '>');
break :leaf null;
},
.builtin => |b| leaf: {
if (b == .io_error) l.uses.insert(.resources);
break :leaf @tagName(b);
},
.resource => |r| leaf: {
l.uses.insert(.resources);
break :leaf r.text();
},
else => unreachable, // All anonymous unary nodes were visited above.
};
if (leaf) |text| {
if (pending.items.len == 0) return text;
try out.appendSlice(l.arena, text);
}
while (pending.pop()) |parent| {
if (parent == .array) {
var digits: [20]u8 = undefined;
const length = std.fmt.bufPrint(&digits, "{d}", .{parent.array.len}) catch unreachable;
try out.appendSlice(l.arena, ", ");
try out.appendSlice(l.arena, length);
}
try out.append(l.arena, '>');
}
return out.toOwnedSlice(l.arena);
}
fn wrap(l: *Lowerer, comptime tag: std.meta.Tag(Ty), t: Ty) Error!Ty {
const b = try l.arena.create(Ty);
b.* = t;
return @unionInit(Ty, @tagName(tag), b);
}
fn arrayOf(l: *Lowerer, elem: Ty, len: u64) Error!Ty {
const a = try l.arena.create(Ty.Arr);
a.* = .{ .elem = elem, .len = len };
return .{ .array = a };
}
fn decl(l: *Lowerer, t: Ty) ?ast.TypeDecl {
return if (t == .named) l.m.types[t.named] else null;
}
fn fmt(l: *Lowerer, comptime f: []const u8, args: anytype) Error![]const u8 {
return std.fmt.allocPrint(l.arena, f, args);
}
// ------------------------------------------------------------ output
fn line(l: *Lowerer, text: []const u8, span: ?Span) Error!void {
try l.lineTagged(text, span, 0);
}
fn lineTagged(l: *Lowerer, text: []const u8, span: ?Span, constant: u32) Error!void {
try l.constant_of.append(l.arena, constant);
try l.out.appendSlice(l.arena, text);
try l.out.append(l.arena, '\n');
try l.lines.append(l.arena, span);
if (span) |s| if (std.mem.startsWith(u8, text, " ") or std.mem.endsWith(u8, text, ":")) {
if (s.file) |file| {
try l.annotated.appendSlice(l.arena, try l.fmt(" ; {s}:{d}:{d}-{d}:{d}\n", .{ file, s.start.line, s.start.col, s.end.line, s.end.col }));
} else try l.annotated.appendSlice(l.arena, try l.fmt(" ; {d}:{d}-{d}:{d}\n", .{ s.start.line, s.start.col, s.end.line, s.end.col }));
};
try l.annotated.appendSlice(l.arena, text);
try l.annotated.append(l.arena, '\n');
}
// ------------------------------------------------------------ module
fn run(l: *Lowerer) Error!void {
const names = try l.arena.alloc([]const u8, l.m.types.len);
for (l.m.types, names, 0..) |t, *n, i| {
for (l.m.types[0..i]) |prev| if (std.mem.eql(u8, prev.name, t.name)) return l.invalid(.duplicate_declaration, t.span, "type defined twice", &.{.{ .name = "name", .value = t.name }});
n.* = try l.fmt("@{s}", .{t.air_name orelse t.name});
}
l.typeNames = names;
for (l.m.functions) |f| {
if (l.sigs.contains(f.name)) return l.invalid(.duplicate_declaration, f.span, "function defined twice", &.{.{ .name = "name", .value = f.name }});
const ps = try l.arena.alloc(Ty, f.params.len);
for (f.params, ps) |p, *t| t.* = try l.typeOf(p.ty);
const ret = try l.typeAt(f.ret, .ret);
var origin: ?usize = null;
if (f.from) |name| {
for (f.params, 0..) |param, i| if (std.mem.eql(u8, param.name, name)) {
origin = i;
break;
};
const i = origin orelse return l.unknown(f.span, name);
if (!ret.isBorrow() or !ps[i].isBorrow()) return l.fail("E7005", f.span, "`from` requires a borrow return and a borrow parameter", &.{});
if (ret.isMutBorrow() and !ps[i].isMutBorrow()) return l.fail("E7005", f.span, "an exclusive return requires an exclusive `from` parameter", &.{});
} else if (ret.isBorrow()) return l.invalid(.invalid_borrow_return, f.span, "a borrow return requires `from parameter`", &.{});
if (std.mem.eql(u8, f.name, "main") and ret.isBorrow()) return l.invalid(.invalid_borrow_return, f.span, "main cannot return a borrow", &.{});
for (f.effects) |effect| if (authority.effectIndex(effect) == null) return l.fail("E7002", f.span, "unknown effect", &.{
.{ .name = "name", .value = effect },
.{ .name = "effect", .value = effect },
});
try l.sigs.put(l.arena, f.name, .{ .params = ps, .ret = ret, .from = origin, .air_name = f.air_name orelse f.name, .display_name = f.display_name orelse f.name });
}
if (!l.sigs.contains("main")) return l.fail("E7002", .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 1 } }, "the module has no `main` function", &.{.{ .name = "name", .value = "main" }});
const whole: Span = if (l.m.functions.len != 0) l.m.functions[0].span else .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 1 } };
// Type lines are built first (they can fail); functions are lowered
// before the header is written, because the `features` header is the
// closure of what the lowered AIR uses (spec 15 §9).
var type_lines: std.ArrayList(Inst) = .empty;
for (l.m.types) |t| try type_lines.append(l.arena, .{ .text = try l.typeDeclText(t), .span = t.span });
try l.checkRequirements();
var failed_declarations: std.ArrayList(Span) = .empty;
for (l.m.functions) |f| {
const failed = for (failed_declarations.items) |span| {
if (sameDeclaration(span, f.span)) break true;
} else false;
if (failed) continue;
// Bodies read only validated signatures/declarations. Restore all
// module accumulations on failure, including byte-string constants,
// features and linearity flags; no failed FnOut is ever appended.
const checkpoint = .{ .uses = l.uses, .linear_enabled = l.linear_enabled, .constants_len = l.constants.items.len };
const output = l.function(f) catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
error.Unimplemented => {
if (l.problems.items.len == 0) return error.Unimplemented;
l.uses = checkpoint.uses;
l.linear_enabled = checkpoint.linear_enabled;
l.constants.items.len = checkpoint.constants_len;
l.in_constant = 0;
l.unimpl = null;
continue;
},
error.Lower => {
const problem = l.problem.?;
l.uses = checkpoint.uses;
l.linear_enabled = checkpoint.linear_enabled;
l.constants.items.len = checkpoint.constants_len;
l.in_constant = 0;
l.problem = null;
try l.problems.append(l.arena, problem);
try failed_declarations.append(l.arena, f.span);
if (l.problems.items.len == @import("../diag.zig").source_diagnostic_limit) return error.Lower;
continue;
},
};
try l.fns.append(l.arena, output);
}
if (l.problems.items.len != 0) return error.Lower;
var features: std.ArrayList(u8) = .empty;
const roots = try l.featureRoots(type_lines.items);
const closure = try features_mod.closure(l.arena, &features_mod.registry, roots, null);
for (closure, 0..) |f, i| try features.appendSlice(l.arena, try l.fmt("{s}{s}", .{ if (i == 0) "" else ", ", f }));
try l.line(try l.fmt("module {s}", .{l.m.name}), whole);
try l.line("air 0", whole);
try l.line("lang 0.1", whole);
try l.line(try l.fmt("features [{s}]", .{features.items}), whole);
if (l.m.types.len != 0) try l.line("", null);
for (type_lines.items) |t| try l.line(t.text, t.span);
for (l.fns.items) |f| try l.emitFunction(f);
}
fn airType(l: *Lowerer, annotation: Ty) Error!air_module.Type {
var root: air_module.Type = undefined;
var target = &root;
var t = annotation;
// Allocate in the original outer-to-inner order. Only the completed
// root is returned; targets point at stable output storage, never Ty.
while (true) {
target.* = switch (t) {
.array => |a| {
const out = try l.arena.create(air_module.Type.Array);
out.len = a.len;
target.* = .{ .array = out };
target = &out.elem;
t = a.elem;
continue;
},
inline .ref, .mut, .slice, .slice_mut, .own, .own_array, .buffer, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |inner, tag| {
const out = try l.arena.create(air_module.Type);
target.* = @unionInit(air_module.Type, @tagName(tag), out);
target = out;
t = inner.*;
continue;
},
.int => |n| .{ .int = std.meta.stringToEnum(air_module.IntType, n).? },
.named => |i| .{ .named = i },
.cap => |k| .{ .cap = authority.kindIndex(k).? },
.builtin => |b| .{ .builtin = b },
.resource => |r| .{ .resource = r },
.bool => .bool,
.void => .void,
.never => .never,
.region => .region,
.scope => .scope,
.shield => .shield,
};
return root;
}
}
fn checkRequirements(l: *Lowerer) Error!void {
const types = try l.arena.alloc(air_module.TypeDecl, l.m.types.len);
for (l.m.types, types, 0..) |d, *out, index| {
out.* = .{ .name = d.air_name orelse d.name, .span = .{ .line = @intCast(index + 1), .col = 1 }, .kind = undefined };
switch (d.kind) {
.@"struct" => |fs| {
const fields = try l.arena.alloc(air_module.Field, fs.len);
for (fs, fields) |f, *target| target.* = .{ .name = f.name, .ty = try l.airType(try l.typeOf(f.ty)) };
out.kind = .{ .@"struct" = fields };
},
.@"enum" => |vs| {
const variants = try l.arena.alloc(air_module.Variant, vs.len);
for (vs, variants) |v, *target| {
const payload = try l.arena.alloc(air_module.Type, v.payload.len);
for (v.payload, payload) |t, *p| p.* = try l.airType(try l.typeOf(t));
target.* = .{ .name = v.name, .payload = payload };
}
out.kind = .{ .@"enum" = variants };
},
}
}
const m: air_module.Module = .{ .name = l.m.name, .format_version = 0, .lang = .{ 0, 1 }, .features = &.{"linear_aggregates"}, .types = types, .functions = &.{} };
var layout_context: @import("../verifier.zig").Context = .{ .arena = l.arena, .file = "<generic>", .module = m };
try verifier_types.checkFiniteLayouts(&layout_context);
if (layout_context.diags.items.len != 0) {
const d = l.m.types[layout_context.diags.items[0].span.?.line - 1];
return l.fail("E1003", d.span, "aggregate type contains itself by value", &.{.{ .name = "type", .value = d.display_name orelse d.name }});
}
l.property_module = try properties.prepare(l.arena, m, null);
for (l.m.types, 0..) |_, i| if (l.isLinear(.{ .named = @intCast(i) })) {
l.linear_enabled = true;
};
for (l.m.requirements) |r| {
const ty = try l.typeOf(r.ty);
const t = try l.airType(ty);
if (!properties.bounded(l.property_module.?, t, 0)) return l.invalid(.implementation_limit, r.span, "constraint type traversal is cyclic or exceeds depth 64", &.{});
if (r.property.len == 0) {
var context: @import("../verifier.zig").Context = .{ .arena = l.arena, .file = "<generic>", .module = l.property_module.? };
try verifier_types.checkTypeArgument(&context, .{ .line = 1, .col = 1 }, t);
if (context.diags.items.len != 0) return l.fail("E7005", r.span, "generic argument is not a well-formed concrete type", &.{ .{ .name = "parameter", .value = r.parameter }, .{ .name = "found", .value = try l.diagnosticTyText(ty) } });
continue;
}
const cached = l.property_module.?;
const ok = if (std.mem.eql(u8, r.property, "Copy")) try verifier_types.isCopy(l.arena, cached, t) else if (std.mem.eql(u8, r.property, "Send")) try verifier_types.isSend(l.arena, cached, t) else if (std.mem.eql(u8, r.property, "Share")) try verifier_types.isShare(l.arena, cached, t) else if (std.mem.eql(u8, r.property, "Freeze")) try verifier_types.isIslandSafe(l.arena, cached, t) else try verifier_types.isLocalType(l.arena, cached, t);
if (!ok) return l.fail("E7005", r.span, "generic argument does not satisfy structural constraint", &.{
.{ .name = "parameter", .value = r.parameter },
.{ .name = "constraint", .value = r.property },
.{ .name = "found", .value = try l.diagnosticTyText(ty) },
});
}
}
/// The features the lowered AIR uses directly; the header is their
/// dependency closure (spec 15 §9). `effects` is always declared.
const UseFeature = enum { capabilities, resources, unsafe };
fn featureRoots(l: *Lowerer, type_lines: []const Inst) Error![]const []const u8 {
var texts: std.ArrayList([]const u8) = .empty;
for (type_lines) |t| try texts.append(l.arena, t.text);
for (l.fns.items) |f| {
try texts.append(l.arena, f.header);
for (f.blocks) |b| {
for (b.params.items) |p| try texts.append(l.arena, try l.tyText(p.ty));
for (b.insts.items) |inst| try texts.append(l.arena, inst.text);
}
}
var roots: std.ArrayList([]const u8) = .empty;
try roots.append(l.arena, "effects");
var signatures = l.sigs.valueIterator();
while (signatures.next()) |f| {
for (f.params) |t| if (l.needsLinearType(t, 0)) {
l.linear_enabled = true;
};
if (l.needsLinearType(f.ret, 0)) l.linear_enabled = true;
}
if (l.linear_enabled) try roots.append(l.arena, "linear_aggregates");
const Rule = struct { []const u8, []const []const u8 };
const rules = [_]Rule{
.{ "arrays", &.{ "array<", "slice", "array.splat", "borrow.index" } },
.{ "ownership", &.{ "local.", "borrow.", " load ", "= load ", "store ", "ref<", "mut<" } },
.{ "linear_buffers", &.{ "buffer<", "buffer." } },
.{ "error_values", &.{"error.const "} },
.{ "linear_aggregates", &.{ "array.make ", "struct.unpack ", "array.unpack ", "enum.take ", "value.swap ", "own.pack " } },
.{ "heap", &.{ "own.", "own<", "own_array<", "alloc_error" } },
.{ "regions", &.{"region"} },
.{ "capabilities", &.{ "cap<", "cap.narrow", "cap_error" } },
.{ "tasks", &.{ "task.", "task<", ": scope" } },
.{ "channels", &.{ "channel.", "sender<", "receiver<", "select [" } },
.{ "sync", &.{ "mutex.", "mutex<", "guard<" } },
.{ "cancellation", &.{ "task.shield", "task.check_cancel", "task.join.cancel" } },
.{ "islands", &.{ "island.", "island<", "frozen.", "frozen<", "iref.", "iref<" } },
.{ "arc", &.{ "arc.", "arc<" } },
// Instructions only: the effect names `atomic` and `atomic.weak`
// in a function header are not uses of the feature.
.{ "atomics", &.{ "= atomic.", "atomic.store.", "atomic.fence.", "atomic<" } },
};
for (rules) |r| {
const used = for (texts.items) |t| {
const hit = for (r[1]) |w| {
if (std.mem.indexOf(u8, t, w) != null or (std.mem.eql(u8, w, "store ") and std.mem.startsWith(u8, t, "store "))) break true;
} else false;
if (hit) break true;
} else false;
if (used) try roots.append(l.arena, r[0]);
}
var it = l.uses.iterator();
while (it.next()) |u| try roots.append(l.arena, @tagName(u));
return roots.items;
}
/// `type @T = struct { … }` / `enum { … }` in canonical form.
fn typeDeclText(l: *Lowerer, t: ast.TypeDecl) Error![]const u8 {
var w: std.ArrayList(u8) = .empty;
try w.appendSlice(l.arena, try l.fmt("type @{s} = ", .{t.air_name orelse t.name}));
switch (t.kind) {
.@"struct" => |fields| {
try w.appendSlice(l.arena, "struct {");
for (fields, 0..) |f, i| {
for (fields[0..i]) |prev| if (std.mem.eql(u8, prev.name, f.name)) return l.invalid(.duplicate_declaration, f.span, "field declared twice", &.{.{ .name = "field", .value = f.name }});
const ft = try l.memberType(f.ty);
try w.appendSlice(l.arena, try l.fmt("{s}{s}: {s}", .{ if (i == 0) " " else ", ", f.name, try l.tyText(ft) }));
}
try w.appendSlice(l.arena, if (fields.len == 0) "}" else " }");
},
.@"enum" => |vs| {
if (vs.len == 0) return l.invalid(.invalid_declaration, t.span, "an enum needs at least one variant", &.{.{ .name = "type", .value = t.name }});
try w.appendSlice(l.arena, "enum { ");
for (vs, 0..) |v, i| {
for (vs[0..i]) |prev| if (std.mem.eql(u8, prev.name, v.name)) return l.invalid(.duplicate_declaration, v.span, "variant declared twice", &.{.{ .name = "variant", .value = v.name }});
if (i != 0) try w.appendSlice(l.arena, ", ");
try w.appendSlice(l.arena, v.name);
if (v.payload.len != 0) {
try w.append(l.arena, '(');
for (v.payload, 0..) |pt, j| try w.appendSlice(l.arena, try l.fmt("{s}{s}", .{ if (j == 0) "" else ", ", try l.tyText(try l.memberType(pt)) }));
try w.append(l.arena, ')');
}
}
try w.appendSlice(l.arena, " }");
},
}
return w.items;
}
fn memberType(l: *Lowerer, t: ast.Type) Error!Ty {
return l.typeAt(t, .member);
}
fn typeOf(l: *Lowerer, t: ast.Type) Error!Ty {
return l.typeAt(t, .param);
}
fn typeAt(l: *Lowerer, t: ast.Type, position: type_positions.Position) Error!Ty {
if (type_positions.firstInvalid(t, position)) |bad| return l.fail("E7005", bad.span, "type constructor not allowed in this position", &.{
.{ .name = "position", .value = @tagName(bad.position) },
.{ .name = "type_constructor", .value = bad.constructor },
});
const ty = try l.resolveType(t);
if (try type_properties.firstInvalid(t, l, propertyDecl, &.{})) |bad| return l.copyArrayError(bad.span);
return ty;
}
fn propertyDecl(l: *Lowerer, name: []const u8, span: Span) ?ast.TypeDecl {
const ty = l.enumOrStruct(name, span) orelse return null;
return l.m.types[ty.named];
}
fn copyArrayError(l: *Lowerer, span: Span) Error {
return l.fail("E7005", span, "dynamic heap arrays require Copy content", &.{
.{ .name = "constraint", .value = "Copy" },
.{ .name = "type_constructor", .value = "own_array" },
});
}
const TypeWrapper = enum { ref, mut, slice, slice_mut, own, own_array, buffer, task, sender, receiver, mutex, island, frozen, arc, iref, atomic };
const TypeResolutionFrame = union(enum) {
array: struct { len: u64, elem_span: Span },
wrapped: struct { which: TypeWrapper, span: Span },
};
fn resolveType(l: *Lowerer, annotation: ast.Type) Error!Ty {
var pending: std.ArrayList(TypeResolutionFrame) = .empty;
defer pending.deinit(l.arena);
var t = annotation;
// Validate each constructor before descending; content checks and
// construction happen while unwinding, in the original order.
var ty: Ty = leaf: while (true) {
switch (t.kind) {
.applied => return l.fail("E7002", t.span, "unknown generic type", &.{}),
.function_ref => return l.invalid(.invalid_static_function, t.span, "static functions are not runtime types", &.{}),
.name => |n| {
if (isIntName(n)) break :leaf .{ .int = n };
if (std.mem.eql(u8, n, "bool")) break :leaf .bool;
if (std.mem.eql(u8, n, "void")) break :leaf .void;
if (std.mem.eql(u8, n, "never")) break :leaf .never;
if (l.enumOrStruct(n, t.span)) |named| break :leaf named;
if (std.mem.eql(u8, n, "region")) break :leaf .region;
if (std.meta.stringToEnum(authority.Builtin, n)) |b| break :leaf .{ .builtin = b };
if (std.mem.eql(u8, n, "stream")) break :leaf .{ .resource = .stream };
if (std.mem.eql(u8, n, "listener")) break :leaf .{ .resource = .listener };
return l.fail("E7002", t.span, "unknown type", &.{.{ .name = "name", .value = n }});
},
.array => |a| {
if (a.len == 0 or a.len > (@as(u64, 1) << 32)) return l.fail("E7005", t.span, "array length must be between 1 and 2^32", &.{});
try pending.append(l.arena, .{ .array = .{ .len = a.len, .elem_span = a.elem.span } });
t = a.elem.*;
},
.wrapped => |w| {
const which = std.meta.stringToEnum(TypeWrapper, w.wrapper) orelse return l.notYet(t.span, "this type (later layers)");
try pending.append(l.arena, .{ .wrapped = .{ .which = which, .span = t.span } });
t = w.inner.*;
},
.cap => |k| {
if (authority.kindIndex(k) == null) return l.fail("E7002", t.span, "unknown capability kind", &.{.{ .name = "capability_kind", .value = k }});
break :leaf .{ .cap = k };
},
.file => |m| {
const r: authority.Resource = if (std.mem.eql(u8, m, "read")) .file_read else if (std.mem.eql(u8, m, "write")) .file_write else if (std.mem.eql(u8, m, "append")) .file_append else return l.fail("E7002", t.span, "unknown file mode (read, write, append)", &.{.{ .name = "mode", .value = m }});
break :leaf .{ .resource = r };
},
}
};
while (pending.pop()) |frame| switch (frame) {
.array => |a| {
if (ty == .void or ty == .never) return l.fail("E7005", a.elem_span, "an array element needs a value type", &.{});
ty = try l.arrayOf(ty, a.len);
},
.wrapped => |w| {
ty = try switch (w.which) {
.ref => l.wrap(.ref, ty),
.mut => l.wrap(.mut, ty),
.slice => l.wrap(.slice, ty),
.slice_mut => l.wrap(.slice_mut, ty),
.own => l.wrap(.own, ty),
.own_array => l.wrap(.own_array, ty),
.buffer => l.wrap(.buffer, ty),
.task => l.wrap(.task, ty),
.sender => l.wrap(.sender, ty),
.receiver => l.wrap(.receiver, ty),
.mutex => l.wrap(.mutex, ty),
.island => l.wrap(.island, ty),
.frozen => l.wrap(.frozen, ty),
.arc => l.wrap(.arc, ty),
.iref => l.wrap(.iref, ty),
.atomic => if (atomicScalar(ty)) l.wrap(.atomic, ty) else l.fail("E7005", w.span, "atomic<T> needs bool or an integer of at most 64 bits", &.{.{ .name = "found", .value = try l.diagnosticTyText(ty) }}),
};
},
};
return ty;
}
// ------------------------------------------------------------ functions
fn arrayElement(l: *Lowerer, span: Span, ty: Ty, repeated: bool) Error!void {
if (ty.isBorrow()) return l.invalid(.invalid_literal, span, "an array element cannot be a borrow", &.{});
const t = try l.airType(ty);
if (!verifier_types.allowedPosition(std.meta.activeTag(t), .member, true)) return l.fail("E7005", span, "type constructor not allowed in this position", &.{
.{ .name = "position", .value = "member" },
.{ .name = "type_constructor", .value = @tagName(t) },
});
if (repeated and !try verifier_types.isCopy(l.arena, l.property_module.?, t)) return l.fail("E7005", span, "an array repetition requires Copy content", &.{
.{ .name = "constraint", .value = "Copy" },
.{ .name = "type_constructor", .value = "array" },
});
}
/// Constructors need a real content value before forming any result or
/// outcome. A never-returning operand has already terminated the block.
fn contentValue(l: *Lowerer, e: ast.Expr) Error!Value {
const v = try l.consuming(e, null);
if (v.ty == .void or v.ty == .never) return l.contentPositionError(e.span, v.ty);
return v;
}
fn contentPositionError(l: *Lowerer, span: Span, ty: Ty) Error {
return l.fail("E7005", span, "type constructor not allowed in this position", &.{
.{ .name = "position", .value = "member" },
.{ .name = "type_constructor", .value = @tagName(ty) },
});
}
fn copyContent(l: *Lowerer, span: Span, ty: Ty, operation: []const u8) Error!void {
if (!try verifier_types.isCopy(l.arena, l.property_module.?, try l.airType(ty))) return l.fail("E7005", span, "this allocation requires Copy content", &.{
.{ .name = "constraint", .value = "Copy" },
.{ .name = "operation", .value = operation },
});
}
fn function(l: *Lowerer, f: ast.FnDecl) Error!FnOut {
l.blocks = .empty;
l.bindings = .empty;
l.loops = .empty;
l.scopes = .empty;
l.allocs = .empty;
l.facts = .empty;
l.addressable = .empty;
l.cur = null;
l.rest = .empty;
l.pending_loop = null;
l.pending_bindings = .empty;
l.pending_ends = .empty;
l.unchecked = false;
l.in_constant = 0;
l.scope_binding_start = 0;
l.problem = null;
l.unimpl = null;
l.counter = 0;
l.params = f.params;
try l.findAddressable(f.body);
const sig = l.sigs.get(f.name).?;
l.ret = sig.ret;
l.borrow_parents = .empty;
// `trusted` is the boundary of runtime, std and toolchain modules; an
// ordinary program cannot declare its own code trusted (spec 15 §8).
if (f.trusted != null) return l.invalid(.trusted_unavailable, f.span, "`trusted` is not available in .aji programs; unsafe operations need `effects [unsafe]`, which propagates to callers", &.{});
for (f.effects) |e| if (std.mem.eql(u8, e, "unsafe")) l.uses.insert(.unsafe);
var header: std.ArrayList(u8) = .empty;
try header.appendSlice(l.arena, try l.fmt("fn @{s}(", .{sig.air_name}));
for (f.params, sig.params, 0..) |p, t, i| {
// Parameters keep their source names: `@main` capabilities are granted by name.
const v = p.name;
// Borrow parameters are lent by the caller: never ended here.
try l.bindings.append(l.arena, .{ .name = p.name, .mutable = false, .value = v, .ty = t, .kind = if (t.isBorrow()) .borrow else .ssa });
try header.appendSlice(l.arena, try l.fmt("{s}%{s}: {s}", .{ if (i == 0) "" else ", ", v, try l.tyText(t) }));
}
try header.appendSlice(l.arena, try l.fmt(") -> {s}", .{try l.tyText(sig.ret)}));
if (f.from) |origin| try header.appendSlice(l.arena, try l.fmt(" from %{s}", .{origin}));
_ = try l.newBlock("entry", f.span);
l.cur = 0;
const tail = try l.blockBodyWant(f.body, sig.ret);
if (l.cur != null) {
if (tail != null and tail.?.ty == .void and sig.ret != .void) {
return l.invalid(.missing_return, f.body.tail.?.span, "the function can end without returning a value", &.{.{ .name = "function", .value = f.name }});
}
if (tail) |v| {
try l.checkTy(f.body.tail.?.span, v.ty, sig.ret);
try l.term(try l.retText(v), f.body.tail.?.span);
} else if (sig.ret == .void) {
try l.term("ret", f.body.span);
} else return l.invalid(.missing_return, f.body.span, "the function can end without returning a value", &.{.{ .name = "function", .value = f.name }});
}
var eff: std.ArrayList(u8) = .empty;
for (f.effects, 0..) |e, i| try eff.appendSlice(l.arena, try l.fmt("{s}{s}", .{ if (i == 0) "" else ", ", e }));
// Frame storage is allocated once, first in the entry block (spec 08 §11.5).
if (l.allocs.items.len != 0) {
const entry = &l.blocks.items[0];
try entry.insts.insertSlice(l.arena, 0, l.allocs.items);
}
return .{ .header = header.items, .effects = try l.fmt("effects [{s}]", .{eff.items}), .span = f.span, .blocks = l.blocks.items };
}
fn emitFunction(l: *Lowerer, f: FnOut) Error!void {
try l.line("", null);
try l.line(f.header, f.span);
try l.line(f.effects, f.span);
for (f.blocks) |b| {
if (b.insts.items.len == 0) continue; // never reached
var head: std.ArrayList(u8) = .empty;
try head.appendSlice(l.arena, b.name);
if (b.params.items.len != 0) {
try head.append(l.arena, '(');
for (b.params.items, 0..) |p, i| try head.appendSlice(l.arena, try l.fmt("{s}%{s}: {s}", .{ if (i == 0) "" else ", ", p.name, try l.tyText(p.ty) }));
try head.append(l.arena, ')');
}
try head.appendSlice(l.arena, ":");
try l.line(head.items, b.span);
for (b.insts.items) |inst| try l.lineTagged(try l.fmt(" {s}", .{inst.text}), inst.span, inst.constant);
}
}
/// `ret %v`, or `ret` for a void value: a void function whose body ends
/// in an `if`, `match`, loop, block or void call falls through with
/// nothing to return (spec 15 §4).
fn retText(l: *Lowerer, v: Value) Error![]const u8 {
if (v.ty == .void) return "ret";
return l.fmt("ret %{s}", .{v.name});
}
fn freshName(l: *Lowerer, base: []const u8) Error![]const u8 {
while (true) {
l.counter += 1;
const n = try l.fmt("{s}_{d}", .{ base, l.counter });
for (l.params) |p| {
if (std.mem.eql(u8, p.name, n)) break;
} else return n;
}
}
fn newBlock(l: *Lowerer, kind: []const u8, span: Span) Error!usize {
const name = if (l.blocks.items.len == 0) kind else blk: {
l.counter += 1;
break :blk try l.fmt("{s}_{d}", .{ kind, l.counter });
};
try l.blocks.append(l.arena, .{ .name = name, .span = span });
return l.blocks.items.len - 1;
}
fn emit(l: *Lowerer, text: []const u8, span: Span) Error!void {
const current = l.cur orelse return l.invalid(.@"unreachable", span, "unreachable expression", &.{});
const b = &l.blocks.items[current];
try b.insts.append(l.arena, .{ .text = text, .span = span, .constant = l.in_constant });
}
/// Emits `%name = text` and returns the value.
fn def(l: *Lowerer, base: []const u8, ty: Ty, text: []const u8, span: Span) Error!Value {
const name = try l.freshName(base);
try l.emit(try l.fmt("%{s} = {s}", .{ name, text }), span);
return .{ .name = name, .ty = ty };
}
fn defBorrow(l: *Lowerer, base: []const u8, ty: Ty, text: []const u8, parent: []const u8, span: Span) Error!Value {
const v = try l.def(base, ty, text, span);
try l.borrow_parents.put(l.arena, v.name, parent);
return v;
}
fn term(l: *Lowerer, text: []const u8, span: Span) Error!void {
try l.emit(text, span);
l.blocks.items[l.cur.?].terminated = true;
l.cur = null;
}
// ------------------------------------------------------------ variables and joins
fn lookup(l: *Lowerer, name: []const u8) ?*Binding {
var i = l.bindings.items.len;
while (i > 0) {
i -= 1;
if (std.mem.eql(u8, l.bindings.items[i].name, name)) return &l.bindings.items[i];
}
return null;
}
/// Indices of the variables (mutable bindings) among the first `depth`
/// bindings: the state carried across joins.
fn carried(l: *Lowerer, depth: usize) Error![]const usize {
var out: std.ArrayList(usize) = .empty;
for (l.bindings.items[0..depth], 0..) |b, i| if (b.mutable and b.kind == .ssa) try out.append(l.arena, i);
return out.items;
}
/// The variables a join after the construct at `construct` carries: those
/// that may be read after it (pruned SSA, spec 15 §4). A variable that is
/// not read again is not passed on, so a linear value consumed before the
/// join does not travel to it.
fn carriedLive(l: *Lowerer, depth: usize, construct: Span, region: Region) Error![]const usize {
var out: std.ArrayList(usize) = .empty;
for (try l.carried(depth)) |i| {
const n = l.bindings.items[i].name;
if (region.assigns(n) and l.liveAfter(n, construct)) try out.append(l.arena, i);
}
return out.items;
}
/// As `carriedLive`, for a loop header: also the variables the loop
/// itself reads (they flow around the back edge).
fn carriedLoop(l: *Lowerer, depth: usize, construct: Span, lp: LoopAst) Error![]const usize {
var out: std.ArrayList(usize) = .empty;
const region: Region = .{ .loop = lp };
for (try l.carried(depth)) |i| {
const n = l.bindings.items[i].name;
if (region.assigns(n) and (loopReads(lp, n) or l.liveAfter(n, construct))) try out.append(l.arena, i);
}
return out.items;
}
/// Whether `name` may be read after the construct whose span is
/// `construct`. Conservative: any read on any later path counts; only a
/// whole-variable assignment in straight-line code before any read ends
/// the variable's life.
fn liveAfter(l: *Lowerer, name: []const u8, construct: Span) bool {
var k = l.rest.items.len;
while (k > 0) {
k -= 1;
const fr = l.rest.items[k];
// The rest of the statement or tail that contains the construct.
var w: After = .{ .name = name, .construct = construct };
if (fr.current) |c| if (w.stmt(c)) return true;
if (fr.current_expr) |ce| if (w.expr(ce.*)) return true;
switch (firstUse(fr.stmts, fr.tail, name)) {
.read => return true,
.kill => return false,
.none => {},
}
if (fr.loop) |lp| if (loopReads(lp, name)) return true;
}
return false;
}
fn argsOf(l: *Lowerer, vars: []const usize, extra: ?[]const u8) Error![]const u8 {
var s: std.ArrayList(u8) = .empty;
try s.append(l.arena, '(');
var first = true;
if (extra) |e| {
try s.appendSlice(l.arena, try l.fmt("%{s}", .{e}));
first = false;
}
for (vars) |i| {
try s.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (first) "" else ", ", l.bindings.items[i].value }));
first = false;
}
try s.append(l.arena, ')');
return s.items;
}
/// Gives `block` one parameter per carried variable (after an optional
/// result parameter) and rebinds the variables to them.
fn joinParams(l: *Lowerer, block: usize, vars: []const usize) Error!void {
for (vars) |i| {
const b = &l.bindings.items[i];
const name = try l.freshName(b.name);
try l.blocks.items[block].params.append(l.arena, .{ .name = name, .ty = b.ty });
}
}
fn rebindToParams(l: *Lowerer, block: usize, vars: []const usize, offset: usize) void {
for (vars, 0..) |i, k| l.bindings.items[i].value = l.blocks.items[block].params.items[offset + k].name;
}
fn snapshot(l: *Lowerer) Error![]const []const u8 {
const s = try l.arena.alloc([]const u8, l.bindings.items.len);
for (l.bindings.items, s) |b, *o| o.* = b.value;
return s;
}
fn restore(l: *Lowerer, s: []const []const u8) void {
l.bindings.shrinkRetainingCapacity(s.len);
for (l.bindings.items, s) |*b, v| b.value = v;
}
// ------------------------------------------------------------ statements
/// Lowers a block's statements in a new scope; returns the tail value.
fn blockBody(l: *Lowerer, b: ast.Block) Error!?Value {
return l.blockBodyWant(b, null);
}
/// As `blockBody`, with the type expected of the tail expression.
fn blockBodyWant(l: *Lowerer, b: ast.Block, want: ?Ty) Error!?Value {
const depth = l.bindings.items.len;
defer l.bindings.shrinkRetainingCapacity(depth);
try l.rest.append(l.arena, .{ .stmts = b.stmts, .tail = b.tail, .loop = l.pending_loop });
l.pending_loop = null;
defer _ = l.rest.pop();
try l.scopes.append(l.arena, .empty);
defer _ = l.scopes.pop();
const saved_start = l.scope_binding_start;
l.scope_binding_start = depth;
defer l.scope_binding_start = saved_start;
if (l.pending_bindings.items.len != 0 or l.pending_ends.items.len != 0) {
try l.bindings.appendSlice(l.arena, l.pending_bindings.items);
try l.scopes.items[l.scopes.items.len - 1].appendSlice(l.arena, l.pending_ends.items);
l.pending_bindings = .empty;
l.pending_ends = .empty;
}
for (b.stmts, 0..) |s, i| {
if (l.cur == null) return l.invalid(.@"unreachable", s.span, "unreachable statement", &.{});
l.rest.items[l.rest.items.len - 1].stmts = b.stmts[i + 1 ..];
l.rest.items[l.rest.items.len - 1].current = s;
try l.stmt(s);
}
var result: ?Value = null;
if (b.tail) |t| {
if (l.cur == null) return l.invalid(.@"unreachable", t.span, "unreachable expression", &.{});
l.rest.items[l.rest.items.len - 1].stmts = &.{};
l.rest.items[l.rest.items.len - 1].current = null;
l.rest.items[l.rest.items.len - 1].tail = null;
l.rest.items[l.rest.items.len - 1].current_expr = t;
if (l.scopes.items.len == 1 and l.ret.isBorrow() and t.kind == .name) {
result = try l.returnValue(t.*);
} else {
result = try l.expr(t.*, want);
if (result.?.ty.isBorrow()) return l.invalid(.invalid_borrow_return, t.span, "a block cannot yield a borrow", &.{});
}
}
// The borrows bound in this block end here (lexical scope, spec 15 §9).
if (l.cur != null) {
const transfer: ?[]const u8 = if (result) |v| (if (v.ty.isBorrow()) v.name else null) else null;
try l.endScopesExcept(l.scopes.items.len - 1, b.span, transfer);
}
return result;
}
/// Ends the borrows of every scope from index `from` upwards, innermost
/// first, without closing the scopes (used at block ends and exits).
fn endScopes(l: *Lowerer, from: usize, span: Span) Error!void {
try l.endScopesExcept(from, span, null);
}
fn endScopesExcept(l: *Lowerer, from: usize, span: Span, transfer: ?[]const u8) Error!void {
var i = l.scopes.items.len;
while (i > from) {
i -= 1;
const ends = l.scopes.items[i].items;
var k = ends.len;
while (k > 0) {
k -= 1;
if (transfer) |v| if (std.mem.eql(u8, ends[k].op, "borrow.end") and l.borrowAncestor(ends[k].name, v)) continue;
try l.emit(try l.fmt("{s} %{s}", .{ ends[k].op, ends[k].name }), if (i == l.scopes.items.len - 1 and from == i) ends[k].span else span);
}
}
}
fn borrowAncestor(l: *Lowerer, ancestor: []const u8, child: []const u8) bool {
var current = child;
while (true) {
if (std.mem.eql(u8, ancestor, current)) return true;
current = l.borrow_parents.get(current) orelse return false;
}
}
fn returnValue(l: *Lowerer, e: ast.Expr) Error!Value {
if (l.ret.isBorrow() and e.kind != .name) return l.invalid(.invalid_borrow_return, e.span, "return a named borrow; bind a returned view or place first", &.{});
return l.consuming(e, l.ret);
}
fn scopeEnds(l: *Lowerer, names: []const []const u8, span: Span) Error!void {
const top = &l.scopes.items[l.scopes.items.len - 1];
for (names) |n| try top.append(l.arena, .{ .name = n, .span = span });
}
fn endNow(l: *Lowerer, names: []const []const u8, span: Span) Error!void {
var k = names.len;
while (k > 0) {
k -= 1;
try l.emit(try l.fmt("borrow.end %{s}", .{names[k]}), span);
}
}
fn stmt(l: *Lowerer, s: ast.Stmt) Error!void {
switch (s.kind) {
.let => |x| {
const annotation: ?Ty = if (x.ty) |t| try l.typeOf(t) else null;
if (x.e.kind == .call) if (pathOf(x.e.kind.call.callee.*)) |p| if (std.mem.eql(u8, p, "struct.unpack") or std.mem.eql(u8, p, "array.unpack")) return l.unpackLet(s, x.names, x.e, x.tuple);
if (x.tuple and x.names.len == 1) return l.invalid(.invalid_binding, s.span, "a single parenthesized binding requires aggregate unpack", &.{});
if (x.names.len != 1) {
if (x.e.kind != .call or x.names.len != 2) return l.invalid(.invalid_binding, s.span, "this multi-binding requires aggregate unpack", &.{});
if (pathOf(x.e.kind.call.callee.*)) |p| if (std.mem.eql(u8, p, "atomic.compare_exchange")) return l.compareExchangeLet(s, x.names, x.e);
return l.splitLet(s, x.names, x.e);
}
if (x.e.kind == .borrow) return l.invalid(.invalid_binding, x.e.span, "bind a borrow with `ref name = place;` or `mut name = place;`", &.{});
if (x.e.kind == .bytes) {
const st = try l.materializeBytes(x.e.kind.bytes, x.e.span);
try l.bindings.append(l.arena, .{ .name = x.names[0], .mutable = false, .value = st.name, .ty = st.ty, .kind = .storage });
return;
}
var want: ?Ty = annotation;
// An untyped `let` takes its type from how the name is used
// later (`return`, arguments, operations, annotations).
if (want == null and l.peekType(x.e) == null) want = l.inferUses(x.names[0]);
if (x.e.kind == .or_trap) {
const v = try l.expr(x.e, want);
if (want) |w| try l.checkTy(x.e.span, v.ty, w);
if (v.ty.isBorrow()) {
// `let item = region.new(arena, v) or trap;`: a borrow bound to the block.
try l.scopeEnds(&.{v.name}, s.span);
try l.bindings.append(l.arena, .{ .name = x.names[0], .mutable = false, .value = v.name, .ty = v.ty, .kind = .borrow });
} else try l.bindings.append(l.arena, .{ .name = x.names[0], .mutable = false, .value = v.name, .ty = v.ty });
return;
}
const v = try l.consuming(x.e, want);
if (want) |w| try l.checkTy(x.e.span, v.ty, w);
if (v.ty == .void or v.ty == .never) return l.fail("E7005", x.e.span, "this expression has no value", &.{});
if (v.ty.isBorrow()) return l.invalid(.invalid_binding, x.e.span, "bind a borrow with `ref name = place;` or `mut name = place;`", &.{});
// Linear values (owners, regions, resources, endpoints, tasks,
// mutexes) are borrowed in place, never moved to frame storage.
if (l.addressable.contains(x.names[0]) and !l.isLinear(v.ty)) {
const st = try l.storageFor(x.names[0], v.ty, s.span);
try l.emit(try l.fmt("local.store %{s}, %{s}", .{ st, v.name }), s.span);
try l.bindings.append(l.arena, .{ .name = x.names[0], .mutable = false, .value = st, .ty = v.ty, .kind = .storage });
} else try l.bindings.append(l.arena, .{ .name = x.names[0], .mutable = false, .value = v.name, .ty = v.ty });
},
.@"var" => |x| {
const ty = try l.typeOf(x.ty);
if (ty.isBorrow()) return l.invalid(.invalid_binding, s.span, "a `var` holds a value; bind a borrow with `ref` or `mut`", &.{});
if (l.addressable.contains(x.name) and !l.isLinear(ty)) {
const st = try l.storageFor(x.name, ty, s.span);
if (x.init) |e| {
const v = try l.consuming(e, ty);
try l.checkTy(e.span, v.ty, ty);
if (v.ty == .never) return;
try l.emit(try l.fmt("local.store %{s}, %{s}", .{ st, v.name }), s.span);
} else try l.emit(try l.fmt("local.zero %{s}", .{st}), s.span);
try l.bindings.append(l.arena, .{ .name = x.name, .mutable = true, .value = st, .ty = ty, .kind = .storage });
return;
}
const v = if (x.init) |e| blk: {
const v = try l.consuming(e, ty);
try l.checkTy(e.span, v.ty, ty);
break :blk v;
} else try l.zeroValue(ty, x.name, s.span);
try l.bindings.append(l.arena, .{ .name = x.name, .mutable = true, .value = v.name, .ty = ty });
},
.assign => |x| {
if (x.place.kind != .name) return l.assignPlace(s.span, x.place, x.e);
const b = l.lookup(x.place.kind.name) orelse return l.unknown(x.place.span, x.place.kind.name);
if (b.kind == .borrow) return l.invalid(.invalid_assignment, x.place.span, "a borrow cannot be reassigned; write through it with `*r = …`, `r.f = …` or `r[i] = …`", &.{.{ .name = "name", .value = b.name }});
if (!b.mutable) return l.invalid(.invalid_assignment, x.place.span, "assignment to an immutable binding; declare it with `var`", &.{.{ .name = "name", .value = b.name }});
const ty = b.ty;
const kind = b.kind;
const storage = b.value;
const v = try l.consuming(x.e, ty);
try l.checkTy(x.e.span, v.ty, ty);
if (kind == .storage) {
if (v.ty == .never) return;
try l.emit(try l.fmt("local.store %{s}, %{s}", .{ storage, v.name }), s.span);
} else {
// `expr` may have created bindings and blocks; look the binding up again.
l.lookup(x.place.kind.name).?.value = v.name;
}
},
.borrow => |x| {
// No shadowing of an active borrow by the same name in the same scope.
const scope_start = l.scopeBindingStart();
for (l.bindings.items[scope_start..]) |b| if (b.kind == .borrow and std.mem.eql(u8, b.name, x.name))
return l.invalid(.invalid_binding, s.span, "a borrow of this name is already active in this scope", &.{.{ .name = "name", .value = x.name }});
if (x.place.kind == .call) if (l.borrowReturnSig(x.place.kind.call.callee.*)) |sig| if (sig.ret.isBorrow()) {
if (x.unchecked) return l.invalid(.invalid_place, s.span, "unchecked applies to element places, not calls", &.{});
if (x.mutable != sig.ret.isMutBorrow()) return l.fail("E7005", s.span, "binding mode must match the returned borrow; use ref for shared or mut for exclusive", &.{});
const call_expr = x.place.kind.call;
const v = try l.call(x.place, call_expr.callee.*, call_expr.args, true);
try l.scopeEnds(&.{v.name}, s.span);
try l.bindings.append(l.arena, .{ .name = x.name, .mutable = false, .value = v.name, .ty = v.ty, .kind = .borrow });
return;
};
if (x.place.kind == .call) if (pathOf(x.place.kind.call.callee.*)) |p| if (std.mem.eql(u8, p, "buffer.view")) return l.bufferView(s, x.name, x.mutable, x.place);
if (x.place.kind == .call) if (pathOf(x.place.kind.call.callee.*)) |p| if (std.mem.endsWith(u8, p, ".at"))
return l.graphAccess(s, x.name, x.mutable, x.place);
// Check the original mode before a whole array becomes a
// slice: shape conversion must not upgrade shared access.
var p = try l.uncheckedPlace(x.place, x.mutable, x.unchecked, false, s.span);
if (x.mutable) try l.requireExclusivePlace(x.place.span, p.v.ty);
p = try l.borrowShape(p, x.mutable, true, s.span);
if (p.ends.len == 0) {
// Borrowing a borrow binding: a reborrow, ended at scope end.
const rb = try l.defBorrow(x.name, p.v.ty, try l.fmt("{s} %{s}", .{ if (x.mutable) "borrow.mut" else "borrow.ref", p.v.name }), p.v.name, s.span);
try l.scopeEnds(&.{rb.name}, s.span);
try l.bindings.append(l.arena, .{ .name = x.name, .mutable = false, .value = rb.name, .ty = rb.ty, .kind = .borrow });
} else {
try l.scopeEnds(p.ends, s.span);
try l.bindings.append(l.arena, .{ .name = x.name, .mutable = false, .value = p.v.name, .ty = p.v.ty, .kind = .borrow });
}
},
.@"return" => |e| {
if (e) |x| {
const v = try l.returnValue(x);
try l.checkTy(x.span, v.ty, l.ret);
if (l.cur != null) {
try l.endScopesExcept(0, s.span, if (v.ty.isBorrow()) v.name else null);
try l.term(try l.retText(v), s.span);
}
} else {
if (l.ret != .void) return l.fail("E7005", s.span, "`return` without a value in a function that returns one", &.{.{ .name = "expected", .value = try l.diagnosticTyText(l.ret) }});
try l.endScopes(0, s.span);
try l.term("ret", s.span);
}
},
.trap => try l.term("trap", s.span),
.@"break", .@"continue" => {
if (l.loops.items.len == 0) return l.invalid(.loop_control_outside_loop, s.span, "`break` or `continue` outside a loop", &.{});
const lp = l.loops.items[l.loops.items.len - 1];
const vars = if (s.kind == .@"break") lp.exit_vars else lp.header_vars;
const target = if (s.kind == .@"break") lp.exit else lp.@"continue";
try l.endScopes(lp.scope_depth, s.span);
try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[target].name, try l.argsOf(vars, null) }), s.span);
},
.expr => |e| {
const v = try l.expr(e, null);
if (s.block_statement and v.ty != .void and v.ty != .never) return l.invalid(.value_block_statement, s.span, "value-producing block statement: use `;` to discard the value or parentheses to continue the expression", &.{});
},
.@"while" => |x| try l.whileLoop(s.span, x.cond, x.body, null),
.loop => |b| try l.whileLoop(s.span, null, b, null),
.@"for" => |x| try l.forLoop(s.span, x.name, x.lo, x.hi, x.body),
.scope => |x| {
// `scope s { … }`: task.scope.begin, and task.scope.end at every
// normal exit of the block (spec 15 §7).
const sv = try l.def(x.name, .scope, "task.scope.begin", s.span);
try l.pending_bindings.append(l.arena, .{ .name = x.name, .mutable = false, .value = sv.name, .ty = .scope });
try l.pending_ends.append(l.arena, .{ .name = sv.name, .span = x.body.span, .op = "task.scope.end" });
_ = try l.blockBody(x.body);
},
.shield => |b| {
// `shield { … }`: task.shield.begin, and task.shield.end at every
// normal exit; shields nest by construction (spec 15 §7).
const sh = try l.def("sh", .shield, "task.shield.begin", s.span);
try l.pending_ends.append(l.arena, .{ .name = sh.name, .span = b.span, .op = "task.shield.end" });
_ = try l.blockBody(b);
},
.lock => |x| try l.lockStmt(s, x.place, x.name, x.body, x.cancelled),
.select => |x| try l.selectStmt(s, x),
}
}
fn unknown(l: *Lowerer, span: Span, name: []const u8) Error {
return l.fail("E7002", span, "unknown name", &.{.{ .name = "name", .value = name }});
}
fn checkTy(l: *Lowerer, span: Span, found: Ty, want: Ty) Error!void {
if (found == .never or found.eql(want)) return;
return l.fail("E7005", span, "type mismatch", &.{ .{ .name = "expected", .value = try l.diagnosticTyText(want) }, .{ .name = "found", .value = try l.diagnosticTyText(found) } });
}
/// Operation inputs must yield an actual value, unlike divergent returns
/// or statement receivers. Check before lowering the next input.
fn checkOperandTy(l: *Lowerer, span: Span, found: Ty, want: Ty) Error!void {
if (found == .never) return l.noOperandValue(span, try l.diagnosticTyText(want));
return l.checkTy(span, found, want);
}
fn noOperandValue(l: *Lowerer, span: Span, expected: []const u8) Error {
return l.fail("E7005", span, "this expression has no value", &.{
.{ .name = "expected", .value = expected },
.{ .name = "found", .value = "never" },
});
}
/// `while cond { body }` (cond null: `loop { body }`). Carried state:
/// every variable visible at the loop.
fn whileLoop(l: *Lowerer, span: Span, cond: ?ast.Expr, body: ast.Block, step: ?ForStep) Error!void {
const depth = l.bindings.items.len;
const lp_ast: LoopAst = .{ .cond = cond, .body = body, .step = if (step) |st| st.name else null };
const vars = try l.carriedLoop(depth, span, lp_ast);
const exit_vars = try l.carriedLive(depth, span, .{ .loop = lp_ast });
const header = try l.newBlock(if (cond == null) "loop" else "while", span);
const exit = try l.newBlock("after", span);
const cont = if (step != null) try l.newBlock("step", span) else header;
try l.joinParams(header, vars);
try l.joinParams(exit, exit_vars);
if (step != null) try l.joinParams(cont, vars);
try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[header].name, try l.argsOf(vars, null) }), span);
l.cur = header;
l.rebindToParams(header, vars, 0);
if (cond) |c| {
const cv = try l.expr(c, .bool);
try l.checkOperandTy(c.span, cv.ty, .bool);
const body_b = try l.newBlock("body", body.span);
try l.term(try l.fmt("cbr %{s}, @{s}(), @{s}{s}", .{ cv.name, l.blocks.items[body_b].name, l.blocks.items[exit].name, try l.argsOf(exit_vars, null) }), c.span);
l.cur = body_b;
}
try l.loops.append(l.arena, .{ .@"continue" = cont, .exit = exit, .depth = depth, .scope_depth = l.scopes.items.len, .header_vars = vars, .exit_vars = exit_vars });
l.pending_loop = lp_ast;
_ = try l.blockBody(body);
_ = l.loops.pop();
if (l.cur != null) try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[cont].name, try l.argsOf(vars, null) }), body.span);
if (step) |st| {
l.cur = cont;
l.rebindToParams(cont, vars, 0);
const i = l.lookup(st.name).?;
const one = try l.def("one", i.ty, try l.fmt("const.{s} 1", .{try l.tyText(i.ty)}), st.span);
const next = try l.def(st.name, i.ty, try l.fmt("add.checked.{s} %{s}, %{s}", .{ try l.tyText(i.ty), i.value, one.name }), st.span);
l.lookup(st.name).?.value = next.name;
try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[header].name, try l.argsOf(vars, null) }), st.span);
}
l.cur = exit;
l.rebindToParams(exit, exit_vars, 0);
// A `loop` without `break` never reaches its exit.
if (!l.reaches(exit)) l.cur = null;
}
const ForStep = struct { name: []const u8, span: Span };
/// `for i in lo..hi { body }`: `var i = lo; let end = hi; while i < end { body; i = i + 1 }`,
/// with `continue` going to the increment.
fn forLoop(l: *Lowerer, span: Span, name: []const u8, lo: ast.Expr, hi: ast.Expr, body: ast.Block) Error!void {
const depth = l.bindings.items.len;
defer l.bindings.shrinkRetainingCapacity(depth);
const ty = l.peekType(lo) orelse l.peekType(hi) orelse return l.fail("E7007", lo.span, "the type of the range cannot be determined; add a suffix such as `0usize`", &.{});
if (ty != .int) return l.fail("E7005", lo.span, "a range needs an integer type", &.{.{ .name = "found", .value = try l.diagnosticTyText(ty) }});
const a = try l.expr(lo, ty);
try l.checkOperandTy(lo.span, a.ty, ty);
const b = try l.expr(hi, ty);
try l.checkOperandTy(hi.span, b.ty, ty);
try l.bindings.append(l.arena, .{ .name = "end of range", .mutable = false, .value = b.name, .ty = ty });
try l.bindings.append(l.arena, .{ .name = name, .mutable = true, .value = a.name, .ty = ty });
const cond: ast.Expr = .{ .span = span, .kind = .{ .binary = .{
.op = .lt,
.l = try box(l.arena, ast.Expr{ .span = lo.span, .kind = .{ .name = name } }),
.r = try box(l.arena, ast.Expr{ .span = hi.span, .kind = .{ .name = "end of range" } }),
} } };
try l.whileLoop(span, cond, body, .{ .name = name, .span = span });
}
fn reaches(l: *Lowerer, block: usize) bool {
const name = l.blocks.items[block].name;
for (l.blocks.items) |b| for (b.insts.items) |inst| {
if (std.mem.indexOf(u8, inst.text, name)) |at| {
const end = at + name.len;
if (at > 0 and inst.text[at - 1] == '@' and (end == inst.text.len or inst.text[end] == '(')) return true;
}
};
return false;
}
// ------------------------------------------------------------ expressions
/// The type of an expression without lowering it, where it follows
/// from names, suffixes, casts and calls; null otherwise.
fn sourceScope(l: *Lowerer, span: Span) ?ast.ModuleScope {
const name = span.namespace orelse l.m.name;
for (l.m.scopes) |scope| if (std.mem.eql(u8, scope.name, name)) return scope;
return null;
}
fn boundName(l: *Lowerer, name: []const u8, span: Span) ?[]const u8 {
if (span.resolved) return name;
const scope = l.sourceScope(span) orelse return name;
if (std.mem.lastIndexOfScalar(u8, name, '.')) |at| {
const owner = name[0..at];
if (std.mem.eql(u8, owner, scope.name)) return if (!scope.qualified_self) null else if (scope.entry) name[at + 1 ..] else name;
for (scope.imports) |imp| if (std.mem.eql(u8, imp.path, owner)) return name;
return null;
}
if (scope.entry) return name;
for (l.m.types) |t| if (localName(t.name, scope.name, name)) return t.name;
for (l.m.functions) |f| if (localName(f.name, scope.name, name)) return f.name;
return null;
}
fn functionSig(l: *Lowerer, name: []const u8, span: Span) ?FnSig {
return l.sigs.get(l.boundName(name, span) orelse return null);
}
fn calleeSig(l: *Lowerer, e: ast.Expr) ?FnSig {
const name = expressionPath(l.arena, e) catch return null;
return l.functionSig(name orelse return null, e.span);
}
fn borrowReturnSig(l: *Lowerer, e: ast.Expr) ?FnSig {
if (pathOf(e) != null) return null;
if (e.kind == .name and (std.mem.eql(u8, e.kind.name, "assert") or std.mem.eql(u8, e.kind.name, "assume"))) return null;
return l.calleeSig(e);
}
fn moduleCall(l: *Lowerer, e: ast.Expr) Error!?[]const u8 {
if (e.kind != .field) return null;
const name = try expressionPath(l.arena, e) orelse return null;
if (standardPath(e)) return name;
if (pathOf(e) != null) return null;
const owner = name[0..std.mem.lastIndexOfScalar(u8, name, '.').?];
for (l.m.scopes) |scope| if (std.mem.eql(u8, owner, scope.name)) return name;
if (l.sourceScope(e.span)) |scope| for (scope.imports) |imp| if (std.mem.eql(u8, owner, imp.path)) return name;
var root = e;
while (root.kind == .field) root = root.kind.field.e.*;
if (root.kind == .name and l.lookup(root.kind.name) == null) return name;
return null;
}
fn peekType(l: *Lowerer, initial: ast.Expr) ?Ty {
// Negation preserves the operand's queried type; skip its unary
// spine without host-stack growth or extra query allocations.
var e = initial;
while (e.kind == .neg) e = e.kind.neg.*;
return switch (e.kind) {
.specialize => null,
.int => |x| if (parse_mod.intSuffix(x.text)) |s| Ty{ .int = s } else null,
.boolean => .bool,
.name => |n| if (l.lookup(n)) |b| b.ty else null,
.deref => |x| if (l.peekType(x.*)) |t| t.inner() else null,
.index => |x| if (x.hi == null) (if (l.peekType(x.e.*)) |t| elemOf(t) else null) else null,
.array_rep => |x| if (l.peekType(x.e.*)) |t| (l.arrayOf(t, x.len) catch null) else null,
.array_list => |xs| if (xs.len != 0) (if (l.peekType(xs[0])) |t| (l.arrayOf(t, xs.len) catch null) else null) else null,
.neg => unreachable,
.not => .bool,
.cast => |x| l.typeOfNoFail(x.ty),
.binary => |x| switch (x.op) {
.eq, .ne, .lt, .le, .gt, .ge, .@"and", .@"or" => .bool,
.shl, .shr => l.peekType(x.l.*),
else => l.peekType(x.l.*) orelse l.peekType(x.r.*),
},
.call => |x| switch (x.callee.kind) {
.name => |n| if (l.functionSig(n, e.span)) |sig| sig.ret else null,
.variant => |v| l.enumType(v.@"enum", e.span),
else => if (l.calleeSig(x.callee.*)) |sig| sig.ret else if (pathOf(x.callee.*)) |p| l.peekPath(p, x.args) else null,
},
.move => |n| if (l.lookup(n)) |b| b.ty else null,
.variant => |v| l.enumType(v.@"enum", e.span),
.struct_lit => |x| l.enumOrStruct(x.name, e.span),
.field => |x| blk: {
const known = l.peekType(x.e.*);
if (std.mem.eql(u8, x.name, "len") and (known == null or !isNominalFieldBase(known.?))) break :blk Ty{ .int = "usize" };
var base = known orelse break :blk null;
if (base.isBorrow()) base = base.inner().?;
const d = l.decl(base) orelse break :blk null;
if (d.kind != .@"struct") break :blk null;
for (d.kind.@"struct") |f| if (std.mem.eql(u8, f.name, x.name)) break :blk l.typeOfNoFail(f.ty);
break :blk null;
},
.if_expr => |x| if (x.then.tail) |t| l.peekType(t.*) else null,
.match_expr => |x| for (x.arms) |a| {
if (l.peekType(a.body)) |t| break t;
} else null,
.block => |b| if (b.tail) |t| l.peekType(t.*) else null,
else => null,
};
}
/// The type the following code expects for the name `n`, if any use
/// determines one. Stops at a rebinding of `n`.
fn inferUses(l: *Lowerer, n: []const u8) ?Ty {
var i = l.rest.items.len;
while (i > 0) {
i -= 1;
const r = l.rest.items[i];
for (r.stmts) |s| {
if (l.usesInStmt(n, s)) |t| return t;
if (s.kind == .let) for (s.kind.let.names) |bn| if (std.mem.eql(u8, bn, n)) return null;
}
if (r.tail) |t| if (l.useIn(n, t.*, if (i == 0) l.ret else null)) |ty| return ty;
}
return null;
}
fn usesInStmt(l: *Lowerer, n: []const u8, s: ast.Stmt) ?Ty {
return switch (s.kind) {
.let => |x| l.useIn(n, x.e, if (x.ty) |t| l.typeOfNoFail(t) else null),
.@"var" => |x| if (x.init) |e| l.useIn(n, e, l.typeOfNoFail(x.ty)) else null,
.assign => |x| l.useIn(n, x.e, if (x.place.kind == .name) (if (l.lookup(x.place.kind.name)) |b| b.ty else null) else null),
.@"return" => |e| if (e) |x| l.useIn(n, x, l.ret) else null,
.expr => |e| l.useIn(n, e, null),
.@"while" => |x| l.useIn(n, x.cond, .bool) orelse l.usesInBlock(n, x.body),
.@"for" => |x| l.useIn(n, x.lo, l.peekType(x.hi)) orelse l.useIn(n, x.hi, l.peekType(x.lo)) orelse l.usesInBlock(n, x.body),
.loop, .shield => |b| l.usesInBlock(n, b),
.scope => |x| l.usesInBlock(n, x.body),
else => null,
};
}
fn usesInBlock(l: *Lowerer, n: []const u8, b: ast.Block) ?Ty {
for (b.stmts) |s| if (l.usesInStmt(n, s)) |t| return t;
if (b.tail) |t| return l.useIn(n, t.*, null);
return null;
}
/// The expected type of `n` inside `e`, evaluated where `e` is expected
/// to have type `want`.
fn useIn(l: *Lowerer, n: []const u8, e: ast.Expr, want: ?Ty) ?Ty {
return switch (e.kind) {
.name => |x| if (std.mem.eql(u8, x, n)) want else null,
.neg => |x| l.useIn(n, x.*, want),
.not => |x| l.useIn(n, x.*, .bool),
.cast => |x| l.useIn(n, x.e.*, null),
.binary => |x| switch (x.op) {
.@"and", .@"or" => l.useIn(n, x.l.*, .bool) orelse l.useIn(n, x.r.*, .bool),
.eq, .ne, .lt, .le, .gt, .ge => l.useIn(n, x.l.*, l.peekType(x.r.*)) orelse l.useIn(n, x.r.*, l.peekType(x.l.*)),
.shl, .shr => l.useIn(n, x.l.*, want) orelse l.useIn(n, x.r.*, l.peekType(x.l.*) orelse want),
else => blk: {
const t = want orelse l.peekType(x.l.*) orelse l.peekType(x.r.*);
break :blk l.useIn(n, x.l.*, t) orelse l.useIn(n, x.r.*, t);
},
},
.call => |x| blk: {
const sig = l.calleeSig(x.callee.*) orelse break :blk null;
for (x.args, 0..) |a, i| {
const pt: ?Ty = if (i < sig.params.len) sig.params[i] else null;
if (l.useIn(n, a, pt)) |t| break :blk t;
}
break :blk null;
},
.if_expr => |x| l.useIn(n, x.cond, .bool) orelse l.usesInBlock(n, x.then) orelse if (x.@"else") |els| switch (els) {
.block => |b| l.usesInBlock(n, b),
.@"if" => |inner| l.useIn(n, .{ .span = e.span, .kind = .{ .if_expr = inner } }, want),
} else null,
.block => |b| l.usesInBlock(n, b.*),
else => null,
};
}
fn typeOfNoFail(l: *Lowerer, annotation: ast.Type) ?Ty {
// Validate before allocating, as the old postorder query did. This
// best-effort lookup recognizes only names and fixed array chains.
var t = annotation;
while (t.kind == .array) {
const a = t.kind.array;
if (a.len == 0 or a.len > (@as(u64, 1) << 32)) return null;
t = a.elem.*;
}
const known: ?Ty = switch (t.kind) {
.name => |n| if (isIntName(n)) Ty{ .int = n } else if (std.mem.eql(u8, n, "bool")) .bool else if (std.meta.stringToEnum(authority.Builtin, n)) |b| Ty{ .builtin = b } else l.enumOrStruct(n, t.span),
else => null,
};
const leaf = known orelse return null;
var result: Ty = undefined;
var target = &result;
t = annotation;
while (t.kind == .array) {
const a = t.kind.array;
// Only fresh output nodes are writable; no source AST is borrowed
// or changed. The caller arena retains partial nodes on OOM.
const node = l.arena.create(Ty.Arr) catch return null;
node.len = a.len;
target.* = .{ .array = node };
target = &node.elem;
t = a.elem.*;
}
target.* = leaf;
return result;
}
fn enumOrStruct(l: *Lowerer, name: []const u8, span: Span) ?Ty {
const n = l.boundName(name, span) orelse return null;
for (l.m.types, 0..) |d, i| if (std.mem.eql(u8, d.name, n)) return .{ .named = @intCast(i) };
return null;
}
fn enumType(l: *Lowerer, n: []const u8, span: Span) ?Ty {
if (std.meta.stringToEnum(authority.Builtin, n)) |b| return .{ .builtin = b };
const t = l.enumOrStruct(n, span) orelse return null;
return if (l.m.types[t.named].kind == .@"enum") t else null;
}
fn expr(l: *Lowerer, e: ast.Expr, want: ?Ty) Error!Value {
switch (e.kind) {
.not, .neg, .deref, .cast => return l.unaryExpr(e, want),
.specialize => return l.invalid(.invalid_generic, e.span, "explicit type arguments require a generic function", &.{}),
.int => |x| {
const ty: Ty = if (parse_mod.intSuffix(x.text)) |s| .{ .int = s } else want orelse
return l.fail("E7007", e.span, "the type of this integer literal cannot be determined; add a suffix such as `0u64` or a type annotation", &.{});
if (ty != .int) return l.fail("E7005", e.span, "an integer literal where another type is expected", &.{.{ .name = "expected", .value = try l.diagnosticTyText(ty) }});
const v = parse_mod.parseIntText(x.text) orelse return l.fail("E7001", e.span, "malformed integer literal", &.{});
const n = ty.int;
const bits = intBits(n);
const max: u128 = if (isSigned(n)) (@as(u128, 1) << @intCast(bits - 1)) - 1 else if (bits == 128) std.math.maxInt(u128) else (@as(u128, 1) << @intCast(bits)) - 1;
if (v > max) return l.fail("E7005", e.span, "integer literal out of range for its type", &.{ .{ .name = "type", .value = n }, .{ .name = "literal", .value = x.text } });
return l.def("c", ty, try l.fmt("const.{s} {d}", .{ n, v }), e.span);
},
.boolean => |b| return l.def("c", .bool, if (b) "const.bool true" else "const.bool false", e.span),
.name => |n| {
const b = try l.valueBinding(e.span, n);
if (b.kind == .storage) return l.def(n, b.ty, try l.fmt("local.load %{s}", .{b.value}), e.span);
return .{ .name = b.value, .ty = b.ty };
},
.index => |x| {
if (x.hi != null) return l.invalid(.invalid_borrow, e.span, "a range `s[a..b]` is a borrow: bind it with `ref r = s[a..b];` or pass `ref s[a..b]`", &.{});
const p = try l.placeBorrow(e, false, false, e.span);
const v = try l.def("v", p.v.ty.inner().?, try l.fmt("load %{s}", .{p.v.name}), e.span);
try l.endNow(p.ends, e.span);
return v;
},
.array_list => |xs| {
if (xs.len == 0 or xs.len > 64) return l.invalid(.implementation_limit, e.span, "array literal requires 1..64 complete elements", &.{});
var ty: ?Ty = if (want) |w| if (w == .array) w.array.elem else null else null;
var names: std.ArrayList(u8) = .empty;
for (xs, 0..) |x, i| {
const v = try l.consuming(x, ty);
try l.arrayElement(x.span, v.ty, false);
if (ty) |t| try l.checkOperandTy(x.span, v.ty, t) else ty = v.ty;
try names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", v.name }));
}
const at = try l.arrayOf(ty.?, xs.len);
return l.def("arr", at, try l.fmt("array.make {s}({s})", .{ try l.tyText(at), names.items }), e.span);
},
.array_rep => |x| {
if (x.len == 0 or x.len > (@as(u64, 1) << 32)) return l.fail("E7005", e.span, "array length must be between 1 and 2^32", &.{});
const want_elem: ?Ty = if (want) |w| (if (w == .array) w.array.elem else null) else null;
const v = try l.expr(x.e.*, want_elem);
try l.arrayElement(x.e.span, v.ty, true);
const at = try l.arrayOf(v.ty, x.len);
return l.def("arr", at, try l.fmt("array.splat {s} %{s}", .{ try l.tyText(at), v.name }), e.span);
},
.bytes => return l.invalid(.invalid_literal, e.span, "a byte string is an array in storage: bind it with `let`/`ref`, or pass it where a slice is expected", &.{}),
.borrow => return l.invalid(.invalid_borrow, e.span, "`ref`/`mut` here: borrows are bound with `ref name = place;` / `mut name = place;` or passed as arguments", &.{}),
.binary => |x| return l.binary(e, x.op, x.l.*, x.r.*, want),
.call => |x| return l.call(e, x.callee.*, x.args, false),
.if_expr => |x| return l.ifExpr(e.span, x.*, want),
.block => |b| {
const v = try l.blockBodyWant(b.*, want);
return v orelse .{ .name = "", .ty = if (l.cur == null) .never else .void };
},
.match_expr => |x| return l.matchExpr(x.*, want),
.struct_lit => |x| return l.structLit(e, x.name, x.fields),
.variant => |v| return l.variantValue(e, v.@"enum", v.name, &.{}),
.field => |x| {
if (std.mem.eql(u8, x.name, "len")) return l.lenOf(e, x.e.*);
return l.fieldValue(e, x.e.*, x.name);
},
.or_trap => |x| return l.orTrap(e, x.*),
.move => |n| {
const b = try l.valueBinding(e.span, n);
if (!l.isLinear(b.ty) and !(e.generic_transfer and b.ty != .void and b.ty != .never and !b.ty.isBorrow() and b.ty != .task and b.ty != .scope and b.ty != .guard and b.ty != .shield)) return l.invalid(if (b.ty.isBorrow()) .move_borrow else if (b.ty == .void or b.ty == .never) .invalid_move else .move_copy, e.span, "`move` applies to linear values; copyable values are passed plainly", &.{ .{ .name = "name", .value = n }, .{ .name = "type", .value = try l.diagnosticTyText(b.ty) } });
if (b.kind == .storage) return l.def(n, b.ty, try l.fmt("local.load %{s}", .{b.value}), e.span);
return .{ .name = b.value, .ty = b.ty };
},
}
}
fn unaryExpr(l: *Lowerer, initial: ast.Expr, initial_want: ?Ty) Error!Value {
const Frame = struct { e: ast.Expr, ty: Ty = .void, zero: ?Value = null };
var pending: std.ArrayList(Frame) = .empty;
defer pending.deinit(l.arena);
var e = initial;
var want = initial_want;
var v: Value = while (true) {
switch (e.kind) {
.not, .deref => |x| {
try pending.append(l.arena, .{ .e = e });
want = if (e.kind == .not) .bool else null;
e = x.*;
},
.neg => |x| {
const ty = want orelse l.peekType(x.*) orelse return l.fail("E7007", e.span, "the type of this negation cannot be determined", &.{});
if (ty != .int) return l.fail("E7005", e.span, "negation of a non-integer", &.{});
// Negative literals retain the boundary magnitude rule
// and bypass ordinary positive-literal lowering.
if (x.kind == .int) {
const bits = parse_mod.parseIntText(x.kind.int.text) orelse return l.fail("E7001", e.span, "malformed integer literal", &.{});
if (!isSigned(ty.int)) return l.fail("E7005", e.span, "negative literal of an unsigned type", &.{.{ .name = "type", .value = ty.int }});
const min_mag: u128 = @as(u128, 1) << @intCast(intBits(ty.int) - 1);
if (bits > min_mag) return l.fail("E7005", e.span, "integer literal out of range for its type", &.{.{ .name = "type", .value = ty.int }});
break try l.def("c", ty, try l.fmt("const.{s} -{d}", .{ ty.int, bits }), e.span);
}
// This zero precedes operand lowering, as before. Other
// unary instructions resume after their operand completes.
const zero = try l.def("zero", ty, try l.fmt("const.{s} 0", .{ty.int}), e.span);
try pending.append(l.arena, .{ .e = e, .ty = ty, .zero = zero });
want = ty;
e = x.*;
},
.cast => |x| {
const to = try l.typeOf(x.ty);
if (to != .int) return l.fail("E7005", x.ty.span, "casts convert between integer types", &.{});
want = l.peekType(x.e.*) orelse to;
try pending.append(l.arena, .{ .e = e, .ty = to });
e = x.e.*;
},
else => break try l.expr(e, want),
}
};
while (pending.pop()) |frame| switch (frame.e.kind) {
.not => |x| {
try l.checkOperandTy(x.span, v.ty, .bool);
const t = try l.def("c", .bool, "const.bool true", frame.e.span);
v = try l.def("not", .bool, try l.fmt("xor.bool %{s}, %{s}", .{ v.name, t.name }), frame.e.span);
},
.neg => |x| {
try l.checkOperandTy(x.span, v.ty, frame.ty);
v = try l.def("neg", frame.ty, try l.fmt("sub.checked.{s} %{s}, %{s}", .{ frame.ty.int, frame.zero.?.name, v.name }), frame.e.span);
},
.deref => {
const in = v.ty.inner() orelse return l.fail("E7005", frame.e.span, "`*` reads through a borrow", &.{.{ .name = "found", .value = try l.diagnosticTyText(v.ty) }});
if (v.ty == .slice or v.ty == .slice_mut or in == .array) return l.invalid(.invalid_expression, frame.e.span, "read slice and array elements with `s[i]`, not `*`", &.{});
// Source-prescribed E4202 (spec 15 §12); no load is emitted.
if (in == .atomic) return l.fail("E4202", frame.e.span, "an atomic cell is read only by atomic operations: use `atomic.load(r, ordering)`", &.{
.{ .name = "found", .value = try l.diagnosticTyText(v.ty) },
.{ .name = "use", .value = "atomic.load" },
});
v = try l.def("v", in, try l.fmt("load %{s}", .{v.name}), frame.e.span);
},
.cast => |x| {
if (v.ty != .int) return l.fail("E7005", x.e.span, "casts convert between integer types", &.{.{ .name = "found", .value = try l.diagnosticTyText(v.ty) }});
if (x.mode == .widen) {
const from = std.meta.stringToEnum(air_module.IntType, v.ty.int).?;
const to = std.meta.stringToEnum(air_module.IntType, frame.ty.int).?;
if (!verifier_types.lossless(from, to)) return l.invalidWidening(frame.e.span, &.{ .{ .name = "from", .value = v.ty.int }, .{ .name = "to", .value = frame.ty.int } });
}
const mode = switch (x.mode) {
.widen => "widen",
.checked => "checked",
.wrap => "wrap",
};
v = try l.def("cast", frame.ty, try l.fmt("cast.{s}.{s} %{s}", .{ mode, frame.ty.int, v.name }), frame.e.span);
},
else => unreachable,
};
return v;
}
fn binary(l: *Lowerer, e: ast.Expr, op: ast.BinOp, a: ast.Expr, b: ast.Expr, want: ?Ty) Error!Value {
switch (op) {
.@"and", .@"or" => {
// Short-circuit: the right operand runs only when needed.
const lv = try l.expr(a, .bool);
try l.checkOperandTy(a.span, lv.ty, .bool);
const short = try l.def("c", .bool, if (op == .@"and") "const.bool false" else "const.bool true", e.span);
const rhs_b = try l.newBlock(if (op == .@"and") "and_rhs" else "or_rhs", b.span);
const join = try l.newBlock(if (op == .@"and") "and_end" else "or_end", e.span);
const rname = try l.freshName(if (op == .@"and") "and" else "or");
try l.blocks.items[join].params.append(l.arena, .{ .name = rname, .ty = .bool });
const jn = l.blocks.items[join].name;
if (op == .@"and") {
try l.term(try l.fmt("cbr %{s}, @{s}(), @{s}(%{s})", .{ lv.name, l.blocks.items[rhs_b].name, jn, short.name }), e.span);
} else try l.term(try l.fmt("cbr %{s}, @{s}(%{s}), @{s}()", .{ lv.name, jn, short.name, l.blocks.items[rhs_b].name }), e.span);
l.cur = rhs_b;
const rv = try l.expr(b, .bool);
try l.checkOperandTy(b.span, rv.ty, .bool);
try l.term(try l.fmt("br @{s}(%{s})", .{ jn, rv.name }), e.span);
l.cur = join;
return .{ .name = rname, .ty = .bool };
},
else => {},
}
const cmp = switch (op) {
.eq, .ne, .lt, .le, .gt, .ge => true,
else => false,
};
const shift = op == .shl or op == .shr;
const operand: ?Ty = if (cmp) (l.peekType(a) orelse l.peekType(b)) else if (shift) (want orelse l.peekType(a)) else (want orelse l.peekType(a) orelse l.peekType(b));
const ty = operand orelse return l.fail("E7007", e.span, "the type of this operation cannot be determined; add a suffix or annotation", &.{});
const lv = try l.expr(a, ty);
try l.checkOperandTy(a.span, lv.ty, ty);
const rv = try l.expr(b, ty);
try l.checkOperandTy(b.span, rv.ty, ty);
// `iref` identity (spec 03 §22): equal graph and slot; never a trap.
if (ty == .iref) {
if (op != .eq and op != .ne) return l.fail("E7005", e.span, "`iref` handles are compared with `==` and `!=` only", &.{});
const c = try l.def("cmp", .bool, try l.fmt("iref.eq %{s}, %{s}", .{ lv.name, rv.name }), e.span);
if (op == .eq) return c;
const t = try l.def("c", .bool, "const.bool true", e.span);
return l.def("cmp", .bool, try l.fmt("xor.bool %{s}, %{s}", .{ c.name, t.name }), e.span);
}
if (ty == .bool and !(op == .eq or op == .ne or op == .bit_and or op == .bit_or or op == .bit_xor))
return l.fail("E7005", e.span, "this operation needs integer operands", &.{});
if (ty != .bool and ty != .int) return l.fail("E7005", e.span, "this operation needs integer or boolean operands", &.{});
const t = try l.tyText(ty);
const text = switch (op) {
.add => try l.fmt("add.checked.{s}", .{t}),
.sub => try l.fmt("sub.checked.{s}", .{t}),
.mul => try l.fmt("mul.checked.{s}", .{t}),
.div => try l.fmt("div.checked.{s}", .{t}),
.rem => try l.fmt("rem.checked.{s}", .{t}),
.add_wrap => try l.fmt("add.wrap.{s}", .{t}),
.sub_wrap => try l.fmt("sub.wrap.{s}", .{t}),
.mul_wrap => try l.fmt("mul.wrap.{s}", .{t}),
.bit_and => try l.fmt("and.{s}", .{t}),
.bit_or => try l.fmt("or.{s}", .{t}),
.bit_xor => try l.fmt("xor.{s}", .{t}),
.shl => try l.fmt("shl.{s}", .{t}),
.shr => try l.fmt("shr.{s}", .{t}),
.eq => try l.fmt("eq.{s}", .{t}),
.ne => try l.fmt("ne.{s}", .{t}),
.lt => try l.fmt("lt.{s}", .{t}),
.le => try l.fmt("le.{s}", .{t}),
.gt => try l.fmt("gt.{s}", .{t}),
.ge => try l.fmt("ge.{s}", .{t}),
.@"and", .@"or" => unreachable,
};
return l.def(if (cmp) "cmp" else "t", if (cmp) .bool else ty, try l.fmt("{s} %{s}, %{s}", .{ text, lv.name, rv.name }), e.span);
}
fn call(l: *Lowerer, e: ast.Expr, callee: ast.Expr, args: []const ast.Expr, borrow_allowed: bool) Error!Value {
if (pathOf(callee)) |p| {
if (std.mem.eql(u8, p, "buffer.len") or std.mem.eql(u8, p, "buffer.capacity")) {
if (args.len != 1) return l.fail("E7005", e.span, "buffer metadata read takes one named borrow", &.{});
const b = try l.bufferBorrow(args[0], false);
return l.def("size", .{ .int = "usize" }, try l.fmt("{s} %{s}", .{ p, b.name }), e.span);
}
if (std.mem.eql(u8, p, "buffer.view")) return l.invalid(.invalid_borrow, e.span, "bind a buffer view with ref/mut name = buffer.view(borrow)", &.{});
}
if (pathOf(callee)) |path| if (std.mem.eql(u8, path, "value.swap")) {
if (args.len != 2 or args[0].kind != .borrow or !args[0].kind.borrow.mutable) return l.invalid(.invalid_operation, e.span, "value.swap requires mut place and replacement", &.{});
const b = args[0].kind.borrow;
const p = try l.placeBorrow(b.place.*, true, false, e.span);
if (p.v.ty != .mut) return l.fail("E7005", e.span, "value.swap requires mut<T>", &.{});
const ty = p.v.ty.inner().?;
const replacement = try l.consuming(args[1], ty);
try l.checkOperandTy(args[1].span, replacement.ty, ty);
const result = try l.def("old", ty, try l.fmt("value.swap %{s}, %{s}", .{ p.v.name, replacement.name }), e.span);
try l.endNow(p.ends, e.span);
l.linear_enabled = true;
return result;
};
if (callee.kind == .variant) return l.variantValue(e, callee.kind.variant.@"enum", callee.kind.variant.name, args);
if (try l.moduleCall(callee)) |name| {
// Reuse ordinary call typing/borrowing/lowering, including E7002.
const owned_name = try l.arena.dupe(u8, name);
return l.call(e, .{ .span = callee.span, .kind = .{ .name = owned_name } }, args, borrow_allowed);
}
if (pathOf(callee)) |p| {
if (std.mem.eql(u8, p, "slice.copy")) return l.sliceCopy(e, args);
if (l.fallible(p) != null) return l.invalid(.invalid_operation, e.span, "a fallible operation is handled with `match` over its outcomes or with `or trap`", &.{.{ .name = "operation", .value = p }});
if (std.mem.eql(u8, p, "own.take")) {
if (args.len != 1) return l.fail("E7005", e.span, "`own.take` takes one owner", &.{});
const o = try l.consuming(args[0], null);
if (o.ty != .own) return l.fail("E7005", args[0].span, "`own.take` takes an `own<T>`", &.{.{ .name = "found", .value = try l.diagnosticTyText(o.ty) }});
return l.def("v", o.ty.own.*, try l.fmt("own.take %{s}", .{o.name}), e.span);
}
if (std.mem.eql(u8, p, "own.free") or std.mem.eql(u8, p, "region.destroy")) {
if (args.len != 1) return l.fail("E7005", e.span, "this operation takes one linear value", &.{});
const o = try l.consuming(args[0], null);
const ok = if (std.mem.eql(u8, p, "own.free")) (o.ty == .own or o.ty == .own_array) else o.ty == .region;
if (!ok) return l.fail("E7005", args[0].span, if (std.mem.eql(u8, p, "own.free")) "`own.free` takes an `own<T>` or `own_array<T>`" else "`region.destroy` takes a region", &.{.{ .name = "found", .value = try l.diagnosticTyText(o.ty) }});
try l.emit(try l.fmt("{s} %{s}", .{ p, o.name }), e.span);
return .{ .name = "", .ty = .void };
}
if (std.mem.eql(u8, p, "region.reset")) {
if (args.len != 1 or args[0].kind != .name) return l.fail("E7005", e.span, "`region.reset` takes the region by name", &.{});
const r = l.lookup(args[0].kind.name) orelse return l.unknown(args[0].span, args[0].kind.name);
if (r.ty != .region) return l.fail("E7005", args[0].span, "`region.reset` takes a region", &.{.{ .name = "found", .value = try l.diagnosticTyText(r.ty) }});
try l.emit(try l.fmt("region.reset %{s}", .{r.value}), e.span);
return .{ .name = "", .ty = .void };
}
if (try l.concurrencyCall(e, p, args)) |v| return v;
if (std.mem.startsWith(u8, p, "atomic.")) return l.atomicCall(e, p, args);
if (authority.intrinsicIndex(p)) |ix| {
const x = authority.intrinsics[ix];
var temps: std.ArrayList([]const u8) = .empty;
const ops = try l.intrinsicOperands(e, x, args, &temps);
l.uses.insert(.capabilities);
const text = try l.fmt("intrinsic {s}({s})", .{ x.name, ops });
const v: Value = if (x.results.len == 0) blk: {
try l.emit(text, e.span);
break :blk .{ .name = "", .ty = .void };
} else try l.def("r", resultTy(x.results[0]), text, e.span);
try l.endNow(temps.items, e.span);
return v;
}
return l.notYet(callee.span, "this built-in operation (later layers)");
}
if (callee.kind == .field and std.mem.eql(u8, callee.kind.field.name, "split_at"))
return l.invalid(.invalid_unpack, e.span, "`split_at` yields two borrows: `let (left, right) = s.split_at(k);`", &.{});
if (callee.kind != .name) return l.notYet(callee.span, "built-in operations (later layers)");
const name = callee.kind.name;
if (std.mem.eql(u8, name, "assert")) {
if (args.len != 1) return l.fail("E7005", e.span, "`assert` takes one boolean", &.{});
const v = try l.expr(args[0], .bool);
try l.checkOperandTy(args[0].span, v.ty, .bool);
try l.emit(try l.fmt("assert %{s}", .{v.name}), e.span);
return .{ .name = "", .ty = .void };
}
if (std.mem.eql(u8, name, "assume")) {
if (args.len != 1) return l.fail("E7005", e.span, "`assume` takes one boolean", &.{});
const v = try l.expr(args[0], .bool);
try l.checkOperandTy(args[0].span, v.ty, .bool);
l.uses.insert(.unsafe);
try l.emit(try l.fmt("assume %{s}", .{v.name}), e.span);
return .{ .name = "", .ty = .void };
}
const sig = l.functionSig(name, callee.span) orelse return l.unknown(callee.span, name);
if (args.len != sig.params.len) return l.fail("E7005", e.span, "wrong number of arguments", &.{ .{ .name = "function", .value = sig.display_name }, .{ .name = "expected", .value = try l.fmt("{d}", .{sig.params.len}) }, .{ .name = "found", .value = try l.fmt("{d}", .{args.len}) } });
if (sig.ret.isBorrow() and !borrow_allowed) return l.invalid(.invalid_borrow_return, e.span, "bind a returned borrow with ref/mut name = call(...) first", &.{});
if (sig.from) |origin| {
const a = args[origin];
if (a.kind != .name) return l.invalid(.invalid_borrow_return, a.span, "the from argument must be a named borrow; bind it first", &.{});
const b = l.lookup(a.kind.name) orelse return l.unknown(a.span, a.kind.name);
if (b.kind != .borrow) return l.invalid(.invalid_borrow_return, a.span, "the from argument must be a named borrow; bind it first", &.{});
}
var parent: ?[]const u8 = null;
var arg_names: std.ArrayList(u8) = .empty;
var temps: std.ArrayList([]const u8) = .empty;
for (args, sig.params, 0..) |a, pt, i| {
const v = try l.argument(a, pt, &temps);
if (sig.from == i) parent = v.name;
try l.checkCallArgumentTy(a, v.ty, pt);
try arg_names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", v.name }));
}
const text = try l.fmt("call @{s}({s})", .{ sig.air_name, arg_names.items });
if (sig.ret == .void or sig.ret == .never) {
try l.emit(text, e.span);
if (sig.ret == .never) {
try l.term("trap", e.span); // `never` returns do not come back
return .{ .name = "", .ty = .never };
}
try l.endNowIfLive(temps.items, e.span);
return .{ .name = "", .ty = .void };
}
const result = try l.def(if (callee.span.resolved) "generic_call" else if (std.mem.startsWith(u8, name, "std.")) "std_call" else if (std.mem.indexOfScalar(u8, name, '.') != null) "module_call" else name, sig.ret, text, e.span);
if (parent) |p| try l.borrow_parents.put(l.arena, result.name, p);
try l.endNowIfLive(temps.items, e.span);
return result;
}
/// `Name { f: e, … }`: every field exactly once; initializers are
/// evaluated in declaration order, so the AIR does not depend on the
/// order the fields are written in (spec 15 §5).
fn structLit(l: *Lowerer, e: ast.Expr, name: []const u8, inits: []const ast.FieldInit) Error!Value {
const t = l.enumOrStruct(name, e.span) orelse return l.fail("E7002", e.span, "unknown type", &.{.{ .name = "name", .value = name }});
const d = l.m.types[t.named];
if (d.kind != .@"struct") return l.fail("E7005", e.span, "`Name { … }` constructs a struct; this is an enum (use `Enum::Variant`)", &.{.{ .name = "type", .value = d.display_name orelse name }});
const fields = d.kind.@"struct";
for (inits, 0..) |fi, i| {
for (inits[0..i]) |prev| if (std.mem.eql(u8, prev.name, fi.name)) return l.invalid(.invalid_literal, fi.span, "field given twice", &.{.{ .name = "field", .value = fi.name }});
const known = for (fields) |f| {
if (std.mem.eql(u8, f.name, fi.name)) break true;
} else false;
if (!known) return l.fail("E7002", fi.span, "no such field", &.{ .{ .name = "type", .value = d.display_name orelse name }, .{ .name = "field", .value = fi.name } });
}
var args: std.ArrayList(u8) = .empty;
for (fields, 0..) |f, i| {
const fi = for (inits) |x| {
if (std.mem.eql(u8, x.name, f.name)) break x;
} else return l.invalid(.invalid_literal, e.span, "missing field", &.{ .{ .name = "type", .value = d.display_name orelse name }, .{ .name = "field", .value = f.name } });
const ft = try l.typeOf(f.ty);
const v = try l.consuming(fi.e, ft);
try l.checkOperandTy(fi.e.span, v.ty, ft);
try args.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", v.name }));
}
return l.def("s", t, try l.fmt("struct.make {s}({s})", .{ try l.tyText(t), args.items }), e.span);
}
fn variantValue(l: *Lowerer, e: ast.Expr, enum_name: []const u8, variant: []const u8, args: []const ast.Expr) Error!Value {
const t = l.enumType(enum_name, e.span) orelse return l.fail("E7002", e.span, "unknown enum", &.{.{ .name = "name", .value = enum_name }});
if (t == .builtin) {
_ = t.builtin.variantIndex(variant) orelse return l.fail("E7002", e.span, "no such variant", &.{ .{ .name = "enum", .value = enum_name }, .{ .name = "variant", .value = variant } });
if (args.len != 0) return l.fail("E7005", e.span, "built-in error variants have no payload", &.{.{ .name = "variant", .value = variant }});
return l.def("e", t, try l.fmt("error.const {s}.{s}", .{ enum_name, variant }), e.span);
}
const vs = l.m.types[t.named].kind.@"enum";
const v = for (vs) |x| {
if (std.mem.eql(u8, x.name, variant)) break x;
} else return l.fail("E7002", e.span, "no such variant", &.{ .{ .name = "enum", .value = enum_name }, .{ .name = "variant", .value = variant } });
if (args.len != v.payload.len) return l.fail("E7005", e.span, "wrong number of payload values", &.{ .{ .name = "variant", .value = variant }, .{ .name = "expected", .value = try l.fmt("{d}", .{v.payload.len}) }, .{ .name = "found", .value = try l.fmt("{d}", .{args.len}) } });
var names: std.ArrayList(u8) = .empty;
for (args, v.payload, 0..) |a, pt, i| {
const ty = try l.typeOf(pt);
const av = try l.consuming(a, ty);
try l.checkOperandTy(a.span, av.ty, ty);
try names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", av.name }));
}
return l.def("e", t, try l.fmt("enum.make {s}.{s}({s})", .{ try l.tyText(t), variant, names.items }), e.span);
}
/// `v.f` on a struct value: `struct.get` (borrows come in layer 4).
fn fieldValue(l: *Lowerer, e: ast.Expr, base: ast.Expr, name: []const u8) Error!Value {
var bt = l.peekType(base) orelse return l.fail("E7007", base.span, "the type of this expression cannot be determined", &.{});
if (bt.isBorrow()) bt = bt.inner().?;
const d = l.decl(bt) orelse return l.fail("E7005", e.span, "field access on a value that is not a struct", &.{.{ .name = "found", .value = try l.diagnosticTyText(bt) }});
if (d.kind != .@"struct") return l.fail("E7005", e.span, "field access on an enum; use `match`", &.{.{ .name = "type", .value = d.display_name orelse d.name }});
const f = for (d.kind.@"struct") |x| {
if (std.mem.eql(u8, x.name, name)) break x;
} else return l.fail("E7002", e.span, "no such field", &.{ .{ .name = "type", .value = d.display_name orelse d.name }, .{ .name = "field", .value = name } });
// Through a borrow: borrow the field and load it.
if (l.rootBinding(base)) |rb| if (rb.kind == .borrow) {
const p = try l.placeBorrow(e, false, false, e.span);
const v = try l.def(name, p.v.ty.inner().?, try l.fmt("load %{s}", .{p.v.name}), e.span);
try l.endNow(p.ends, e.span);
return v;
};
const v = try l.expr(base, bt);
return l.def(name, try l.typeOf(f.ty), try l.fmt("struct.get @{s}.{s}, %{s}", .{ d.air_name orelse d.name, name, v.name }), e.span);
}
/// One branch of a conditional or `match`: where it ended (null if it
/// diverged), its value and the variables' values there.
const ArmEnd = struct { block: ?usize, value: ?Value, values: []const []const u8, span: Span };
/// Joins branches that reach the end: one block with a parameter for
/// the result (if any) and one per carried variable (spec 15 §4).
fn mergeArms(l: *Lowerer, span: Span, what: []const u8, arms: []const ArmEnd, vars: []const usize, before: []const []const u8, join_kind: []const u8) Error!Value {
l.restore(before);
var result_ty: ?Ty = null;
for (arms) |a| if (a.block != null) {
const vt: Ty = if (a.value) |v| v.ty else .void;
if (vt == .never) continue;
if (result_ty) |prev| {
if (!prev.eql(vt)) return l.fail("E7005", a.span, try l.fmt("the branches of this `{s}` have different types", .{what}), &.{ .{ .name = "expected", .value = try l.diagnosticTyText(prev) }, .{ .name = "found", .value = try l.diagnosticTyText(vt) } });
} else result_ty = vt;
};
if (result_ty == null) {
l.cur = null;
return .{ .name = "", .ty = .never };
}
const join = try l.newBlock(join_kind, span);
const has_value = result_ty.? != .void;
var result_name: []const u8 = "";
if (has_value) {
result_name = try l.freshName(what);
try l.blocks.items[join].params.append(l.arena, .{ .name = result_name, .ty = result_ty.? });
}
try l.joinParams(join, vars);
for (arms) |a| if (a.block) |b| {
l.cur = b;
l.restore(a.values);
const vt: Ty = if (a.value) |v| v.ty else .void;
if (vt == .never) continue;
try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[join].name, try l.argsOf(vars, if (has_value) a.value.?.name else null) }), a.span);
};
l.restore(before);
l.cur = join;
l.rebindToParams(join, vars, if (has_value) 1 else 0);
return .{ .name = result_name, .ty = result_ty.? };
}
/// `match` over an enum (`enum.switch`; exhaustive, no `_`) or an
/// integer (`switch`; `_` required). Payload names live in their arm.
fn matchExpr(l: *Lowerer, m: ast.Match, want: ?Ty) Error!Value {
if (m.kind == .outcome) return l.outcomeMatch(m, want);
const st = l.peekType(m.scrutinee) orelse return l.fail("E7007", m.scrutinee.span, "the type of this value cannot be determined", &.{});
if (st == .builtin) return l.builtinMatch(m, st.builtin, want);
const sv = try l.consuming(m.scrutinee, st);
const depth = l.bindings.items.len;
const vars = try l.carriedLive(depth, m.span, .{ .match = m });
const before = try l.snapshot();
var ends: std.ArrayList(ArmEnd) = .empty;
if (l.decl(st)) |d| {
if (d.kind != .@"enum") return l.fail("E7005", m.scrutinee.span, "`match` over a struct; use field access", &.{.{ .name = "type", .value = d.display_name orelse d.name }});
const vs = d.kind.@"enum";
const blocks = try l.arena.alloc(usize, m.arms.len);
var head: std.ArrayList(u8) = .empty;
try head.appendSlice(l.arena, try l.fmt("{s} {s} %{s}", .{ if (l.isLinear(st)) "enum.take" else "enum.switch", try l.tyText(st), sv.name }));
for (m.arms, blocks, 0..) |arm, *blk, i| {
if (arm.pattern.kind != .ctor or arm.pattern.kind.ctor.qualifier == null)
return l.invalid(.invalid_match, arm.pattern.span, "an arm of a `match` over an enum names one variant as `Enum::Variant`; `_` is not allowed", &.{.{ .name = "enum", .value = d.display_name orelse d.name }});
const c = arm.pattern.kind.ctor;
const pattern_type = l.enumType(c.qualifier.?, arm.pattern.span);
if (std.mem.indexOfScalar(u8, c.qualifier.?, '.') != null and pattern_type == null) return l.unknown(arm.pattern.span, c.qualifier.?);
if (pattern_type == null or !Ty.eql(st, pattern_type.?)) return l.fail("E7005", arm.pattern.span, "variant of a different enum", &.{ .{ .name = "expected", .value = d.display_name orelse d.name }, .{ .name = "found", .value = c.qualifier.? } });
const vi = for (vs, 0..) |v, k| {
if (std.mem.eql(u8, v.name, c.name)) break k;
} else return l.fail("E7002", arm.pattern.span, "no such variant", &.{ .{ .name = "enum", .value = d.display_name orelse d.name }, .{ .name = "variant", .value = c.name } });
for (m.arms[0..i]) |prev| if (std.mem.eql(u8, prev.pattern.kind.ctor.name, c.name)) return l.invalid(.invalid_match, arm.pattern.span, "variant matched twice", &.{.{ .name = "variant", .value = c.name }});
if (c.binds.len != vs[vi].payload.len) return l.fail("E7005", arm.pattern.span, "the pattern binds a different number of payload values", &.{ .{ .name = "variant", .value = c.name }, .{ .name = "expected", .value = try l.fmt("{d}", .{vs[vi].payload.len}) } });
blk.* = try l.newBlock(try l.fmt("case_{s}", .{c.name}), arm.body.span);
for (vs[vi].payload, c.binds) |pt, bn| {
const pname = try l.freshName(if (std.mem.eql(u8, bn, "_")) "unused" else bn);
try l.blocks.items[blk.*].params.append(l.arena, .{ .name = pname, .ty = try l.typeOf(pt) });
}
try head.appendSlice(l.arena, try l.fmt(", {s} -> @{s}", .{ c.name, l.blocks.items[blk.*].name }));
}
var missing: std.ArrayList(u8) = .empty;
for (vs) |v| {
const covered = for (m.arms) |arm| {
if (std.mem.eql(u8, arm.pattern.kind.ctor.name, v.name)) break true;
} else false;
if (!covered) try missing.appendSlice(l.arena, try l.fmt("{s}{s}::{s}", .{ if (missing.items.len == 0) "" else ", ", d.name, v.name }));
}
if (missing.items.len != 0) return l.fail("E7004", m.span, "`match` does not cover every variant", &.{.{ .name = "missing", .value = missing.items }});
try l.term(head.items, m.span);
for (m.arms, blocks) |arm, blk| {
l.restore(before);
l.cur = blk;
const c = arm.pattern.kind.ctor;
for (c.binds, l.blocks.items[blk].params.items) |bn, prm| {
if (!std.mem.eql(u8, bn, "_")) try l.bindings.append(l.arena, .{ .name = bn, .mutable = false, .value = prm.name, .ty = prm.ty });
}
const v = try l.armBody(arm.body, want);
// Payload names end with their arm.
l.bindings.shrinkRetainingCapacity(before.len);
try ends.append(l.arena, .{ .block = l.cur, .value = v, .values = try l.snapshot(), .span = arm.body.span });
}
return l.mergeArms(m.span, "match", ends.items, vars, before, "endmatch");
}
if (st != .int) return l.fail("E7005", m.scrutinee.span, "`match` needs an enum or integer value; use `if` for booleans", &.{.{ .name = "found", .value = try l.diagnosticTyText(st) }});
var head: std.ArrayList(u8) = .empty;
try head.appendSlice(l.arena, try l.fmt("switch.{s} %{s}, ", .{ st.int, sv.name }));
const blocks = try l.arena.alloc(usize, m.arms.len);
var default: ?usize = null;
var seen: std.ArrayList(u128) = .empty;
for (m.arms, blocks, 0..) |arm, *blk, i| {
switch (arm.pattern.kind) {
.wildcard => {
if (default != null) return l.invalid(.invalid_match, arm.pattern.span, "`_` given twice", &.{});
default = i;
blk.* = try l.newBlock("case_default", arm.body.span);
},
.int => |text| {
const neg = text[0] == '-';
const mag = parse_mod.parseIntText(if (neg) text[1..] else text) orelse return l.fail("E7001", arm.pattern.span, "malformed integer pattern", &.{});
const width = intBits(st.int);
const negative = neg and mag != 0;
const signed = isSigned(st.int);
const limit: u128 = if (signed) (@as(u128, 1) << @intCast(width - 1)) - @as(u128, if (negative) 0 else 1) else if (width == 128) std.math.maxInt(u128) else (@as(u128, 1) << @intCast(width)) - 1;
if ((negative and !signed) or mag > limit) return l.fail("E7005", arm.pattern.span, "integer pattern out of range for its scrutinee type", &.{ .{ .name = "type", .value = st.int }, .{ .name = "literal", .value = text } });
const bits: u128 = if (neg) (0 -% mag) else mag;
for (seen.items) |prev| if (prev == bits) return l.invalid(.invalid_match, arm.pattern.span, "integer matched twice", &.{.{ .name = "value", .value = text }});
try seen.append(l.arena, bits);
blk.* = try l.newBlock("case", arm.body.span);
// AIR uses canonical decimal literals without source
// suffixes/separators. Validate range before formatting
// rather than truncating a pattern's bit representation.
try head.appendSlice(l.arena, try l.fmt("{s}{d} -> @{s}(), ", .{ if (neg and mag != 0) "-" else "", mag, l.blocks.items[blk.*].name }));
},
.ctor => return l.fail("E7005", arm.pattern.span, "an arm of a `match` over an integer is an integer literal or `_`", &.{}),
}
}
const d = default orelse return l.fail("E7004", m.span, "a `match` over an integer needs a `_` arm", &.{});
try head.appendSlice(l.arena, try l.fmt("default -> @{s}()", .{l.blocks.items[blocks[d]].name}));
try l.term(head.items, m.span);
for (m.arms, blocks) |arm, blk| {
l.restore(before);
l.cur = blk;
const v = try l.armBody(arm.body, want);
try ends.append(l.arena, .{ .block = l.cur, .value = v, .values = try l.snapshot(), .span = arm.body.span });
}
return l.mergeArms(m.span, "match", ends.items, vars, before, "endmatch");
}
/// A match over a built-in enum (`alloc_error::out_of_memory`, …):
/// exhaustive, no `_`, like a declared enum.
fn builtinMatch(l: *Lowerer, m: ast.Match, b: authority.Builtin, want: ?Ty) Error!Value {
const name = @tagName(b);
const sv = try l.expr(m.scrutinee, .{ .builtin = b });
const depth = l.bindings.items.len;
const vars = try l.carriedLive(depth, m.span, .{ .match = m });
const before = try l.snapshot();
const blocks = try l.arena.alloc(usize, m.arms.len);
var head: std.ArrayList(u8) = .empty;
try head.appendSlice(l.arena, try l.fmt("enum.switch {s} %{s}", .{ name, sv.name }));
for (m.arms, blocks, 0..) |arm, *blk, i| {
if (arm.pattern.kind != .ctor or arm.pattern.kind.ctor.qualifier == null or !std.mem.eql(u8, arm.pattern.kind.ctor.qualifier.?, name))
return l.invalid(.invalid_match, arm.pattern.span, try l.fmt("an arm names one variant as `{s}::variant`; `_` is not allowed", .{name}), &.{});
const c = arm.pattern.kind.ctor;
if (b.variantIndex(c.name) == null) return l.fail("E7002", arm.pattern.span, "no such variant", &.{ .{ .name = "enum", .value = name }, .{ .name = "variant", .value = c.name } });
if (c.binds.len != 0) return l.fail("E7005", arm.pattern.span, "built-in error variants have no payload", &.{});
for (m.arms[0..i]) |prev| if (std.mem.eql(u8, prev.pattern.kind.ctor.name, c.name)) return l.invalid(.invalid_match, arm.pattern.span, "variant matched twice", &.{.{ .name = "variant", .value = c.name }});
blk.* = try l.newBlock(try l.fmt("case_{s}", .{c.name}), arm.body.span);
try head.appendSlice(l.arena, try l.fmt(", {s} -> @{s}", .{ c.name, l.blocks.items[blk.*].name }));
}
var missing: std.ArrayList(u8) = .empty;
for (b.variants()) |v| {
const covered = for (m.arms) |arm| {
if (std.mem.eql(u8, arm.pattern.kind.ctor.name, v)) break true;
} else false;
if (!covered) try missing.appendSlice(l.arena, try l.fmt("{s}{s}::{s}", .{ if (missing.items.len == 0) "" else ", ", name, v }));
}
if (missing.items.len != 0) return l.fail("E7004", m.span, "`match` does not cover every variant", &.{.{ .name = "missing", .value = missing.items }});
try l.term(head.items, m.span);
var ends: std.ArrayList(ArmEnd) = .empty;
for (m.arms, blocks) |arm, blk| {
l.restore(before);
l.cur = blk;
const v = try l.armBody(arm.body, want);
try ends.append(l.arena, .{ .block = l.cur, .value = v, .values = try l.snapshot(), .span = arm.body.span });
}
return l.mergeArms(m.span, "match", ends.items, vars, before, "endmatch");
}
/// The result type of a built-in operation called plainly, if known
/// without lowering it.
fn peekPath(l: *Lowerer, p: []const u8, args: []const ast.Expr) ?Ty {
const eq = std.mem.eql;
if (eq(u8, p, "buffer.len") or eq(u8, p, "buffer.capacity")) return .{ .int = "usize" };
if ((eq(u8, p, "own.take") or eq(u8, p, "task.join")) and args.len == 1) return if (l.peekType(args[0])) |t| t.inner() else null;
if (eq(u8, p, "task.cancelled")) return .bool;
if (std.mem.startsWith(u8, p, "atomic.") and args.len >= 1) {
if (eq(u8, p, "atomic.new")) return if (l.peekType(args[0])) |t| (l.wrap(.atomic, t) catch null) else null;
if (eq(u8, p, "atomic.take")) return if (l.peekType(args[0])) |t| t.inner() else null;
if (eq(u8, p, "atomic.store") or eq(u8, p, "atomic.fence") or eq(u8, p, "atomic.compare_exchange")) return null;
// A `ref a` argument, or a `ref<atomic<T>>` binding: the cell's T.
const cell: ?Ty = if (args[0].kind == .borrow) l.peekType(args[0].kind.borrow.place.*) else if (l.peekType(args[0])) |t| t.inner() else null;
return if (cell) |c| (if (c == .atomic) c.inner() else null) else null;
}
if ((eq(u8, p, "island.root") or eq(u8, p, "frozen.root") or eq(u8, p, "arc.root")) and args.len == 1)
return if (l.peekType(args[0])) |t| (if (t.inner()) |o| (if (o.inner()) |root| l.wrap(.iref, root) catch null else null) else null) else null;
if (eq(u8, p, "island.freeze") and args.len == 1) return if (l.peekType(args[0])) |t| (if (t == .island) l.wrap(.frozen, t.inner().?) catch null else null) else null;
if (eq(u8, p, "arc.from_frozen") and args.len == 1) return if (l.peekType(args[0])) |t| (if (t == .frozen) l.wrap(.arc, t.inner().?) catch null else null) else null;
if (eq(u8, p, "arc.clone") and args.len == 1) return if (l.peekType(args[0])) |t| (if (t == .arc) t else if (t.inner()) |in| (if (in == .arc) in else null) else null) else null;
if (eq(u8, p, "channel.dup") and args.len == 1) return if (l.peekType(args[0])) |t| (if (t == .sender) t else if (t.inner()) |in| (if (in == .sender) in else null) else null) else null;
if (eq(u8, p, "task.spawn") and args.len >= 2) {
const sig = l.calleeSig(args[1]) orelse return null;
return l.wrap(.task, sig.ret) catch null;
}
return null;
}
fn armBody(l: *Lowerer, body: ast.Expr, want: ?Ty) Error!?Value {
const v = try l.expr(body, want);
if (v.ty == .void) return null;
if (v.ty == .never) {
l.cur = null;
return v;
}
return v;
}
// ------------------------------------------------------------ places, storage and borrows (layers 3–4)
fn endNowIfLive(l: *Lowerer, names: []const []const u8, span: Span) Error!void {
if (l.cur != null) try l.endNow(names, span);
}
/// Index of the first binding of the innermost lexical scope.
fn scopeBindingStart(l: *Lowerer) usize {
return l.scope_binding_start;
}
/// Frame storage for a variable, allocated in the entry block.
fn storageFor(l: *Lowerer, name: []const u8, ty: Ty, span: Span) Error![]const u8 {
const st = try l.freshName(name);
try l.allocs.append(l.arena, .{ .text = try l.fmt("%{s} = local.alloc {s}", .{ st, try l.tyText(ty) }), .span = span });
return st;
}
fn zeroValue(l: *Lowerer, annotation: Ty, base: []const u8, span: Span) Error!Value {
var leaf = annotation;
var count: usize = 0;
while (leaf == .array) {
count += 1;
leaf = leaf.array.elem;
}
// An unsupported leaf rejects before allocating traversal metadata,
// just as the recursive descent did before emitting any instruction.
if (leaf != .int and leaf != .bool) return l.invalid(.zero_not_zeroable, span, "`zero` needs a zeroable type (integers, booleans, arrays of them)", &.{});
const parents = try l.arena.alloc(*const Ty.Arr, count);
var t = annotation;
for (parents) |*parent| {
parent.* = t.array;
t = t.array.elem;
}
var value = switch (leaf) {
.int => |n| try l.def(base, leaf, try l.fmt("const.{s} 0", .{n}), span),
.bool => try l.def(base, leaf, "const.bool false", span),
else => unreachable,
};
// Original leaf-first order: one constant followed by each splat,
// retaining the source type nodes, names and source spans.
while (count != 0) {
count -= 1;
const ty: Ty = .{ .array = parents[count] };
value = try l.def(base, ty, try l.fmt("array.splat {s} %{s}", .{ try l.tyText(ty), value.name }), span);
}
return value;
}
/// A byte string in frame storage: `[u8; N]`, one store per byte (no heap).
fn materializeBytes(l: *Lowerer, bytes: []const u8, span: Span) Error!Value {
if (bytes.len == 0) return l.invalid(.invalid_literal, span, "an empty byte string has no array type", &.{});
const ty = try l.arrayOf(.{ .int = "u8" }, bytes.len);
const st = try l.storageFor("bytes", ty, span);
// Everything from here to the final `borrow.end` is the constant's
// initialization; the `local.alloc` is real frame storage.
try l.constants.append(l.arena, .{ .storage = st, .bytes = bytes });
l.in_constant = @intCast(l.constants.items.len);
defer l.in_constant = 0;
try l.emit(try l.fmt("local.zero %{s}", .{st}), span);
const b = try l.defBorrow("w", try l.wrap(.mut, ty), try l.fmt("borrow.mut %{s}", .{st}), st, span);
for (bytes, 0..) |byte, i| {
if (byte == 0) continue; // already zero
const idx = try l.def("i", .{ .int = "usize" }, try l.fmt("const.usize {d}", .{i}), span);
const c = try l.def("c", .{ .int = "u8" }, try l.fmt("const.u8 {d}", .{byte}), span);
const el = try l.defBorrow("e", try l.wrap(.mut, .{ .int = "u8" }), try l.fmt("borrow.index %{s}, %{s}", .{ b.name, idx.name }), b.name, span);
try l.emit(try l.fmt("store %{s}, %{s}", .{ el.name, c.name }), span);
try l.emit(try l.fmt("borrow.end %{s}", .{el.name}), span);
}
try l.emit(try l.fmt("borrow.end %{s}", .{b.name}), span);
return .{ .name = st, .ty = ty };
}
/// Advice belongs to the existing ordinary-call mismatch, after argument
/// lowering. Never change earlier name/move errors or infer a borrow.
fn checkCallArgumentTy(l: *Lowerer, a: ast.Expr, found: Ty, want: Ty) Error!void {
l.checkOperandTy(a.span, found, want) catch |err| {
if (err == error.Lower and a.kind == .name and found == .array and
(want == .slice or want == .slice_mut) and found.array.elem.eql(want.inner().?) and !l.isLinear(found))
{
const kind = @import("../diag.zig").SourceRepairKind.array_slice_argument;
l.problem.?.repair_candidates = if (want == .slice)
comptime &.{kind.candidate(&.{"ref"})}
else
comptime &.{kind.candidate(&.{"mut"})};
}
return err;
};
}
/// A call argument: `ref place` / `mut place` and byte strings are
/// borrowed for the call (`temps` end after it); anything else is a value.
fn argument(l: *Lowerer, a: ast.Expr, want: ?Ty, temps: *std.ArrayList([]const u8)) Error!Value {
switch (a.kind) {
.borrow => |x| {
// Only a known array-borrow parameter preserves the array
// (spec 15 §5). Bindings and all other arguments keep slices.
const want_slice = if (want) |t| !(t == .ref or t == .mut) or t.inner().? != .array else true;
var p = try l.uncheckedPlace(x.place.*, x.mutable, x.unchecked, false, a.span);
if (x.mutable) try l.requireExclusivePlace(a.span, p.v.ty);
p = try l.borrowShape(p, x.mutable, want_slice, a.span);
if (p.ends.len == 0) {
const rb = try l.defBorrow("b", p.v.ty, try l.fmt("{s} %{s}", .{ if (x.mutable) "borrow.mut" else "borrow.ref", p.v.name }), p.v.name, a.span);
try temps.append(l.arena, rb.name);
return rb;
}
try temps.appendSlice(l.arena, p.ends);
return p.v;
},
.bytes => |b| {
const st = try l.materializeBytes(b, a.span);
const r = try l.defBorrow("b", try l.wrap(.ref, st.ty), try l.fmt("borrow.ref %{s}", .{st.name}), st.name, a.span);
const sl = try l.defBorrow("s", try l.wrap(.slice, .{ .int = "u8" }), try l.fmt("slice.make %{s}", .{r.name}), r.name, a.span);
try temps.appendSlice(l.arena, &.{ r.name, sl.name });
return sl;
},
else => return l.consuming(a, want),
}
}
/// Scope identifiers are lexical operands, not ordinary source values
/// (spec 15 §7). Do not suggest moving their retained completion handle.
fn valueBinding(l: *Lowerer, span: Span, name: []const u8) Error!*Binding {
const b = l.lookup(name) orelse return l.unknown(span, name);
if (b.ty == .scope) return l.invalid(.invalid_expression, span, "a scope name is only the first operand of `task.spawn`; it cannot be used as a value", &.{ .{ .name = "name", .value = name }, .{ .name = "type", .value = "scope" } });
return b;
}
/// An operand that consumes its value: a named linear value must be
/// written `move x` (spec 15 §5). Use after move, double consumption and
/// leaks are the verifier's (E2001, E2002, E3001, E3002).
fn consuming(l: *Lowerer, e: ast.Expr, want: ?Ty) Error!Value {
if (e.kind == .name) {
const b = try l.valueBinding(e.span, e.kind.name);
if (l.isLinear(b.ty) and b.kind == .ssa)
return l.fail("E7003", e.span, "a linear value is consumed here: write `move` to transfer it, or borrow it with `ref`/`mut`", &.{ .{ .name = "name", .value = e.kind.name }, .{ .name = "suggestion", .value = try l.fmt("move {s}", .{e.kind.name}) } });
}
return l.expr(e, want);
}
/// `ref unchecked s[i]`: `borrow.index.unchecked` (spec 13 §6). Only an
/// element place can be unchecked; the boundary (`effects [unsafe]`) is
/// the verifier's (`E6001`).
fn uncheckedPlace(l: *Lowerer, place: ast.Expr, mutable: bool, unchecked: bool, want_slice: bool, span: Span) Error!Placed {
if (!unchecked) return l.borrowShape(try l.placeRaw(place, mutable, span), mutable, want_slice, span);
if (place.kind != .index or place.kind.index.hi != null) return l.invalid(.invalid_place, place.span, "`unchecked` applies to one element `s[i]`", &.{});
l.unchecked = true;
defer l.unchecked = false;
return l.borrowShape(try l.placeRaw(place, mutable, span), mutable, want_slice, span);
}
fn rootBinding(l: *Lowerer, e: ast.Expr) ?*Binding {
var x = e;
while (true) switch (x.kind) {
.name => |n| return l.lookup(n),
.field => |f| x = f.e.*,
.index => |i| x = i.e.*,
.deref => |d| x = d.*,
else => return null,
};
}
/// Borrows a place (spec 15 §5). `want_slice`: a borrow of a whole
/// array becomes a slice. A place that is itself a borrow binding is
/// returned as is (`ends` empty).
fn placeBorrow(l: *Lowerer, place: ast.Expr, mutable: bool, want_slice: bool, span: Span) Error!Placed {
const p = try l.placeRaw(place, mutable, span);
return if (want_slice) l.borrowShape(p, mutable, true, span) else p;
}
/// Explicit `mut` cannot upgrade shared access, including before array
/// shape conversion. Aliasing and lifetime legality stay with AIR.
fn requireExclusivePlace(l: *Lowerer, span: Span, t: Ty) Error!void {
if (t.isMutBorrow()) return;
const expected = if (t == .slice) try l.wrap(.slice_mut, t.inner().?) else try l.wrap(.mut, t.inner().?);
return l.fail("E7005", span, "mut needs an exclusive place", &.{ .{ .name = "expected", .value = try l.diagnosticTyText(expected) }, .{ .name = "found", .value = try l.diagnosticTyText(t) } });
}
/// Explicit argument/binding modes apply independently of array shape.
/// In particular, `ref` through `mut<[T; N]>` still reborrows shared.
fn borrowShape(l: *Lowerer, raw: Placed, mutable: bool, want_slice: bool, span: Span) Error!Placed {
var p = raw;
// `ref place` reached through a `mut` borrow (`ref s.buf` with
// `s: mut<S>`) is a shared reborrow of it (spec 07a `borrow.ref`).
if (!mutable and (p.v.ty == .mut or p.v.ty == .slice_mut)) {
const t = if (p.v.ty == .mut) try l.wrap(.ref, p.v.ty.inner().?) else try l.wrap(.slice, p.v.ty.inner().?);
const r = try l.defBorrow("r", t, try l.fmt("borrow.ref %{s}", .{p.v.name}), p.v.name, span);
p = .{ .v = r, .ends = try l.concat(p.ends, r.name) };
}
if (want_slice and (p.v.ty == .ref or p.v.ty == .mut) and p.v.ty.inner().? == .array) {
const elem = p.v.ty.inner().?.array.elem;
const sl = try l.defBorrow("s", (if (mutable) try l.wrap(.slice_mut, elem) else try l.wrap(.slice, elem)), try l.fmt("slice.make %{s}", .{p.v.name}), p.v.name, span);
var ends: std.ArrayList([]const u8) = .empty;
try ends.appendSlice(l.arena, p.ends);
try ends.append(l.arena, sl.name);
p = .{ .v = sl, .ends = ends.items };
}
return p;
}
fn placeRaw(l: *Lowerer, place: ast.Expr, mutable: bool, span: Span) Error!Placed {
const op = if (mutable) "borrow.mut" else "borrow.ref";
switch (place.kind) {
.name => |n| {
const b = l.lookup(n) orelse return l.unknown(place.span, n);
switch (b.kind) {
.storage => {
const v = try l.def(n, if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty), try l.fmt("{s} %{s}", .{ op, b.value }), span);
return .{ .v = v, .ends = try l.arena.dupe([]const u8, &.{v.name}) };
},
.borrow => return .{ .v = .{ .name = b.value, .ty = b.ty }, .ends = &.{} },
.ssa => {
// A linear value (owner, region) is borrowed in place.
const bt: ?Ty = switch (b.ty) {
.named, .array => if (l.isLinear(b.ty)) (if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty)) else null,
.own => |in| if (mutable) try l.wrap(.mut, in.*) else try l.wrap(.ref, in.*),
.own_array => |in| if (mutable) try l.wrap(.slice_mut, in.*) else try l.wrap(.slice, in.*),
.buffer => if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty),
.region => if (mutable) try l.wrap(.mut, .region) else try l.wrap(.ref, .region),
.resource, .mutex, .sender, .receiver, .task, .island => if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty),
.frozen, .arc => if (mutable) return l.fail("E7005", place.span, "frozen graphs and arcs are immutable: borrow them with `ref`", &.{.{ .name = "name", .value = n }}) else try l.wrap(.ref, b.ty),
// Atomic operations go through a shared borrow (spec 04 §23).
.atomic => if (mutable) return l.fail("E7005", place.span, "an atomic cell is borrowed with `ref`: every atomic operation goes through a shared borrow", &.{.{ .name = "name", .value = n }}) else try l.wrap(.ref, b.ty),
else => null,
};
const t = bt orelse return l.invalid(.invalid_place, place.span, "this value is not addressable here; borrow a variable, a field or an element", &.{.{ .name = "name", .value = n }});
const v = try l.def(n, t, try l.fmt("{s} %{s}", .{ op, b.value }), span);
return .{ .v = v, .ends = try l.arena.dupe([]const u8, &.{v.name}) };
},
}
},
.bytes => |bytes| {
const st = try l.materializeBytes(bytes, place.span);
const v = try l.def("b", if (mutable) try l.wrap(.mut, st.ty) else try l.wrap(.ref, st.ty), try l.fmt("{s} %{s}", .{ op, st.name }), span);
return .{ .v = v, .ends = try l.arena.dupe([]const u8, &.{v.name}) };
},
.deref => |d| {
const r = try l.expr(d.*, null);
if (!r.ty.isBorrow()) return l.fail("E7005", place.span, "`*` needs a borrow", &.{});
return .{ .v = r, .ends = &.{} };
},
.field => |f| {
const base = try l.placeRaw(f.e.*, mutable, span);
const st = base.v.ty.inner() orelse return l.fail("E7005", place.span, "field of a value that is not a struct", &.{});
const d = l.decl(st) orelse return l.fail("E7005", place.span, "field of a value that is not a struct", &.{.{ .name = "found", .value = try l.diagnosticTyText(st) }});
if (d.kind != .@"struct") return l.fail("E7005", place.span, "field of an enum; use `match`", &.{});
const fd = for (d.kind.@"struct") |x| {
if (std.mem.eql(u8, x.name, f.name)) break x;
} else return l.fail("E7002", place.span, "no such field", &.{ .{ .name = "type", .value = d.display_name orelse d.name }, .{ .name = "field", .value = f.name } });
const ft = try l.typeOf(fd.ty);
const v = try l.defBorrow(f.name, if (base.v.ty.isMutBorrow()) try l.wrap(.mut, ft) else try l.wrap(.ref, ft), try l.fmt("borrow.field @{s}.{s}, %{s}", .{ d.air_name orelse d.name, f.name, base.v.name }), base.v.name, span);
return .{ .v = v, .ends = try l.concat(base.ends, v.name) };
},
.index => |x| {
const outer_unchecked = l.unchecked;
l.unchecked = false;
const base = try l.placeRaw(x.e.*, mutable, span);
l.unchecked = outer_unchecked;
const bt = base.v.ty;
const elem = elemOf(bt) orelse return l.fail("E7005", place.span, "indexing needs an array or a slice", &.{.{ .name = "found", .value = try l.diagnosticTyText(bt) }});
if (x.hi) |hi| {
// `s[a..b]`: slice.sub with start a and length b - a (checked).
var sl = base.v;
var ends = base.ends;
if (bt == .ref or bt == .mut) {
sl = try l.defBorrow("s", (if (bt == .mut) try l.wrap(.slice_mut, elem) else try l.wrap(.slice, elem)), try l.fmt("slice.make %{s}", .{base.v.name}), base.v.name, span);
ends = try l.concat(ends, sl.name);
}
const a = try l.expr(x.lo.*, .{ .int = "usize" });
try l.checkOperandTy(x.lo.span, a.ty, .{ .int = "usize" });
const b = try l.expr(hi.*, .{ .int = "usize" });
try l.checkOperandTy(hi.span, b.ty, .{ .int = "usize" });
const len = try l.def("len", .{ .int = "usize" }, try l.fmt("sub.checked.usize %{s}, %{s}", .{ b.name, a.name }), span);
const sub_ = try l.defBorrow("s", sl.ty, try l.fmt("slice.sub %{s}, %{s}, %{s}", .{ sl.name, a.name, len.name }), sl.name, span);
return .{ .v = sub_, .ends = try l.concat(ends, sub_.name) };
}
// Only the outermost index of an unchecked place is unchecked.
const unchecked = l.unchecked;
l.unchecked = false;
const i = try l.expr(x.lo.*, .{ .int = "usize" });
try l.checkOperandTy(x.lo.span, i.ty, .{ .int = "usize" });
const proven = for (l.facts.items) |f| {
if (std.mem.eql(u8, f.index, i.name) and std.mem.eql(u8, f.slice, base.v.name)) break true;
} else false;
if (unchecked) l.uses.insert(.unsafe);
const index_op = if (unchecked) "borrow.index.unchecked" else if (proven) "borrow.index.proven" else "borrow.index";
const v = try l.defBorrow("e", if (bt.isMutBorrow()) try l.wrap(.mut, elem) else try l.wrap(.ref, elem), try l.fmt("{s} %{s}, %{s}", .{ index_op, base.v.name, i.name }), base.v.name, span);
return .{ .v = v, .ends = try l.concat(base.ends, v.name) };
},
else => return l.invalid(.invalid_place, place.span, "not a place: borrow a variable, a field `x.f`, an element `s[i]` or a range `s[a..b]`", &.{}),
}
}
fn concat(l: *Lowerer, a: []const []const u8, b: []const u8) Error![]const []const u8 {
const out = try l.arena.alloc([]const u8, a.len + 1);
@memcpy(out[0..a.len], a);
out[a.len] = b;
return out;
}
/// `*r = v`, `r.f = v`, `x.f = v`, `s[i] = v`, `x[i] = v`.
fn assignPlace(l: *Lowerer, span: Span, place: ast.Expr, value: ast.Expr) Error!void {
switch (place.kind) {
.deref, .field, .index => {},
else => return l.invalid(.invalid_assignment, place.span, "cannot assign to this expression", &.{}),
}
if (place.kind == .index and place.kind.index.hi != null) return l.invalid(.invalid_assignment, place.span, "assign elements one by one, or use `slice.copy(mut dst, ref src)`", &.{});
// The value is evaluated first, then the place is borrowed for the
// store (spec 15 §4), so `s[i] = s[i] + 1` reads before it writes.
const target_type = l.placeType(place);
const v = try l.expr(value, target_type);
if (v.ty == .never) return l.noOperandValue(value.span, if (target_type) |t| try l.diagnosticTyText(t) else "a stored value");
const p = try l.placeBorrow(place, true, false, span);
const in = p.v.ty.inner() orelse return l.fail("E7005", place.span, "assignment needs a mutable place", &.{});
if (in == .array and place.kind == .deref) return l.invalid(.invalid_assignment, place.span, "write array elements with `s[i] = …`", &.{});
if (p.v.ty != .mut) return l.fail("E7005", place.span, "assignment needs a mutable place", &.{ .{ .name = "expected", .value = try l.diagnosticTyText(try l.wrap(.mut, in)) }, .{ .name = "found", .value = try l.diagnosticTyText(p.v.ty) } });
try l.checkOperandTy(value.span, v.ty, in);
try l.emit(try l.fmt("store %{s}, %{s}", .{ p.v.name, v.name }), span);
try l.endNow(p.ends, span);
}
/// The type stored at a place, without lowering it.
fn placeType(l: *Lowerer, place: ast.Expr) ?Ty {
return switch (place.kind) {
.deref => |d| if (l.peekType(d.*)) |t| t.inner() else null,
.field, .index => l.peekType(place),
else => null,
};
}
fn isNominalFieldBase(t: Ty) bool {
// Slices of structs retain their builtin length; only ref/mut
// receivers expose fields of their nominal inner type.
return t == .named or ((t == .ref or t == .mut) and t.inner().? == .named);
}
/// `x.len`: a nominal field, `slice.len`, or the static array length.
fn lenOf(l: *Lowerer, e: ast.Expr, base: ast.Expr) Error!Value {
const bt = l.peekType(base) orelse return l.fail("E7007", base.span, "the type of this expression cannot be determined", &.{});
if (isNominalFieldBase(bt)) return l.fieldValue(e, base, "len");
const arr: ?u64 = switch (bt) {
.array => |a| a.len,
.ref, .mut => |x| if (x.* == .array) x.array.len else null,
else => null,
};
if (arr) |n| return l.def("len", .{ .int = "usize" }, try l.fmt("const.usize {d}", .{n}), e.span);
if (bt != .slice and bt != .slice_mut) return l.fail("E7005", e.span, "`.len` needs an array or a slice", &.{.{ .name = "found", .value = try l.diagnosticTyText(bt) }});
const s_ = try l.expr(base, bt);
return l.def("len", .{ .int = "usize" }, try l.fmt("slice.len %{s}", .{s_.name}), e.span);
}
/// `let (left, right) = s.split_at(k);`: two disjoint borrows of `s`,
/// bound for the rest of the block (spec 15 §5).
fn unpackLet(l: *Lowerer, s: ast.Stmt, names: []const []const u8, e: ast.Expr, tuple: bool) Error!void {
if (!tuple or s.kind.let.ty != null or e.kind.call.args.len != 1) return l.invalid(.invalid_unpack, s.span, "unpack requires a parenthesized complete binding and one argument", &.{});
const v = try l.consuming(e.kind.call.args[0], null);
const operation = pathOf(e.kind.call.callee.*).?;
var components: std.ArrayList(Ty) = .empty;
if (std.mem.eql(u8, operation, "struct.unpack") and v.ty == .named and l.m.types[v.ty.named].kind == .@"struct") {
for (l.m.types[v.ty.named].kind.@"struct") |f| try components.append(l.arena, try l.typeOf(f.ty));
} else if (std.mem.eql(u8, operation, "array.unpack") and v.ty == .array) {
if (v.ty.array.len > 64) return l.invalid(.implementation_limit, s.span, "unpack exceeds 64 block parameters", &.{});
for (0..@intCast(v.ty.array.len)) |_| try components.append(l.arena, v.ty.array.elem);
} else return l.fail("E7005", e.span, "unpack needs the corresponding struct or array", &.{});
if (names.len != components.items.len or names.len > 64) return l.fail("E7005", s.span, "unpack must bind every component", &.{});
const next = try l.newBlock("unpacked", s.span);
for (names, components.items, 0..) |n, t, i| {
for (names[0..i]) |previous| if (!std.mem.eql(u8, n, "_") and std.mem.eql(u8, n, previous)) return l.invalid(.invalid_unpack, s.span, "duplicate unpack binding", &.{});
const pn = try l.freshName(if (std.mem.eql(u8, n, "_")) "unused" else n);
try l.blocks.items[next].params.append(l.arena, .{ .name = pn, .ty = t });
if (!std.mem.eql(u8, n, "_")) try l.bindings.append(l.arena, .{ .name = n, .value = pn, .ty = t, .mutable = false });
}
try l.term(try l.fmt("{s} {s} %{s}, next -> @{s}", .{ operation, try l.tyText(v.ty), v.name, l.blocks.items[next].name }), s.span);
l.cur = next;
l.linear_enabled = true;
}
fn splitLet(l: *Lowerer, s: ast.Stmt, names: []const []const u8, e: ast.Expr) Error!void {
if (e.kind != .call or e.kind.call.callee.kind != .field or !std.mem.eql(u8, e.kind.call.callee.kind.field.name, "split_at") or e.kind.call.args.len != 1)
return l.invalid(.invalid_unpack, e.span, "`let (a, b) = …` is only for `s.split_at(k)`", &.{});
const base = e.kind.call.callee.kind.field.e.*;
const rb = l.rootBinding(base) orelse return l.fail("E7002", base.span, "unknown name", &.{});
const mutable = rb.ty.isMutBorrow() or rb.kind == .storage and rb.mutable;
const p = try l.placeBorrow(base, mutable, true, s.span);
if (p.v.ty != .slice and p.v.ty != .slice_mut) return l.fail("E7005", base.span, "`split_at` splits a slice", &.{.{ .name = "found", .value = try l.diagnosticTyText(p.v.ty) }});
const k = try l.expr(e.kind.call.args[0], .{ .int = "usize" });
try l.checkOperandTy(e.kind.call.args[0].span, k.ty, .{ .int = "usize" });
const left = try l.freshName(names[0]);
const right = try l.freshName(names[1]);
try l.emit(try l.fmt("%{s}, %{s} = slice.split %{s}, %{s}", .{ left, right, p.v.name, k.name }), s.span);
try l.borrow_parents.put(l.arena, left, p.v.name);
try l.borrow_parents.put(l.arena, right, p.v.name);
try l.scopeEnds(p.ends, s.span);
try l.scopeEnds(&.{ left, right }, s.span);
try l.bindings.append(l.arena, .{ .name = names[0], .mutable = false, .value = left, .ty = p.v.ty, .kind = .borrow });
try l.bindings.append(l.arena, .{ .name = names[1], .mutable = false, .value = right, .ty = p.v.ty, .kind = .borrow });
}
/// `slice.copy(mut dst, ref src)`: the only copy form (spec 15 §5).
fn sliceCopy(l: *Lowerer, e: ast.Expr, args: []const ast.Expr) Error!Value {
if (args.len != 2) return l.fail("E7005", e.span, "`slice.copy` takes `mut dst` and `ref src`", &.{});
var temps: std.ArrayList([]const u8) = .empty;
const d = try l.argument(args[0], null, &temps);
const src = try l.argument(args[1], null, &temps);
if (d.ty != .slice_mut) return l.fail("E7005", args[0].span, "`slice.copy` writes to `mut dst` (a `slice_mut<T>`)", &.{.{ .name = "found", .value = try l.diagnosticTyText(d.ty) }});
if (src.ty != .slice and src.ty != .slice_mut) return l.fail("E7005", args[1].span, "`slice.copy` reads from `ref src` (a `slice<T>`)", &.{.{ .name = "found", .value = try l.diagnosticTyText(src.ty) }});
if (!d.ty.inner().?.eql(src.ty.inner().?)) return l.fail("E7005", args[1].span, "`slice.copy` copies between slices of the same element type", &.{ .{ .name = "expected", .value = try l.diagnosticTyText(d.ty.inner().?) }, .{ .name = "found", .value = try l.diagnosticTyText(src.ty.inner().?) } });
try l.emit(try l.fmt("slice.copy %{s}, %{s}", .{ d.name, src.name }), e.span);
try l.endNow(temps.items, e.span);
return .{ .name = "", .ty = .void };
}
/// Names that need frame storage in this function: every variable that is
/// borrowed, indexed, or written through a field or element (spec 15 §9).
/// Deterministic and by name.
fn findAddressable(l: *Lowerer, body: ast.Block) Error!void {
try l.markAddressable(.{ .block = body });
}
const AddressNode = union(enum) {
block: ast.Block,
stmt: ast.Stmt,
expr: ast.Expr,
root: ast.Expr,
stmts: []const ast.Stmt,
exprs: []const ast.Expr,
fields: []const ast.FieldInit,
arms: []const ast.Arm,
};
fn markAddressable(l: *Lowerer, initial: AddressNode) Error!void {
var pending: std.ArrayList(AddressNode) = .empty;
defer pending.deinit(l.arena);
try pending.append(l.arena, initial);
while (pending.pop()) |node| switch (node) {
.block => |b| {
if (b.tail) |t| try pending.append(l.arena, .{ .expr = t.* });
try pending.append(l.arena, .{ .stmts = b.stmts });
},
.stmts => |xs| if (xs.len != 0) {
try pending.append(l.arena, .{ .stmts = xs[1..] });
try pending.append(l.arena, .{ .stmt = xs[0] });
},
.exprs => |xs| if (xs.len != 0) {
try pending.append(l.arena, .{ .exprs = xs[1..] });
try pending.append(l.arena, .{ .expr = xs[0] });
},
.fields => |xs| if (xs.len != 0) {
try pending.append(l.arena, .{ .fields = xs[1..] });
try pending.append(l.arena, .{ .expr = xs[0].e });
},
.arms => |xs| if (xs.len != 0) {
try pending.append(l.arena, .{ .arms = xs[1..] });
try pending.append(l.arena, .{ .expr = xs[0].body });
},
.root => |e| switch (e.kind) {
.name => |n| try l.addressable.put(l.arena, n, {}),
.field => |x| try pending.append(l.arena, .{ .root = x.e.* }),
.index => |x| {
// Bounds precede descending the base, matching the old
// root loop even for multiple nested projections.
try pending.append(l.arena, .{ .root = x.e.* });
if (x.hi) |h| try pending.append(l.arena, .{ .expr = h.* });
try pending.append(l.arena, .{ .expr = x.lo.* });
},
else => try pending.append(l.arena, .{ .expr = e }),
},
.stmt => |s| switch (s.kind) {
.let => |x| try pending.append(l.arena, .{ .expr = x.e }),
.@"var" => |x| if (x.init) |e| try pending.append(l.arena, .{ .expr = e }),
.assign => |x| {
try pending.append(l.arena, .{ .expr = x.e });
if (x.place.kind != .name) try pending.append(l.arena, .{ .root = x.place });
},
.borrow => |x| try pending.append(l.arena, .{ .root = x.place }),
.@"return" => |e| if (e) |x| try pending.append(l.arena, .{ .expr = x }),
.expr => |e| try pending.append(l.arena, .{ .expr = e }),
.@"while" => |x| {
try pending.append(l.arena, .{ .block = x.body });
try pending.append(l.arena, .{ .expr = x.cond });
},
.@"for" => |x| {
try pending.append(l.arena, .{ .block = x.body });
try pending.append(l.arena, .{ .expr = x.hi });
try pending.append(l.arena, .{ .expr = x.lo });
},
.loop, .shield => |b| try pending.append(l.arena, .{ .block = b }),
.scope => |x| try pending.append(l.arena, .{ .block = x.body }),
.lock => |x| {
try pending.append(l.arena, .{ .block = x.cancelled });
try pending.append(l.arena, .{ .block = x.body });
},
else => {},
},
.expr => |e| switch (e.kind) {
.borrow => |x| try pending.append(l.arena, .{ .root = x.place.* }),
.index => try pending.append(l.arena, .{ .root = e }),
.neg, .not, .deref, .or_trap => |x| try pending.append(l.arena, .{ .expr = x.* }),
.binary => |x| {
try pending.append(l.arena, .{ .expr = x.r.* });
try pending.append(l.arena, .{ .expr = x.l.* });
},
.cast => |x| try pending.append(l.arena, .{ .expr = x.e.* }),
.call => |x| {
if (x.callee.kind == .field and std.mem.eql(u8, x.callee.kind.field.name, "split_at")) try pending.append(l.arena, .{ .root = x.callee.kind.field.e.* });
try pending.append(l.arena, .{ .exprs = x.args });
try pending.append(l.arena, .{ .expr = x.callee.* });
},
.field => |x| try pending.append(l.arena, .{ .expr = x.e.* }),
.struct_lit => |x| try pending.append(l.arena, .{ .fields = x.fields }),
.array_rep => |x| try pending.append(l.arena, .{ .expr = x.e.* }),
.array_list => |xs| try pending.append(l.arena, .{ .exprs = xs }),
.if_expr => |x| {
if (x.@"else") |els| switch (els) {
.block => |b| try pending.append(l.arena, .{ .block = b }),
.@"if" => |inner| try pending.append(l.arena, .{ .expr = .{ .span = e.span, .kind = .{ .if_expr = inner } } }),
};
try pending.append(l.arena, .{ .block = x.then });
try pending.append(l.arena, .{ .expr = x.cond });
},
.match_expr => |x| {
try pending.append(l.arena, .{ .arms = x.arms });
try pending.append(l.arena, .{ .expr = x.scrutinee });
},
.block => |b| try pending.append(l.arena, .{ .block = b.* }),
else => {},
},
};
}
// ------------------------------------------------------------ fallible operations (layer 5)
const Outcome = struct { role: []const u8, params: []const Ty };
/// A lowered fallible operation: its AIR text before the targets and its
/// outcomes in AIR order.
/// `temps`: borrows made for the operation, ended at the start of every
/// outcome block.
const Fallible = struct { text: []const u8, outcomes: []const Outcome, borrow_parent: ?[]const u8 = null, temps: []const []const u8 = &.{} };
fn fallible(l: *Lowerer, path: []const u8) ?void {
_ = l;
const ops = [_][]const u8{ "buffer.new", "buffer.reserve", "buffer.push", "buffer.pop", "buffer.free", "own.new", "own.pack", "own.array", "region.create", "region.new", "region.array", "cap.narrow.budget", "cap.narrow.prefix", "channel.make", "channel.send", "channel.recv", "channel.close_receiver", "task.check_cancel", "task.join_cancel", "island.create", "island.alloc", "arc.new" };
for (ops) |o| if (std.mem.eql(u8, o, path)) return {};
if (authority.intrinsicIndex(path)) |i| if (authority.intrinsics[i].fallible) return {};
return null;
}
// ------------------------------------------------------------ tasks and channels (layer 7)
// ------------------------------------------------------------ atomics (spec 15 §12, spec 04 §42)
/// An ordering, written as a bare word (spec 15 §12).
fn ordering(l: *Lowerer, a: ast.Expr) Error![]const u8 {
const words = [_][]const u8{ "relaxed", "acquire", "release", "acq_rel", "seq_cst" };
if (a.kind == .name) for (words) |w| if (std.mem.eql(u8, a.kind.name, w)) return w;
return l.invalid(.invalid_operation, a.span, "an ordering is one of the words relaxed, acquire, release, acq_rel, seq_cst, written in place", &.{});
}
/// The cell operand of an atomic operation: a `ref<atomic<T>>` binding or
/// parameter, or `ref a` of an atomic, borrowed for the operation.
fn cellOperand(l: *Lowerer, a: ast.Expr, temps: *std.ArrayList([]const u8)) Error!Value {
if (a.kind == .borrow) {
const br = a.kind.borrow;
if (br.mutable) return l.fail("E7005", a.span, "atomic operations take `ref` of the cell, never `mut`", &.{});
const b = try l.bindingOf(br.place.*, "an atomic cell");
if (b.ty != .atomic) return l.fail("E7005", a.span, "an atomic operation takes `ref` of an `atomic<T>`", &.{.{ .name = "found", .value = try l.diagnosticTyText(b.ty) }});
const r = try l.def(br.place.kind.name, try l.wrap(.ref, b.ty), try l.fmt("borrow.ref %{s}", .{b.value}), a.span);
try temps.append(l.arena, r.name);
return r;
}
const b = try l.bindingOf(a, "an atomic cell");
if (b.ty == .atomic) return l.fail("E7005", a.span, "pass the cell as `ref a` (or a `ref` binding of it): atomic operations go through a shared borrow", &.{.{ .name = "suggestion", .value = try l.fmt("ref {s}", .{a.kind.name}) }});
if (b.ty == .ref and b.ty.inner().? == .atomic) return .{ .name = b.value, .ty = b.ty };
return l.fail("E7005", a.span, "an atomic operation takes a `ref<atomic<T>>`", &.{.{ .name = "found", .value = try l.diagnosticTyText(b.ty) }});
}
fn atomicCall(l: *Lowerer, e: ast.Expr, p: []const u8, args: []const ast.Expr) Error!Value {
const eq = std.mem.eql;
if (eq(u8, p, "atomic.new")) {
if (args.len != 1) return l.fail("E7005", e.span, "`atomic.new` takes the initial value", &.{});
const v = try l.expr(args[0], null);
if (!atomicScalar(v.ty)) return l.fail("E7005", args[0].span, "atomic<T> needs bool or an integer of at most 64 bits", &.{.{ .name = "found", .value = try l.diagnosticTyText(v.ty) }});
return l.def("atomic", try l.wrap(.atomic, v.ty), try l.fmt("atomic.new %{s}", .{v.name}), e.span);
}
if (eq(u8, p, "atomic.take")) {
if (args.len != 1) return l.fail("E7005", e.span, "`atomic.take` takes one cell", &.{});
const c = try l.consuming(args[0], null);
if (c.ty != .atomic) return l.fail("E7005", args[0].span, "`atomic.take` takes an `atomic<T>`", &.{.{ .name = "found", .value = try l.diagnosticTyText(c.ty) }});
return l.def("v", c.ty.inner().?, try l.fmt("atomic.take %{s}", .{c.name}), e.span);
}
if (eq(u8, p, "atomic.fence")) {
if (args.len != 1) return l.fail("E7005", e.span, "`atomic.fence` takes one ordering", &.{});
try l.emit(try l.fmt("atomic.fence.{s}", .{try l.ordering(args[0])}), e.span);
return .{ .name = "", .ty = .void };
}
if (eq(u8, p, "atomic.compare_exchange"))
return l.invalid(.invalid_unpack, e.span, "`atomic.compare_exchange` has two results: `let (old, exchanged) = atomic.compare_exchange(c, expected, desired, success, failure);`", &.{});
var temps: std.ArrayList([]const u8) = .empty;
const want: usize = if (eq(u8, p, "atomic.load")) 2 else 3;
if (args.len != want) return l.fail("E7005", e.span, "wrong number of operands", &.{ .{ .name = "operation", .value = p }, .{ .name = "expected", .value = try l.fmt("{d}", .{want}) } });
const c = try l.cellOperand(args[0], &temps);
const t = c.ty.inner().?.inner().?;
const ord = try l.ordering(args[want - 1]);
if (eq(u8, p, "atomic.load")) {
const v = try l.def("v", t, try l.fmt("atomic.load.{s} %{s}", .{ ord, c.name }), e.span);
try l.endNow(temps.items, e.span);
return v;
}
const operand = try l.expr(args[1], t);
try l.checkOperandTy(args[1].span, operand.ty, t);
if (eq(u8, p, "atomic.store")) {
try l.emit(try l.fmt("atomic.store.{s} %{s}, %{s}", .{ ord, c.name, operand.name }), e.span);
try l.endNow(temps.items, e.span);
return .{ .name = "", .ty = .void };
}
const op: []const u8 = if (eq(u8, p, "atomic.swap")) "xchg" else p["atomic.".len..];
if ((eq(u8, op, "add.wrap") or eq(u8, op, "sub.wrap")) and t != .int) return l.fail("E7005", args[1].span, "`atomic.add.wrap` and `atomic.sub.wrap` need an integer cell", &.{.{ .name = "found", .value = try l.diagnosticTyText(t) }});
const v = try l.def("old", t, try l.fmt("atomic.{s}.{s} %{s}, %{s}", .{ op, ord, c.name, operand.name }), e.span);
try l.endNow(temps.items, e.span);
return v;
}
/// `let (old, exchanged) = atomic.compare_exchange(c, expected, desired,
/// success, failure);` (spec 15 §12): the second multi-result binding.
fn compareExchangeLet(l: *Lowerer, s: ast.Stmt, names: []const []const u8, e: ast.Expr) Error!void {
const args = e.kind.call.args;
if (args.len != 5) return l.fail("E7005", e.span, "`atomic.compare_exchange` takes a cell, the expected and the desired value, and two orderings", &.{});
var temps: std.ArrayList([]const u8) = .empty;
const c = try l.cellOperand(args[0], &temps);
const t = c.ty.inner().?.inner().?;
const expected = try l.expr(args[1], t);
try l.checkOperandTy(args[1].span, expected.ty, t);
const desired = try l.expr(args[2], t);
try l.checkOperandTy(args[2].span, desired.ty, t);
const succ = try l.ordering(args[3]);
const failure = try l.ordering(args[4]);
const old = try l.freshName(names[0]);
const ok = try l.freshName(names[1]);
try l.emit(try l.fmt("%{s}, %{s} = atomic.cmpxchg.{s}.{s} %{s}, %{s}, %{s}", .{ old, ok, succ, failure, c.name, expected.name, desired.name }), s.span);
try l.endNow(temps.items, s.span);
try l.bindings.append(l.arena, .{ .name = names[0], .mutable = false, .value = old, .ty = t, .kind = .ssa });
try l.bindings.append(l.arena, .{ .name = names[1], .mutable = false, .value = ok, .ty = .bool, .kind = .ssa });
}
fn bindingOf(l: *Lowerer, a: ast.Expr, what: []const u8) Error!*Binding {
if (a.kind != .name) return l.fail("E7005", a.span, try l.fmt("{s} is expected here, by name", .{what}), &.{});
return l.lookup(a.kind.name) orelse l.unknown(a.span, a.kind.name);
}
/// An endpoint operand the operation borrows (`mut` or `ref`): the
/// endpoint by name, borrowed for the operation, or a borrow binding of it.
fn endpointOperand(l: *Lowerer, a: ast.Expr, tag: std.meta.Tag(Ty), mutable: bool, temps: *std.ArrayList([]const u8)) Error!Value {
const what = if (tag == .sender) "a sender" else "a receiver";
if (a.kind == .borrow) return l.invalid(.invalid_borrow, a.span, "an endpoint operand is written by name; the operation borrows it", &.{});
const b = try l.bindingOf(a, what);
if (std.meta.activeTag(b.ty) == tag) {
const bt = if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty);
const v = try l.def(a.kind.name, bt, try l.fmt("{s} %{s}", .{ if (mutable) "borrow.mut" else "borrow.ref", b.value }), a.span);
try temps.append(l.arena, v.name);
return v;
}
if ((b.ty == .mut or (b.ty == .ref and !mutable)) and std.meta.activeTag(b.ty.inner().?) == tag) return .{ .name = b.value, .ty = b.ty };
return l.fail("E7005", a.span, try l.fmt("{s} is expected here", .{what}), &.{.{ .name = "found", .value = try l.diagnosticTyText(b.ty) }});
}
/// The task and channel operations that are plain calls; null for any
/// other path.
fn concurrencyCall(l: *Lowerer, e: ast.Expr, p: []const u8, args: []const ast.Expr) Error!?Value {
const eq = struct {
fn f(a: []const u8, b: []const u8) bool {
return std.mem.eql(u8, a, b);
}
}.f;
if (eq(p, "task.spawn")) {
if (args.len < 2) return l.fail("E7005", e.span, "`task.spawn` takes a scope, a function and its arguments", &.{});
const sb = try l.bindingOf(args[0], "a task scope");
if (sb.ty != .scope) return l.fail("E7005", args[0].span, "`task.spawn` spawns into a scope: `scope s { … task.spawn(s, f, …) … }`", &.{.{ .name = "found", .value = try l.diagnosticTyText(sb.ty) }});
const scope_name = sb.value;
const fname = try expressionPath(l.arena, args[1]) orelse return l.fail("E7005", args[1].span, "the function to spawn is named", &.{});
const sig = l.functionSig(fname, args[1].span) orelse return l.unknown(args[1].span, fname);
if (sig.ret.isBorrow()) return l.invalid(.invalid_borrow_return, e.span, "a spawned function cannot return a borrow (reserved: task_borrow_returns)", &.{.{ .name = "function", .value = sig.display_name }});
const fargs = args[2..];
if (fargs.len != sig.params.len) return l.fail("E7005", e.span, "wrong number of arguments", &.{ .{ .name = "function", .value = sig.display_name }, .{ .name = "expected", .value = try l.fmt("{d}", .{sig.params.len}) }, .{ .name = "found", .value = try l.fmt("{d}", .{fargs.len}) } });
var names: std.ArrayList(u8) = .empty;
for (fargs, sig.params, 0..) |a, pt, i| {
// A borrow is lent to the task until its join, so it is bound
// by the program, not made for the call (spec 15 §7).
if (a.kind == .borrow or a.kind == .bytes) return l.invalid(.invalid_borrow, a.span, "a borrow lent to a task stays lent until the join: bind it first (`mut part = …;`) and pass the name", &.{});
const v = try l.consuming(a, pt);
try l.checkOperandTy(a.span, v.ty, pt);
try names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", v.name }));
}
return try l.def("t", try l.wrap(.task, sig.ret), try l.fmt("task.spawn %{s}, @{s}({s})", .{ scope_name, sig.air_name, names.items }), e.span);
}
if (eq(p, "task.join")) {
if (args.len != 1) return l.fail("E7005", e.span, "`task.join` takes one task", &.{});
const t = try l.consuming(args[0], null);
if (t.ty != .task) return l.fail("E7005", args[0].span, "`task.join` takes a `task<T>`", &.{.{ .name = "found", .value = try l.diagnosticTyText(t.ty) }});
const rt = t.ty.task.*;
if (rt == .void) {
try l.emit(try l.fmt("task.join %{s}", .{t.name}), e.span);
return .{ .name = "", .ty = .void };
}
return try l.def("r", rt, try l.fmt("task.join %{s}", .{t.name}), e.span);
}
if (eq(p, "task.cancel")) {
if (args.len != 1) return l.fail("E7005", e.span, "`task.cancel` takes one task, by name", &.{});
const b = try l.bindingOf(args[0], "a task");
if (b.ty != .task) return l.fail("E7005", args[0].span, "`task.cancel` takes a `task<T>`", &.{.{ .name = "found", .value = try l.diagnosticTyText(b.ty) }});
try l.emit(try l.fmt("task.cancel %{s}", .{b.value}), e.span);
return .{ .name = "", .ty = .void };
}
if (eq(p, "task.cancelled")) {
if (args.len != 0) return l.fail("E7005", e.span, "`task.cancelled()` takes no operands", &.{});
return try l.def("c", .bool, "task.cancelled", e.span);
}
if (eq(p, "channel.dup")) {
if (args.len != 1) return l.fail("E7005", e.span, "`channel.dup` takes one sender", &.{});
var temps: std.ArrayList([]const u8) = .empty;
const tx = try l.endpointOperand(args[0], .sender, false, &temps);
const st = tx.ty.inner().?;
const v = try l.def("tx", st, try l.fmt("channel.sender.dup %{s}", .{tx.name}), e.span);
try l.endNow(temps.items, e.span);
return v;
}
if (eq(p, "island.root") or eq(p, "frozen.root") or eq(p, "arc.root")) {
if (args.len != 1) return l.fail("E7005", e.span, "`.root` takes the graph's borrow binding", &.{});
const g = try l.graphBorrow(args[0], p[0..std.mem.indexOfScalar(u8, p, '.').?], false);
return try l.def("root", try l.wrap(.iref, g.ty.inner().?.inner().?), try l.fmt("{s} %{s}", .{ p, g.name }), e.span);
}
if (eq(p, "island.freeze") or eq(p, "arc.from_frozen")) {
if (args.len != 1) return l.fail("E7005", e.span, "this operation takes one graph owner", &.{});
const o = try l.consuming(args[0], null);
const want: std.meta.Tag(Ty) = if (eq(p, "island.freeze")) .island else .frozen;
if (std.meta.activeTag(o.ty) != want) return l.fail("E7005", args[0].span, if (want == .island) "`island.freeze` takes an `island<T>`" else "`arc.from_frozen` takes a `frozen<T>`", &.{.{ .name = "found", .value = try l.diagnosticTyText(o.ty) }});
const out = if (want == .island) try l.wrap(.frozen, o.ty.inner().?) else try l.wrap(.arc, o.ty.inner().?);
return try l.def(if (want == .island) "frozen" else "arc", out, try l.fmt("{s} %{s}", .{ p, o.name }), e.span);
}
if (eq(p, "island.destroy") or eq(p, "frozen.release") or eq(p, "arc.release")) {
if (args.len != 1) return l.fail("E7005", e.span, "this operation takes one graph owner", &.{});
const o = try l.consuming(args[0], null);
const want: std.meta.Tag(Ty) = if (eq(p, "island.destroy")) .island else if (eq(p, "frozen.release")) .frozen else .arc;
if (std.meta.activeTag(o.ty) != want) return l.fail("E7005", args[0].span, "this operation takes another graph owner", &.{ .{ .name = "operation", .value = p }, .{ .name = "found", .value = try l.diagnosticTyText(o.ty) } });
try l.emit(try l.fmt("{s} %{s}", .{ p, o.name }), e.span);
return .{ .name = "", .ty = .void };
}
if (eq(p, "arc.clone")) {
if (args.len != 1 or args[0].kind != .name) return l.fail("E7005", e.span, "`arc.clone` takes an arc by name", &.{});
const b = l.lookup(args[0].kind.name) orelse return l.unknown(args[0].span, args[0].kind.name);
if (b.ty == .arc) {
const r = try l.def(args[0].kind.name, try l.wrap(.ref, b.ty), try l.fmt("borrow.ref %{s}", .{b.value}), args[0].span);
const v = try l.def("arc", b.ty, try l.fmt("arc.clone %{s}", .{r.name}), e.span);
try l.emit(try l.fmt("borrow.end %{s}", .{r.name}), e.span);
return v;
}
if (b.ty == .ref and b.ty.inner().? == .arc) return try l.def("arc", b.ty.inner().?, try l.fmt("arc.clone %{s}", .{b.value}), e.span);
return l.fail("E7005", args[0].span, "`arc.clone` takes an `arc<T>`", &.{.{ .name = "found", .value = try l.diagnosticTyText(b.ty) }});
}
if (eq(p, "island.at") or eq(p, "frozen.at") or eq(p, "arc.at"))
return l.invalid(.invalid_borrow, e.span, "a graph access is a borrow: bind it with `ref x = island.at(g, r);` or `mut x = island.at(g, r);`", &.{});
if (eq(p, "mutex.make")) {
if (args.len != 1) return l.fail("E7005", e.span, "`mutex.make` takes the initial value", &.{});
const v = try l.contentValue(args[0]);
try l.elementRule(v.ty, args[0].span, "a mutex's content");
return try l.def("m", try l.wrap(.mutex, v.ty), try l.fmt("mutex.make %{s}", .{v.name}), e.span);
}
if (eq(p, "mutex.take")) {
if (args.len != 1) return l.fail("E7005", e.span, "`mutex.take` takes one mutex", &.{});
const m = try l.consuming(args[0], null);
if (m.ty != .mutex) return l.fail("E7005", args[0].span, "`mutex.take` takes a `mutex<T>`", &.{.{ .name = "found", .value = try l.diagnosticTyText(m.ty) }});
return try l.def("v", m.ty.mutex.*, try l.fmt("mutex.take %{s}", .{m.name}), e.span);
}
if (eq(p, "channel.close_sender")) {
if (args.len != 1) return l.fail("E7005", e.span, "`channel.close_sender` takes one sender", &.{});
const tx = try l.consuming(args[0], null);
if (tx.ty != .sender) return l.fail("E7005", args[0].span, "`channel.close_sender` takes a `sender<T>`", &.{.{ .name = "found", .value = try l.diagnosticTyText(tx.ty) }});
try l.emit(try l.fmt("channel.close_sender %{s}", .{tx.name}), e.span);
return .{ .name = "", .ty = .void };
}
return null;
}
/// `lock ref m as x { body } cancelled { cb }` (spec 15 §7): `mutex.lock`
/// on a shared borrow of the mutex; on `ok`, `mutex.borrow` of the guard
/// bound as `x: mut<T>`, and at every normal exit of the body
/// `borrow.end x` then `mutex.unlock`. The guard is never a source value.
fn lockStmt(l: *Lowerer, s: ast.Stmt, place: ast.Expr, name: []const u8, body: ast.Block, cancelled: ast.Block) Error!void {
// The mutex: a `ref<mutex<T>>` binding, or a mutex borrowed for the lock.
var temps: std.ArrayList([]const u8) = .empty;
if (place.kind != .name) return l.fail("E7005", place.span, "`lock ref m`: the mutex or a `ref<mutex<T>>` binding, by name", &.{});
const b = l.lookup(place.kind.name) orelse return l.unknown(place.span, place.kind.name);
const mr: Value = switch (b.ty) {
.mutex => blk: {
const v = try l.def(place.kind.name, try l.wrap(.ref, b.ty), try l.fmt("borrow.ref %{s}", .{b.value}), place.span);
try temps.append(l.arena, v.name);
break :blk v;
},
.ref => if (b.ty.ref.* == .mutex) .{ .name = b.value, .ty = b.ty } else return l.fail("E7005", place.span, "`lock` needs a mutex", &.{.{ .name = "found", .value = try l.diagnosticTyText(b.ty) }}),
else => return l.fail("E7005", place.span, "`lock` needs a mutex", &.{.{ .name = "found", .value = try l.diagnosticTyText(b.ty) }}),
};
const elem = mr.ty.ref.mutex.*;
const depth = l.bindings.items.len;
const vars = try l.carriedLive(depth, s.span, .{ .lock = .{ body, cancelled } });
const before = try l.snapshot();
const locked = try l.newBlock("locked", s.span);
const guard = try l.freshName("guard");
try l.blocks.items[locked].params.append(l.arena, .{ .name = guard, .ty = try l.wrap(.guard, elem) });
const canc = try l.newBlock("lock_cancelled", cancelled.span);
try l.term(try l.fmt("mutex.lock %{s}, ok -> @{s}, cancelled -> @{s}", .{ mr.name, l.blocks.items[locked].name, l.blocks.items[canc].name }), s.span);
var ends: std.ArrayList(ArmEnd) = .empty;
l.cur = locked;
const x = try l.def(name, try l.wrap(.mut, elem), try l.fmt("mutex.borrow %{s}", .{guard}), s.span);
for (temps.items) |t| try l.pending_ends.append(l.arena, .{ .name = t, .span = body.span });
try l.pending_ends.append(l.arena, .{ .name = guard, .span = body.span, .op = "mutex.unlock" });
try l.pending_ends.append(l.arena, .{ .name = x.name, .span = body.span });
try l.pending_bindings.append(l.arena, .{ .name = name, .mutable = false, .value = x.name, .ty = x.ty, .kind = .borrow });
const bv = try l.blockBody(body);
try ends.append(l.arena, .{ .block = l.cur, .value = bv, .values = try l.snapshot(), .span = body.span });
l.restore(before);
l.cur = canc;
try l.endNow(temps.items, cancelled.span);
const cv = try l.blockBody(cancelled);
try ends.append(l.arena, .{ .block = l.cur, .value = cv, .values = try l.snapshot(), .span = cancelled.span });
_ = try l.mergeArms(s.span, "lock", ends.items, vars, before, "endlock");
}
/// `select { recv(rx) { … } send(tx, v) { … } cancelled(…) => … }`
/// (spec 15 §7, spec 04 §39). Each endpoint is borrowed once for the
/// operation. `V` is the distinct send values in order of first
/// appearance; every edge binds its own value (a received `T`) and then
/// the values of `V` not sent on it.
fn selectStmt(l: *Lowerer, s: ast.Stmt, sel: ast.Select) Error!void {
if (sel.arms.len == 0) return l.invalid(.invalid_match, s.span, "a `select` has at least one `recv` or `send` arm", &.{});
const Sent = struct { key: ?[]const u8, v: Value };
var values: std.ArrayList(Sent) = .empty;
const arm_value = try l.arena.alloc(?usize, sel.arms.len);
// Values first (as for an assignment), then the endpoint borrows.
for (sel.arms, arm_value) |a, *av| {
av.* = null;
const ve = a.value orelse continue;
const key: ?[]const u8 = switch (ve.kind) {
.move, .name => |n| n,
else => null,
};
if (key) |k| for (values.items, 0..) |x, i| if (x.key != null and std.mem.eql(u8, x.key.?, k)) {
av.* = i;
break;
};
if (av.* == null) {
const v = try l.consuming(ve, null);
if (v.ty == .never) {
// Values precede endpoint borrows. Inspect a known binding
// without emitting a borrow or evaluating another input.
const endpoint_ty: Ty = if (l.lookup(a.endpoint)) |b| b.ty else .void;
const channel_ty = if (endpoint_ty.isBorrow()) endpoint_ty.inner().? else endpoint_ty;
return l.noOperandValue(ve.span, if (channel_ty == .sender) try l.diagnosticTyText(channel_ty.sender.*) else "a channel element");
}
try values.append(l.arena, .{ .key = key, .v = v });
av.* = values.items.len - 1;
}
}
var temps: std.ArrayList([]const u8) = .empty;
const Ep = struct { name: []const u8, v: Value };
var eps: std.ArrayList(Ep) = .empty;
const arm_ep = try l.arena.alloc(Value, sel.arms.len);
for (sel.arms, arm_ep, 0..) |a, *ae, ai| {
const found = for (eps.items) |x| {
if (std.mem.eql(u8, x.name, a.endpoint)) break x.v;
} else null;
ae.* = found orelse blk: {
const ex: ast.Expr = .{ .span = a.span, .kind = .{ .name = a.endpoint } };
const v = try l.endpointOperand(ex, if (a.send) .sender else .receiver, true, &temps);
try eps.append(l.arena, .{ .name = a.endpoint, .v = v });
break :blk v;
};
if (a.send) {
const et = ae.ty.inner().?.sender.*;
try l.checkOperandTy(a.value.?.span, values.items[arm_value[ai].?].v.ty, et);
}
}
// Edges: per arm `ok` and `closed`, then `cancelled`.
const Edge = struct { arm: ?usize, role: []const u8, params: []const Ty, values: []const usize, block: usize = 0 };
var edges: std.ArrayList(Edge) = .empty;
const notSent = struct {
fn f(lw: *Lowerer, n: usize, sent: ?usize) Error![]const usize {
var out: std.ArrayList(usize) = .empty;
for (0..n) |i| if (sent == null or sent.? != i) try out.append(lw.arena, i);
return out.items;
}
}.f;
for (sel.arms, 0..) |a, i| {
if (a.send) {
try edges.append(l.arena, .{ .arm = i, .role = "ok", .params = &.{}, .values = try notSent(l, values.items.len, arm_value[i]) });
} else {
try edges.append(l.arena, .{ .arm = i, .role = "ok", .params = try l.arena.dupe(Ty, &.{arm_ep[i].ty.inner().?.receiver.*}), .values = try notSent(l, values.items.len, null) });
}
try edges.append(l.arena, .{ .arm = i, .role = "closed", .params = &.{}, .values = try notSent(l, values.items.len, null) });
}
try edges.append(l.arena, .{ .arm = null, .role = "cancelled", .params = &.{}, .values = try notSent(l, values.items.len, null) });
// Every outcome of every arm is matched exactly once.
for (sel.arms) |a| {
for (a.arms, 0..) |arm, k| {
if (arm.pattern.kind != .ctor or arm.pattern.kind.ctor.qualifier != null) return l.invalid(.invalid_match, arm.pattern.span, "a `select` arm names its outcomes: `ok(…)` and `closed(…)`", &.{});
const c = arm.pattern.kind.ctor;
if (!std.mem.eql(u8, c.name, "ok") and !std.mem.eql(u8, c.name, "closed")) return l.fail("E7002", arm.pattern.span, "a `select` arm has the outcomes `ok` and `closed`; `cancelled` is the `select`'s own arm", &.{.{ .name = "outcome", .value = c.name }});
for (a.arms[0..k]) |prev| if (std.mem.eql(u8, prev.pattern.kind.ctor.name, c.name)) return l.invalid(.invalid_match, arm.pattern.span, "outcome matched twice", &.{.{ .name = "outcome", .value = c.name }});
}
for ([_][]const u8{ "ok", "closed" }) |role| {
const covered = for (a.arms) |arm| {
if (std.mem.eql(u8, arm.pattern.kind.ctor.name, role)) break true;
} else false;
if (!covered) return l.fail("E7004", a.span, "the arm does not handle every outcome", &.{.{ .name = "missing", .value = role }});
}
}
const depth = l.bindings.items.len;
const vars = try l.carriedLive(depth, s.span, .{ .select = sel });
const before = try l.snapshot();
var text: std.ArrayList(u8) = .empty;
try text.appendSlice(l.arena, "select ");
for (edges.items) |*ed| {
ed.block = try l.newBlock(ed.role, s.span);
for (ed.params) |pt| try l.blocks.items[ed.block].params.append(l.arena, .{ .name = try l.freshName(ed.role), .ty = pt });
for (ed.values) |vi| try l.blocks.items[ed.block].params.append(l.arena, .{ .name = try l.freshName(ed.role), .ty = values.items[vi].v.ty });
}
for (sel.arms, 0..) |a, i| {
const okb = edges.items[2 * i].block;
const clb = edges.items[2 * i + 1].block;
if (a.send) {
try text.appendSlice(l.arena, try l.fmt("[send %{s}, %{s}, ok -> @{s}, closed -> @{s}], ", .{ arm_ep[i].name, values.items[arm_value[i].?].v.name, l.blocks.items[okb].name, l.blocks.items[clb].name }));
} else {
try text.appendSlice(l.arena, try l.fmt("[recv %{s}, ok -> @{s}, closed -> @{s}], ", .{ arm_ep[i].name, l.blocks.items[okb].name, l.blocks.items[clb].name }));
}
}
try text.appendSlice(l.arena, try l.fmt("cancelled -> @{s}", .{l.blocks.items[edges.items[edges.items.len - 1].block].name}));
try l.term(text.items, s.span);
var ends: std.ArrayList(ArmEnd) = .empty;
for (edges.items) |ed| {
const binds: []const []const u8, const body: ast.Expr, const pspan: Span = if (ed.arm) |ai| blk: {
const a = sel.arms[ai];
const arm = for (a.arms) |x| {
if (std.mem.eql(u8, x.pattern.kind.ctor.name, ed.role)) break x;
} else unreachable;
break :blk .{ arm.pattern.kind.ctor.binds, arm.body, arm.pattern.span };
} else .{ sel.cancelled_binds, sel.cancelled, sel.span };
const params = l.blocks.items[ed.block].params.items;
if (binds.len != params.len) return l.fail("E7005", pspan, "the edge binds its own value, then the values not sent on it, in order of first appearance", &.{ .{ .name = "outcome", .value = ed.role }, .{ .name = "expected", .value = try l.fmt("{d}", .{params.len}) } });
l.restore(before);
l.cur = ed.block;
try l.endNow(temps.items, pspan);
try l.scopes.append(l.arena, .empty);
for (binds, params) |bn, prm| {
if (std.mem.eql(u8, bn, "_")) continue;
if (l.lookup(bn)) |old| if (old.mutable and old.kind == .ssa and old.ty.eql(prm.ty)) {
old.value = prm.name;
continue;
};
try l.bindings.append(l.arena, .{ .name = bn, .mutable = false, .value = prm.name, .ty = prm.ty });
}
const v = try l.armBody(body, null);
if (l.cur != null) try l.endScopes(l.scopes.items.len - 1, body.span);
_ = l.scopes.pop();
l.bindings.shrinkRetainingCapacity(before.len);
try ends.append(l.arena, .{ .block = l.cur, .value = v, .values = try l.snapshot(), .span = body.span });
}
_ = try l.mergeArms(s.span, "select", ends.items, vars, before, "endselect");
}
/// Element rules of channels and mutexes (spec 04 §38.1): no borrow,
/// scope, task, shield or guard, at any depth. Endpoints inside are the
/// reserved `channel_transfer`, left to the verifier (`E0006`).
fn elementRule(l: *Lowerer, t: Ty, span: Span, what: []const u8) Error!void {
if (try l.forbiddenIn(t, 0)) |bad| return l.fail("E7005", span, try l.fmt("{s} contains no borrow, scope, task, shield or guard", .{what}), &.{ .{ .name = "type", .value = try l.diagnosticTyText(t) }, .{ .name = "found", .value = try l.diagnosticTyText(bad) } });
}
fn forbiddenIn(l: *Lowerer, t: Ty, depth: u32) Error!?Ty {
if (@import("builtin").is_test) l.property_visits += 1;
if (depth > 32) return null;
if (t == .named and properties.sourceForbiddenDepth(l.property_module.?, .{ .named = t.named }) > 32 - depth) return null;
return switch (t) {
.ref, .mut, .slice, .slice_mut, .scope, .task, .shield, .guard => t,
.array => |a| l.forbiddenIn(a.elem, depth + 1),
.own, .own_array, .buffer, .mutex => |x| l.forbiddenIn(x.*, depth + 1),
.named => |i| blk: {
const d = l.m.types[i];
switch (d.kind) {
.@"struct" => |fs| for (fs) |f| if (try l.forbiddenIn(try l.typeOf(f.ty), depth + 1)) |bad| break :blk bad,
.@"enum" => |vs| for (vs) |v| for (v.payload) |pt| if (try l.forbiddenIn(try l.typeOf(pt), depth + 1)) |bad| break :blk bad,
}
break :blk null;
},
else => null,
};
}
/// The named borrow binding of a graph owner that `.root`, `.at` and
/// `island.alloc` take (spec 15 §8: container borrows are explicit).
fn graphBorrow(l: *Lowerer, a: ast.Expr, owner: []const u8, mutable: bool) Error!Value {
if (a.kind == .borrow) return l.invalid(.invalid_borrow, a.span, "the graph's borrow is bound first (`mut g = isl;`), so it outlives the borrows taken from it", &.{});
if (a.kind != .name) return l.fail("E7005", a.span, "the graph's borrow binding is expected here, by name", &.{});
const b = l.lookup(a.kind.name) orelse return l.unknown(a.span, a.kind.name);
const tag = std.meta.stringToEnum(std.meta.Tag(Ty), owner).?;
if (std.meta.activeTag(b.ty) == tag) return l.fail("E7005", a.span, try l.fmt("this takes a borrow of the {s}, not the owner: bind `{s} g = {s};` in an enclosing block and pass `g`", .{ owner, if (mutable) "mut" else "ref", a.kind.name }), &.{.{ .name = "name", .value = a.kind.name }});
const ok = (b.ty == .ref or (b.ty == .mut and !mutable) or (b.ty == .mut and mutable)) and std.meta.activeTag(b.ty.inner().?) == tag;
if (!ok or (mutable and b.ty != .mut)) return l.fail("E7005", a.span, try l.fmt("a {s} borrow of an `{s}<T>` is expected here", .{ if (mutable) "`mut`" else "`ref` or `mut`", owner }), &.{.{ .name = "found", .value = try l.diagnosticTyText(b.ty) }});
return .{ .name = b.value, .ty = b.ty };
}
/// Buffer operations require an explicit named borrow of the handle.
fn bufferBorrow(l: *Lowerer, e: ast.Expr, mutable: bool) Error!Value {
if (e.kind == .name) if (l.lookup(e.kind.name)) |b| {
if ((b.ty == .mut or (!mutable and b.ty == .ref)) and b.ty.inner().? == .buffer) return .{ .name = b.value, .ty = b.ty };
};
return l.fail("E7005", e.span, if (mutable) "bind a named mut<buffer<T>> first" else "bind a named ref/mut<buffer<T>> first", &.{});
}
fn bufferView(l: *Lowerer, s: ast.Stmt, name_: []const u8, mutable: bool, place: ast.Expr) Error!void {
const args = place.kind.call.args;
if (args.len != 1) return l.fail("E7005", place.span, "buffer.view takes one named buffer borrow", &.{});
const parent = try l.bufferBorrow(args[0], mutable);
// A shared view from a mutable parent uses an explicit shared reborrow.
var borrow = parent;
var shared_end: ?[]const u8 = null;
if (!mutable and parent.ty == .mut) {
borrow = try l.defBorrow("buffer_ref", try l.wrap(.ref, parent.ty.inner().?), try l.fmt("borrow.ref %{s}", .{parent.name}), parent.name, place.span);
shared_end = borrow.name;
}
const ty = if (mutable) try l.wrap(.slice_mut, parent.ty.inner().?.buffer.*) else try l.wrap(.slice, parent.ty.inner().?.buffer.*);
const view = try l.defBorrow(name_, ty, try l.fmt("buffer.view %{s}", .{borrow.name}), borrow.name, place.span);
if (shared_end) |n| try l.scopeEnds(&.{n}, s.span);
try l.scopeEnds(&.{view.name}, s.span);
try l.bindings.append(l.arena, .{ .name = name_, .mutable = false, .value = view.name, .ty = ty, .kind = .borrow });
}
/// Graph access binds a child borrow of its named graph borrow.
fn graphAccess(l: *Lowerer, s: ast.Stmt, name: []const u8, mutable: bool, place: ast.Expr) Error!void {
const ac = place.kind.call;
const p = pathOf(ac.callee.*).?;
const owner = p[0..std.mem.indexOfScalar(u8, p, '.').?];
if (mutable and !std.mem.eql(u8, owner, "island")) return l.fail("E7005", s.span, "frozen graphs and arcs give `ref` access only", &.{});
if (ac.args.len != 2) return l.fail("E7005", place.span, "`.at` takes the graph's borrow binding and an `iref`", &.{});
const g = try l.graphBorrow(ac.args[0], owner, mutable);
const r = try l.expr(ac.args[1], null);
if (r.ty != .iref) return l.fail("E7005", ac.args[1].span, "an `iref` is expected here", &.{.{ .name = "found", .value = try l.diagnosticTyText(r.ty) }});
const op = if (std.mem.eql(u8, owner, "island")) "island.borrow" else if (std.mem.eql(u8, owner, "frozen")) "frozen.borrow" else "arc.borrow";
const target = r.ty.inner().?;
const v = try l.defBorrow(name, if (mutable) try l.wrap(.mut, target) else try l.wrap(.ref, target), try l.fmt("{s} %{s}, %{s}", .{ op, g.name, r.name }), g.name, s.span);
try l.scopeEnds(&.{v.name}, s.span);
try l.bindings.append(l.arena, .{ .name = name, .mutable = false, .value = v.name, .ty = v.ty, .kind = .borrow });
}
fn resultTy(r: authority.ResultType) Ty {
return switch (r) {
.usize => .{ .int = "usize" },
.u64 => .{ .int = "u64" },
.resource => |x| .{ .resource = x },
};
}
/// Operands of an intrinsic in registry order (`reference/intrinsics.md`).
/// A capability is passed plainly; a resource operand that is borrowed
/// is named and borrowed for the operation; a consumed one is `move`d;
/// data borrows are written (`ref`/`mut`, or a byte string).
fn intrinsicOperands(l: *Lowerer, e: ast.Expr, x: authority.Intrinsic, args: []const ast.Expr, temps: *std.ArrayList([]const u8)) Error![]const u8 {
if (args.len != x.operands.len) return l.fail("E7005", e.span, "wrong number of operands", &.{ .{ .name = "operation", .value = x.name }, .{ .name = "expected", .value = try l.fmt("{d}", .{x.operands.len}) } });
var text: std.ArrayList(u8) = .empty;
for (x.operands, args, 0..) |o, a, i| {
const v: Value = switch (o) {
.cap => |k| try l.expectCap(a, k),
.bytes, .buffer => blk: {
const want: Ty = if (o == .bytes) try l.wrap(.slice, .{ .int = "u8" }) else try l.wrap(.slice_mut, .{ .int = "u8" });
if (o == .buffer and a.kind == .bytes) return l.fail("E7005", a.span, "this operand is a buffer the operation writes: pass `mut buf`", &.{});
const v = try l.argument(a, want, temps);
if (!v.ty.eql(want)) return l.fail("E7005", a.span, if (o == .bytes) "bytes are passed as a borrow: `ref buf`, `ref buf[a..b]` or a byte string `b\"…\"`" else "a buffer is passed as `mut buf` or `mut buf[a..b]`", &.{ .{ .name = "expected", .value = try l.diagnosticTyText(want) }, .{ .name = "found", .value = try l.diagnosticTyText(v.ty) } });
break :blk v;
},
.borrowed => |rs| try l.resourceOperand(a, rs, temps),
.consumed => |rs| blk: {
const v = try l.consuming(a, null);
if (v.ty != .resource or std.mem.indexOfScalar(authority.Resource, rs, v.ty.resource) == null)
return l.fail("E7005", a.span, "this operation consumes a resource of another type", &.{ .{ .name = "operation", .value = x.name }, .{ .name = "found", .value = try l.diagnosticTyText(v.ty) } });
break :blk v;
},
};
try text.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", v.name }));
}
return text.items;
}
/// A resource operand the operation borrows: the resource by name
/// (borrowed `mut` for the operation) or a `mut` borrow binding of one.
fn resourceOperand(l: *Lowerer, a: ast.Expr, rs: []const authority.Resource, temps: *std.ArrayList([]const u8)) Error!Value {
const expected = try l.resourceList(rs);
if (a.kind == .borrow) return l.invalid(.invalid_borrow, a.span, "a resource operand is written by name; the operation borrows it", &.{.{ .name = "expected", .value = expected }});
if (a.kind != .name) return l.fail("E7005", a.span, "a resource is expected here, by name", &.{.{ .name = "expected", .value = expected }});
const b = l.lookup(a.kind.name) orelse return l.unknown(a.span, a.kind.name);
const r: ?authority.Resource = switch (b.ty) {
.resource => |r| r,
.mut => |in| if (in.* == .resource) in.resource else null,
else => null,
};
if (r == null or std.mem.indexOfScalar(authority.Resource, rs, r.?) == null)
return l.fail("E7005", a.span, "this operation needs a resource of another type", &.{ .{ .name = "expected", .value = expected }, .{ .name = "found", .value = try l.diagnosticTyText(b.ty) } });
if (b.ty == .mut) return .{ .name = b.value, .ty = b.ty };
const v = try l.def(a.kind.name, try l.wrap(.mut, b.ty), try l.fmt("borrow.mut %{s}", .{b.value}), a.span);
try temps.append(l.arena, v.name);
return v;
}
fn resourceList(l: *Lowerer, rs: []const authority.Resource) Error![]const u8 {
var out: std.ArrayList(u8) = .empty;
for (rs, 0..) |r, i| try out.appendSlice(l.arena, try l.fmt("{s}{s}", .{ if (i == 0) "" else " or ", r.text() }));
return out.items;
}
fn expectCap(l: *Lowerer, a: ast.Expr, kind: []const u8) Error!Value {
const c = try l.expr(a, null);
if (c.ty != .cap) return l.fail("E7005", a.span, "a capability is expected here", &.{ .{ .name = "expected", .value = try l.fmt("cap<{s}>", .{kind}) }, .{ .name = "found", .value = try l.diagnosticTyText(c.ty) } });
return c;
}
/// The region borrow of `region.new`/`region.array` must be an explicit
/// borrow binding, so that it outlives the allocation borrows derived
/// from it (spec 15 §8).
fn regionBorrow(l: *Lowerer, a: ast.Expr) Error!Value {
if (a.kind == .name) if (l.lookup(a.kind.name)) |b| {
if (b.kind == .borrow and (b.ty == .ref or b.ty == .mut) and b.ty.inner().? == .region) return .{ .name = b.value, .ty = b.ty };
if (b.ty == .region) return l.fail("E7005", a.span, "allocation in a region takes a borrow of it that outlives the allocations: bind `ref arena = region;` in an enclosing block and pass `arena`", &.{.{ .name = "name", .value = a.kind.name }});
};
return l.fail("E7005", a.span, "allocation in a region takes a `ref<region>` borrow binding", &.{});
}
fn lowerFallible(l: *Lowerer, e: ast.Expr) Error!Fallible {
if (e.kind != .call) return l.invalid(.invalid_match, e.span, "outcome arms (`ok`, `err`, …) belong to a fallible operation", &.{});
const path = pathOf(e.kind.call.callee.*) orelse return l.invalid(.invalid_match, e.span, "outcome arms (`ok`, `err`, …) belong to a fallible operation", &.{});
const args = e.kind.call.args;
const want = struct {
fn n(lw: *Lowerer, sp: Span, as: []const ast.Expr, k: usize, op: []const u8) Error!void {
if (as.len != k) return lw.fail("E7005", sp, "wrong number of operands", &.{ .{ .name = "operation", .value = op }, .{ .name = "expected", .value = try lw.fmt("{d}", .{k}) } });
}
}.n;
const alloc_err: Ty = .{ .builtin = .alloc_error };
const usize_ty: Ty = .{ .int = "usize" };
if (std.mem.eql(u8, path, "buffer.new")) {
try want(l, e.span, args, 2, path);
const source_ty = e.kind.call.type_arg orelse return l.fail("E7005", e.span, "buffer.new needs an explicit content type", &.{});
const ty = try l.memberType(source_ty);
const n = try l.expr(args[0], usize_ty);
try l.checkOperandTy(args[0].span, n.ty, usize_ty);
const cap = try l.expectCap(args[1], "mem.alloc");
return .{ .text = try l.fmt("buffer.new {s} %{s}, %{s}", .{ try l.tyText(ty), n.name, cap.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{try l.wrap(.buffer, ty)} }, .{ .role = "err", .params = &.{alloc_err} } }) };
}
if (std.mem.eql(u8, path, "buffer.free")) {
try want(l, e.span, args, 1, path);
const v = try l.consuming(args[0], null);
if (v.ty != .buffer) return l.fail("E7005", e.span, "buffer.free consumes a buffer<T>", &.{});
return .{ .text = try l.fmt("buffer.free %{s}", .{v.name}), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{} }, .{ .role = "err", .params = &.{v.ty} } }) };
}
if (std.mem.eql(u8, path, "buffer.push") or std.mem.eql(u8, path, "buffer.pop") or std.mem.eql(u8, path, "buffer.reserve")) {
const is_push = std.mem.eql(u8, path, "buffer.push");
const is_pop = std.mem.eql(u8, path, "buffer.pop");
try want(l, e.span, args, if (is_push) 2 else if (is_pop) 1 else 3, path);
const b = try l.bufferBorrow(args[0], true);
const ty = b.ty.inner().?.buffer.*;
if (is_push) {
const v = try l.consuming(args[1], ty);
try l.checkOperandTy(args[1].span, v.ty, ty);
return .{ .text = try l.fmt("buffer.push %{s}, %{s}", .{ b.name, v.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{} }, .{ .role = "err", .params = &.{ty} } }) };
}
if (is_pop) return .{ .text = try l.fmt("buffer.pop %{s}", .{b.name}), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{ty} }, .{ .role = "err", .params = &.{} } }) };
const n = try l.expr(args[1], usize_ty);
try l.checkOperandTy(args[1].span, n.ty, usize_ty);
const cap = try l.expectCap(args[2], "mem.alloc");
return .{ .text = try l.fmt("buffer.reserve %{s}, %{s}, %{s}", .{ b.name, n.name, cap.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{} }, .{ .role = "err", .params = &.{alloc_err} } }) };
}
if (std.mem.eql(u8, path, "own.pack")) {
try want(l, e.span, args, 2, path);
const v = try l.contentValue(args[0]);
if (v.ty.isBorrow()) return l.contentPositionError(args[0].span, v.ty);
const c = try l.expectCap(args[1], "mem.alloc");
l.linear_enabled = true;
return .{ .text = try l.fmt("own.pack {s} %{s}, %{s}", .{ try l.tyText(v.ty), v.name, c.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{try l.wrap(.own, v.ty)} }, .{ .role = "err", .params = &.{ alloc_err, v.ty } } }) };
}
if (std.mem.eql(u8, path, "own.new")) {
try want(l, e.span, args, 2, path);
const v = try l.contentValue(args[0]);
try l.copyContent(args[0].span, v.ty, path);
const c = try l.expectCap(args[1], "mem.alloc");
return .{ .text = try l.fmt("own.new %{s}, %{s}", .{ v.name, c.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{try l.wrap(.own, v.ty)} }, .{ .role = "err", .params = &.{alloc_err} } }) };
}
if (std.mem.eql(u8, path, "own.array")) {
try want(l, e.span, args, 3, path);
const n = try l.expr(args[0], usize_ty);
try l.checkOperandTy(args[0].span, n.ty, usize_ty);
const v = try l.consuming(args[1], null);
if (!try verifier_types.isCopy(l.arena, l.property_module.?, try l.airType(v.ty))) return l.copyArrayError(args[1].span);
const c = try l.expectCap(args[2], "mem.alloc");
return .{ .text = try l.fmt("own.array %{s}, %{s}, %{s}", .{ n.name, v.name, c.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{try l.wrap(.own_array, v.ty)} }, .{ .role = "err", .params = &.{alloc_err} } }) };
}
if (std.mem.eql(u8, path, "region.create")) {
try want(l, e.span, args, 1, path);
const c = try l.expectCap(args[0], "mem.alloc");
return .{ .text = try l.fmt("region.create %{s}", .{c.name}), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{.region} }, .{ .role = "err", .params = &.{alloc_err} } }) };
}
if (std.mem.eql(u8, path, "region.new")) {
try want(l, e.span, args, 2, path);
const rb = try l.regionBorrow(args[0]);
const v = try l.contentValue(args[1]);
try l.copyContent(args[1].span, v.ty, path);
return .{ .borrow_parent = rb.name, .text = try l.fmt("region.new %{s}, %{s}", .{ rb.name, v.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{try l.wrap(.mut, v.ty)} }, .{ .role = "err", .params = &.{alloc_err} } }) };
}
if (std.mem.eql(u8, path, "region.array")) {
try want(l, e.span, args, 3, path);
const rb = try l.regionBorrow(args[0]);
const n = try l.expr(args[1], usize_ty);
try l.checkOperandTy(args[1].span, n.ty, usize_ty);
const v = try l.contentValue(args[2]);
try l.copyContent(args[2].span, v.ty, path);
return .{ .borrow_parent = rb.name, .text = try l.fmt("region.array %{s}, %{s}, %{s}", .{ rb.name, n.name, v.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{try l.wrap(.slice_mut, v.ty)} }, .{ .role = "err", .params = &.{alloc_err} } }) };
}
if (authority.intrinsicIndex(path)) |ix| {
const x = authority.intrinsics[ix];
if (!x.fallible) return l.invalid(.invalid_operation, e.span, "this intrinsic cannot fail: call it plainly", &.{.{ .name = "operation", .value = x.name }});
var temps: std.ArrayList([]const u8) = .empty;
const ops = try l.intrinsicOperands(e, x, args, &temps);
l.uses.insert(.capabilities);
const ok = try l.arena.alloc(Ty, x.results.len);
for (x.results, ok) |r, *t| t.* = resultTy(r);
return .{
.text = try l.fmt("intrinsic {s}({s})", .{ x.name, ops }),
.outcomes = try l.outs(&.{ .{ .role = "ok", .params = ok }, .{ .role = "err", .params = &.{.{ .builtin = .io_error }} } }),
.temps = temps.items,
};
}
if (std.mem.eql(u8, path, "island.create") or std.mem.eql(u8, path, "arc.new")) {
try want(l, e.span, args, 2, path);
const v = try l.contentValue(args[0]);
const c = try l.expectCap(args[1], "mem.alloc");
const owner = if (std.mem.eql(u8, path, "arc.new")) try l.wrap(.arc, v.ty) else try l.wrap(.island, v.ty);
return .{ .text = try l.fmt("{s} %{s}, %{s}", .{ path, v.name, c.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{owner} }, .{ .role = "err", .params = &.{alloc_err} } }) };
}
if (std.mem.eql(u8, path, "island.alloc")) {
try want(l, e.span, args, 2, path);
const g = try l.graphBorrow(args[0], "island", true);
const v = try l.contentValue(args[1]);
return .{ .text = try l.fmt("island.alloc %{s}, %{s}", .{ g.name, v.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{try l.wrap(.iref, v.ty)} }, .{ .role = "err", .params = &.{alloc_err} } }) };
}
if (std.mem.eql(u8, path, "task.check_cancel")) {
try want(l, e.span, args, 0, path);
return .{ .text = "task.check_cancel", .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{} }, .{ .role = "cancelled", .params = &.{} } }) };
}
if (std.mem.eql(u8, path, "task.join_cancel")) {
try want(l, e.span, args, 1, path);
const t = try l.consuming(args[0], null);
if (t.ty != .task) return l.fail("E7005", args[0].span, "`task.join_cancel` takes a `task<T>`", &.{.{ .name = "found", .value = try l.diagnosticTyText(t.ty) }});
const rt = t.ty.task.*;
const ok: []const Ty = if (rt == .void) &.{} else &.{rt};
return .{ .text = try l.fmt("task.join.cancel %{s}", .{t.name}), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = ok }, .{ .role = "cancelled", .params = &.{t.ty} } }) };
}
if (std.mem.eql(u8, path, "channel.make")) {
try want(l, e.span, args, 2, path);
const ta = e.kind.call.type_arg orelse return l.fail("E7005", e.span, "`channel.make` names its element type: `channel.make<T>(n, mem)`", &.{});
const et = try l.memberType(ta);
try l.elementRule(et, ta.span, "a channel element");
const n = try l.expr(args[0], usize_ty);
try l.checkOperandTy(args[0].span, n.ty, usize_ty);
const c = try l.expectCap(args[1], "mem.alloc");
return .{ .text = try l.fmt("channel.make {s}, %{s}, %{s}", .{ try l.tyText(et), n.name, c.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{ try l.wrap(.sender, et), try l.wrap(.receiver, et) } }, .{ .role = "err", .params = &.{alloc_err} } }) };
}
if (std.mem.eql(u8, path, "channel.send")) {
try want(l, e.span, args, 2, path);
var temps: std.ArrayList([]const u8) = .empty;
const tx = try l.endpointOperand(args[0], .sender, true, &temps);
const et = tx.ty.inner().?.sender.*;
const v = try l.consuming(args[1], et);
try l.checkOperandTy(args[1].span, v.ty, et);
return .{ .text = try l.fmt("channel.send %{s}, %{s}", .{ tx.name, v.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{} }, .{ .role = "closed", .params = &.{et} }, .{ .role = "cancelled", .params = &.{et} } }), .temps = temps.items };
}
if (std.mem.eql(u8, path, "channel.recv")) {
try want(l, e.span, args, 1, path);
var temps: std.ArrayList([]const u8) = .empty;
const rx = try l.endpointOperand(args[0], .receiver, true, &temps);
const et = rx.ty.inner().?.receiver.*;
return .{ .text = try l.fmt("channel.recv %{s}", .{rx.name}), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{et} }, .{ .role = "closed", .params = &.{} }, .{ .role = "cancelled", .params = &.{} } }), .temps = temps.items };
}
if (std.mem.eql(u8, path, "channel.close_receiver")) {
try want(l, e.span, args, 1, path);
const rx = try l.consuming(args[0], null);
if (rx.ty != .receiver) return l.fail("E7005", args[0].span, "`channel.close_receiver` takes a `receiver<T>`", &.{.{ .name = "found", .value = try l.diagnosticTyText(rx.ty) }});
return .{ .text = try l.fmt("channel.close_receiver %{s}", .{rx.name}), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{} }, .{ .role = "pending", .params = &.{rx.ty} } }) };
}
if (std.mem.eql(u8, path, "cap.narrow.prefix")) {
try want(l, e.span, args, 2, path);
const c = try l.expr(args[0], null);
if (c.ty != .cap) return l.fail("E7005", args[0].span, "a capability is expected here", &.{.{ .name = "found", .value = try l.diagnosticTyText(c.ty) }});
var temps: std.ArrayList([]const u8) = .empty;
const bytes = try l.wrap(.slice, .{ .int = "u8" });
const p = try l.argument(args[1], bytes, &temps);
if (!p.ty.eql(bytes)) return l.fail("E7005", args[1].span, "the path is a byte string or a `ref` borrow of bytes", &.{.{ .name = "found", .value = try l.diagnosticTyText(p.ty) }});
return .{ .text = try l.fmt("cap.narrow.prefix %{s}, %{s}", .{ c.name, p.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{c.ty} }, .{ .role = "err", .params = &.{.{ .builtin = .cap_error }} } }), .temps = temps.items };
}
if (std.mem.eql(u8, path, "cap.narrow.budget")) {
try want(l, e.span, args, 2, path);
const c = try l.expr(args[0], null);
if (c.ty != .cap) return l.fail("E7005", args[0].span, "a capability is expected here", &.{.{ .name = "found", .value = try l.diagnosticTyText(c.ty) }});
const n = try l.expr(args[1], usize_ty);
try l.checkOperandTy(args[1].span, n.ty, usize_ty);
return .{ .text = try l.fmt("cap.narrow.budget %{s}, %{s}", .{ c.name, n.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{c.ty} }, .{ .role = "err", .params = &.{.{ .builtin = .cap_error }} } }) };
}
return l.invalid(.invalid_operation, e.span, "not a fallible operation", &.{.{ .name = "operation", .value = path }});
}
fn outs(l: *Lowerer, o: []const Outcome) Error![]const Outcome {
const out = try l.arena.alloc(Outcome, o.len);
for (o, out) |x, *y| y.* = .{ .role = x.role, .params = try l.arena.dupe(Ty, x.params) };
return out;
}
/// Creates one block per outcome (parameters = the outcome's values)
/// and emits the terminator `<op>, ok -> @a, err -> @b`.
fn outcomeBlocks(l: *Lowerer, f: Fallible, span: Span) Error![]const usize {
const blocks = try l.arena.alloc(usize, f.outcomes.len);
var text: std.ArrayList(u8) = .empty;
try text.appendSlice(l.arena, f.text);
for (f.outcomes, blocks) |o, *b| {
b.* = try l.newBlock(o.role, span);
for (o.params) |pt| {
const name = try l.freshName(o.role);
try l.blocks.items[b.*].params.append(l.arena, .{ .name = name, .ty = pt });
if (pt.isBorrow()) if (f.borrow_parent) |parent| try l.borrow_parents.put(l.arena, name, parent);
}
try text.appendSlice(l.arena, try l.fmt(", {s} -> @{s}", .{ o.role, l.blocks.items[b.*].name }));
}
try l.term(text.items, span);
// The operation's temporary borrows end on every edge.
for (blocks) |b| {
l.cur = b;
try l.endNow(f.temps, span);
}
return blocks;
}
/// `match op(…) { ok(x) => …, err(e) => … }`: the arms are the edges of
/// the operation's terminator; every outcome exactly once (spec 15 §6).
fn outcomeMatch(l: *Lowerer, m: ast.Match, want: ?Ty) Error!Value {
const f = try l.lowerFallible(m.scrutinee);
for (m.arms, 0..) |arm, i| {
if (arm.pattern.kind != .ctor or arm.pattern.kind.ctor.qualifier != null)
return l.invalid(.invalid_match, arm.pattern.span, "every arm of an outcome match names an outcome of the operation (`ok(…)`, `err(e)`, …)", &.{});
const c = arm.pattern.kind.ctor;
const o = for (f.outcomes) |o| {
if (std.mem.eql(u8, o.role, c.name)) break o;
} else return l.fail("E7002", arm.pattern.span, "this operation has no such outcome", &.{.{ .name = "outcome", .value = c.name }});
for (m.arms[0..i]) |prev| if (std.mem.eql(u8, prev.pattern.kind.ctor.name, c.name)) return l.invalid(.invalid_match, arm.pattern.span, "outcome matched twice", &.{.{ .name = "outcome", .value = c.name }});
if (c.binds.len != o.params.len) return l.fail("E7005", arm.pattern.span, "the outcome binds a different number of values", &.{ .{ .name = "outcome", .value = c.name }, .{ .name = "expected", .value = try l.fmt("{d}", .{o.params.len}) } });
}
var missing: std.ArrayList(u8) = .empty;
for (f.outcomes) |o| {
const covered = for (m.arms) |arm| {
if (std.mem.eql(u8, arm.pattern.kind.ctor.name, o.role)) break true;
} else false;
if (!covered) try missing.appendSlice(l.arena, try l.fmt("{s}{s}", .{ if (missing.items.len == 0) "" else ", ", o.role }));
}
if (missing.items.len != 0) return l.fail("E7004", m.span, "the match does not handle every outcome of the operation", &.{.{ .name = "missing", .value = missing.items }});
const depth = l.bindings.items.len;
const vars = try l.carriedLive(depth, m.span, .{ .match = m });
const before = try l.snapshot();
const blocks = try l.outcomeBlocks(f, m.scrutinee.span);
var ends: std.ArrayList(ArmEnd) = .empty;
for (f.outcomes, blocks) |o, blk| {
const arm = for (m.arms) |a| {
if (std.mem.eql(u8, a.pattern.kind.ctor.name, o.role)) break a;
} else unreachable;
l.restore(before);
l.cur = blk;
// The outcome's values are bound in the arm; a borrow among them
// (a region allocation) ends with the arm.
try l.scopes.append(l.arena, .empty);
for (arm.pattern.kind.ctor.binds, l.blocks.items[blk].params.items) |bn, prm| {
if (prm.ty.isBorrow()) try l.scopeEnds(&.{prm.name}, arm.pattern.span);
if (std.mem.eql(u8, bn, "_")) continue;
// Rebinding (spec 15 §6): a value that comes back on an edge
// under the name of a variable of its type is that variable's
// new value (`pending(rx)`, `closed(v)`).
if (l.lookup(bn)) |old| if (old.mutable and old.kind == .ssa and old.ty.eql(prm.ty)) {
old.value = prm.name;
continue;
};
try l.bindings.append(l.arena, .{ .name = bn, .mutable = false, .value = prm.name, .ty = prm.ty, .kind = if (prm.ty.isBorrow()) .borrow else .ssa });
}
const v = try l.armBody(arm.body, want);
if (l.cur != null) try l.endScopes(l.scopes.items.len - 1, arm.body.span);
_ = l.scopes.pop();
l.bindings.shrinkRetainingCapacity(before.len);
try ends.append(l.arena, .{ .block = l.cur, .value = v, .values = try l.snapshot(), .span = arm.body.span });
}
return l.mergeArms(m.span, "match", ends.items, vars, before, "endmatch");
}
/// `op(…) or trap`: the `ok` value; every other outcome traps.
fn orTrap(l: *Lowerer, e: ast.Expr, inner_e: ast.Expr) Error!Value {
const f = try l.lowerFallible(inner_e);
const blocks = try l.outcomeBlocks(f, e.span);
for (f.outcomes, blocks) |o, blk| if (!std.mem.eql(u8, o.role, "ok")) {
l.cur = blk;
try l.term("trap", e.span);
};
const ok = for (f.outcomes, blocks) |o, blk| {
if (std.mem.eql(u8, o.role, "ok")) break blk;
} else unreachable;
l.cur = ok;
const ps = l.blocks.items[ok].params.items;
if (ps.len == 0) return .{ .name = "", .ty = .void };
if (ps.len != 1) return l.invalid(.invalid_operation, e.span, "`or trap` on an operation with several results: use `match`", &.{});
return .{ .name = ps[0].name, .ty = ps[0].ty };
}
fn ifExpr(l: *Lowerer, span: Span, x: ast.If, want: ?Ty) Error!Value {
// `if i < s.len`: the verifier proves `i < len(s)` in the true branch
// (spec 08 §12); record it so that `s[i]` there needs no runtime check.
var fact: ?Fact = null;
const cv = blk: {
const c = x.cond;
if (c.kind == .binary and c.kind.binary.op == .lt and c.kind.binary.r.kind == .field and std.mem.eql(u8, c.kind.binary.r.kind.field.name, "len")) {
const st = l.peekType(c.kind.binary.r.kind.field.e.*);
if (st != null and (st.? == .slice or st.? == .slice_mut)) {
const iv = try l.expr(c.kind.binary.l.*, .{ .int = "usize" });
try l.checkOperandTy(c.kind.binary.l.span, iv.ty, .{ .int = "usize" });
const sv = try l.expr(c.kind.binary.r.kind.field.e.*, st.?);
const n = try l.def("len", .{ .int = "usize" }, try l.fmt("slice.len %{s}", .{sv.name}), c.kind.binary.r.span);
fact = .{ .index = iv.name, .slice = sv.name };
break :blk try l.def("cmp", .bool, try l.fmt("lt.usize %{s}, %{s}", .{ iv.name, n.name }), c.span);
}
}
break :blk try l.expr(c, .bool);
};
try l.checkOperandTy(x.cond.span, cv.ty, .bool);
const depth = l.bindings.items.len;
const vars = try l.carriedLive(depth, span, .{ .@"if" = x });
const then_b = try l.newBlock("then", x.then.span);
const else_b = try l.newBlock("else", span);
try l.term(try l.fmt("cbr %{s}, @{s}(), @{s}()", .{ cv.name, l.blocks.items[then_b].name, l.blocks.items[else_b].name }), x.cond.span);
const before = try l.snapshot();
var ends: [2]ArmEnd = undefined;
for (0..2) |k| {
l.restore(before);
l.cur = if (k == 0) then_b else else_b;
var v: ?Value = null;
var arm_span = x.then.span;
if (k == 0) {
if (fact) |f| try l.facts.append(l.arena, f);
v = try l.blockBodyWant(x.then, want);
if (fact != null) _ = l.facts.pop();
} else if (x.@"else") |els| switch (els) {
.block => |b| {
arm_span = b.span;
v = try l.blockBodyWant(b, want);
},
.@"if" => |inner| {
arm_span = span;
v = try l.ifExpr(span, inner.*, want);
},
} else arm_span = span;
if (v != null and v.?.ty == .void) v = null;
ends[k] = .{ .block = l.cur, .value = v, .values = try l.snapshot(), .span = arm_span };
}
return l.mergeArms(span, "if", &ends, vars, before, "endif");
}
};
fn sameDeclaration(a: Span, b: Span) bool {
return a.start.line == b.start.line and a.start.col == b.start.col and
std.mem.eql(u8, a.file orelse "", b.file orelse "") and
std.mem.eql(u8, a.namespace orelse "", b.namespace orelse "");
}
fn elemOf(t: Ty) ?Ty {
return switch (t) {
.array => |a| a.elem,
.slice, .slice_mut => |x| x.*,
.ref, .mut => |x| if (x.* == .array) x.array.elem else null,
else => null,
};
}
/// The built-in operation named by a callee such as `own.new` or
/// `cap.narrow.budget`; null for anything else.
fn pathOf(e: ast.Expr) ?[]const u8 {
const known = [_][]const u8{
"buffer.new", "buffer.len", "buffer.capacity", "buffer.reserve", "buffer.push", "buffer.pop", "buffer.view", "buffer.free",
"struct.unpack", "array.unpack", "value.swap", "own.pack", "slice.copy", "own.new", "own.array", "own.take",
"own.free", "region.create", "region.new", "region.array", "region.reset", "region.destroy", "cap.narrow.budget", "cap.narrow.prefix",
"task.spawn", "task.join", "task.cancel", "task.cancelled", "channel.make", "channel.dup", "channel.send", "channel.recv",
"channel.close_sender", "channel.close_receiver", "mutex.make", "mutex.take", "task.check_cancel", "task.join_cancel", "island.create", "island.alloc",
"island.root", "island.at", "island.freeze", "island.destroy", "frozen.root", "frozen.at", "frozen.release", "arc.from_frozen",
"arc.new", "arc.clone", "arc.release", "arc.root", "arc.at", "atomic.new", "atomic.take", "atomic.load",
"atomic.store", "atomic.swap", "atomic.add.wrap", "atomic.sub.wrap", "atomic.and", "atomic.or", "atomic.xor", "atomic.compare_exchange",
"atomic.fence",
};
var buf: [64]u8 = undefined;
const text = dotted(e, &buf) orelse return null;
for (known) |k| if (std.mem.eql(u8, k, text)) return k;
if (authority.intrinsicIndex(text)) |i| return authority.intrinsics[i].name;
return null;
}
fn dotted(e: ast.Expr, buf: []u8) ?[]const u8 {
switch (e.kind) {
.name => |n| {
if (n.len > buf.len) return null;
@memcpy(buf[0..n.len], n);
return buf[0..n.len];
},
.field => |f| {
const base = dotted(f.e.*, buf) orelse return null;
const len = base.len + 1 + f.name.len;
if (len > buf.len) return null;
buf[base.len] = '.';
@memcpy(buf[base.len + 1 .. len], f.name);
return buf[0..len];
},
else => return null,
}
}
fn standardPath(e: ast.Expr) bool {
if (e.kind != .field) return false;
var root = e;
while (root.kind == .field) root = root.kind.field.e.*;
return root.kind == .name and std.mem.eql(u8, root.kind.name, "std");
}
fn box(arena: Allocator, e: ast.Expr) Error!*const ast.Expr {
const b = try arena.create(ast.Expr);
b.* = e;
return b;
}
// ---------------------------------------------------------------- liveness (pruned joins)
fn spanEq(a: Span, b: Span) bool {
return a.start.line == b.start.line and a.start.col == b.start.col and a.end.line == b.end.line and a.end.col == b.end.col;
}
const Use = enum { read, kill, none };
/// The first use of `name` in statements executed in order: a read, a
/// whole-variable assignment that does not read it (`name = e;`), or none.
fn firstUse(stmts: []const ast.Stmt, tail: ?*const ast.Expr, name: []const u8) Use {
for (stmts) |st| {
if (st.kind == .assign and st.kind.assign.place.kind == .name and std.mem.eql(u8, st.kind.assign.place.kind.name, name)) {
if (exprReads(st.kind.assign.e, name, null)) return .read;
return .kill;
}
if (stmtReads(st, name, null)) return .read;
}
if (tail) |t| if (exprReads(t.*, name, null)) return .read;
return .none;
}
fn loopReads(lp: LoopAst, name: []const u8) bool {
if (lp.step) |st| if (std.mem.eql(u8, st, name)) return true;
if (lp.cond) |c| if (exprReads(c, name, null)) return true;
return blockReads(lp.body, name, null);
}
fn blockReads(b: ast.Block, name: []const u8, skip: ?Span) bool {
for (b.stmts) |st| if (stmtReads(st, name, skip)) return true;
if (b.tail) |t| if (exprReads(t.*, name, skip)) return true;
return false;
}
/// Whether the statement mentions `name` other than as the target of a
/// whole-variable assignment. `skip`: a construct whose own reads happen
/// before the join being decided.
fn stmtReads(st: ast.Stmt, name: []const u8, skip: ?Span) bool {
return switch (st.kind) {
.let => |x| exprReads(x.e, name, skip),
.@"var" => |x| if (x.init) |e| exprReads(e, name, skip) else false,
.assign => |x| exprReads(x.e, name, skip) or (x.place.kind != .name and exprReads(x.place, name, skip)),
.borrow => |x| exprReads(x.place, name, skip),
.@"return" => |e| if (e) |x| exprReads(x, name, skip) else false,
.expr => |e| exprReads(e, name, skip),
.@"while" => |x| exprReads(x.cond, name, skip) or blockReads(x.body, name, skip),
.@"for" => |x| exprReads(x.lo, name, skip) or exprReads(x.hi, name, skip) or blockReads(x.body, name, skip),
.loop, .shield => |b| blockReads(b, name, skip),
.scope => |x| blockReads(x.body, name, skip),
.lock => |x| exprReads(x.place, name, skip) or blockReads(x.body, name, skip) or blockReads(x.cancelled, name, skip),
.select => |x| selectReads(x, name, skip),
.@"break", .@"continue", .trap => false,
};
}
fn exprReads(e: ast.Expr, name: []const u8, skip: ?Span) bool {
if (skip) |sk| if (spanEq(e.span, sk)) return false;
return switch (e.kind) {
.name => |n| std.mem.eql(u8, n, name),
.move => |n| std.mem.eql(u8, n, name),
.int, .boolean, .bytes, .variant, .specialize => false,
.neg, .not, .deref, .or_trap => |x| exprReads(x.*, name, skip),
.borrow => |x| exprReads(x.place.*, name, skip),
.binary => |x| exprReads(x.l.*, name, skip) or exprReads(x.r.*, name, skip),
.cast => |x| exprReads(x.e.*, name, skip),
.call => |x| blk: {
if (exprReads(x.callee.*, name, skip)) break :blk true;
for (x.args) |a| if (exprReads(a, name, skip)) break :blk true;
break :blk false;
},
.field => |x| exprReads(x.e.*, name, skip),
.index => |x| exprReads(x.e.*, name, skip) or exprReads(x.lo.*, name, skip) or (if (x.hi) |h| exprReads(h.*, name, skip) else false),
.struct_lit => |x| blk: {
for (x.fields) |f| if (exprReads(f.e, name, skip)) break :blk true;
break :blk false;
},
.array_rep => |x| exprReads(x.e.*, name, skip),
.array_list => |xs| for (xs) |x| {
if (exprReads(x, name, skip)) break true;
} else false,
.if_expr => |x| ifReads(x.*, name, skip),
.match_expr => |x| blk: {
if (exprReads(x.scrutinee, name, skip)) break :blk true;
for (x.arms) |a| if (exprReads(a.body, name, skip)) break :blk true;
break :blk false;
},
.block => |b| blockReads(b.*, name, skip),
};
}
fn selectReads(x: ast.Select, name: []const u8, skip: ?Span) bool {
for (x.arms) |a| {
if (std.mem.eql(u8, a.endpoint, name)) return true;
if (a.value) |v| if (exprReads(v, name, skip)) return true;
for (a.arms) |arm| if (exprReads(arm.body, name, skip)) return true;
}
return exprReads(x.cancelled, name, skip);
}
fn ifReads(x: ast.If, name: []const u8, skip: ?Span) bool {
if (exprReads(x.cond, name, skip) or blockReads(x.then, name, skip)) return true;
if (x.@"else") |els| return switch (els) {
.block => |b| blockReads(b, name, skip),
.@"if" => |inner| ifReads(inner.*, name, skip),
};
return false;
}
/// Reads of `name` after `construct`, in evaluation order, within the
/// statement or expression that contains it. Once the construct is found in
/// one arm of an `if` or `match`, the other arms are not "after" it; once it
/// is found in a loop, the whole loop is (the back edge).
const After = struct {
name: []const u8,
construct: Span,
seen: bool = false,
fn expr(w: *After, e: ast.Expr) bool {
if (!w.seen and spanEq(e.span, w.construct)) {
w.seen = true;
return false;
}
return switch (e.kind) {
.name, .move => |n| w.seen and std.mem.eql(u8, n, w.name),
.int, .boolean, .bytes, .variant, .specialize => false,
.neg, .not, .deref, .or_trap => |x| w.expr(x.*),
.borrow => |x| w.expr(x.place.*),
.binary => |x| w.expr(x.l.*) or w.expr(x.r.*),
.cast => |x| w.expr(x.e.*),
.call => |x| blk: {
if (w.expr(x.callee.*)) break :blk true;
for (x.args) |a| if (w.expr(a)) break :blk true;
break :blk false;
},
.field => |x| w.expr(x.e.*),
.index => |x| w.expr(x.e.*) or w.expr(x.lo.*) or (if (x.hi) |h| w.expr(h.*) else false),
.struct_lit => |x| blk: {
for (x.fields) |f| if (w.expr(f.e)) break :blk true;
break :blk false;
},
.array_rep => |x| w.expr(x.e.*),
.array_list => |xs| for (xs) |x| {
if (w.expr(x)) break true;
} else false,
.if_expr => |x| w.ifExpr(x.*),
.match_expr => |x| blk: {
if (w.expr(x.scrutinee)) break :blk true;
if (w.seen) {
for (x.arms) |a| if (w.expr(a.body)) break :blk true;
break :blk false;
}
for (x.arms) |a| {
const r = w.expr(a.body);
if (w.seen) break :blk r; // found in this arm: siblings are not after it
}
break :blk false;
},
.block => |b| w.block(b.*),
};
}
fn select(w: *After, x: ast.Select) bool {
for (x.arms) |a| {
if (w.seen and std.mem.eql(u8, a.endpoint, w.name)) return true;
if (a.value) |v| if (w.expr(v)) return true;
}
var bodies: std.ArrayList(ast.Expr) = .empty;
defer bodies.deinit(std.heap.page_allocator);
for (x.arms) |a| for (a.arms) |arm| bodies.append(std.heap.page_allocator, arm.body) catch return true;
bodies.append(std.heap.page_allocator, x.cancelled) catch return true;
if (w.seen) {
for (bodies.items) |b| if (w.expr(b)) return true;
return false;
}
for (bodies.items) |b| {
const r = w.expr(b);
if (w.seen) return r;
}
return false;
}
fn ifExpr(w: *After, x: ast.If) bool {
if (w.expr(x.cond)) return true;
if (w.seen) return w.block(x.then) or (if (x.@"else") |els| w.elseBranch(els) else false);
const r = w.block(x.then);
if (w.seen) return r;
if (x.@"else") |els| return w.elseBranch(els);
return false;
}
fn elseBranch(w: *After, els: ast.Else) bool {
return switch (els) {
.block => |b| w.block(b),
.@"if" => |inner| w.ifExpr(inner.*),
};
}
fn block(w: *After, b: ast.Block) bool {
for (b.stmts) |st| if (w.stmt(st)) return true;
if (b.tail) |t| if (w.expr(t.*)) return true;
return false;
}
fn loopBody(w: *After, cond: ?ast.Expr, body: ast.Block, step: ?[]const u8) bool {
const was = w.seen;
if (cond) |c| if (w.expr(c)) return true;
const r = w.block(body);
if (r) return true;
// Found inside this loop: everything in it can run again.
if (!was and w.seen) return loopReads(.{ .cond = cond, .body = body, .step = step }, w.name);
return false;
}
fn stmt(w: *After, st: ast.Stmt) bool {
if (!w.seen and spanEq(st.span, w.construct)) {
w.seen = true;
return false;
}
return switch (st.kind) {
.let => |x| w.expr(x.e),
.@"var" => |x| if (x.init) |e| w.expr(e) else false,
.assign => |x| w.expr(x.e) or (x.place.kind != .name and w.expr(x.place)),
.borrow => |x| w.expr(x.place),
.@"return" => |e| if (e) |x| w.expr(x) else false,
.expr => |e| w.expr(e),
.@"while" => |x| w.loopBody(x.cond, x.body, null),
.@"for" => |x| w.expr(x.lo) or w.expr(x.hi) or w.loopBody(null, x.body, x.name),
.loop => |b| w.loopBody(null, b, null),
.shield => |b| w.block(b),
.scope => |x| w.block(x.body),
.lock => |x| w.expr(x.place) or w.block(x.body) or w.block(x.cancelled),
.select => |x| w.select(x),
.@"break", .@"continue", .trap => false,
};
}
};
/// The code of a branching construct, for deciding which variables it
/// assigns: a join carries only variables that may change inside.
const Region = union(enum) {
loop: LoopAst,
@"if": ast.If,
match: ast.Match,
lock: struct { ast.Block, ast.Block },
select: ast.Select,
fn assigns(r: Region, name: []const u8) bool {
return switch (r) {
.loop => |lp| (if (lp.step) |st| std.mem.eql(u8, st, name) else false) or (if (lp.cond) |c| exprAssigns(c, name) else false) or blockAssigns(lp.body, name),
.@"if" => |x| ifAssigns(x, name),
.match => |m| matchAssigns(m, name),
.lock => |b| blockAssigns(b[0], name) or blockAssigns(b[1], name),
.select => |x| selectAssigns(x, name),
};
}
};
/// Whether code assigns variable `name`: `name = e;`, or a pattern of an
/// outcome or `select` edge rebinding it (spec 15 §6).
fn blockAssigns(b: ast.Block, name: []const u8) bool {
for (b.stmts) |st| if (stmtAssigns(st, name)) return true;
if (b.tail) |t| if (exprAssigns(t.*, name)) return true;
return false;
}
fn stmtAssigns(st: ast.Stmt, name: []const u8) bool {
return switch (st.kind) {
.assign => |x| (x.place.kind == .name and std.mem.eql(u8, x.place.kind.name, name)) or exprAssigns(x.e, name),
.let => |x| exprAssigns(x.e, name),
.@"var" => |x| if (x.init) |e| exprAssigns(e, name) else false,
.borrow => |x| exprAssigns(x.place, name),
.@"return" => |e| if (e) |x| exprAssigns(x, name) else false,
.expr => |e| exprAssigns(e, name),
.@"while" => |x| exprAssigns(x.cond, name) or blockAssigns(x.body, name),
.@"for" => |x| std.mem.eql(u8, x.name, name) or blockAssigns(x.body, name),
.loop, .shield => |b| blockAssigns(b, name),
.scope => |x| blockAssigns(x.body, name),
.lock => |x| blockAssigns(x.body, name) or blockAssigns(x.cancelled, name),
.select => |x| selectAssigns(x, name),
.@"break", .@"continue", .trap => false,
};
}
fn exprAssigns(e: ast.Expr, name: []const u8) bool {
return switch (e.kind) {
.if_expr => |x| ifAssigns(x.*, name),
.match_expr => |x| matchAssigns(x.*, name),
.block => |b| blockAssigns(b.*, name),
.neg, .not, .deref, .or_trap => |x| exprAssigns(x.*, name),
.binary => |x| exprAssigns(x.l.*, name) or exprAssigns(x.r.*, name),
.cast => |x| exprAssigns(x.e.*, name),
.call => |x| blk: {
for (x.args) |a| if (exprAssigns(a, name)) break :blk true;
break :blk false;
},
.struct_lit => |x| blk: {
for (x.fields) |f| if (exprAssigns(f.e, name)) break :blk true;
break :blk false;
},
.field => |x| exprAssigns(x.e.*, name),
.index => |x| exprAssigns(x.e.*, name) or exprAssigns(x.lo.*, name) or (if (x.hi) |h| exprAssigns(h.*, name) else false),
.array_rep => |x| exprAssigns(x.e.*, name),
.array_list => |xs| for (xs) |x| {
if (exprAssigns(x, name)) break true;
} else false,
else => false,
};
}
fn ifAssigns(x: ast.If, name: []const u8) bool {
if (exprAssigns(x.cond, name) or blockAssigns(x.then, name)) return true;
if (x.@"else") |els| return switch (els) {
.block => |b| blockAssigns(b, name),
.@"if" => |inner| ifAssigns(inner.*, name),
};
return false;
}
fn matchAssigns(m: ast.Match, name: []const u8) bool {
if (exprAssigns(m.scrutinee, name)) return true;
for (m.arms) |a| {
if (a.pattern.kind == .ctor) for (a.pattern.kind.ctor.binds) |b| if (std.mem.eql(u8, b, name)) return true;
if (exprAssigns(a.body, name)) return true;
}
return false;
}
fn selectAssigns(x: ast.Select, name: []const u8) bool {
for (x.arms) |a| for (a.arms) |arm| {
if (arm.pattern.kind == .ctor) for (arm.pattern.kind.ctor.binds) |b| if (std.mem.eql(u8, b, name)) return true;
if (exprAssigns(arm.body, name)) return true;
};
for (x.cancelled_binds) |b| if (std.mem.eql(u8, b, name)) return true;
return exprAssigns(x.cancelled, name);
}
fn localName(full: []const u8, module: []const u8, short: []const u8) bool {
return full.len == module.len + 1 + short.len and std.mem.startsWith(u8, full, module) and full[module.len] == '.' and std.mem.eql(u8, full[module.len + 1 ..], short);
}
fn expressionPath(arena: Allocator, e: ast.Expr) Allocator.Error!?[]const u8 {
return switch (e.kind) {
.name => |name| name,
.field => |field| if (try expressionPath(arena, field.e.*)) |base| try std.fmt.allocPrint(arena, "{s}.{s}", .{ base, field.name }) else null,
else => null,
};
}
test "terminated blocks reject further emission with a source diagnostic" {
var scratch = std.heap.ArenaAllocator.init(std.testing.allocator);
defer scratch.deinit();
var l: Lowerer = .{ .arena = scratch.allocator(), .m = .{ .name = "test", .types = &.{}, .functions = &.{} } };
const span: Span = .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 2 } };
l.cur = try l.newBlock("entry", span);
try l.term("trap", span);
try std.testing.expectError(error.Lower, l.emit("ret", span));
try std.testing.expectEqualStrings("E7006", l.problem.?.code);
try std.testing.expectEqual(InvalidReason.@"unreachable", l.problem.?.reason.?);
try std.testing.expectEqual(span, l.problem.?.span);
try std.testing.expectEqual(@as(usize, 1), l.blocks.items[0].insts.items.len);
try std.testing.expect(l.blocks.items[0].terminated);
}
// Independent pre-repair unary expression derivation. Non-unary leaves use
// the unchanged expression handlers; this oracle is only for shallow chains.
const ReferenceUnary = struct {
fn expr(l: *Lowerer, e: ast.Expr, want: ?Ty) Error!Value {
switch (e.kind) {
.not => |x| {
const v = try expr(l, x.*, .bool);
try l.checkOperandTy(x.span, v.ty, .bool);
const t = try l.def("c", .bool, "const.bool true", e.span);
return l.def("not", .bool, try l.fmt("xor.bool %{s}, %{s}", .{ v.name, t.name }), e.span);
},
.neg => |x| {
const ty = want orelse l.peekType(x.*) orelse return l.fail("E7007", e.span, "the type of this negation cannot be determined", &.{});
if (ty != .int) return l.fail("E7005", e.span, "negation of a non-integer", &.{});
if (x.kind == .int) {
const v = parse_mod.parseIntText(x.kind.int.text) orelse return l.fail("E7001", e.span, "malformed integer literal", &.{});
if (!isSigned(ty.int)) return l.fail("E7005", e.span, "negative literal of an unsigned type", &.{.{ .name = "type", .value = ty.int }});
const min_mag: u128 = @as(u128, 1) << @intCast(intBits(ty.int) - 1);
if (v > min_mag) return l.fail("E7005", e.span, "integer literal out of range for its type", &.{.{ .name = "type", .value = ty.int }});
return l.def("c", ty, try l.fmt("const.{s} -{d}", .{ ty.int, v }), e.span);
}
const z = try l.def("zero", ty, try l.fmt("const.{s} 0", .{ty.int}), e.span);
const v = try expr(l, x.*, ty);
try l.checkOperandTy(x.span, v.ty, ty);
return l.def("neg", ty, try l.fmt("sub.checked.{s} %{s}, %{s}", .{ ty.int, z.name, v.name }), e.span);
},
.deref => |x| {
const r = try expr(l, x.*, null);
const in = r.ty.inner() orelse return l.fail("E7005", e.span, "`*` reads through a borrow", &.{.{ .name = "found", .value = try l.diagnosticTyText(r.ty) }});
if (r.ty == .slice or r.ty == .slice_mut or in == .array) return l.invalid(.invalid_expression, e.span, "read slice and array elements with `s[i]`, not `*`", &.{});
if (in == .atomic) return l.fail("E4202", e.span, "an atomic cell is read only by atomic operations: use `atomic.load(r, ordering)`", &.{
.{ .name = "found", .value = try l.diagnosticTyText(r.ty) },
.{ .name = "use", .value = "atomic.load" },
});
return l.def("v", in, try l.fmt("load %{s}", .{r.name}), e.span);
},
.cast => |x| {
const to = try l.typeOf(x.ty);
if (to != .int) return l.fail("E7005", x.ty.span, "casts convert between integer types", &.{});
const from = l.peekType(x.e.*) orelse to;
const v = try expr(l, x.e.*, from);
if (v.ty != .int) return l.fail("E7005", x.e.span, "casts convert between integer types", &.{.{ .name = "found", .value = try l.diagnosticTyText(v.ty) }});
if (x.mode == .widen) {
const a = std.meta.stringToEnum(air_module.IntType, v.ty.int).?;
const b = std.meta.stringToEnum(air_module.IntType, to.int).?;
if (!verifier_types.lossless(a, b)) return l.invalidWidening(e.span, &.{ .{ .name = "from", .value = v.ty.int }, .{ .name = "to", .value = to.int } });
}
const mode = switch (x.mode) {
.widen => "widen",
.checked => "checked",
.wrap => "wrap",
};
return l.def("cast", to, try l.fmt("cast.{s}.{s} %{s}", .{ mode, to.int, v.name }), e.span);
},
else => return l.expr(e, want),
}
}
};
fn expectUnaryMatches(a: Allocator, e: ast.Expr, want: ?Ty, bindings: []const Binding) !void {
const m: ast.Module = .{ .name = "unary", .types = &.{}, .functions = &.{} };
const parameter: ast.Param = .{ .name = "c_1", .ty = .{ .span = e.span, .kind = .{ .name = "bool" } }, .span = e.span };
var old: Lowerer = .{ .arena = a, .m = m, .params = &.{parameter}, .in_constant = 7 };
var current: Lowerer = .{ .arena = a, .m = m, .params = &.{parameter}, .in_constant = 7 };
try old.bindings.appendSlice(a, bindings);
try current.bindings.appendSlice(a, bindings);
old.cur = try old.newBlock("entry", e.span);
current.cur = try current.newBlock("entry", e.span);
const expected = ReferenceUnary.expr(&old, e, want);
const actual = current.expr(e, want);
if (expected) |v| {
const result = try actual;
try std.testing.expectEqualStrings(v.name, result.name);
try std.testing.expect(v.ty.eql(result.ty));
} else |err| try std.testing.expectError(err, actual);
try std.testing.expectEqualDeep(old.problem, current.problem);
try std.testing.expectEqualDeep(old.unimpl, current.unimpl);
try std.testing.expectEqualDeep(old.blocks.items, current.blocks.items);
try std.testing.expectEqual(old.counter, current.counter);
try std.testing.expectEqualDeep(old.uses, current.uses);
}
test "unary expression lowering preserves instruction order and diagnostic priority" {
var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
var builder: Lowerer = .{ .arena = a, .m = .{ .name = "unary", .types = &.{}, .functions = &.{} } };
const bindings = [_]Binding{
.{ .name = "p", .value = "pointer", .mutable = false, .ty = try builder.wrap(.ref, .{ .int = "i64" }) },
.{ .name = "s", .value = "slice", .mutable = false, .ty = try builder.wrap(.slice, .{ .int = "u8" }) },
.{ .name = "r", .value = "array", .mutable = false, .ty = try builder.wrap(.ref, try builder.arrayOf(.{ .int = "u8" }, 2)) },
.{ .name = "atomic", .value = "atomic_view", .mutable = false, .ty = try builder.wrap(.ref, try builder.wrap(.atomic, .{ .int = "u64" })) },
};
const operands = [_][]const u8{ "true", "0i64", "1u64", "127i8", "128i8", "1", "unknown", "*p", "*s", "*r", "*atomic", "{ trap; }" };
const forms = [_][]const u8{ "{s}", "not {s}", "- {s}", "* {s}", "({s}) as i64", "({s}) as! u8", "({s}) as% usize", "({s}) as bool" };
inline for (forms) |outer| inline for (forms) |inner| for (operands) |operand| {
const nested = try std.fmt.allocPrint(a, inner, .{operand});
const expression = try std.fmt.allocPrint(a, outer, .{nested});
const source = try std.fmt.allocPrint(a, "module unary\nfn f() -> void effects [] {{ return {s}; }}", .{expression});
const parsed = try parse_mod.parseWithFile(a, source, "unary.aji");
try std.testing.expect(parsed == .ok);
const e = parsed.ok.functions[0].body.stmts[0].kind.@"return".?;
for ([_]?Ty{ null, .bool, .{ .int = "i64" }, .{ .int = "u8" } }) |want| try expectUnaryMatches(a, e, want, &bindings);
};
}
fn unaryTestSpan(column: u32) Span {
return .{ .file = "deep.aji", .start = .{ .line = 2, .col = column }, .end = .{ .line = 2, .col = 100_000 } };
}
// Independent old addressability walk. Its deliberately skipped select/lock
// inputs are retained: this repair changes traversal, not storage policy.
const ReferenceAddress = struct {
fn block(l: *Lowerer, b: ast.Block) Error!void {
for (b.stmts) |s| try stmt(l, s);
if (b.tail) |t| try expr(l, t.*);
}
fn root(l: *Lowerer, e: ast.Expr) Error!void {
var x = e;
while (true) switch (x.kind) {
.name => |n| return l.addressable.put(l.arena, n, {}),
.field => |f| x = f.e.*,
.index => |i| {
try expr(l, i.lo.*);
if (i.hi) |h| try expr(l, h.*);
x = i.e.*;
},
else => return expr(l, x),
};
}
fn stmt(l: *Lowerer, s: ast.Stmt) Error!void {
switch (s.kind) {
.let => |x| try expr(l, x.e),
.@"var" => |x| if (x.init) |e| try expr(l, e),
.assign => |x| {
if (x.place.kind != .name) try root(l, x.place);
try expr(l, x.e);
},
.borrow => |x| try root(l, x.place),
.@"return" => |e| if (e) |x| try expr(l, x),
.expr => |e| try expr(l, e),
.@"while" => |x| {
try expr(l, x.cond);
try block(l, x.body);
},
.@"for" => |x| {
try expr(l, x.lo);
try expr(l, x.hi);
try block(l, x.body);
},
.loop, .shield => |b| try block(l, b),
.scope => |x| try block(l, x.body),
.lock => |x| {
try block(l, x.body);
try block(l, x.cancelled);
},
else => {},
}
}
fn expr(l: *Lowerer, e: ast.Expr) Error!void {
switch (e.kind) {
.borrow => |x| try root(l, x.place.*),
.index => try root(l, e),
.neg, .not, .deref, .or_trap => |x| try expr(l, x.*),
.binary => |x| {
try expr(l, x.l.*);
try expr(l, x.r.*);
},
.cast => |x| try expr(l, x.e.*),
.call => |x| {
try expr(l, x.callee.*);
for (x.args) |arg| try expr(l, arg);
if (x.callee.kind == .field and std.mem.eql(u8, x.callee.kind.field.name, "split_at")) try root(l, x.callee.kind.field.e.*);
},
.field => |x| try expr(l, x.e.*),
.struct_lit => |x| for (x.fields) |f| try expr(l, f.e),
.array_rep => |x| try expr(l, x.e.*),
.array_list => |xs| for (xs) |x| try expr(l, x),
.if_expr => |x| {
try expr(l, x.cond);
try block(l, x.then);
if (x.@"else") |els| switch (els) {
.block => |b| try block(l, b),
.@"if" => |inner| try expr(l, .{ .span = e.span, .kind = .{ .if_expr = inner } }),
};
},
.match_expr => |x| {
try expr(l, x.scrutinee);
for (x.arms) |arm| try expr(l, arm.body);
},
.block => |b| try block(l, b.*),
else => {},
}
}
};
fn expectAddressMatches(a: Allocator, b: ast.Block) !void {
const m: ast.Module = .{ .name = "address", .types = &.{}, .functions = &.{} };
var old: Lowerer = .{ .arena = a, .m = m };
var current: Lowerer = .{ .arena = a, .m = m };
try ReferenceAddress.block(&old, b);
try current.findAddressable(b);
try std.testing.expectEqual(old.addressable.count(), current.addressable.count());
var before = old.addressable.keyIterator();
var after = current.addressable.keyIterator();
while (before.next()) |name| try std.testing.expectEqualStrings(name.*, after.next().?.*);
try std.testing.expect(after.next() == null);
try std.testing.expect(current.problem == null);
try std.testing.expectEqual(@as(usize, 0), current.blocks.items.len);
}
test "addressability continuations retain roots, skipped inputs and sibling order" {
var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
const expressions = [_][]const u8{
"x", "ref x", "mut x", "x[y[0]..z[0]]", "x[y[0]].field[z[0]]",
"foo(ref a, b[i], mut c[j])", "r.split_at(i[0])", "[ref a, ref b]", "[ref a; 2]", "Holder { left: ref x, right: ref y }",
"not - *x[i]", "x[i] as! u8", "foo(ref a) or trap", "if cond[i] { ref a } else if flag[j] { mut b } else { mut c }", "match value[i] { Shape::A => ref a, Shape::B => mut b }",
};
for (expressions) |expression| {
const source = try std.fmt.allocPrint(a, "module address fn f() -> void effects [] {{ let result = {s}; }}", .{expression});
const parsed = try parse_mod.parse(a, source);
try std.testing.expect(parsed == .ok);
try expectAddressMatches(a, parsed.ok.functions[0].body);
}
const parsed = try parse_mod.parse(a, "module address fn f() -> void effects [] { " ++
"let a = ref alpha; var b: [u8; 2] = [other[i]; 2]; " ++
"target[j] = call(ref source); while cond[k] { body[l]; break; } " ++
"for i in lo[0]..hi[0] { element[i]; continue; } " ++
"loop { ref r = data[j]; break; } shield { foo(ref shared); } " ++
"scope s { bar(ref scoped); } " ++
"lock ref skipped[0] as g { normal[0]; } cancelled { cancel[0]; } " ++
"return ref tail; }");
try std.testing.expect(parsed == .ok);
try expectAddressMatches(a, parsed.ok.functions[0].body);
const span = unaryTestSpan(1);
const ignored: ast.Expr = .{ .span = span, .kind = .{ .name = "ignored" } };
const ignored_borrow: ast.Expr = .{ .span = span, .kind = .{ .borrow = .{ .place = &ignored, .mutable = false, .unchecked = false } } };
const statements = [_]ast.Stmt{
.{ .span = span, .kind = .{ .select = .{ .arms = &.{}, .cancelled_binds = &.{}, .cancelled = ignored_borrow, .span = span } } },
.{ .span = span, .kind = .{ .@"return" = null } },
.{ .span = span, .kind = .trap },
};
try expectAddressMatches(a, .{ .span = span, .stmts = &statements, .tail = &ignored });
}
test "addressability descends deep expressions and blocks and releases OOM metadata" {
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer fixture.deinit();
const a = fixture.allocator();
const span = unaryTestSpan(1);
const m: ast.Module = .{ .name = "address", .types = &.{}, .functions = &.{} };
const name: ast.Expr = .{ .span = span, .kind = .{ .name = "root" } };
var e: ast.Expr = .{ .span = span, .kind = .{ .borrow = .{ .place = &name, .mutable = false, .unchecked = false } } };
for (0..32_768) |i| {
const inner = try a.create(ast.Expr);
inner.* = e;
if (i % 2 == 0) e = .{ .span = span, .kind = .{ .not = inner } } else {
const b = try a.create(ast.Block);
const statements = try a.alloc(ast.Stmt, 1);
statements[0] = .{ .span = span, .kind = .{ .expr = inner.* } };
b.* = .{ .span = span, .stmts = statements, .tail = null };
e = .{ .span = span, .kind = .{ .block = b } };
}
}
var successful: Lowerer = .{ .arena = a, .m = m };
try successful.markAddressable(.{ .expr = e });
try std.testing.expectEqual(@as(u32, 1), successful.addressable.count());
try std.testing.expect(successful.addressable.contains("root"));
var fail_index: usize = 0;
while (true) : (fail_index += 1) {
try std.testing.expect(fail_index < 256);
var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = fail_index });
var arena: std.heap.ArenaAllocator = .init(failing.allocator());
var l: Lowerer = .{ .arena = arena.allocator(), .m = m };
const result = l.markAddressable(.{ .expr = e });
if (failing.has_induced_failure) try std.testing.expectError(error.OutOfMemory, result) else {
try result;
try std.testing.expectEqual(@as(u32, 1), l.addressable.count());
try std.testing.expect(l.addressable.contains("root"));
}
try std.testing.expect(l.problem == null);
try std.testing.expectEqual(@as(usize, 0), l.out.items.len);
arena.deinit();
try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes);
if (!failing.has_induced_failure) break;
}
}
test "unary lowering processes deep boolean, negative and cast spines" {
var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
const count = 32_768;
const m: ast.Module = .{ .name = "deep", .types = &.{}, .functions = &.{} };
for ([_]enum { not, neg, cast, deref }{ .not, .neg, .cast, .deref }) |kind| {
var l: Lowerer = .{ .arena = a, .m = m };
try l.bindings.append(a, .{ .name = "n", .value = "input", .mutable = false, .ty = .{ .int = "i64" } });
var e: ast.Expr = .{ .span = unaryTestSpan(count + 1), .kind = if (kind == .not or kind == .deref) .{ .boolean = false } else .{ .name = "n" } };
var i: usize = count;
while (i != 0) {
i -= 1;
const inner = try l.arena.create(ast.Expr);
inner.* = e;
const span = unaryTestSpan(@intCast(i + 1));
e = .{ .span = span, .kind = switch (kind) {
.not => .{ .not = inner },
.neg => .{ .neg = inner },
.deref => .{ .deref = inner },
.cast => .{ .cast = .{ .e = inner, .mode = switch (i % 3) {
0 => .widen,
1 => .checked,
else => .wrap,
}, .ty = .{ .span = span, .kind = .{ .name = "i64" } } } },
} };
}
l.cur = try l.newBlock("entry", e.span);
const result = l.expr(e, null);
if (kind == .deref) {
try std.testing.expectError(error.Lower, result);
try std.testing.expectEqualStrings("E7005", l.problem.?.code);
try std.testing.expectEqualDeep(unaryTestSpan(count), l.problem.?.span);
try std.testing.expectEqual(@as(usize, 1), l.blocks.items[0].insts.items.len);
continue;
}
const value = try result;
try std.testing.expectEqualDeep(if (kind == .not) Ty.bool else Ty{ .int = "i64" }, value.ty);
const instructions = l.blocks.items[0].insts.items;
try std.testing.expectEqual(@as(usize, switch (kind) {
.not => 2 * count + 1,
.neg => 2 * count,
.cast => count,
.deref => unreachable,
}), instructions.len);
for (0..count) |index| {
const span = unaryTestSpan(@intCast(count - index));
switch (kind) {
.not => {
try std.testing.expectEqualDeep(@as(?Span, span), instructions[2 * index + 1].span);
try std.testing.expectEqualDeep(@as(?Span, span), instructions[2 * index + 2].span);
},
.neg => {
try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(@intCast(index + 1))), instructions[index].span);
const previous = if (index == 0) "input" else try std.fmt.allocPrint(a, "neg_{d}", .{count + index});
const expected = try std.fmt.allocPrint(a, "%neg_{d} = sub.checked.i64 %zero_{d}, %{s}", .{ count + index + 1, count - index, previous });
try std.testing.expectEqualStrings(expected, instructions[count + index].text);
try std.testing.expectEqualDeep(@as(?Span, span), instructions[count + index].span);
},
.cast => try std.testing.expectEqualDeep(@as(?Span, span), instructions[index].span),
.deref => unreachable,
}
}
try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(1)), instructions[instructions.len - 1].span);
try std.testing.expect(l.problem == null);
}
}
test "unary lowering OOM retains complete instruction prefixes and no output" {
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer fixture.deinit();
const a = fixture.allocator();
const m: ast.Module = .{ .name = "oom", .types = &.{}, .functions = &.{} };
const span = unaryTestSpan(1);
var e: ast.Expr = .{ .span = span, .kind = .{ .int = .{ .text = "1i64" } } };
for (0..64) |_| {
const operand = try a.create(ast.Expr);
operand.* = e;
e = .{ .span = span, .kind = .{ .neg = operand } };
const cast = try a.create(ast.Expr);
cast.* = e;
e = .{ .span = span, .kind = .{ .cast = .{ .e = cast, .mode = .checked, .ty = .{ .span = span, .kind = .{ .name = "i64" } } } } };
}
var old: Lowerer = .{ .arena = a, .m = m };
old.cur = try old.newBlock("entry", span);
_ = try ReferenceUnary.expr(&old, e, null);
const expected = old.blocks.items[0].insts.items;
var fail_index: usize = 0;
while (true) : (fail_index += 1) {
try std.testing.expect(fail_index < 256);
var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = fail_index });
var arena: std.heap.ArenaAllocator = .init(failing.allocator());
var l: Lowerer = .{ .arena = arena.allocator(), .m = m };
const result: Error!Value = blk: {
l.cur = l.newBlock("entry", span) catch |err| break :blk err;
break :blk l.expr(e, null);
};
if (failing.has_induced_failure) {
try std.testing.expectError(error.OutOfMemory, result);
try std.testing.expect(l.problem == null);
} else {
try std.testing.expect((try result).ty.eql(.{ .int = "i64" }));
try std.testing.expectEqual(expected.len, l.blocks.items[0].insts.items.len);
}
if (l.cur) |index| {
const actual = l.blocks.items[index].insts.items;
try std.testing.expect(actual.len <= expected.len);
try std.testing.expectEqualDeep(expected[0..actual.len], actual);
}
try std.testing.expectEqual(@as(usize, 0), l.out.items.len);
arena.deinit();
try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes);
if (!failing.has_induced_failure) break;
}
}
test "source property queries prune deep diamonds without changing witnesses" {
var scratch = std.heap.ArenaAllocator.init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
var text: std.ArrayList(u8) = .empty;
try text.appendSlice(a, "module t\n");
for (0..41) |i| try text.print(a, "struct N{d} {{ a: N{d}, b: N{d} }}\n", .{ i, i + 1, i + 1 });
try text.appendSlice(a, "struct N41 { a: ref<u64>, b: task<u64> }\nfn main() -> void effects [] {}\n");
var l: Lowerer = .{ .arena = a, .m = (try parse_mod.parse(a, text.items)).ok };
try l.checkRequirements();
try std.testing.expect(l.isLinear(.{ .named = 0 }));
try std.testing.expectEqual(@as(?Ty, null), try l.forbiddenIn(.{ .named = 0 }, 0));
try std.testing.expectEqual(@as(usize, 1), l.property_visits);
l.property_visits = 0;
const bad = (try l.forbiddenIn(.{ .named = 10 }, 0)).?;
try std.testing.expect(bad == .ref and bad.inner().? == .int);
try std.testing.expect(l.property_visits <= 33);
}
test "cyclic source diamonds reject before property construction" {
var scratch = std.heap.ArenaAllocator.init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
var text: std.ArrayList(u8) = .empty;
try text.appendSlice(a, "module t\n");
for (0..41) |i| try text.print(a, "struct N{d} {{ a: N{d}, b: N{d} }}\n", .{ i, (i + 1) % 41, (i + 1) % 41 });
try text.appendSlice(a, "fn main() -> void effects [] {}\n");
var l: Lowerer = .{ .arena = a, .m = (try parse_mod.parse(a, text.items)).ok };
try std.testing.expectError(error.Lower, l.checkRequirements());
try std.testing.expectEqualStrings("E1003", l.problem.?.code);
try std.testing.expectEqual(@as(u32, 2), l.problem.?.span.start.line);
try std.testing.expect(l.property_module == null);
}
test "failed body discards constants and features and never emits partial AIR" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const source =
\\module collection
\\fn good() -> void effects [] { let text = b"good"; }
\\fn bad() -> void effects [unsafe] { let text = b"bad"; let x = missing; }
\\fn main() -> void effects [] {}
;
const m = (try parse_mod.parse(a, source)).ok;
var l: Lowerer = .{ .arena = a, .m = m };
try std.testing.expectError(error.Lower, l.run());
try std.testing.expectEqual(@as(usize, 1), l.problems.items.len);
try std.testing.expectEqualStrings("E7002", l.problems.items[0].code);
try std.testing.expectEqual(@as(usize, 2), l.fns.items.len);
try std.testing.expectEqual(@as(usize, 1), l.constants.items.len);
try std.testing.expectEqualStrings("good", l.constants.items[0].bytes);
try std.testing.expect(!l.uses.contains(.unsafe));
try std.testing.expectEqual(@as(usize, 0), l.out.items.len);
try std.testing.expectEqual(@as(usize, 0), l.annotated.items.len);
try std.testing.expectEqual(@as(usize, 0), l.lines.items.len);
try std.testing.expectEqual(@as(usize, 0), l.constant_of.items.len);
}
test "later function output matches fresh lowering after failed borrow and scope bodies" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const stable =
\\fn stable() -> u64 effects [] {
\\ let inferred = 7;
\\ let text = b"ok";
\\ var bytes: [u8; 4] = zero;
\\ var total: u64 = inferred;
\\ for i in 0usize..2usize { total = total + (bytes[i] as u64); }
\\ return total + (text.len as! u64);
\\}
\\fn main() -> void effects [] {}
;
const baseline_source = try std.fmt.allocPrint(a, "module collection\n{s}", .{stable});
const baseline_module = (try parse_mod.parse(a, baseline_source)).ok;
var baseline: Lowerer = .{ .arena = a, .m = baseline_module };
try baseline.run();
var baseline_emission: Lowerer = .{ .arena = a, .m = baseline_module };
try baseline_emission.emitFunction(baseline.fns.items[0]);
for ([_][]const u8{
"fn bad() -> void effects [] { let shadow = 1u64; let x = missing; }",
"fn bad() -> void effects [] { var bytes: [u8; 4] = zero; ref unchecked view = bytes[missing]; }",
"fn bad() -> void effects [unsafe] { scope s { let text = b\"bad\"; loop { let x = missing; } } }",
}) |bad| {
const source = try std.fmt.allocPrint(a, "module collection\n{s}\n{s}", .{ bad, stable });
const m = (try parse_mod.parse(a, source)).ok;
var recovered: Lowerer = .{ .arena = a, .m = m };
try std.testing.expectError(error.Lower, recovered.run());
try std.testing.expectEqual(@as(usize, 1), recovered.problems.items.len);
try std.testing.expectEqualStrings("E7002", recovered.problems.items[0].code);
try std.testing.expectEqual(@as(usize, 2), recovered.fns.items.len);
try std.testing.expectEqual(@as(usize, 0), recovered.out.items.len);
var emission: Lowerer = .{ .arena = a, .m = m };
try emission.emitFunction(recovered.fns.items[0]);
try std.testing.expectEqualStrings(baseline_emission.out.items, emission.out.items);
try std.testing.expectEqualSlices(u32, baseline_emission.constant_of.items, emission.constant_of.items);
try std.testing.expectEqual(@as(usize, 1), recovered.constants.items.len);
try std.testing.expectEqualStrings("ok", recovered.constants.items[0].bytes);
}
}
test "defensive nonmaterializable moves retain invalid_move even in generic transfers" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const span: Span = .{ .start = .{ .line = 2, .col = 3 }, .end = .{ .line = 2, .col = 9 } };
// Annotation/binding checks normally reject these values earlier. Keep
// the lower-level guard stable without inventing accepted void parameters.
for ([_]Ty{ .void, .never }) |ty| for ([_]bool{ false, true }) |generic| {
var l: Lowerer = .{ .arena = a, .m = .{ .name = "defensive", .types = &.{}, .functions = &.{} } };
try l.bindings.append(a, .{ .name = "value", .value = "v", .ty = ty, .mutable = false });
try std.testing.expectError(error.Lower, l.expr(.{ .span = span, .generic_transfer = generic, .kind = .{ .move = "value" } }, null));
try std.testing.expectEqualStrings("E7006", l.problem.?.code);
try std.testing.expectEqual(InvalidReason.invalid_move, l.problem.?.reason.?);
try std.testing.expectEqual(span, l.problem.?.span);
try std.testing.expectEqual(@as(usize, 0), l.out.items.len);
};
}
// Independent pre-repair derivation, used only on shallow test trees.
const ReferenceTypeResolution = struct {
fn resolveType(l: *Lowerer, t: ast.Type) Error!Ty {
switch (t.kind) {
.applied => return l.fail("E7002", t.span, "unknown generic type", &.{}),
.function_ref => return l.invalid(.invalid_static_function, t.span, "static functions are not runtime types", &.{}),
.name => |n| {
if (isIntName(n)) return .{ .int = n };
if (std.mem.eql(u8, n, "bool")) return .bool;
if (std.mem.eql(u8, n, "void")) return .void;
if (std.mem.eql(u8, n, "never")) return .never;
if (l.enumOrStruct(n, t.span)) |ty| return ty;
if (std.mem.eql(u8, n, "region")) return .region;
if (std.meta.stringToEnum(authority.Builtin, n)) |b| return .{ .builtin = b };
if (std.mem.eql(u8, n, "stream")) return .{ .resource = .stream };
if (std.mem.eql(u8, n, "listener")) return .{ .resource = .listener };
return l.fail("E7002", t.span, "unknown type", &.{.{ .name = "name", .value = n }});
},
.array => |a| {
if (a.len == 0 or a.len > (@as(u64, 1) << 32)) return l.fail("E7005", t.span, "array length must be between 1 and 2^32", &.{});
const elem = try ReferenceTypeResolution.resolveType(l, a.elem.*);
if (elem == .void or elem == .never) return l.fail("E7005", a.elem.span, "an array element needs a value type", &.{});
return l.arrayOf(elem, a.len);
},
.wrapped => |w| {
const Wr = enum { ref, mut, slice, slice_mut, own, own_array, buffer, task, sender, receiver, mutex, island, frozen, arc, iref, atomic };
const which = std.meta.stringToEnum(Wr, w.wrapper) orelse return l.notYet(t.span, "this type (later layers)");
const in = try ReferenceTypeResolution.resolveType(l, w.inner.*);
return switch (which) {
.ref => l.wrap(.ref, in),
.mut => l.wrap(.mut, in),
.slice => l.wrap(.slice, in),
.slice_mut => l.wrap(.slice_mut, in),
.own => l.wrap(.own, in),
.own_array => l.wrap(.own_array, in),
.buffer => l.wrap(.buffer, in),
.task => l.wrap(.task, in),
.sender => l.wrap(.sender, in),
.receiver => l.wrap(.receiver, in),
.mutex => l.wrap(.mutex, in),
.island => l.wrap(.island, in),
.frozen => l.wrap(.frozen, in),
.arc => l.wrap(.arc, in),
.iref => l.wrap(.iref, in),
.atomic => if (atomicScalar(in)) l.wrap(.atomic, in) else l.fail("E7005", t.span, "atomic<T> needs bool or an integer of at most 64 bits", &.{.{ .name = "found", .value = try l.diagnosticTyText(in) }}),
};
},
.cap => |k| {
if (authority.kindIndex(k) == null) return l.fail("E7002", t.span, "unknown capability kind", &.{.{ .name = "capability_kind", .value = k }});
return .{ .cap = k };
},
.file => |m| {
const r: authority.Resource = if (std.mem.eql(u8, m, "read")) .file_read else if (std.mem.eql(u8, m, "write")) .file_write else if (std.mem.eql(u8, m, "append")) .file_append else return l.fail("E7002", t.span, "unknown file mode (read, write, append)", &.{.{ .name = "mode", .value = m }});
return .{ .resource = r };
},
}
}
};
fn expectTypeResolutionMatches(arena: Allocator, m: ast.Module, t: ast.Type) !void {
const names = try arena.alloc([]const u8, m.types.len);
for (m.types, names) |declaration, *name| name.* = try std.fmt.allocPrint(arena, "@{s}", .{declaration.name});
var original: Lowerer = .{ .arena = arena, .m = m, .typeNames = names };
var current: Lowerer = .{ .arena = arena, .m = m, .typeNames = names };
var original_error: ?Error = null;
var current_error: ?Error = null;
const before = ReferenceTypeResolution.resolveType(&original, t) catch |err| blk: {
original_error = err;
break :blk Ty.void;
};
const after = current.resolveType(t) catch |err| blk: {
current_error = err;
break :blk Ty.void;
};
try std.testing.expectEqual(original_error, current_error);
if (original_error == null) try std.testing.expect(before.eql(after));
try std.testing.expectEqualDeep(original.problem, current.problem);
try std.testing.expectEqualDeep(original.unimpl, current.unimpl);
}
test "source type resolution preserves shallow types and diagnostic priority" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const m = (try parse_mod.parse(a, "module resolution\nstruct S { x: u8 }\nfn main() -> void effects [] {}\n")).ok;
const leaf_span: Span = .{ .start = .{ .line = 7, .col = 9 }, .end = .{ .line = 7, .col = 12 }, .file = "annotation.aji" };
const outer_span: Span = .{ .start = .{ .line = 6, .col = 3 }, .end = .{ .line = 8, .col = 17 }, .file = "annotation.aji" };
var leaves: std.ArrayList(ast.Type) = .empty;
for (int_types ++ [_][]const u8{ "bool", "void", "never", "region", "S", "alloc_error", "cap_error", "io_error", "stream", "listener", "missing" }) |name| {
try leaves.append(a, .{ .span = leaf_span, .kind = .{ .name = name } });
}
for ([_][]const u8{ "mem.alloc", "unknown.kind" }) |kind| try leaves.append(a, .{ .span = leaf_span, .kind = .{ .cap = kind } });
for ([_][]const u8{ "read", "write", "append", "unknown" }) |mode| try leaves.append(a, .{ .span = leaf_span, .kind = .{ .file = mode } });
try leaves.append(a, .{ .span = leaf_span, .kind = .{ .applied = .{ .name = "Missing", .args = &.{} } } });
try leaves.append(a, .{ .span = leaf_span, .kind = .{ .function_ref = .{ .name = "operation" } } });
const wrappers = comptime std.meta.fieldNames(Lowerer.TypeWrapper) ++ [_][]const u8{"unknown_wrapper"};
var comparisons: usize = 0;
for (leaves.items) |*leaf| {
try expectTypeResolutionMatches(a, m, leaf.*);
comparisons += 1;
for ([_]u64{ 0, 1, @as(u64, 1) << 32, (@as(u64, 1) << 32) + 1 }) |len| {
const array: ast.Type = .{ .span = outer_span, .kind = .{ .array = .{ .elem = leaf, .len = len } } };
try expectTypeResolutionMatches(a, m, array);
comparisons += 1;
}
for (wrappers) |wrapper| {
const wrapped: ast.Type = .{ .span = outer_span, .kind = .{ .wrapped = .{ .wrapper = wrapper, .inner = leaf } } };
try expectTypeResolutionMatches(a, m, wrapped);
comparisons += 1;
const outer_array: ast.Type = .{ .span = outer_span, .kind = .{ .array = .{ .elem = &wrapped, .len = 1 } } };
try expectTypeResolutionMatches(a, m, outer_array);
comparisons += 1;
const bad_array: ast.Type = .{ .span = outer_span, .kind = .{ .array = .{ .elem = leaf, .len = 0 } } };
const outer_wrapper: ast.Type = .{ .span = outer_span, .kind = .{ .wrapped = .{ .wrapper = wrapper, .inner = &bad_array } } };
try expectTypeResolutionMatches(a, m, outer_wrapper);
comparisons += 1;
}
}
try std.testing.expectEqual(@as(usize, 1736), comparisons);
}
test "source type resolution constructs deep types and preserves leaf errors iteratively" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const span: Span = .{ .start = .{ .line = 2, .col = 3 }, .end = .{ .line = 2, .col = 9 } };
var leaf: ast.Type = .{ .span = span, .kind = .{ .name = "u8" } };
const nodes = try a.alloc(ast.Type, 32_768);
var child: *const ast.Type = &leaf;
for (nodes, 0..) |*node, i| {
node.* = .{ .span = span, .kind = if (i % 2 == 0) .{ .array = .{ .elem = child, .len = i + 1 } } else .{ .wrapped = .{ .wrapper = "ref", .inner = child } } };
child = node;
}
var l: Lowerer = .{ .arena = a, .m = .{ .name = "resolution", .types = &.{}, .functions = &.{} } };
var ty = try l.resolveType(child.*);
var remaining = nodes.len;
while (remaining != 0) {
remaining -= 1;
if (remaining % 2 == 0) {
try std.testing.expect(ty == .array);
try std.testing.expectEqual(@as(u64, remaining + 1), ty.array.len);
ty = ty.array.elem;
} else {
try std.testing.expect(ty == .ref);
ty = ty.ref.*;
}
}
try std.testing.expectEqualStrings("u8", ty.int);
leaf.kind = .{ .name = "missing" };
try std.testing.expectError(error.Lower, l.resolveType(child.*));
try std.testing.expectEqualStrings("E7002", l.problem.?.code);
try std.testing.expectEqualDeep(span, l.problem.?.span);
leaf.kind = .{ .name = "never" };
try std.testing.expectError(error.Lower, l.resolveType(child.*));
try std.testing.expectEqualStrings("an array element needs a value type", l.problem.?.message);
try std.testing.expectEqualDeep(span, l.problem.?.span);
}
test "source type resolution allocation errors propagate and arena storage is released" {
var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer scratch.deinit();
const span: Span = .{ .start = .{ .line = 2, .col = 1 }, .end = .{ .line = 2, .col = 2 } };
const leaf: ast.Type = .{ .span = span, .kind = .{ .name = "u8" } };
const nodes = try scratch.allocator().alloc(ast.Type, 256);
var child: *const ast.Type = &leaf;
for (nodes, 0..) |*node, i| {
node.* = .{ .span = span, .kind = if (i % 2 == 0) .{ .array = .{ .elem = child, .len = 1 } } else .{ .wrapped = .{ .wrapper = "ref", .inner = child } } };
child = node;
}
var fail_index: usize = 0;
while (true) : (fail_index += 1) {
try std.testing.expect(fail_index < 100);
var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = fail_index });
var arena: std.heap.ArenaAllocator = .init(failing.allocator());
var l: Lowerer = .{ .arena = arena.allocator(), .m = .{ .name = "resolution", .types = &.{}, .functions = &.{} } };
const result = l.resolveType(child.*);
if (failing.has_induced_failure) {
try std.testing.expectError(error.OutOfMemory, result);
try std.testing.expect(l.problem == null);
} else {
_ = try result;
}
arena.deinit();
try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes);
if (!failing.has_induced_failure) break;
}
}
// Independent pre-repair printer, used only with shallow test types.
const ReferenceTypeText = struct {
fn typeText(l: *Lowerer, t: Ty, source_names: bool) []const u8 {
return switch (t) {
.int => |x| x,
.bool => "bool",
.void => "void",
.never => "never",
.named => |i| if (source_names and l.m.types[i].air_name != null) (l.m.types[i].display_name orelse l.m.types[i].name) else l.typeNames[i],
.array => |a| std.fmt.allocPrint(l.arena, "array<{s}, {d}>", .{ ReferenceTypeText.typeText(l, a.elem, source_names), a.len }) catch "array",
.ref, .mut, .slice, .slice_mut, .own, .own_array, .buffer, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| std.fmt.allocPrint(l.arena, "{s}<{s}>", .{ @tagName(t), ReferenceTypeText.typeText(l, x.*, source_names) }) catch "borrow",
.scope => "scope",
.shield => "shield",
.region => "region",
.cap => |k| std.fmt.allocPrint(l.arena, "cap<{s}>", .{k}) catch "cap",
.builtin => |b| blk: {
if (b == .io_error) l.uses.insert(.resources);
break :blk @tagName(b);
},
.resource => |r| blk: {
l.uses.insert(.resources);
break :blk r.text();
},
};
}
};
fn expectTypeTextMatches(a: Allocator, m: ast.Module, names: []const []const u8, t: Ty) !void {
for ([_]bool{ false, true }) |source_names| {
var old: Lowerer = .{ .arena = a, .m = m, .typeNames = names };
var current: Lowerer = .{ .arena = a, .m = m, .typeNames = names };
old.uses.insert(.unsafe);
current.uses.insert(.unsafe);
try std.testing.expectEqualStrings(ReferenceTypeText.typeText(&old, t, source_names), try current.typeText(t, source_names));
try std.testing.expectEqualDeep(old.uses, current.uses);
}
}
test "source type text preserves canonical and diagnostic names and resource features" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const span: Span = .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 2 } };
const declarations = [_]ast.TypeDecl{
.{ .span = span, .name = "Local", .kind = .{ .@"struct" = &.{} } },
.{ .span = span, .name = "pkg.Box", .air_name = "__g_box", .display_name = "Box<u8>", .kind = .{ .@"struct" = &.{} } },
.{ .span = span, .name = "pkg.Record", .air_name = "__g_record", .kind = .{ .@"struct" = &.{} } },
};
const names = [_][]const u8{ "@Local", "@__g_box", "@__g_record" };
const m: ast.Module = .{ .name = "printing", .types = &declarations, .functions = &.{} };
var builder: Lowerer = .{ .arena = a, .m = m, .typeNames = &names };
var leaves: std.ArrayList(Ty) = .empty;
for (int_types) |n| try leaves.append(a, .{ .int = n });
try leaves.appendSlice(a, &.{ .bool, .void, .never, .scope, .shield, .region, .{ .named = 0 }, .{ .named = 1 }, .{ .named = 2 } });
for ([_][]const u8{ "mem.alloc", "io.read", "fs.open", "unknown.kind" }) |k| try leaves.append(a, .{ .cap = k });
inline for (@typeInfo(authority.Builtin).@"enum".field_names) |name| try leaves.append(a, .{ .builtin = @field(authority.Builtin, name) });
inline for (@typeInfo(authority.Resource).@"enum".field_names) |name| try leaves.append(a, .{ .resource = @field(authority.Resource, name) });
var comparisons: usize = 0;
for (leaves.items) |leaf| {
try expectTypeTextMatches(a, m, &names, leaf);
comparisons += 2;
for ([_]u64{ 0, 1, @as(u64, 1) << 32, std.math.maxInt(u64) }) |length| {
try expectTypeTextMatches(a, m, &names, try builder.arrayOf(leaf, length));
comparisons += 2;
}
inline for (@typeInfo(Ty).@"union".field_names, @typeInfo(Ty).@"union".field_types) |name, FieldType| if (comptime FieldType == *const Ty) {
const wrapped = try builder.wrap(@field(std.meta.Tag(Ty), name), leaf);
try expectTypeTextMatches(a, m, &names, wrapped);
try expectTypeTextMatches(a, m, &names, try builder.arrayOf(wrapped, 123));
try expectTypeTextMatches(a, m, &names, try builder.wrap(@field(std.meta.Tag(Ty), name), try builder.arrayOf(leaf, 456)));
comparisons += 6;
};
}
try std.testing.expectEqual(@as(usize, 3696), comparisons);
}
test "source type text prints deep mixed chains with one growing output" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const m: ast.Module = .{ .name = "printing", .types = &.{}, .functions = &.{} };
var l: Lowerer = .{ .arena = a, .m = m };
var ty: Ty = .{ .cap = "mem.alloc" };
const count = 65_536;
for (0..count) |i| ty = if (i % 2 == 0) try l.arrayOf(ty, i + 1) else try l.wrap(.ref, ty);
var expected: std.ArrayList(u8) = .empty;
var i: usize = count;
while (i != 0) {
i -= 1;
try expected.appendSlice(a, if (i % 2 == 0) "array<" else "ref<");
}
try expected.appendSlice(a, "cap<mem.alloc>");
for (0..count) |j| {
if (j % 2 == 0) {
var digits: [20]u8 = undefined;
try expected.appendSlice(a, ", ");
try expected.appendSlice(a, std.fmt.bufPrint(&digits, "{d}", .{j + 1}) catch unreachable);
}
try expected.append(a, '>');
}
try std.testing.expectEqualStrings(expected.items, try l.tyText(ty));
try std.testing.expectEqualStrings(expected.items, try l.diagnosticTyText(ty));
}
test "source type text OOM reaches diagnostics and emission without fallback text" {
var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
const m: ast.Module = .{ .name = "printing", .types = &.{}, .functions = &.{} };
var builder: Lowerer = .{ .arena = a, .m = m };
var deep: Ty = .{ .cap = "mem.alloc" };
for (0..128) |i| deep = if (i % 2 == 0) try builder.arrayOf(deep, std.math.maxInt(u64)) else try builder.wrap(.own, deep);
for ([_]Ty{ .{ .cap = "mem.alloc" }, deep }) |ty| for ([_]bool{ false, true }) |source_names| {
var fail_index: usize = 0;
while (true) : (fail_index += 1) {
try std.testing.expect(fail_index < 100);
var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = fail_index });
var arena: std.heap.ArenaAllocator = .init(failing.allocator());
var l: Lowerer = .{ .arena = arena.allocator(), .m = m };
const text = l.typeText(ty, source_names);
if (failing.has_induced_failure) {
try std.testing.expectError(error.OutOfMemory, text);
} else {
try std.testing.expectEqualStrings(try builder.typeText(ty, source_names), try text);
}
arena.deinit();
try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes);
if (!failing.has_induced_failure) break;
}
};
const span: Span = .{ .start = .{ .line = 2, .col = 3 }, .end = .{ .line = 2, .col = 9 } };
for ([_]bool{ false, true }) |diagnostic| {
var fail_index: usize = 0;
while (true) : (fail_index += 1) {
try std.testing.expect(fail_index < 100);
var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = fail_index });
var arena: std.heap.ArenaAllocator = .init(failing.allocator());
var l: Lowerer = .{ .arena = arena.allocator(), .m = m };
const result: Error!void = if (diagnostic) l.checkTy(span, deep, .bool) else blk: {
_ = l.storageFor("x", deep, span) catch |err| break :blk err;
break :blk {};
};
if (failing.has_induced_failure) {
try std.testing.expectError(error.OutOfMemory, result);
try std.testing.expect(l.problem == null);
try std.testing.expectEqual(@as(usize, 0), l.allocs.items.len);
} else if (diagnostic) {
try std.testing.expectError(error.Lower, result);
try std.testing.expectEqualStrings("E7005", l.problem.?.code);
try std.testing.expectEqualStrings(try builder.diagnosticTyText(deep), l.problem.?.fields[1].value);
} else {
try result;
try std.testing.expectEqual(@as(usize, 1), l.allocs.items.len);
try std.testing.expect(std.mem.endsWith(u8, l.allocs.items[0].text, try builder.tyText(deep)));
}
try std.testing.expectEqual(@as(usize, 0), l.out.items.len);
arena.deinit();
try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes);
if (!failing.has_induced_failure) break;
}
}
// Constant leaves keep the original allocation-free path.
var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 0 });
var l: Lowerer = .{ .arena = failing.allocator(), .m = m };
try std.testing.expectEqualStrings("u8", try l.tyText(.{ .int = "u8" }));
try std.testing.expectEqualStrings("file<read>", try l.diagnosticTyText(.{ .resource = .file_read }));
try std.testing.expect(l.uses.contains(.resources));
try std.testing.expect(!failing.has_induced_failure);
}
// Independent old conversion, used only on shallow test types.
const ReferenceAirType = struct {
fn airType(l: *Lowerer, t: Ty) Error!air_module.Type {
return switch (t) {
.int => |n| .{ .int = std.meta.stringToEnum(air_module.IntType, n).? },
.named => |i| .{ .named = i },
.cap => |k| .{ .cap = authority.kindIndex(k).? },
.builtin => |b| .{ .builtin = b },
.resource => |r| .{ .resource = r },
.array => |a| blk: {
const out = try l.arena.create(air_module.Type.Array);
out.* = .{ .elem = try ReferenceAirType.airType(l, a.elem), .len = a.len };
break :blk .{ .array = out };
},
inline .ref, .mut, .slice, .slice_mut, .own, .own_array, .buffer, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |inner, tag| blk: {
const out = try l.arena.create(air_module.Type);
out.* = try ReferenceAirType.airType(l, inner.*);
break :blk @unionInit(air_module.Type, @tagName(tag), out);
},
.bool => .bool,
.void => .void,
.never => .never,
.region => .region,
.scope => .scope,
.shield => .shield,
};
}
};
fn expectAirTypeMatches(a: Allocator, t: Ty) !void {
const m: ast.Module = .{ .name = "conversion", .types = &.{}, .functions = &.{} };
var original: Lowerer = .{ .arena = a, .m = m };
var current: Lowerer = .{ .arena = a, .m = m };
try std.testing.expect((try ReferenceAirType.airType(&original, t)).eql(try current.airType(t)));
try std.testing.expectEqualDeep(original.uses, current.uses);
}
test "source AIR conversion matches the independent shallow derivation" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const m: ast.Module = .{ .name = "conversion", .types = &.{}, .functions = &.{} };
var builder: Lowerer = .{ .arena = a, .m = m };
var leaves: std.ArrayList(Ty) = .empty;
for (int_types) |n| try leaves.append(a, .{ .int = n });
try leaves.appendSlice(a, &.{ .bool, .void, .never, .region, .scope, .shield, .{ .named = 0 }, .{ .named = 123 } });
for (authority.kinds) |kind| try leaves.append(a, .{ .cap = kind.name });
inline for (@typeInfo(authority.Builtin).@"enum".field_names) |name| try leaves.append(a, .{ .builtin = @field(authority.Builtin, name) });
inline for (@typeInfo(authority.Resource).@"enum".field_names) |name| try leaves.append(a, .{ .resource = @field(authority.Resource, name) });
var comparisons: usize = 0;
for (leaves.items) |leaf| {
try expectAirTypeMatches(a, leaf);
comparisons += 1;
for ([_]u64{ 0, 1, @as(u64, 1) << 32, std.math.maxInt(u64) }) |length| {
try expectAirTypeMatches(a, try builder.arrayOf(leaf, length));
comparisons += 1;
}
inline for (@typeInfo(Ty).@"union".field_names, @typeInfo(Ty).@"union".field_types) |name, FieldType| if (comptime FieldType == *const Ty) {
const wrapped = try builder.wrap(@field(std.meta.Tag(Ty), name), leaf);
try expectAirTypeMatches(a, wrapped);
try expectAirTypeMatches(a, try builder.arrayOf(wrapped, 123));
try expectAirTypeMatches(a, try builder.wrap(@field(std.meta.Tag(Ty), name), try builder.arrayOf(leaf, 456)));
comparisons += 3;
};
}
try std.testing.expectEqual(@as(usize, 2352), comparisons);
}
test "source AIR conversion builds deep trees without work metadata" {
var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
const m: ast.Module = .{ .name = "conversion", .types = &.{}, .functions = &.{} };
var builder: Lowerer = .{ .arena = a, .m = m };
var ty: Ty = .{ .int = "u8" };
const count = 65_536;
for (0..count) |i| ty = if (i % 2 == 0) try builder.arrayOf(ty, i + 1) else try builder.wrap(.ref, ty);
var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{});
var output: Lowerer = .{ .arena = failing.allocator(), .m = m };
const root = try output.airType(ty);
var current = root;
// Free output nodes in this test only; production uses the caller arena.
var remaining: usize = count;
while (remaining != 0) {
remaining -= 1;
if (remaining % 2 == 0) {
try std.testing.expect(current == .array);
const node = current.array;
try std.testing.expectEqual(@as(u64, remaining + 1), node.len);
current = node.elem;
failing.allocator().destroy(node);
} else {
try std.testing.expect(current == .ref);
const node = current.ref;
current = node.*;
failing.allocator().destroy(node);
}
}
try std.testing.expectEqual(air_module.IntType.u8, current.int);
try std.testing.expectEqual(@as(usize, count), failing.allocations);
try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes);
// No pointer in the output was borrowed from the source tree.
// Leaf-only conversion retains the allocation-free original path.
var no_alloc: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 0 });
var leaf: Lowerer = .{ .arena = no_alloc.allocator(), .m = m };
try std.testing.expectEqual(@as(u32, 17), (try leaf.airType(.{ .named = 17 })).named);
try std.testing.expect(!no_alloc.has_induced_failure);
}
test "source AIR conversion preserves allocation order and OOM publication" {
var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
const m: ast.Module = .{ .name = "conversion", .types = &.{}, .functions = &.{} };
var builder: Lowerer = .{ .arena = a, .m = m };
var deep: Ty = .{ .resource = .file_read };
for (0..64) |i| deep = if (i % 2 == 0) try builder.arrayOf(deep, std.math.maxInt(u64)) else try builder.wrap(.own, deep);
var fail_index: usize = 0;
while (true) : (fail_index += 1) {
try std.testing.expect(fail_index <= 64);
var old_fail: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = fail_index });
var new_fail: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = fail_index });
var old_nodes: AirConversionAllocations = .{ .backing = old_fail.allocator() };
defer old_nodes.deinit();
var new_nodes: AirConversionAllocations = .{ .backing = new_fail.allocator() };
defer new_nodes.deinit();
var original: Lowerer = .{ .arena = old_nodes.allocator(), .m = m };
var current: Lowerer = .{ .arena = new_nodes.allocator(), .m = m };
const before = ReferenceAirType.airType(&original, deep);
const after = current.airType(deep);
try std.testing.expectEqual(old_fail.has_induced_failure, new_fail.has_induced_failure);
if (new_fail.has_induced_failure) {
try std.testing.expectError(error.OutOfMemory, before);
try std.testing.expectError(error.OutOfMemory, after);
try std.testing.expect(current.property_module == null);
try std.testing.expect(current.problem == null);
} else {
try std.testing.expect((try before).eql(try after));
}
try std.testing.expectEqual(old_nodes.count, new_nodes.count);
for (old_nodes.nodes[0..old_nodes.count], new_nodes.nodes[0..new_nodes.count]) |old_node, new_node| {
try std.testing.expectEqual(old_node.length, new_node.length);
try std.testing.expectEqual(old_node.alignment, new_node.alignment);
}
try std.testing.expectEqual(old_fail.allocated_bytes, new_fail.allocated_bytes);
try std.testing.expectEqual(old_fail.allocations, new_fail.allocations);
old_nodes.deinit();
new_nodes.deinit();
try std.testing.expectEqual(old_fail.allocated_bytes, old_fail.freed_bytes);
try std.testing.expectEqual(new_fail.allocated_bytes, new_fail.freed_bytes);
if (!new_fail.has_induced_failure) break;
}
}
// Records direct node requests. Arena growth/resize decisions depend on the
// backing allocator and are not an oracle of constructor allocation order.
const AirConversionAllocations = struct {
backing: Allocator,
nodes: [128]struct { pointer: ?[*]u8, length: usize, alignment: std.mem.Alignment } = undefined,
count: usize = 0,
fn allocator(self: *@This()) Allocator {
return .{ .ptr = self, .vtable = &.{ .alloc = alloc, .resize = resize, .remap = remap, .free = free } };
}
fn alloc(raw: *anyopaque, length: usize, alignment: std.mem.Alignment, ret_addr: usize) ?[*]u8 {
const self: *@This() = @ptrCast(@alignCast(raw));
std.debug.assert(self.count < self.nodes.len);
const pointer = self.backing.rawAlloc(length, alignment, ret_addr);
self.nodes[self.count] = .{ .pointer = pointer, .length = length, .alignment = alignment };
self.count += 1;
return pointer;
}
fn resize(_: *anyopaque, _: []u8, _: std.mem.Alignment, _: usize, _: usize) bool {
return false;
}
fn remap(_: *anyopaque, _: []u8, _: std.mem.Alignment, _: usize, _: usize) ?[*]u8 {
return null;
}
fn free(_: *anyopaque, _: []u8, _: std.mem.Alignment, _: usize) void {
unreachable; // Type construction transfers nodes to the caller.
}
fn deinit(self: *@This()) void {
for (self.nodes[0..self.count]) |node| if (node.pointer) |ptr| self.backing.rawFree(ptr[0..node.length], node.alignment, @returnAddress());
self.count = 0;
}
};
// Independent pre-repair best-effort lookup, only for shallow test trees.
fn referenceTypeHint(l: *Lowerer, t: ast.Type) ?Ty {
return switch (t.kind) {
.name => |n| if (isIntName(n)) Ty{ .int = n } else if (std.mem.eql(u8, n, "bool")) .bool else if (std.meta.stringToEnum(authority.Builtin, n)) |b| Ty{ .builtin = b } else l.enumOrStruct(n, t.span),
.array => |a| blk: {
if (a.len == 0 or a.len > (@as(u64, 1) << 32)) break :blk null;
const elem = referenceTypeHint(l, a.elem.*) orelse break :blk null;
if (elem == .void or elem == .never) break :blk null;
break :blk l.arrayOf(elem, a.len) catch null;
},
else => null,
};
}
fn expectTypeHintMatches(l: *Lowerer, t: ast.Type) !void {
const before = referenceTypeHint(l, t);
const after = l.typeOfNoFail(t);
try std.testing.expectEqual(before == null, after == null);
if (before) |b| try std.testing.expect(b.eql(after.?));
try std.testing.expect(l.problem == null and l.unimpl == null);
}
test "best-effort source type lookup matches the shallow independent query" {
var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
const m = (try parse_mod.parse(a, "module hints\nstruct S { x: u8 }\nenum E { Some, None }\nfn main() -> void effects [] {}\n")).ok;
var l: Lowerer = .{ .arena = a, .m = m };
var leaves: std.ArrayList(ast.Type) = .empty;
const span: Span = .{ .start = .{ .line = 2, .col = 7 }, .end = .{ .line = 2, .col = 8 } };
for (int_types ++ [_][]const u8{ "bool", "S", "E", "alloc_error", "cap_error", "io_error", "void", "never", "region", "stream", "listener", "missing", "f32", "f64" }) |name| {
try leaves.append(a, .{ .span = span, .kind = .{ .name = name } });
}
const u8_type: ast.Type = .{ .span = span, .kind = .{ .name = "u8" } };
const wrappers = comptime std.meta.fieldNames(Lowerer.TypeWrapper) ++ [_][]const u8{"unknown"};
for (wrappers) |wrapper| {
try leaves.append(a, .{ .span = span, .kind = .{ .wrapped = .{ .wrapper = wrapper, .inner = &u8_type } } });
}
try leaves.appendSlice(a, &.{
.{ .span = span, .kind = .{ .cap = "mem.alloc" } },
.{ .span = span, .kind = .{ .file = "read" } },
.{ .span = span, .kind = .{ .applied = .{ .name = "S", .args = &.{u8_type} } } },
.{ .span = span, .kind = .{ .function_ref = .{ .name = "main" } } },
});
const lengths = [_]u64{ 0, 1, 7, @as(u64, 1) << 32, (@as(u64, 1) << 32) + 1, std.math.maxInt(u64) };
for (leaves.items) |*leaf| {
try expectTypeHintMatches(&l, leaf.*);
for (lengths) |length| {
const inner: ast.Type = .{ .span = span, .kind = .{ .array = .{ .elem = leaf, .len = length } } };
try expectTypeHintMatches(&l, inner);
for (lengths) |outer_length| {
try expectTypeHintMatches(&l, .{ .span = span, .kind = .{ .array = .{ .elem = &inner, .len = outer_length } } });
}
}
}
}
test "deep best-effort source type lookup owns output and rejects without allocation" {
var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
const m: ast.Module = .{ .name = "hints", .types = &.{}, .functions = &.{} };
const count = 65_536;
const nodes = try a.alloc(ast.Type, count + 1);
const span: Span = .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 2 } };
nodes[0] = .{ .span = span, .kind = .{ .name = "u8" } };
for (nodes[1..], 1..) |*node, i| node.* = .{ .span = span, .kind = .{ .array = .{ .elem = &nodes[i - 1], .len = i } } };
var allocations: std.testing.FailingAllocator = .init(std.testing.allocator, .{});
var l: Lowerer = .{ .arena = allocations.allocator(), .m = m };
var current = l.typeOfNoFail(nodes[count]).?;
var remaining: usize = count;
while (remaining != 0) : (remaining -= 1) {
try std.testing.expect(current == .array);
const node = current.array;
try std.testing.expectEqual(@as(u64, remaining), node.len);
current = node.elem;
// Only tests individually free nodes; production owns a caller arena.
allocations.allocator().destroy(node);
}
try std.testing.expectEqualStrings("u8", current.int);
try std.testing.expectEqual(@as(usize, count), allocations.allocations);
try std.testing.expectEqual(allocations.allocated_bytes, allocations.freed_bytes);
var no_alloc: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 0 });
var invalid: Lowerer = .{ .arena = no_alloc.allocator(), .m = m };
for ([_][]const u8{ "missing", "void", "never" }) |name| {
nodes[0].kind = .{ .name = name };
try std.testing.expect(invalid.typeOfNoFail(nodes[count]) == null);
}
nodes[0].kind = .{ .name = "u8" };
nodes[1].kind.array.len = 0;
try std.testing.expect(invalid.typeOfNoFail(nodes[count]) == null);
nodes[1].kind.array.len = (@as(u64, 1) << 32) + 1;
try std.testing.expect(invalid.typeOfNoFail(nodes[count]) == null);
try std.testing.expect(!no_alloc.has_induced_failure);
try std.testing.expect(invalid.problem == null and invalid.unimpl == null);
}
test "best-effort source type lookup preserves null on every allocation failure" {
var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
const m: ast.Module = .{ .name = "hints", .types = &.{}, .functions = &.{} };
const nodes = try a.alloc(ast.Type, 65);
const span: Span = .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 2 } };
nodes[0] = .{ .span = span, .kind = .{ .name = "u8" } };
for (nodes[1..], 1..) |*node, i| node.* = .{ .span = span, .kind = .{ .array = .{ .elem = &nodes[i - 1], .len = i } } };
for (0..65) |fail_index| {
var before_fail: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = fail_index });
var after_fail: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = fail_index });
var before_nodes: AirConversionAllocations = .{ .backing = before_fail.allocator() };
var after_nodes: AirConversionAllocations = .{ .backing = after_fail.allocator() };
var before: Lowerer = .{ .arena = before_nodes.allocator(), .m = m };
var after: Lowerer = .{ .arena = after_nodes.allocator(), .m = m };
const original = referenceTypeHint(&before, nodes[64]);
const current = after.typeOfNoFail(nodes[64]);
try std.testing.expectEqual(original == null, current == null);
try std.testing.expectEqual(fail_index < 64, current == null);
if (original) |ty| try std.testing.expect(ty.eql(current.?));
try std.testing.expectEqual(before_nodes.count, after_nodes.count);
for (before_nodes.nodes[0..before_nodes.count], after_nodes.nodes[0..after_nodes.count]) |old, new| {
try std.testing.expectEqual(old.length, new.length);
try std.testing.expectEqual(old.alignment, new.alignment);
}
try std.testing.expect(after.problem == null and after.unimpl == null);
before_nodes.deinit();
after_nodes.deinit();
try std.testing.expectEqual(before_fail.allocated_bytes, before_fail.freed_bytes);
try std.testing.expectEqual(after_fail.allocated_bytes, after_fail.freed_bytes);
}
}
// Independent pre-repair comparison, restricted to shallow test trees.
fn referenceSourceEquality(a: Ty, b: Ty) bool {
if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false;
return switch (a) {
.int => |x| std.mem.eql(u8, x, b.int),
.named => |i| i == b.named,
.array => |x| x.len == b.array.len and referenceSourceEquality(x.elem, b.array.elem),
.ref, .mut, .slice, .slice_mut, .own, .own_array, .buffer, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| referenceSourceEquality(x.*, Ty.inner(b).?),
.cap => |k| std.mem.eql(u8, k, b.cap),
.builtin => |e| e == b.builtin,
.resource => |r| r == b.resource,
else => true,
};
}
test "source equality matches the independent shallow comparison" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const m: ast.Module = .{ .name = "equality", .types = &.{}, .functions = &.{} };
var builder: Lowerer = .{ .arena = a, .m = m };
var leaves: std.ArrayList(Ty) = .empty;
for (int_types) |name| {
try leaves.append(a, .{ .int = name });
// Equal contents in different storage must still compare equal.
try leaves.append(a, .{ .int = try a.dupe(u8, name) });
}
try leaves.appendSlice(a, &.{ .bool, .void, .never, .region, .scope, .shield, .{ .named = 0 }, .{ .named = 123 } });
for (authority.kinds) |kind| {
try leaves.append(a, .{ .cap = kind.name });
try leaves.append(a, .{ .cap = try a.dupe(u8, kind.name) });
}
inline for (@typeInfo(authority.Builtin).@"enum".field_names) |name| try leaves.append(a, .{ .builtin = @field(authority.Builtin, name) });
inline for (@typeInfo(authority.Resource).@"enum".field_names) |name| try leaves.append(a, .{ .resource = @field(authority.Resource, name) });
var shapes: std.ArrayList(Ty) = .empty;
for (leaves.items) |leaf| {
try shapes.append(a, leaf);
for ([_]u64{ 0, 1, @as(u64, 1) << 32, std.math.maxInt(u64) }) |length| try shapes.append(a, try builder.arrayOf(leaf, length));
inline for (@typeInfo(Ty).@"union".field_names, @typeInfo(Ty).@"union".field_types) |name, FieldType| if (comptime FieldType == *const Ty) {
const tag = @field(std.meta.Tag(Ty), name);
try shapes.append(a, try builder.wrap(tag, leaf));
try shapes.append(a, try builder.arrayOf(try builder.wrap(tag, leaf), 123));
try shapes.append(a, try builder.wrap(tag, try builder.arrayOf(leaf, 456)));
};
}
for (shapes.items) |left| for (shapes.items) |right| {
try std.testing.expectEqual(referenceSourceEquality(left, right), left.eql(right));
};
}
test "source equality traverses deep trees and detects leaf, interior and outer mismatches" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const m: ast.Module = .{ .name = "equality", .types = &.{}, .functions = &.{} };
var builder: Lowerer = .{ .arena = a, .m = m };
const count = 65_536;
var left: Ty = .{ .int = "u8" };
var right: Ty = .{ .int = try a.dupe(u8, "u8") };
var wrong_leaf: Ty = .{ .int = "u16" };
var wrong_length: Ty = left;
var wrong_tag: Ty = left;
for (0..count) |i| {
if (i % 2 == 0) {
left = try builder.arrayOf(left, i + 1);
right = try builder.arrayOf(right, i + 1);
wrong_leaf = try builder.arrayOf(wrong_leaf, i + 1);
wrong_length = try builder.arrayOf(wrong_length, if (i == count / 2) i + 2 else i + 1);
wrong_tag = try builder.arrayOf(wrong_tag, i + 1);
} else {
left = try builder.wrap(.ref, left);
right = try builder.wrap(.ref, right);
wrong_leaf = try builder.wrap(.ref, wrong_leaf);
wrong_length = try builder.wrap(.ref, wrong_length);
wrong_tag = if (i == count / 2 + 1) try builder.wrap(.mut, wrong_tag) else try builder.wrap(.ref, wrong_tag);
}
}
try std.testing.expect(left.ref != right.ref);
try std.testing.expect(left.eql(right));
try std.testing.expect(right.eql(left));
for ([_]Ty{ wrong_leaf, wrong_length, wrong_tag, .bool, try builder.wrap(.mut, right.ref.*) }) |different| {
try std.testing.expect(!left.eql(different));
try std.testing.expect(!different.eql(left));
}
}
const ReferenceSourceLinear = struct {
fn isLinear(l: *Lowerer, t: Ty) bool {
if (t.isLinear()) return true;
return switch (t) {
.array => |a| isLinear(l, a.elem),
.named => |i| l.property_module.?.nominal_properties.?[i].linear,
else => false,
};
}
fn needsLinearType(l: *Lowerer, t: Ty, depth: usize) bool {
if (depth > l.m.types.len + 32) return false;
if (t == .named) return isLinear(l, t);
if (t.inner()) |inner| {
if ((t == .array or t == .own or t == .own_array or t == .slice or t == .slice_mut) and isLinear(l, inner)) return true;
return needsLinearType(l, inner, depth + 1);
}
return false;
}
};
fn expectSourceLinearMatches(l: *Lowerer, t: Ty) !void {
try std.testing.expectEqual(ReferenceSourceLinear.isLinear(l, t), l.isLinear(t));
for ([_]usize{ 0, 31, 32, 33, 34, 35, 64 }) |depth| try std.testing.expectEqual(ReferenceSourceLinear.needsLinearType(l, t, depth), l.needsLinearType(t, depth));
}
test "source linear queries preserve shallow classification and guard order" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
var l: Lowerer = .{ .arena = a, .m = (try parse_mod.parse(a, "module t\nstruct Plain { x: u8 }\nstruct Linear { x: own<u8> }\nfn main() -> void effects [] {}\n")).ok };
try l.checkRequirements();
var leaves: std.ArrayList(Ty) = .empty;
for (int_types) |name| try leaves.append(a, .{ .int = name });
try leaves.appendSlice(a, &.{ .bool, .void, .never, .region, .scope, .shield, .{ .named = 0 }, .{ .named = 1 } });
for (authority.kinds) |kind| try leaves.append(a, .{ .cap = kind.name });
inline for (@typeInfo(authority.Builtin).@"enum".field_names) |name| try leaves.append(a, .{ .builtin = @field(authority.Builtin, name) });
inline for (@typeInfo(authority.Resource).@"enum".field_names) |name| try leaves.append(a, .{ .resource = @field(authority.Resource, name) });
for (leaves.items) |leaf| {
try expectSourceLinearMatches(&l, leaf);
for ([_]u64{ 0, 1, @as(u64, 1) << 32, std.math.maxInt(u64) }) |length| try expectSourceLinearMatches(&l, try l.arrayOf(leaf, length));
inline for (@typeInfo(Ty).@"union".field_names, @typeInfo(Ty).@"union".field_types) |name, FieldType| if (comptime FieldType == *const Ty) {
const tag = @field(std.meta.Tag(Ty), name);
try expectSourceLinearMatches(&l, try l.wrap(tag, leaf));
try expectSourceLinearMatches(&l, try l.arrayOf(try l.wrap(tag, leaf), 123));
try expectSourceLinearMatches(&l, try l.wrap(tag, try l.arrayOf(leaf, 456)));
};
var chain = leaf;
for (0..41) |_| {
try expectSourceLinearMatches(&l, chain);
chain = try l.wrap(.ref, chain);
}
}
// Guard before a named leaf; a qualifying parent's content query still
// precedes advancing the guard, even if that child would exceed it.
try std.testing.expect(l.needsLinearType(.{ .named = 1 }, 34));
try std.testing.expect(!l.needsLinearType(.{ .named = 1 }, 35));
try std.testing.expect(l.needsLinearType(try l.arrayOf(.{ .named = 1 }, 1), 34));
try std.testing.expect(!l.needsLinearType(try l.arrayOf(.{ .named = 1 }, 1), 35));
try std.testing.expect(!l.needsLinearType(try l.wrap(.own, .{ .int = "u8" }), 0));
}
test "source linear queries walk deep arrays and module-sized feature guards" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const initial = (try parse_mod.parse(a, "module t\nstruct Plain { x: u8 }\nstruct Linear { x: own<u8> }\nfn main() -> void effects [] {}\n")).ok;
const count = 65_536;
const declarations = try a.alloc(ast.TypeDecl, count);
@memcpy(declarations[0..2], initial.types);
for (declarations[2..], 2..) |*d, i| d.* = .{ .name = try std.fmt.allocPrint(a, "Padding{d}", .{i}), .span = initial.types[0].span, .kind = .{ .@"struct" = &.{} } };
var m = initial;
m.types = declarations;
var l: Lowerer = .{ .arena = a, .m = m };
// Construct a complete immutable property snapshot, not a forged cache.
// This is a helper-stage fixture, not a complete CLI acceptance claim.
try l.checkRequirements();
var plain: Ty = .{ .named = 0 };
var linear: Ty = .{ .named = 1 };
var borrowed: Ty = .{ .named = 1 };
for (0..count) |_| {
plain = try l.arrayOf(plain, 1);
linear = try l.arrayOf(linear, 1);
borrowed = try l.wrap(.ref, borrowed);
}
try std.testing.expect(!l.isLinear(plain));
try std.testing.expect(l.isLinear(linear));
try std.testing.expect(!l.isLinear(borrowed));
try std.testing.expect(l.needsLinearType(borrowed, 0));
try std.testing.expect(l.needsLinearType(borrowed, 32));
try std.testing.expect(!l.needsLinearType(borrowed, 33));
try std.testing.expect(!l.needsLinearType(.{ .named = 1 }, count + 33));
}
// Independent original SSA zero lowering, used only on shallow test types.
const ReferenceSourceZero = struct {
fn zeroValue(l: *Lowerer, ty: Ty, base: []const u8, span: Span) Error!Value {
return switch (ty) {
.int => |n| l.def(base, ty, try l.fmt("const.{s} 0", .{n}), span),
.bool => l.def(base, ty, "const.bool false", span),
.array => |a| blk: {
const z = try zeroValue(l, a.elem, base, span);
break :blk l.def(base, ty, try l.fmt("array.splat {s} %{s}", .{ try l.tyText(ty), z.name }), span);
},
else => l.invalid(.zero_not_zeroable, span, "`zero` needs a zeroable type (integers, booleans, arrays of them)", &.{}),
};
}
};
fn expectSourceZeroMatches(a: Allocator, ty: Ty) !void {
const m: ast.Module = .{ .name = "zero", .types = &.{}, .functions = &.{} };
const span: Span = .{ .start = .{ .line = 7, .col = 9 }, .end = .{ .line = 7, .col = 26 } };
const boolean: ast.Type = .{ .span = span, .kind = .{ .name = "bool" } };
const params = [_]ast.Param{ .{ .name = "z_1", .ty = boolean, .span = span }, .{ .name = "z_3", .ty = boolean, .span = span } };
var old: Lowerer = .{ .arena = a, .m = m, .params = &params, .in_constant = 12 };
var current: Lowerer = .{ .arena = a, .m = m, .params = &params, .in_constant = 12 };
old.cur = try old.newBlock("entry", span);
current.cur = try current.newBlock("entry", span);
const before = ReferenceSourceZero.zeroValue(&old, ty, "z", span);
const after = current.zeroValue(ty, "z", span);
if (before) |value| {
const result = try after;
try std.testing.expectEqualStrings(value.name, result.name);
try std.testing.expect(value.ty.eql(result.ty));
if (ty == .array) try std.testing.expect(ty.array == result.ty.array);
} else |err| try std.testing.expectError(err, after);
try std.testing.expectEqualDeep(old.problem, current.problem);
try std.testing.expectEqualDeep(old.blocks.items[0].insts.items, current.blocks.items[0].insts.items);
try std.testing.expectEqual(old.counter, current.counter);
try std.testing.expectEqualDeep(old.uses, current.uses);
}
test "source SSA zero retains shallow instructions, names, types and errors" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
var l: Lowerer = .{ .arena = a, .m = .{ .name = "zero", .types = &.{}, .functions = &.{} } };
var leaves: std.ArrayList(Ty) = .empty;
for (int_types) |name| try leaves.append(a, .{ .int = name });
try leaves.appendSlice(a, &.{ .bool, .void, .never, .region, .scope, .shield, .{ .named = 0 }, .{ .named = 123 } });
for (authority.kinds) |kind| try leaves.append(a, .{ .cap = kind.name });
inline for (@typeInfo(authority.Builtin).@"enum".field_names) |name| try leaves.append(a, .{ .builtin = @field(authority.Builtin, name) });
inline for (@typeInfo(authority.Resource).@"enum".field_names) |name| try leaves.append(a, .{ .resource = @field(authority.Resource, name) });
inline for (@typeInfo(Ty).@"union".field_names, @typeInfo(Ty).@"union".field_types) |name, FieldType| if (comptime FieldType == *const Ty) try leaves.append(a, try l.wrap(@field(std.meta.Tag(Ty), name), .bool));
for (leaves.items) |leaf| {
try expectSourceZeroMatches(a, leaf);
for ([_]u64{ 0, 1, @as(u64, 1) << 32, std.math.maxInt(u64) }) |length| {
try expectSourceZeroMatches(a, try l.arrayOf(leaf, length));
try expectSourceZeroMatches(a, try l.arrayOf(try l.arrayOf(leaf, length), 7));
}
}
}
test "source SSA zero rejects deep unsupported leaves without traversal allocation" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const m: ast.Module = .{ .name = "zero", .types = &.{}, .functions = &.{} };
var builder: Lowerer = .{ .arena = a, .m = m };
var ty: Ty = .{ .named = 0 };
for (0..65_536) |_| ty = try builder.arrayOf(ty, 1);
var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 0 });
var l: Lowerer = .{ .arena = failing.allocator(), .m = m };
const span: Span = .{ .start = .{ .line = 3, .col = 31 }, .end = .{ .line = 3, .col = 100 } };
try std.testing.expectError(error.Lower, l.zeroValue(ty, "z", span));
try std.testing.expectEqualStrings("E7006", l.problem.?.code);
try std.testing.expectEqual(InvalidReason.zero_not_zeroable, l.problem.?.reason.?);
try std.testing.expectEqual(span, l.problem.?.span);
try std.testing.expectEqual(@as(usize, 0), l.problem.?.fields.len);
try std.testing.expectEqual(@as(usize, 0), l.blocks.items.len);
try std.testing.expectEqual(@as(usize, 0), l.counter);
try std.testing.expect(!failing.has_induced_failure);
try std.testing.expectEqual(@as(usize, 0), failing.allocated_bytes);
}
test "source SSA zero emits every supported array in inner-to-outer order" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
var l: Lowerer = .{ .arena = a, .m = .{ .name = "zero", .types = &.{}, .functions = &.{} } };
const span: Span = .{ .start = .{ .line = 2, .col = 3 }, .end = .{ .line = 2, .col = 9 } };
var ty: Ty = .{ .int = "u8" };
const count = 1024;
for (0..count) |i| ty = try l.arrayOf(ty, i + 1);
l.cur = try l.newBlock("entry", span);
const value = try l.zeroValue(ty, "z", span);
try std.testing.expect(value.ty.array == ty.array);
try std.testing.expectEqualStrings("z_1025", value.name);
const instructions = l.blocks.items[0].insts.items;
try std.testing.expectEqual(@as(usize, count + 1), instructions.len);
try std.testing.expectEqualStrings("%z_1 = const.u8 0", instructions[0].text);
var expected_type: []const u8 = "u8";
for (instructions[1..], 0..) |inst, i| {
expected_type = try std.fmt.allocPrint(a, "array<{s}, {d}>", .{ expected_type, i + 1 });
const expected = try std.fmt.allocPrint(a, "%z_{d} = array.splat {s} %z_{d}", .{ i + 2, expected_type, i + 1 });
try std.testing.expectEqualStrings(expected, inst.text);
}
for (instructions) |inst| {
try std.testing.expectEqual(@as(?Span, span), inst.span);
try std.testing.expectEqual(@as(u32, 0), inst.constant);
}
}
test "source SSA zero OOM propagates with complete instruction prefixes and arena cleanup" {
var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
const m: ast.Module = .{ .name = "zero", .types = &.{}, .functions = &.{} };
const span: Span = .{ .start = .{ .line = 2, .col = 3 }, .end = .{ .line = 2, .col = 9 } };
var builder: Lowerer = .{ .arena = a, .m = m };
var ty: Ty = .bool;
for (0..64) |i| ty = try builder.arrayOf(ty, i + 1);
builder.cur = try builder.newBlock("entry", span);
_ = try ReferenceSourceZero.zeroValue(&builder, ty, "z", span);
const expected = builder.blocks.items[0].insts.items;
var fail_index: usize = 0;
while (true) : (fail_index += 1) {
try std.testing.expect(fail_index < 100);
var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = fail_index });
var arena: std.heap.ArenaAllocator = .init(failing.allocator());
var l: Lowerer = .{ .arena = arena.allocator(), .m = m };
const result: Error!Value = blk: {
l.cur = l.newBlock("entry", span) catch |err| break :blk err;
break :blk l.zeroValue(ty, "z", span);
};
if (failing.has_induced_failure) {
try std.testing.expectError(error.OutOfMemory, result);
try std.testing.expect(l.problem == null);
} else {
try std.testing.expect((try result).ty.eql(ty));
try std.testing.expectEqual(@as(usize, 65), l.blocks.items[0].insts.items.len);
}
if (l.cur) |index| {
const actual = l.blocks.items[index].insts.items;
try std.testing.expect(actual.len <= expected.len);
try std.testing.expectEqualDeep(expected[0..actual.len], actual);
}
try std.testing.expectEqual(@as(usize, 0), l.out.items.len);
arena.deinit();
try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes);
if (!failing.has_induced_failure) break;
}
}