Phase 6A: .aji layer 5 (linear values, own, regions, outcome matches, or trap)
- explicit move for named linear values; E7003 with suggestion "move x"; move of a copyable value is E7006; moved state left to the verifier - own.new/own.array/region.create/region.new/region.array/cap.narrow.budget as outcome matches or with `or trap`; own.take/own.free/region.reset/ region.destroy as AIR names in AIR operand order - region.new/region.array take an explicit ref/mut region binding (E7005 otherwise); reset/destroy end nothing (verifier E2104) - match kind (enum/outcome/integer) decided by the parser; built-in error enums (alloc_error, cap_error, io_error) matched exhaustively - cap<K> types; linear owners borrowed in place - features header = registry closure of the features used - parameters keep their source names (grants by @main parameter name) - aji lower --stats: mechanical_air_eliminated = 1 - source/AIR bytes - spec 15, grammar, quick reference, plan updated
This commit is contained in:
1 parent
eca30f817a
commit
bdcf871e5d
28 files changed
+882
-78
No files matched your search
+16
-1
@@ -103,7 +103,22 @@ pub const Pattern = struct {
|
||||
|
||||
pub const Arm = struct { pattern: Pattern, body: Expr };
|
||||
|
||||
pub const Match = struct { scrutinee: Expr, arms: []const Arm, span: Span };
|
||||
pub const Match = struct {
|
||||
scrutinee: Expr,
|
||||
arms: []const Arm,
|
||||
span: Span,
|
||||
/// Decided by the parser from the arms' patterns (spec 15 §6).
|
||||
kind: Kind,
|
||||
|
||||
pub const Kind = enum {
|
||||
/// `Enum::Variant` arms: `enum.switch`.
|
||||
@"enum",
|
||||
/// Outcome arms (`ok(…)`, `err(e)`, `closed`, …) of a fallible operation: its terminator's edges.
|
||||
outcome,
|
||||
/// Integer literals and `_`: `switch`.
|
||||
integer,
|
||||
};
|
||||
};
|
||||
|
||||
pub const SelectArm = struct {
|
||||
span: Span,
|
||||
|
||||
+394
-51
@@ -15,11 +15,15 @@
|
||||
//! 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.
|
||||
//! borrows, places, arrays, slices, byte strings;
|
||||
//! 5. linear values with explicit `move`, `own`, regions, `cap<mem.alloc>`,
|
||||
//! outcome matches and `or trap`.
|
||||
|
||||
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;
|
||||
@@ -37,23 +41,37 @@ pub const Ty = union(enum) {
|
||||
mut: *const Ty,
|
||||
slice: *const Ty,
|
||||
slice_mut: *const Ty,
|
||||
own: *const Ty,
|
||||
own_array: *const Ty,
|
||||
region,
|
||||
/// `cap<K>`: the kind.
|
||||
cap: []const u8,
|
||||
/// A built-in enum (`alloc_error`, `cap_error`, `io_error`).
|
||||
builtin: authority.Builtin,
|
||||
|
||||
pub const Arr = struct { elem: Ty, len: u64 };
|
||||
|
||||
/// Linear: consumed exactly once, by `move` (spec 15 §5).
|
||||
fn isLinear(t: Ty) bool {
|
||||
return t == .own or t == .own_array or t == .region;
|
||||
}
|
||||
|
||||
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 => |x| x.eql(inner(b).?),
|
||||
.ref, .mut, .slice, .slice_mut, .own, .own_array => |x| x.eql(inner(b).?),
|
||||
.cap => |k| std.mem.eql(u8, k, b.cap),
|
||||
.builtin => |e| e == b.builtin,
|
||||
else => true,
|
||||
};
|
||||
}
|
||||
|
||||
fn inner(t: Ty) ?Ty {
|
||||
return switch (t) {
|
||||
.ref, .mut, .slice, .slice_mut => |x| x.*,
|
||||
.ref, .mut, .slice, .slice_mut, .own, .own_array => |x| x.*,
|
||||
.array => |a| a.elem,
|
||||
else => null,
|
||||
};
|
||||
@@ -202,6 +220,8 @@ const Lowerer = struct {
|
||||
bindings: std.ArrayList(Binding) = .empty,
|
||||
loops: std.ArrayList(Loop) = .empty,
|
||||
counter: u32 = 0,
|
||||
/// 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.
|
||||
@@ -236,7 +256,10 @@ const Lowerer = struct {
|
||||
.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 => |x| std.fmt.allocPrint(l.arena, "{s}<{s}>", .{ @tagName(t), l.tyText(x.*) }) catch "borrow",
|
||||
.ref, .mut, .slice, .slice_mut, .own, .own_array => |x| std.fmt.allocPrint(l.arena, "{s}<{s}>", .{ @tagName(t), l.tyText(x.*) }) catch "borrow",
|
||||
.region => "region",
|
||||
.cap => |k| std.fmt.allocPrint(l.arena, "cap<{s}>", .{k}) catch "cap",
|
||||
.builtin => |b| @tagName(b),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -299,10 +322,9 @@ const Lowerer = struct {
|
||||
for (l.m.functions) |f| try l.fns.append(l.arena, try l.function(f));
|
||||
|
||||
var features: std.ArrayList(u8) = .empty;
|
||||
const uses = l.featureUse(type_lines.items);
|
||||
if (uses.arrays) try features.appendSlice(l.arena, "arrays, ");
|
||||
try features.appendSlice(l.arena, "effects");
|
||||
if (uses.ownership) try features.appendSlice(l.arena, ", ownership");
|
||||
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);
|
||||
@@ -313,31 +335,38 @@ const Lowerer = struct {
|
||||
for (l.fns.items) |f| try l.emitFunction(f);
|
||||
}
|
||||
|
||||
/// Which features the lowered AIR uses: `arrays` (and so `ownership`)
|
||||
/// for arrays and slices, `ownership` for frame storage and borrows.
|
||||
fn featureUse(l: *Lowerer, type_lines: []const Inst) struct { arrays: bool, ownership: bool } {
|
||||
var arrays = false;
|
||||
var ownership = false;
|
||||
const scan = struct {
|
||||
fn has(text: []const u8, word: []const u8) bool {
|
||||
return std.mem.indexOf(u8, text, word) != null;
|
||||
}
|
||||
}.has;
|
||||
/// The features the lowered AIR uses directly; the header is their
|
||||
/// dependency closure (spec 15 §9). `effects` is always declared.
|
||||
fn featureRoots(l: *Lowerer, type_lines: []const Inst) Error![]const []const u8 {
|
||||
var texts: std.ArrayList([]const u8) = .empty;
|
||||
for (type_lines) |t| texts.append(l.arena, t.text) catch {};
|
||||
for (type_lines) |t| try texts.append(l.arena, t.text);
|
||||
for (l.fns.items) |f| {
|
||||
texts.append(l.arena, f.header) catch {};
|
||||
try texts.append(l.arena, f.header);
|
||||
for (f.blocks) |b| {
|
||||
for (b.params.items) |p| texts.append(l.arena, l.tyText(p.ty)) catch {};
|
||||
for (b.insts.items) |inst| texts.append(l.arena, inst.text) catch {};
|
||||
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);
|
||||
}
|
||||
}
|
||||
for (texts.items) |t| {
|
||||
if (scan(t, "array<") or scan(t, "slice") or scan(t, "array.splat") or scan(t, "borrow.index")) arrays = true;
|
||||
if (scan(t, "local.") or scan(t, "borrow.") or scan(t, " load ") or scan(t, "= load ") or std.mem.startsWith(u8, t, "store ") or scan(t, "ref<") or scan(t, "mut<")) ownership = true;
|
||||
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" } },
|
||||
};
|
||||
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]);
|
||||
}
|
||||
if (arrays) ownership = true;
|
||||
return .{ .arrays = arrays, .ownership = ownership };
|
||||
return roots.items;
|
||||
}
|
||||
|
||||
/// `type @T = struct { … }` / `enum { … }` in canonical form.
|
||||
@@ -387,13 +416,15 @@ const Lowerer = struct {
|
||||
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) };
|
||||
const later = [_][]const u8{ "region", "listener", "stream", "io_error", "alloc_error", "cap_error" };
|
||||
for (later) |x| if (std.mem.eql(u8, x, n)) return l.notYet(t.span, "this type (later layers)");
|
||||
if (std.mem.eql(u8, n, "region")) return .region;
|
||||
if (std.meta.stringToEnum(authority.Builtin, n)) |b| return .{ .builtin = b };
|
||||
const later = [_][]const u8{ "listener", "stream" };
|
||||
for (later) |x| if (std.mem.eql(u8, x, n)) return l.notYet(t.span, "this type (layer 6)");
|
||||
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 };
|
||||
const Wr = enum { ref, mut, slice, slice_mut, own, own_array };
|
||||
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) {
|
||||
@@ -401,8 +432,14 @@ const Lowerer = struct {
|
||||
.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),
|
||||
};
|
||||
},
|
||||
.cap => |k| {
|
||||
if (authority.kindIndex(k) == null) return l.fail("E7002", t.span, "unknown capability kind", &.{.{ .name = "kind", .value = k }});
|
||||
return .{ .cap = k };
|
||||
},
|
||||
else => return l.notYet(t.span, "this type (later layers)"),
|
||||
}
|
||||
}
|
||||
@@ -418,6 +455,7 @@ const Lowerer = struct {
|
||||
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;
|
||||
@@ -427,7 +465,8 @@ const Lowerer = struct {
|
||||
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| {
|
||||
const v = try l.freshName(p.name);
|
||||
// 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) }));
|
||||
@@ -479,8 +518,13 @@ const Lowerer = struct {
|
||||
}
|
||||
|
||||
fn freshName(l: *Lowerer, base: []const u8) Error![]const u8 {
|
||||
l.counter += 1;
|
||||
return l.fmt("{s}_{d}", .{ base, l.counter });
|
||||
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 {
|
||||
@@ -646,7 +690,17 @@ const Lowerer = struct {
|
||||
// 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]);
|
||||
const v = try l.expr(x.e, want);
|
||||
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;`", &.{});
|
||||
@@ -662,7 +716,7 @@ const Lowerer = struct {
|
||||
if (l.addressable.contains(x.name)) {
|
||||
const st = try l.storageFor(x.name, ty, s.span);
|
||||
if (x.init) |e| {
|
||||
const v = try l.expr(e, ty);
|
||||
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);
|
||||
@@ -670,7 +724,7 @@ const Lowerer = struct {
|
||||
return;
|
||||
}
|
||||
const v = if (x.init) |e| blk: {
|
||||
const v = try l.expr(e, ty);
|
||||
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);
|
||||
@@ -684,7 +738,7 @@ const Lowerer = struct {
|
||||
const ty = b.ty;
|
||||
const kind = b.kind;
|
||||
const storage = b.value;
|
||||
const v = try l.expr(x.e, ty);
|
||||
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);
|
||||
@@ -711,7 +765,7 @@ const Lowerer = struct {
|
||||
},
|
||||
.@"return" => |e| {
|
||||
if (e) |x| {
|
||||
const v = try l.expr(x, l.ret);
|
||||
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);
|
||||
@@ -853,8 +907,9 @@ const Lowerer = struct {
|
||||
.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 => null,
|
||||
else => if (pathOf(x.callee.*)) |p| (if (std.mem.eql(u8, p, "own.take") and x.args.len == 1) (if (l.peekType(x.args[0])) |t| t.inner() else null) else null) 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: {
|
||||
@@ -1053,8 +1108,12 @@ const Lowerer = struct {
|
||||
if (std.mem.eql(u8, x.name, "len")) return l.lenOf(e, x.e.*);
|
||||
return l.fieldValue(e, x.e.*, x.name);
|
||||
},
|
||||
.or_trap => return l.notYet(e.span, "`or trap` (layer 5, with fallible operations)"),
|
||||
.move => return l.notYet(e.span, "`move` (layer 5, with linear values)"),
|
||||
.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 };
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1124,7 +1183,30 @@ const Lowerer = struct {
|
||||
|
||||
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 (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<T>`", &.{.{ .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 };
|
||||
}
|
||||
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)");
|
||||
@@ -1267,7 +1349,9 @@ const Lowerer = struct {
|
||||
/// `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.carried(depth);
|
||||
@@ -1358,6 +1442,46 @@ const Lowerer = struct {
|
||||
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.carried(depth);
|
||||
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");
|
||||
}
|
||||
|
||||
fn armBody(l: *Lowerer, body: ast.Expr, want: ?Ty) Error!?Value {
|
||||
const v = try l.expr(body, want);
|
||||
if (v.ty == .void) return null;
|
||||
@@ -1438,10 +1562,19 @@ const Lowerer = struct {
|
||||
try temps.appendSlice(l.arena, &.{ r.name, sl.name });
|
||||
return sl;
|
||||
},
|
||||
else => return l.expr(a, want),
|
||||
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);
|
||||
}
|
||||
|
||||
fn rootBinding(l: *Lowerer, e: ast.Expr) ?*Binding {
|
||||
var x = e;
|
||||
while (true) switch (x.kind) {
|
||||
@@ -1480,7 +1613,18 @@ const Lowerer = struct {
|
||||
return .{ .v = v, .ends = try l.arena.dupe([]const u8, &.{v.name}) };
|
||||
},
|
||||
.borrow => return .{ .v = .{ .name = b.value, .ty = b.ty }, .ends = &.{} },
|
||||
.ssa => return l.fail("E7006", place.span, "this value is not addressable here; borrow a variable, a field or an element", &.{.{ .name = "name", .value = n }}),
|
||||
.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),
|
||||
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| {
|
||||
@@ -1708,6 +1852,183 @@ const Lowerer = struct {
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ 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.
|
||||
const Fallible = struct { text: []const u8, outcomes: []const Outcome };
|
||||
|
||||
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" };
|
||||
for (ops) |o| if (std.mem.eql(u8, o, path)) return {};
|
||||
return null;
|
||||
}
|
||||
|
||||
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<region>` 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", &.{});
|
||||
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 (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 `<op>, ok -> @a, err -> @b`.
|
||||
fn outcomeBlocks(l: *Lowerer, f: Fallible, span: Span) Error![]const usize {
|
||||
const blocks = try l.arena.alloc(usize, f.outcomes.len);
|
||||
var text: std.ArrayList(u8) = .empty;
|
||||
try text.appendSlice(l.arena, f.text);
|
||||
for (f.outcomes, blocks) |o, *b| {
|
||||
b.* = try l.newBlock(o.role);
|
||||
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);
|
||||
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.carried(depth);
|
||||
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;
|
||||
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.
|
||||
@@ -1770,15 +2091,37 @@ fn elemOf(t: Ty) ?Ty {
|
||||
};
|
||||
}
|
||||
|
||||
/// `a.b.c` for a callee made of names and fields.
|
||||
/// 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 {
|
||||
return switch (e.kind) {
|
||||
.field => |f| switch (f.e.kind) {
|
||||
.name => |n| if (std.mem.eql(u8, n, "slice") and std.mem.eql(u8, f.name, "copy")) "slice.copy" else null,
|
||||
else => null,
|
||||
},
|
||||
else => null,
|
||||
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",
|
||||
};
|
||||
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;
|
||||
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 {
|
||||
|
||||
@@ -701,7 +701,15 @@ const Parser = struct {
|
||||
const scrut = try p.condition();
|
||||
_ = try p.expect(.l_brace, "`{`");
|
||||
const as = try p.arms();
|
||||
return .{ .span = p.span(start), .kind = .{ .match_expr = try p.box(ast.Match, .{ .scrutinee = scrut, .arms = as, .span = p.span(start) }) } };
|
||||
var kind: ast.Match.Kind = .integer;
|
||||
for (as) |a| switch (a.pattern.kind) {
|
||||
.ctor => |c| {
|
||||
kind = if (c.qualifier != null) .@"enum" else .outcome;
|
||||
break;
|
||||
},
|
||||
else => {},
|
||||
};
|
||||
return .{ .span = p.span(start), .kind = .{ .match_expr = try p.box(ast.Match, .{ .scrutinee = scrut, .arms = as, .span = p.span(start), .kind = kind }) } };
|
||||
}
|
||||
if (isKeyword(t.text)) return p.fail(t, "an expression");
|
||||
_ = p.next();
|
||||
|
||||
@@ -125,6 +125,8 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
|
||||
.air_lines = ac.lines,
|
||||
.expansion_bytes = @as(f64, @floatFromInt(ac.bytes)) / @as(f64, @floatFromInt(@max(sc.bytes, 1))),
|
||||
.expansion_lines = @as(f64, @floatFromInt(ac.lines)) / @as(f64, @floatFromInt(@max(sc.lines, 1))),
|
||||
// 1 − source/AIR: the share of AIR text the frontend writes for the author.
|
||||
.mechanical_air_eliminated = 1.0 - @as(f64, @floatFromInt(sc.bytes)) / @as(f64, @floatFromInt(@max(ac.bytes, 1))),
|
||||
});
|
||||
try out.writeByte('\n');
|
||||
return .accepted;
|
||||
|
||||
Reference in new issue
Block a user