//! 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`, //! 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. 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 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, region, /// `cap`: the kind. cap: []const u8, /// A built-in enum (`alloc_error`, `cap_error`, `io_error`). builtin: authority.Builtin, /// `file`, `stream`, `listener`. resource: authority.Resource, /// `task`, `sender`, `receiver`: 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, 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, .region, .resource, .task, .sender, .receiver, .scope => true, else => false, }; } fn eql(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 x.elem.eql(b.array.elem), .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver => |x| x.eql(inner(b).?), .cap => |k| std.mem.eql(u8, k, b.cap), .builtin => |e| e == b.builtin, .resource => |r| r == b.resource, else => true, }; } fn inner(t: Ty) ?Ty { return switch (t) { .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver => |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" }; 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 Problem = struct { code: []const u8, span: Span, message: []const u8, fields: []const Field = &.{}, 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 (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, /// 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 .{ .err = 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, 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` 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 }; 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, 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, /// 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 s { … }` just before lowering its body: a binding and an /// end that belong to the body's own lexical scope. pending_entry: ?struct { binding: Binding, end: BorrowEnd } = null, /// 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, fn fail(l: *Lowerer, code: []const u8, span: Span, message: []const u8, fields: []const Problem.Field) Error { // `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 notYet(l: *Lowerer, span: Span, construct: []const u8) Error { l.unimpl = .{ .span = span, .construct = construct }; return error.Unimplemented; } fn tyText(l: *Lowerer, t: Ty) []const u8 { return switch (t) { .int => |x| x, .bool => "bool", .void => "void", .never => "never", .named => |i| l.typeNames[i], .array => |a| std.fmt.allocPrint(l.arena, "array<{s}, {d}>", .{ l.tyText(a.elem), a.len }) catch "array", .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver => |x| std.fmt.allocPrint(l.arena, "{s}<{s}>", .{ @tagName(t), l.tyText(x.*) }) catch "borrow", .scope => "scope", .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 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, " ")) { 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.fail("E7006", t.span, "type defined twice", &.{.{ .name = "name", .value = t.name }}); n.* = try l.fmt("@{s}", .{t.name}); } l.typeNames = names; for (l.m.functions) |f| { if (l.sigs.contains(f.name)) return l.fail("E7006", 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); try l.sigs.put(l.arena, f.name, .{ .params = ps, .ret = try l.typeOf(f.ret) }); } 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 }); for (l.m.functions) |f| try l.fns.append(l.arena, try l.function(f)); 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); } /// 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, 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"); 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<" } }, .{ "heap", &.{ "own.", "own<", "own_array<", "alloc_error" } }, .{ "regions", &.{"region"} }, .{ "capabilities", &.{ "cap<", "cap.narrow", "cap_error" } }, .{ "tasks", &.{ "task.", "task<", ": scope" } }, .{ "channels", &.{ "channel.", "sender<", "receiver<" } }, }; 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.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.fail("E7006", 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, l.tyText(ft) })); } try w.appendSlice(l.arena, if (fields.len == 0) "}" else " }"); }, .@"enum" => |vs| { if (vs.len == 0) return l.fail("E7006", 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.fail("E7006", 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 ", ", 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 { const ty = try l.typeOf(t); if (ty == .void or ty == .never) return l.fail("E7005", t.span, "a field or payload needs a value type", &.{}); return ty; } fn typeOf(l: *Lowerer, t: ast.Type) Error!Ty { switch (t.kind) { .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; for (l.m.types, 0..) |d, i| if (std.mem.eql(u8, d.name, n)) return .{ .named = @intCast(i) }; 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| return l.arrayOf(try l.memberType(a.elem.*), a.len), .wrapped => |w| { const Wr = enum { ref, mut, slice, slice_mut, own, own_array, task, sender, receiver }; const which = std.meta.stringToEnum(Wr, w.wrapper) orelse return l.notYet(t.span, "this type (later layers)"); const in = try l.typeOf(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), .task => l.wrap(.task, in), .sender => l.wrap(.sender, in), .receiver => l.wrap(.receiver, in), }; }, .cap => |k| { if (authority.kindIndex(k) == null) return l.fail("E7002", t.span, "unknown capability kind", &.{.{ .name = "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 }; }, } } // ------------------------------------------------------------ functions 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.counter = 0; l.params = f.params; try l.findAddressable(f.body); const sig = l.sigs.get(f.name).?; l.ret = sig.ret; if (f.from != null) return l.notYet(f.span, "borrow returns (layer 4)"); // `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.fail("E7006", 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}(", .{f.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, l.tyText(t) })); } try header.appendSlice(l.arena, try l.fmt(") -> {s}", .{l.tyText(sig.ret)})); _ = try l.newBlock("entry"); 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.fail("E7006", 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.fail("E7006", 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, l.tyText(p.ty) })); try head.append(l.arena, ')'); } try head.appendSlice(l.arena, ":"); try l.line(head.items, null); 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) 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 }); return l.blocks.items.len - 1; } fn emit(l: *Lowerer, text: []const u8, span: Span) Error!void { const b = &l.blocks.items[l.cur.?]; 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 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) Error![]const usize { var out: std.ArrayList(usize) = .empty; for (try l.carried(depth)) |i| if (l.liveAfter(l.bindings.items[i].name, 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; for (try l.carried(depth)) |i| { const n = l.bindings.items[i].name; if (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_entry) |pe| { l.pending_entry = null; try l.bindings.append(l.arena, pe.binding); try l.scopes.items[l.scopes.items.len - 1].append(l.arena, pe.end); } for (b.stmts, 0..) |s, i| { if (l.cur == null) return l.fail("E7006", 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.fail("E7006", 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; result = try l.expr(t.*, want); if (result.?.ty.isBorrow()) return l.fail("E7006", 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) try l.endScopes(l.scopes.items.len - 1, b.span); 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 { 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; 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 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| { if (x.names.len == 2) return l.splitLet(s, x.names, x.e); if (x.e.kind == .borrow) return l.fail("E7006", 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 = if (x.ty) |t| try l.typeOf(t) else null; // 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.fail("E7006", x.e.span, "bind a borrow with `ref name = place;` or `mut name = place;`", &.{}); if (l.addressable.contains(x.names[0])) { 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.fail("E7006", s.span, "a `var` holds a value; bind a borrow with `ref` or `mut`", &.{}); if (l.addressable.contains(x.name)) { 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); 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.fail("E7006", 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.fail("E7006", 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) { 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.fail("E7006", s.span, "a borrow of this name is already active in this scope", &.{.{ .name = "name", .value = x.name }}); const p = try l.uncheckedPlace(x.place, x.mutable, x.unchecked, s.span); if (p.ends.len == 0) { // Borrowing a borrow binding: a reborrow, ended at scope end. const rb = try l.def(x.name, p.v.ty, try l.fmt("{s} %{s}", .{ if (x.mutable) "borrow.mut" else "borrow.ref", 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.consuming(x, l.ret); try l.checkTy(x.span, v.ty, l.ret); if (l.cur != null) { try l.endScopes(0, s.span); 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 = l.tyText(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.fail("E7006", 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); _ = v; }, .@"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); l.pending_entry = .{ .binding = .{ .name = x.name, .mutable = false, .value = sv.name, .ty = .scope }, .end = .{ .name = sv.name, .span = x.body.span, .op = "task.scope.end" } }; _ = try l.blockBody(x.body); }, .shield => return l.notYet(s.span, "`shield` (layer 8)"), .lock => return l.notYet(s.span, "`lock` (layer 8)"), .select => return l.notYet(s.span, "`select` (layer 8)"), } } 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 = l.tyText(want) }, .{ .name = "found", .value = l.tyText(found) } }); } /// `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); const header = try l.newBlock(if (cond == null) "loop" else "while"); const exit = try l.newBlock("after"); const cont = if (step != null) try l.newBlock("step") 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.checkTy(c.span, cv.ty, .bool); const body_b = try l.newBlock("body"); 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", .{l.tyText(i.ty)}), st.span); const next = try l.def(st.name, i.ty, try l.fmt("add.checked.{s} %{s}, %{s}", .{ 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 = l.tyText(ty) }}); const a = try l.expr(lo, ty); try l.checkTy(lo.span, a.ty, ty); const b = try l.expr(hi, ty); try l.checkTy(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 peekType(l: *Lowerer, e: ast.Expr) ?Ty { return switch (e.kind) { .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, .neg => |x| l.peekType(x.*), .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.sigs.get(n)) |sig| sig.ret else null, .variant => |v| l.enumType(v.@"enum"), 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"), .struct_lit => |x| l.enumOrStruct(x.name), .field => |x| blk: { if (std.mem.eql(u8, x.name, "len")) break :blk Ty{ .int = "usize" }; var base = l.peekType(x.e.*) 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: { if (x.callee.kind != .name) break :blk null; const sig = l.sigs.get(x.callee.kind.name) 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, 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 l.enumOrStruct(n), else => null, }; } fn enumOrStruct(l: *Lowerer, n: []const u8) ?Ty { 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) ?Ty { const t = l.enumOrStruct(n) 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) { .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 = l.tyText(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 = l.lookup(n) orelse return l.unknown(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 }; }, .deref => |x| { const r = try l.expr(x.*, null); const in = r.ty.inner() orelse return l.fail("E7005", e.span, "`*` reads through a borrow", &.{.{ .name = "found", .value = l.tyText(r.ty) }}); if (r.ty == .slice or r.ty == .slice_mut or in == .array) return l.fail("E7006", e.span, "read slice and array elements with `s[i]`, not `*`", &.{}); return l.def("v", in, try l.fmt("load %{s}", .{r.name}), e.span); }, .index => |x| { if (x.hi != null) return l.fail("E7006", 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_rep => |x| { 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); if (v.ty.isBorrow()) return l.fail("E7006", x.e.span, "an array element cannot be a borrow", &.{}); const at = try l.arrayOf(v.ty, x.len); return l.def("arr", at, try l.fmt("array.splat {s} %{s}", .{ l.tyText(at), v.name }), e.span); }, .bytes => return l.fail("E7006", 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.fail("E7006", e.span, "`ref`/`mut` here: borrows are bound with `ref name = place;` / `mut name = place;` or passed as arguments", &.{}), .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", &.{}); // `-literal` is the negative literal. 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 l.expr(x.*, ty); try l.checkTy(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); }, .not => |x| { const v = try l.expr(x.*, .bool); try l.checkTy(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); }, .binary => |x| return l.binary(e, x.op, x.l.*, x.r.*, want), .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 l.expr(x.e.*, from); 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); }, .call => |x| return l.call(e, x.callee.*, x.args), .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 = l.lookup(n) orelse return l.unknown(e.span, n); if (!b.ty.isLinear()) return l.fail("E7006", e.span, "`move` applies to linear values; copyable values are passed plainly", &.{ .{ .name = "name", .value = n }, .{ .name = "type", .value = l.tyText(b.ty) } }); return .{ .name = b.value, .ty = b.ty }; }, } } 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.checkTy(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"); const join = try l.newBlock(if (op == .@"and") "and_end" else "or_end"); 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.checkTy(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.checkTy(a.span, lv.ty, ty); const rv = try l.expr(b, ty); try l.checkTy(b.span, rv.ty, ty); 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 = 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) Error!Value { if (callee.kind == .variant) return l.variantValue(e, callee.kind.variant.@"enum", callee.kind.variant.name, args); if (pathOf(callee)) |p| { if (std.mem.eql(u8, p, "slice.copy")) return l.sliceCopy(e, args); if (l.fallible(p) != null) return l.fail("E7006", 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`", &.{.{ .name = "found", .value = l.tyText(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); 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 = l.tyText(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 (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.fail("E7006", 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.checkTy(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.checkTy(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.sigs.get(name) 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 = name }, .{ .name = "expected", .value = try l.fmt("{d}", .{sig.params.len}) }, .{ .name = "found", .value = try l.fmt("{d}", .{args.len}) } }); 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); try l.checkTy(a.span, 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})", .{ name, arg_names.items }); defer l.endNowIfLive(temps.items, e.span) catch {}; 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 }; } return .{ .name = "", .ty = .void }; } return l.def(name, sig.ret, text, e.span); } /// `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) 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 = 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.fail("E7006", 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 = 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.fail("E7006", e.span, "missing field", &.{ .{ .name = "type", .value = name }, .{ .name = "field", .value = f.name } }); const ft = try l.typeOf(f.ty); const v = try l.expr(fi.e, ft); try l.checkTy(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})", .{ name, 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) orelse return l.fail("E7002", e.span, "unknown enum", &.{.{ .name = "name", .value = enum_name }}); 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.expr(a, ty); try l.checkTy(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})", .{ enum_name, 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 = l.tyText(bt) }}); if (d.kind != .@"struct") return l.fail("E7005", e.span, "field access on an enum; use `match`", &.{.{ .name = "type", .value = 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.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.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, 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 = l.tyText(prev) }, .{ .name = "found", .value = l.tyText(vt) } }); } else result_ty = vt; }; if (result_ty == null) { l.cur = null; return .{ .name = "", .ty = .never }; } const join = try l.newBlock(join_kind); 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.expr(m.scrutinee, st); const depth = l.bindings.items.len; const vars = try l.carriedLive(depth, m.span); 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.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("enum.switch @{s} %{s}", .{ d.name, sv.name })); for (m.arms, blocks, 0..) |arm, *blk, i| { if (arm.pattern.kind != .ctor or arm.pattern.kind.ctor.qualifier == null) return l.fail("E7006", arm.pattern.span, "an arm of a `match` over an enum names one variant as `Enum::Variant`; `_` is not allowed", &.{.{ .name = "enum", .value = d.name }}); const c = arm.pattern.kind.ctor; if (!std.mem.eql(u8, c.qualifier.?, d.name)) return l.fail("E7005", arm.pattern.span, "variant of a different enum", &.{ .{ .name = "expected", .value = 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.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.fail("E7006", 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})); 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 = l.tyText(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.fail("E7006", arm.pattern.span, "`_` given twice", &.{}); default = i; blk.* = try l.newBlock("case_default"); }, .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 bits: u128 = if (neg) (0 -% mag) else mag; for (seen.items) |prev| if (prev == bits) return l.fail("E7006", arm.pattern.span, "integer matched twice", &.{.{ .name = "value", .value = text }}); try seen.append(l.arena, bits); blk.* = try l.newBlock("case"); try head.appendSlice(l.arena, try l.fmt("{s} -> @{s}(), ", .{ text, 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); 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.fail("E7006", 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.fail("E7006", arm.pattern.span, "variant matched twice", &.{.{ .name = "variant", .value = c.name }}); blk.* = try l.newBlock(try l.fmt("case_{s}", .{c.name})); 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, "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 (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 and args[1].kind == .name) { const sig = l.sigs.get(args[1].kind.name) 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, l.tyText(ty) }), .span = span }); return st; } 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 l.zeroValue(a.elem, base, span); break :blk l.def(base, ty, try l.fmt("array.splat {s} %{s}", .{ l.tyText(ty), z.name }), span); }, else => l.fail("E7006", span, "`zero` needs a zeroable type (integers, booleans, arrays of them)", &.{}), }; } /// 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.fail("E7006", 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.def("w", try l.wrap(.mut, ty), try l.fmt("borrow.mut %{s}", .{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.def("e", try l.wrap(.mut, .{ .int = "u8" }), try l.fmt("borrow.index %{s}, %{s}", .{ b.name, idx.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 }; } /// 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| { const p = try l.uncheckedPlace(x.place.*, x.mutable, x.unchecked, a.span); if (p.ends.len == 0) { const rb = try l.def("b", p.v.ty, try l.fmt("{s} %{s}", .{ if (x.mutable) "borrow.mut" else "borrow.ref", 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.def("b", try l.wrap(.ref, st.ty), try l.fmt("borrow.ref %{s}", .{st.name}), a.span); const sl = try l.def("s", try l.wrap(.slice, .{ .int = "u8" }), try l.fmt("slice.make %{s}", .{r.name}), a.span); try temps.appendSlice(l.arena, &.{ r.name, sl.name }); return sl; }, else => return l.consuming(a, want), } } /// 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) if (l.lookup(e.kind.name)) |b| if (b.ty.isLinear() 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, span: Span) Error!Placed { if (!unchecked) return l.placeBorrow(place, mutable, true, span); if (place.kind != .index or place.kind.index.hi != null) return l.fail("E7006", place.span, "`unchecked` applies to one element `s[i]`", &.{}); l.unchecked = true; defer l.unchecked = false; return l.placeBorrow(place, mutable, true, 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 { var p = try l.placeRaw(place, mutable, span); 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.def("s", (if (mutable) try l.wrap(.slice_mut, elem) else try l.wrap(.slice, elem)), try l.fmt("slice.make %{s}", .{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) { .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.*), .region => if (mutable) try l.wrap(.mut, .region) else try l.wrap(.ref, .region), .resource => if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty), else => null, }; const t = bt orelse return l.fail("E7006", 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 = l.tyText(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.name }, .{ .name = "field", .value = f.name } }); const ft = try l.typeOf(fd.ty); const v = try l.def(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.name, f.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 = l.tyText(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.def("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}), span); ends = try l.concat(ends, sl.name); } const a = try l.expr(x.lo.*, .{ .int = "usize" }); try l.checkTy(x.lo.span, a.ty, .{ .int = "usize" }); const b = try l.expr(hi.*, .{ .int = "usize" }); try l.checkTy(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.def("s", sl.ty, try l.fmt("slice.sub %{s}, %{s}, %{s}", .{ sl.name, a.name, len.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.checkTy(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.def("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 }), span); return .{ .v = v, .ends = try l.concat(base.ends, v.name) }; }, else => return l.fail("E7006", 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.fail("E7006", place.span, "cannot assign to this expression", &.{}), } if (place.kind == .index and place.kind.index.hi != null) return l.fail("E7006", 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 v = try l.expr(value, l.placeType(place)); 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.fail("E7006", place.span, "write array elements with `s[i] = …`", &.{}); try l.checkTy(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, }; } /// `x.len`: `slice.len` of a slice, the static length of an array. 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", &.{}); 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 = l.tyText(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 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.fail("E7006", 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 = l.tyText(p.v.ty) }}); const k = try l.expr(e.kind.call.args[0], .{ .int = "usize" }); try l.checkTy(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.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); 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.markBlock(body); } fn markBlock(l: *Lowerer, b: ast.Block) Error!void { for (b.stmts) |s| try l.markStmt(s); if (b.tail) |t| try l.markExpr(t.*); } fn markRoot(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 l.markExpr(i.lo.*); if (i.hi) |h| try l.markExpr(h.*); x = i.e.*; }, else => return l.markExpr(x), }; } fn markStmt(l: *Lowerer, s: ast.Stmt) Error!void { switch (s.kind) { .let => |x| try l.markExpr(x.e), .@"var" => |x| if (x.init) |e| try l.markExpr(e), .assign => |x| { if (x.place.kind != .name) try l.markRoot(x.place); try l.markExpr(x.e); }, .borrow => |x| try l.markRoot(x.place), .@"return" => |e| if (e) |x| try l.markExpr(x), .expr => |e| try l.markExpr(e), .@"while" => |x| { try l.markExpr(x.cond); try l.markBlock(x.body); }, .@"for" => |x| { try l.markExpr(x.lo); try l.markExpr(x.hi); try l.markBlock(x.body); }, .loop, .shield => |b| try l.markBlock(b), .scope => |x| try l.markBlock(x.body), .lock => |x| { try l.markBlock(x.body); try l.markBlock(x.cancelled); }, else => {}, } } fn markExpr(l: *Lowerer, e: ast.Expr) Error!void { switch (e.kind) { .borrow => |x| try l.markRoot(x.place.*), .index => try l.markRoot(e), .neg, .not, .deref, .or_trap => |x| try l.markExpr(x.*), .binary => |x| { try l.markExpr(x.l.*); try l.markExpr(x.r.*); }, .cast => |x| try l.markExpr(x.e.*), .call => |x| { try l.markExpr(x.callee.*); for (x.args) |a| try l.markExpr(a); if (x.callee.kind == .field and std.mem.eql(u8, x.callee.kind.field.name, "split_at")) try l.markRoot(x.callee.kind.field.e.*); }, .field => |x| try l.markExpr(x.e.*), .struct_lit => |x| for (x.fields) |f| try l.markExpr(f.e), .array_rep => |x| try l.markExpr(x.e.*), .if_expr => |x| { try l.markExpr(x.cond); try l.markBlock(x.then); if (x.@"else") |els| switch (els) { .block => |b| try l.markBlock(b), .@"if" => |inner| try l.markExpr(.{ .span = e.span, .kind = .{ .if_expr = inner } }), }; }, .match_expr => |x| { try l.markExpr(x.scrutinee); for (x.arms) |a| try l.markExpr(a.body); }, .block => |b| try l.markBlock(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, temps: []const []const u8 = &.{} }; fn fallible(l: *Lowerer, path: []const u8) ?void { _ = l; const ops = [_][]const u8{ "own.new", "own.array", "region.create", "region.new", "region.array", "cap.narrow.budget", "cap.narrow.prefix", "channel.make", "channel.send", "channel.recv", "channel.close_receiver" }; 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) 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.fail("E7006", 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 = l.tyText(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 = l.tyText(sb.ty) }}); const scope_name = sb.value; if (args[1].kind != .name) return l.fail("E7005", args[1].span, "the function to spawn is named", &.{}); const fname = args[1].kind.name; const sig = l.sigs.get(fname) orelse return l.unknown(args[1].span, fname); const fargs = args[2..]; if (fargs.len != sig.params.len) return l.fail("E7005", e.span, "wrong number of arguments", &.{ .{ .name = "function", .value = fname }, .{ .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.fail("E7006", 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.checkTy(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, fname, 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`", &.{.{ .name = "found", .value = l.tyText(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`", &.{.{ .name = "found", .value = l.tyText(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, "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`", &.{.{ .name = "found", .value = l.tyText(tx.ty) }}); try l.emit(try l.fmt("channel.close_sender %{s}", .{tx.name}), e.span); return .{ .name = "", .ty = .void }; } return null; } 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 = l.tyText(want) }, .{ .name = "found", .value = l.tyText(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 = l.tyText(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.fail("E7006", 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 = l.tyText(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 = l.tyText(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` borrow binding", &.{}); } fn lowerFallible(l: *Lowerer, e: ast.Expr) Error!Fallible { if (e.kind != .call) return l.fail("E7006", e.span, "outcome arms (`ok`, `err`, …) belong to a fallible operation", &.{}); if (laterLayer(e.kind.call.callee.*)) return l.notYet(e.span, "this operation (layer 8)"); const path = pathOf(e.kind.call.callee.*) orelse return l.fail("E7006", 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, "own.new")) { try want(l, e.span, args, 2, path); const v = try l.consuming(args[0], null); 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.checkTy(args[0].span, n.ty, usize_ty); const v = try l.consuming(args[1], null); 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.consuming(args[1], null); return .{ .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.checkTy(args[1].span, n.ty, usize_ty); const v = try l.consuming(args[2], null); return .{ .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.fail("E7006", 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, "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(n, mem)`", &.{}); const et = try l.memberType(ta); const n = try l.expr(args[0], usize_ty); try l.checkTy(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}", .{ 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.checkTy(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`", &.{.{ .name = "found", .value = l.tyText(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 = l.tyText(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 = l.tyText(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 = l.tyText(c.ty) }}); const n = try l.expr(args[1], usize_ty); try l.checkTy(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.fail("E7006", 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 `, 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); for (o.params) |pt| try l.blocks.items[b.*].params.append(l.arena, .{ .name = try l.freshName(o.role), .ty = pt }); 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.fail("E7006", 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.fail("E7006", 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); 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.fail("E7006", 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.checkTy(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.checkTy(x.cond.span, cv.ty, .bool); const depth = l.bindings.items.len; const vars = try l.carriedLive(depth, span); const then_b = try l.newBlock("then"); const else_b = try l.newBlock("else"); 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 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, }; } /// `task.check_cancel`, `task.join_cancel`, `mutex.*`: operations of layer 8. fn laterLayer(e: ast.Expr) bool { var buf: [64]u8 = undefined; const text = dotted(e, &buf) orelse return false; for ([_][]const u8{ "task.check_cancel", "task.join_cancel", "mutex." }) |p| if (std.mem.startsWith(u8, text, p)) return true; return false; } /// 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{ "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", }; 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 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), // Layer 8; until then, assume it reads everything. .select => true, .@"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 => 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), .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 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 => 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.*), .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 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 => w.seen, .@"break", .@"continue", .trap => false, }; } };