Specialize explicit function, struct and enum templates into deterministic ordinary AIR, with structural constraints and bounded expansion. Preserve source provenance and readable names in specialization diagnostics. Add Copy-only std.option/std.result and vertical specification, grammar, Quick Reference, RFC and source coverage updates. Keep linear aggregates and existing unsupported source from-returns explicit follow-up work. Repair the finite-layout check through arrays under the existing E1003 contract, with positive and rejected source/AIR fixtures. Validation: build, unit tests, 640 conformance cases, 82/82 source constructs, 32-seed generic task stress, agent-reference, formatting, hosted smoke, 20 generic and 36 package CLI checks. Record three-encoding documentation budgets; AIR reference is unchanged.
3593 lines
201 KiB
Zig
3593 lines
201 KiB
Zig
//! Lowering of `.aji` source 0.1 to canonical text AIR (spec 15).
|
||
//!
|
||
//! The frontend is a thin layer: it resolves names and source types only as
|
||
//! far as needed to choose AIR instructions, and writes canonical AIR text
|
||
//! together with a line map (AIR line → source span). Every semantic
|
||
//! judgement — ownership, borrows, resources, effects, concurrency — is left
|
||
//! to the AIR verifier, which reports at the mapped source location.
|
||
//!
|
||
//! The frontend never repairs a program: it does not add `move`, effects,
|
||
//! closes or error handling. It generates only representation mechanics
|
||
//! (SSA, blocks, block parameters, the `features` header).
|
||
//!
|
||
//! Layers implemented here (spec 15 is implemented layer by layer; a
|
||
//! construct of a later layer is reported as not yet implemented):
|
||
//! 1. scalars, expressions, functions, control flow;
|
||
//! 2. structs, enums, exhaustive `match`;
|
||
//! 3–4. addressable values (frame storage chosen by lowering), lexical
|
||
//! borrows, places, arrays, slices, byte strings;
|
||
//! 5. linear values with explicit `move`, `own`, regions, `cap<mem.alloc>`,
|
||
//! outcome matches and `or trap`;
|
||
//! 6. intrinsics (I/O, files, TCP, clock, random), resources, capability
|
||
//! narrowing, unsafe operations;
|
||
//! 7. task scopes, spawn and join, channels;
|
||
//! 8. `lock` and mutexes, `select`, cancellation points, shields;
|
||
//! 9. islands, frozen graphs, arcs and `iref` handles (spec 03 §22–§24).
|
||
|
||
const std = @import("std");
|
||
const ast = @import("ast.zig");
|
||
const parse_mod = @import("parse.zig");
|
||
const authority = @import("../air/authority.zig");
|
||
const features_mod = @import("../air/features.zig");
|
||
const air_module = @import("../air/module.zig");
|
||
const verifier_types = @import("../verifier/types.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<K>`: the kind.
|
||
cap: []const u8,
|
||
/// A built-in enum (`alloc_error`, `cap_error`, `io_error`).
|
||
builtin: authority.Builtin,
|
||
/// `file<read|write|append>`, `stream`, `listener`.
|
||
resource: authority.Resource,
|
||
/// `task<T>`, `sender<T>`, `receiver<T>`: the element or result type.
|
||
task: *const Ty,
|
||
sender: *const Ty,
|
||
receiver: *const Ty,
|
||
/// A task scope (bound by `scope s { … }`, never written as a type).
|
||
scope,
|
||
/// `mutex<T>`; `guard<T>` is never a source value (the `lock` block).
|
||
mutex: *const Ty,
|
||
guard: *const Ty,
|
||
/// A shield (`shield { … }`, never a source value).
|
||
shield,
|
||
/// Graph owners and handles (spec 03 §22–§24).
|
||
island: *const Ty,
|
||
frozen: *const Ty,
|
||
arc: *const Ty,
|
||
iref: *const Ty,
|
||
/// `atomic<T>` (spec 04 §23; layer 10): a linear cell.
|
||
atomic: *const Ty,
|
||
|
||
pub const Arr = struct { elem: Ty, len: u64 };
|
||
|
||
/// Linear: consumed exactly once, by `move` (spec 15 §5).
|
||
fn isLinear(t: Ty) bool {
|
||
return switch (t) {
|
||
.own, .own_array, .region, .resource, .task, .sender, .receiver, .scope, .mutex, .guard, .shield, .island, .frozen, .arc, .atomic => 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, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |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, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| x.*,
|
||
.array => |a| a.elem,
|
||
else => null,
|
||
};
|
||
}
|
||
|
||
fn isBorrow(t: Ty) bool {
|
||
return t == .ref or t == .mut or t == .slice or t == .slice_mut;
|
||
}
|
||
|
||
fn isMutBorrow(t: Ty) bool {
|
||
return t == .mut or t == .slice_mut;
|
||
}
|
||
};
|
||
|
||
const int_types = [_][]const u8{ "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize" };
|
||
|
||
/// AtomicScalar (spec 04 §23): `bool` and integers of at most 64 bits.
|
||
fn atomicScalar(t: Ty) bool {
|
||
return t == .bool or (t == .int and intBits(t.int) <= 64);
|
||
}
|
||
|
||
fn isIntName(n: []const u8) bool {
|
||
for (int_types) |t| if (std.mem.eql(u8, t, n)) return true;
|
||
return false;
|
||
}
|
||
|
||
fn isSigned(n: []const u8) bool {
|
||
return n[0] == 'i';
|
||
}
|
||
|
||
fn intBits(n: []const u8) u16 {
|
||
if (std.mem.endsWith(u8, n, "size")) return 64;
|
||
return std.fmt.parseInt(u16, n[1..], 10) catch 64;
|
||
}
|
||
|
||
pub const 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<T>` value. For
|
||
/// `borrow`: the borrow value.
|
||
value: []const u8,
|
||
/// For `storage`: the stored type `T`.
|
||
ty: Ty,
|
||
kind: Kind = .ssa,
|
||
|
||
const Kind = enum { ssa, storage, borrow };
|
||
};
|
||
|
||
/// A borrow to end with `borrow.end` when its scope ends (spec 15 §9).
|
||
/// Something ended at every normal exit of a lexical scope, innermost
|
||
/// first: a borrow (`borrow.end`) or a task scope (`task.scope.end`).
|
||
const BorrowEnd = struct { name: []const u8, span: Span, op: []const u8 = "borrow.end" };
|
||
|
||
/// A bounds fact the verifier can prove (spec 08 §12, "fact on the same
|
||
/// slice"): inside the true branch of `if i < s.len`, with `i` and `s`
|
||
/// still the same SSA values.
|
||
const Fact = struct { index: []const u8, slice: []const u8 };
|
||
|
||
/// A borrowed place: the final borrow and the chain of borrows created for
|
||
/// it, to be ended in reverse order.
|
||
const Placed = struct { v: Value, ends: []const []const u8 };
|
||
|
||
const Loop = struct {
|
||
/// Target of `continue`.
|
||
@"continue": usize,
|
||
exit: usize,
|
||
/// Number of bindings visible when the loop started; the variables among
|
||
/// them are the loop's carried state.
|
||
depth: usize,
|
||
/// Number of borrow scopes open when the loop started: `break` and
|
||
/// `continue` end the borrows of every scope above it.
|
||
scope_depth: usize,
|
||
/// Variables carried to the loop's header (and `continue` target) and
|
||
/// to its exit.
|
||
header_vars: []const usize = &.{},
|
||
exit_vars: []const usize = &.{},
|
||
};
|
||
|
||
const FnOut = struct {
|
||
header: []const u8,
|
||
effects: []const u8,
|
||
span: Span,
|
||
blocks: []const Block,
|
||
};
|
||
|
||
const Value = struct { name: []const u8, ty: Ty };
|
||
|
||
/// What remains to be lowered in an enclosing block: the statements after
|
||
/// the current one, the tail, the current statement itself, and, for a loop
|
||
/// body, the loop (whose next iteration also follows).
|
||
const Rest = struct {
|
||
stmts: []const ast.Stmt,
|
||
tail: ?*const ast.Expr,
|
||
current: ?ast.Stmt = null,
|
||
/// The tail expression, while it is being lowered.
|
||
current_expr: ?*const ast.Expr = null,
|
||
loop: ?LoopAst = null,
|
||
};
|
||
|
||
const LoopAst = struct { cond: ?ast.Expr, body: ast.Block, step: ?[]const u8 };
|
||
|
||
const FnSig = struct { params: []const Ty, ret: Ty, air_name: []const u8, display_name: []const u8 };
|
||
|
||
const Lowerer = struct {
|
||
arena: Allocator,
|
||
m: ast.Module,
|
||
out: std.ArrayList(u8) = .empty,
|
||
annotated: std.ArrayList(u8) = .empty,
|
||
lines: std.ArrayList(?Span) = .empty,
|
||
constant_of: std.ArrayList(u32) = .empty,
|
||
constants: std.ArrayList(Output.Constant) = .empty,
|
||
/// Set while a byte string is materialized: the tag for its instructions.
|
||
in_constant: u32 = 0,
|
||
problem: ?Problem = null,
|
||
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`, `shield` and `lock` just before lowering a body:
|
||
/// bindings and ends that belong to the body's own lexical scope (ends
|
||
/// in creation order; they run innermost first at every normal exit).
|
||
pending_bindings: std.ArrayList(Binding) = .empty,
|
||
pending_ends: std.ArrayList(BorrowEnd) = .empty,
|
||
/// Borrows to end at the end of each open lexical scope (innermost last).
|
||
scopes: std.ArrayList(std.ArrayList(BorrowEnd)) = .empty,
|
||
/// `local.alloc` instructions; they go first in the entry block.
|
||
allocs: std.ArrayList(Inst) = .empty,
|
||
/// Names whose variables need frame storage (borrowed or indexed).
|
||
addressable: std.StringHashMapUnmanaged(void) = .empty,
|
||
facts: std.ArrayList(Fact) = .empty,
|
||
/// Index of the first binding of the innermost scope (for the no-shadowing rule).
|
||
scope_binding_start: usize = 0,
|
||
fns: std.ArrayList(FnOut) = .empty,
|
||
|
||
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 l.typeText(t, false);
|
||
}
|
||
|
||
fn diagnosticTyText(l: *Lowerer, t: Ty) []const u8 {
|
||
return l.typeText(t, true);
|
||
}
|
||
|
||
fn typeText(l: *Lowerer, t: Ty, source_names: bool) []const u8 {
|
||
return switch (t) {
|
||
.int => |x| x,
|
||
.bool => "bool",
|
||
.void => "void",
|
||
.never => "never",
|
||
.named => |i| if (source_names and l.m.types[i].air_name != null) (l.m.types[i].display_name orelse l.m.types[i].name) else l.typeNames[i],
|
||
.array => |a| std.fmt.allocPrint(l.arena, "array<{s}, {d}>", .{ l.typeText(a.elem, source_names), a.len }) catch "array",
|
||
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| std.fmt.allocPrint(l.arena, "{s}<{s}>", .{ @tagName(t), l.typeText(x.*, source_names) }) catch "borrow",
|
||
.scope => "scope",
|
||
.shield => "shield",
|
||
.region => "region",
|
||
.cap => |k| std.fmt.allocPrint(l.arena, "cap<{s}>", .{k}) catch "cap",
|
||
.builtin => |b| blk: {
|
||
if (b == .io_error) l.uses.insert(.resources);
|
||
break :blk @tagName(b);
|
||
},
|
||
.resource => |r| blk: {
|
||
l.uses.insert(.resources);
|
||
break :blk r.text();
|
||
},
|
||
};
|
||
}
|
||
|
||
fn 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, " ")) {
|
||
if (s.file) |file| {
|
||
try l.annotated.appendSlice(l.arena, try l.fmt(" ; {s}:{d}:{d}-{d}:{d}\n", .{ file, s.start.line, s.start.col, s.end.line, s.end.col }));
|
||
} else try l.annotated.appendSlice(l.arena, try l.fmt(" ; {d}:{d}-{d}:{d}\n", .{ s.start.line, s.start.col, s.end.line, s.end.col }));
|
||
};
|
||
try l.annotated.appendSlice(l.arena, text);
|
||
try l.annotated.append(l.arena, '\n');
|
||
}
|
||
|
||
// ------------------------------------------------------------ module
|
||
|
||
fn run(l: *Lowerer) Error!void {
|
||
const names = try l.arena.alloc([]const u8, l.m.types.len);
|
||
for (l.m.types, names, 0..) |t, *n, i| {
|
||
for (l.m.types[0..i]) |prev| if (std.mem.eql(u8, prev.name, t.name)) return l.fail("E7006", t.span, "type defined twice", &.{.{ .name = "name", .value = t.name }});
|
||
n.* = try l.fmt("@{s}", .{t.air_name orelse t.name});
|
||
}
|
||
l.typeNames = names;
|
||
for (l.m.functions) |f| {
|
||
if (l.sigs.contains(f.name)) return l.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), .air_name = f.air_name orelse f.name, .display_name = f.display_name orelse f.name });
|
||
}
|
||
if (!l.sigs.contains("main")) return l.fail("E7002", .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 1 } }, "the module has no `main` function", &.{.{ .name = "name", .value = "main" }});
|
||
|
||
const whole: Span = if (l.m.functions.len != 0) l.m.functions[0].span else .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 1 } };
|
||
// Type lines are built first (they can fail); functions are lowered
|
||
// before the header is written, because the `features` header is the
|
||
// closure of what the lowered AIR uses (spec 15 §9).
|
||
var type_lines: std.ArrayList(Inst) = .empty;
|
||
for (l.m.types) |t| try type_lines.append(l.arena, .{ .text = try l.typeDeclText(t), .span = t.span });
|
||
try l.checkRequirements();
|
||
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);
|
||
}
|
||
|
||
fn airType(l: *Lowerer, t: Ty) Error!air_module.Type {
|
||
return switch (t) {
|
||
.int => |n| .{ .int = std.meta.stringToEnum(air_module.IntType, n).? },
|
||
.named => |i| .{ .named = i },
|
||
.cap => |k| .{ .cap = authority.kindIndex(k).? },
|
||
.builtin => |b| .{ .builtin = b },
|
||
.resource => |r| .{ .resource = r },
|
||
.array => |a| blk: {
|
||
const out = try l.arena.create(air_module.Type.Array);
|
||
out.* = .{ .elem = try l.airType(a.elem), .len = a.len };
|
||
break :blk .{ .array = out };
|
||
},
|
||
inline .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |inner, tag| blk: {
|
||
const out = try l.arena.create(air_module.Type);
|
||
out.* = try l.airType(inner.*);
|
||
break :blk @unionInit(air_module.Type, @tagName(tag), out);
|
||
},
|
||
.bool => .bool,
|
||
.void => .void,
|
||
.never => .never,
|
||
.region => .region,
|
||
.scope => .scope,
|
||
.shield => .shield,
|
||
};
|
||
}
|
||
|
||
fn checkRequirements(l: *Lowerer) Error!void {
|
||
if (l.m.requirements.len == 0) return;
|
||
const types = try l.arena.alloc(air_module.TypeDecl, l.m.types.len);
|
||
for (l.m.types, types, 0..) |d, *out, index| {
|
||
out.* = .{ .name = d.air_name orelse d.name, .span = .{ .line = @intCast(index + 1), .col = 1 }, .kind = undefined };
|
||
switch (d.kind) {
|
||
.@"struct" => |fs| {
|
||
const fields = try l.arena.alloc(air_module.Field, fs.len);
|
||
for (fs, fields) |f, *target| target.* = .{ .name = f.name, .ty = try l.airType(try l.typeOf(f.ty)) };
|
||
out.kind = .{ .@"struct" = fields };
|
||
},
|
||
.@"enum" => |vs| {
|
||
const variants = try l.arena.alloc(air_module.Variant, vs.len);
|
||
for (vs, variants) |v, *target| {
|
||
const payload = try l.arena.alloc(air_module.Type, v.payload.len);
|
||
for (v.payload, payload) |t, *p| p.* = try l.airType(try l.typeOf(t));
|
||
target.* = .{ .name = v.name, .payload = payload };
|
||
}
|
||
out.kind = .{ .@"enum" = variants };
|
||
},
|
||
}
|
||
}
|
||
const m: air_module.Module = .{ .name = l.m.name, .format_version = 0, .lang = .{ 0, 1 }, .features = &.{}, .types = types, .functions = &.{} };
|
||
var layout_context: @import("../verifier.zig").Context = .{ .arena = l.arena, .file = "<generic>", .module = m };
|
||
try verifier_types.checkFiniteLayouts(&layout_context);
|
||
if (layout_context.diags.items.len != 0) {
|
||
const d = l.m.types[layout_context.diags.items[0].span.?.line - 1];
|
||
return l.fail("E1003", d.span, "aggregate type contains itself by value", &.{.{ .name = "type", .value = d.display_name orelse d.name }});
|
||
}
|
||
for (l.m.requirements) |r| {
|
||
const ty = try l.typeOf(r.ty);
|
||
const t = try l.airType(ty);
|
||
if (!boundedType(m, t, 0)) return l.fail("E7006", r.span, "constraint type traversal is cyclic or exceeds depth 64", &.{});
|
||
if (r.property.len == 0) {
|
||
var context: @import("../verifier.zig").Context = .{ .arena = l.arena, .file = "<generic>", .module = m };
|
||
try verifier_types.checkTypeArgument(&context, .{ .line = 1, .col = 1 }, t);
|
||
if (context.diags.items.len != 0) return l.fail("E7005", r.span, "generic argument is not a well-formed concrete type", &.{ .{ .name = "parameter", .value = r.parameter }, .{ .name = "found", .value = l.diagnosticTyText(ty) } });
|
||
continue;
|
||
}
|
||
const ok = if (std.mem.eql(u8, r.property, "Copy")) verifier_types.isCopy(m, t) else if (std.mem.eql(u8, r.property, "Send")) verifier_types.isSend(m, t) else if (std.mem.eql(u8, r.property, "Share")) verifier_types.isShare(m, t) else if (std.mem.eql(u8, r.property, "Freeze")) verifier_types.isIslandSafe(m, t) else verifier_types.isLocalType(m, t);
|
||
if (!ok) return l.fail("E7005", r.span, "generic argument does not satisfy structural constraint", &.{
|
||
.{ .name = "parameter", .value = r.parameter },
|
||
.{ .name = "constraint", .value = r.property },
|
||
.{ .name = "found", .value = l.diagnosticTyText(ty) },
|
||
});
|
||
}
|
||
}
|
||
|
||
/// The features the lowered AIR uses directly; the header is their
|
||
/// dependency closure (spec 15 §9). `effects` is always declared.
|
||
const UseFeature = enum { capabilities, resources, unsafe };
|
||
|
||
fn featureRoots(l: *Lowerer, type_lines: []const Inst) Error![]const []const u8 {
|
||
var texts: std.ArrayList([]const u8) = .empty;
|
||
for (type_lines) |t| try texts.append(l.arena, t.text);
|
||
for (l.fns.items) |f| {
|
||
try texts.append(l.arena, f.header);
|
||
for (f.blocks) |b| {
|
||
for (b.params.items) |p| try texts.append(l.arena, 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<", "select [" } },
|
||
.{ "sync", &.{ "mutex.", "mutex<", "guard<" } },
|
||
.{ "cancellation", &.{ "task.shield", "task.check_cancel", "task.join.cancel" } },
|
||
.{ "islands", &.{ "island.", "island<", "frozen.", "frozen<", "iref.", "iref<" } },
|
||
.{ "arc", &.{ "arc.", "arc<" } },
|
||
// Instructions only: the effect names `atomic` and `atomic.weak`
|
||
// in a function header are not uses of the feature.
|
||
.{ "atomics", &.{ "= atomic.", "atomic.store.", "atomic.fence.", "atomic<" } },
|
||
};
|
||
for (rules) |r| {
|
||
const used = for (texts.items) |t| {
|
||
const hit = for (r[1]) |w| {
|
||
if (std.mem.indexOf(u8, t, w) != null or (std.mem.eql(u8, w, "store ") and std.mem.startsWith(u8, t, "store "))) break true;
|
||
} else false;
|
||
if (hit) break true;
|
||
} else false;
|
||
if (used) try roots.append(l.arena, r[0]);
|
||
}
|
||
var it = l.uses.iterator();
|
||
while (it.next()) |u| try roots.append(l.arena, @tagName(u));
|
||
return roots.items;
|
||
}
|
||
|
||
/// `type @T = struct { … }` / `enum { … }` in canonical form.
|
||
fn typeDeclText(l: *Lowerer, t: ast.TypeDecl) Error![]const u8 {
|
||
var w: std.ArrayList(u8) = .empty;
|
||
try w.appendSlice(l.arena, try l.fmt("type @{s} = ", .{t.air_name orelse t.name}));
|
||
switch (t.kind) {
|
||
.@"struct" => |fields| {
|
||
try w.appendSlice(l.arena, "struct {");
|
||
for (fields, 0..) |f, i| {
|
||
for (fields[0..i]) |prev| if (std.mem.eql(u8, prev.name, f.name)) return l.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) {
|
||
.applied => return l.fail("E7002", t.span, "unknown generic type", &.{}),
|
||
.name => |n| {
|
||
if (isIntName(n)) return .{ .int = n };
|
||
if (std.mem.eql(u8, n, "bool")) return .bool;
|
||
if (std.mem.eql(u8, n, "void")) return .void;
|
||
if (std.mem.eql(u8, n, "never")) return .never;
|
||
if (l.enumOrStruct(n, t.span)) |ty| return ty;
|
||
if (std.mem.eql(u8, n, "region")) return .region;
|
||
if (std.meta.stringToEnum(authority.Builtin, n)) |b| return .{ .builtin = b };
|
||
if (std.mem.eql(u8, n, "stream")) return .{ .resource = .stream };
|
||
if (std.mem.eql(u8, n, "listener")) return .{ .resource = .listener };
|
||
return l.fail("E7002", t.span, "unknown type", &.{.{ .name = "name", .value = n }});
|
||
},
|
||
.array => |a| 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, mutex, island, frozen, arc, iref, atomic };
|
||
const which = std.meta.stringToEnum(Wr, w.wrapper) orelse return l.notYet(t.span, "this type (later layers)");
|
||
const in = try 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),
|
||
.mutex => l.wrap(.mutex, in),
|
||
.island => l.wrap(.island, in),
|
||
.frozen => l.wrap(.frozen, in),
|
||
.arc => l.wrap(.arc, in),
|
||
.iref => l.wrap(.iref, in),
|
||
.atomic => if (atomicScalar(in)) l.wrap(.atomic, in) else l.fail("E7005", t.span, "atomic<T> needs bool or an integer of at most 64 bits", &.{.{ .name = "found", .value = l.diagnosticTyText(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}(", .{sig.air_name}));
|
||
for (f.params, sig.params, 0..) |p, t, i| {
|
||
// Parameters keep their source names: `@main` capabilities are granted by name.
|
||
const v = p.name;
|
||
// Borrow parameters are lent by the caller: never ended here.
|
||
try l.bindings.append(l.arena, .{ .name = p.name, .mutable = false, .value = v, .ty = t, .kind = if (t.isBorrow()) .borrow else .ssa });
|
||
try header.appendSlice(l.arena, try l.fmt("{s}%{s}: {s}", .{ if (i == 0) "" else ", ", v, 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, region: Region) Error![]const usize {
|
||
var out: std.ArrayList(usize) = .empty;
|
||
for (try l.carried(depth)) |i| {
|
||
const n = l.bindings.items[i].name;
|
||
if (region.assigns(n) and l.liveAfter(n, construct)) try out.append(l.arena, i);
|
||
}
|
||
return out.items;
|
||
}
|
||
|
||
/// As `carriedLive`, for a loop header: also the variables the loop
|
||
/// itself reads (they flow around the back edge).
|
||
fn carriedLoop(l: *Lowerer, depth: usize, construct: Span, lp: LoopAst) Error![]const usize {
|
||
var out: std.ArrayList(usize) = .empty;
|
||
const region: Region = .{ .loop = lp };
|
||
for (try l.carried(depth)) |i| {
|
||
const n = l.bindings.items[i].name;
|
||
if (region.assigns(n) and (loopReads(lp, n) or l.liveAfter(n, construct))) try out.append(l.arena, i);
|
||
}
|
||
return out.items;
|
||
}
|
||
|
||
/// Whether `name` may be read after the construct whose span is
|
||
/// `construct`. Conservative: any read on any later path counts; only a
|
||
/// whole-variable assignment in straight-line code before any read ends
|
||
/// the variable's life.
|
||
fn liveAfter(l: *Lowerer, name: []const u8, construct: Span) bool {
|
||
var k = l.rest.items.len;
|
||
while (k > 0) {
|
||
k -= 1;
|
||
const fr = l.rest.items[k];
|
||
// The rest of the statement or tail that contains the construct.
|
||
var w: After = .{ .name = name, .construct = construct };
|
||
if (fr.current) |c| if (w.stmt(c)) return true;
|
||
if (fr.current_expr) |ce| if (w.expr(ce.*)) return true;
|
||
switch (firstUse(fr.stmts, fr.tail, name)) {
|
||
.read => return true,
|
||
.kill => return false,
|
||
.none => {},
|
||
}
|
||
if (fr.loop) |lp| if (loopReads(lp, name)) return true;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
fn argsOf(l: *Lowerer, vars: []const usize, extra: ?[]const u8) Error![]const u8 {
|
||
var s: std.ArrayList(u8) = .empty;
|
||
try s.append(l.arena, '(');
|
||
var first = true;
|
||
if (extra) |e| {
|
||
try s.appendSlice(l.arena, try l.fmt("%{s}", .{e}));
|
||
first = false;
|
||
}
|
||
for (vars) |i| {
|
||
try s.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (first) "" else ", ", l.bindings.items[i].value }));
|
||
first = false;
|
||
}
|
||
try s.append(l.arena, ')');
|
||
return s.items;
|
||
}
|
||
|
||
/// Gives `block` one parameter per carried variable (after an optional
|
||
/// result parameter) and rebinds the variables to them.
|
||
fn joinParams(l: *Lowerer, block: usize, vars: []const usize) Error!void {
|
||
for (vars) |i| {
|
||
const b = &l.bindings.items[i];
|
||
const name = try l.freshName(b.name);
|
||
try l.blocks.items[block].params.append(l.arena, .{ .name = name, .ty = b.ty });
|
||
}
|
||
}
|
||
|
||
fn rebindToParams(l: *Lowerer, block: usize, vars: []const usize, offset: usize) void {
|
||
for (vars, 0..) |i, k| l.bindings.items[i].value = l.blocks.items[block].params.items[offset + k].name;
|
||
}
|
||
|
||
fn snapshot(l: *Lowerer) Error![]const []const u8 {
|
||
const s = try l.arena.alloc([]const u8, l.bindings.items.len);
|
||
for (l.bindings.items, s) |b, *o| o.* = b.value;
|
||
return s;
|
||
}
|
||
|
||
fn restore(l: *Lowerer, s: []const []const u8) void {
|
||
l.bindings.shrinkRetainingCapacity(s.len);
|
||
for (l.bindings.items, s) |*b, v| b.value = v;
|
||
}
|
||
|
||
// ------------------------------------------------------------ statements
|
||
|
||
/// Lowers a block's statements in a new scope; returns the tail value.
|
||
fn blockBody(l: *Lowerer, b: ast.Block) Error!?Value {
|
||
return l.blockBodyWant(b, null);
|
||
}
|
||
|
||
/// As `blockBody`, with the type expected of the tail expression.
|
||
fn blockBodyWant(l: *Lowerer, b: ast.Block, want: ?Ty) Error!?Value {
|
||
const depth = l.bindings.items.len;
|
||
defer l.bindings.shrinkRetainingCapacity(depth);
|
||
try l.rest.append(l.arena, .{ .stmts = b.stmts, .tail = b.tail, .loop = l.pending_loop });
|
||
l.pending_loop = null;
|
||
defer _ = l.rest.pop();
|
||
try l.scopes.append(l.arena, .empty);
|
||
defer _ = l.scopes.pop();
|
||
const saved_start = l.scope_binding_start;
|
||
l.scope_binding_start = depth;
|
||
defer l.scope_binding_start = saved_start;
|
||
if (l.pending_bindings.items.len != 0 or l.pending_ends.items.len != 0) {
|
||
try l.bindings.appendSlice(l.arena, l.pending_bindings.items);
|
||
try l.scopes.items[l.scopes.items.len - 1].appendSlice(l.arena, l.pending_ends.items);
|
||
l.pending_bindings = .empty;
|
||
l.pending_ends = .empty;
|
||
}
|
||
for (b.stmts, 0..) |s, i| {
|
||
if (l.cur == null) return l.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) {
|
||
if (pathOf(x.e.kind.call.callee.*)) |p| if (std.mem.eql(u8, p, "atomic.compare_exchange")) return l.compareExchangeLet(s, x.names, x.e);
|
||
return l.splitLet(s, x.names, x.e);
|
||
}
|
||
if (x.e.kind == .borrow) return l.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;`", &.{});
|
||
// Linear values (owners, regions, resources, endpoints, tasks,
|
||
// mutexes) are borrowed in place, never moved to frame storage.
|
||
if (l.addressable.contains(x.names[0]) and !v.ty.isLinear()) {
|
||
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) and !ty.isLinear()) {
|
||
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 }});
|
||
if (x.place.kind == .call) if (pathOf(x.place.kind.call.callee.*)) |p| if (std.mem.endsWith(u8, p, ".at"))
|
||
return l.graphAccess(s, x.name, x.mutable, x.place);
|
||
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.diagnosticTyText(l.ret) }});
|
||
try l.endScopes(0, s.span);
|
||
try l.term("ret", s.span);
|
||
}
|
||
},
|
||
.trap => try l.term("trap", s.span),
|
||
.@"break", .@"continue" => {
|
||
if (l.loops.items.len == 0) return l.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);
|
||
try l.pending_bindings.append(l.arena, .{ .name = x.name, .mutable = false, .value = sv.name, .ty = .scope });
|
||
try l.pending_ends.append(l.arena, .{ .name = sv.name, .span = x.body.span, .op = "task.scope.end" });
|
||
_ = try l.blockBody(x.body);
|
||
},
|
||
.shield => |b| {
|
||
// `shield { … }`: task.shield.begin, and task.shield.end at every
|
||
// normal exit; shields nest by construction (spec 15 §7).
|
||
const sh = try l.def("sh", .shield, "task.shield.begin", s.span);
|
||
try l.pending_ends.append(l.arena, .{ .name = sh.name, .span = b.span, .op = "task.shield.end" });
|
||
_ = try l.blockBody(b);
|
||
},
|
||
.lock => |x| try l.lockStmt(s, x.place, x.name, x.body, x.cancelled),
|
||
.select => |x| try l.selectStmt(s, x),
|
||
}
|
||
}
|
||
|
||
fn unknown(l: *Lowerer, span: Span, name: []const u8) Error {
|
||
return l.fail("E7002", span, "unknown name", &.{.{ .name = "name", .value = name }});
|
||
}
|
||
|
||
fn checkTy(l: *Lowerer, span: Span, found: Ty, want: Ty) Error!void {
|
||
if (found == .never or found.eql(want)) return;
|
||
return l.fail("E7005", span, "type mismatch", &.{ .{ .name = "expected", .value = l.diagnosticTyText(want) }, .{ .name = "found", .value = l.diagnosticTyText(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, .{ .loop = lp_ast });
|
||
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.diagnosticTyText(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 sourceScope(l: *Lowerer, span: Span) ?ast.ModuleScope {
|
||
const name = span.namespace orelse l.m.name;
|
||
for (l.m.scopes) |scope| if (std.mem.eql(u8, scope.name, name)) return scope;
|
||
return null;
|
||
}
|
||
|
||
fn boundName(l: *Lowerer, name: []const u8, span: Span) ?[]const u8 {
|
||
if (span.resolved) return name;
|
||
const scope = l.sourceScope(span) orelse return name;
|
||
if (std.mem.lastIndexOfScalar(u8, name, '.')) |at| {
|
||
const owner = name[0..at];
|
||
if (std.mem.eql(u8, owner, scope.name)) return if (!scope.qualified_self) null else if (scope.entry) name[at + 1 ..] else name;
|
||
for (scope.imports) |imp| if (std.mem.eql(u8, imp.path, owner)) return name;
|
||
return null;
|
||
}
|
||
if (scope.entry) return name;
|
||
for (l.m.types) |t| if (localName(t.name, scope.name, name)) return t.name;
|
||
for (l.m.functions) |f| if (localName(f.name, scope.name, name)) return f.name;
|
||
return null;
|
||
}
|
||
|
||
fn functionSig(l: *Lowerer, name: []const u8, span: Span) ?FnSig {
|
||
return l.sigs.get(l.boundName(name, span) orelse return null);
|
||
}
|
||
|
||
fn calleeSig(l: *Lowerer, e: ast.Expr) ?FnSig {
|
||
const name = expressionPath(l.arena, e) catch return null;
|
||
return l.functionSig(name orelse return null, e.span);
|
||
}
|
||
|
||
fn moduleCall(l: *Lowerer, e: ast.Expr) Error!?[]const u8 {
|
||
if (e.kind != .field) return null;
|
||
const name = try expressionPath(l.arena, e) orelse return null;
|
||
if (standardPath(e)) return name;
|
||
if (pathOf(e) != null) return null;
|
||
const owner = name[0..std.mem.lastIndexOfScalar(u8, name, '.').?];
|
||
for (l.m.scopes) |scope| if (std.mem.eql(u8, owner, scope.name)) return name;
|
||
if (l.sourceScope(e.span)) |scope| for (scope.imports) |imp| if (std.mem.eql(u8, owner, imp.path)) return name;
|
||
var root = e;
|
||
while (root.kind == .field) root = root.kind.field.e.*;
|
||
if (root.kind == .name and l.lookup(root.kind.name) == null) return name;
|
||
return null;
|
||
}
|
||
|
||
fn peekType(l: *Lowerer, e: ast.Expr) ?Ty {
|
||
return switch (e.kind) {
|
||
.specialize => null,
|
||
.int => |x| if (parse_mod.intSuffix(x.text)) |s| Ty{ .int = s } else null,
|
||
.boolean => .bool,
|
||
.name => |n| if (l.lookup(n)) |b| b.ty else null,
|
||
.deref => |x| if (l.peekType(x.*)) |t| t.inner() else null,
|
||
.index => |x| if (x.hi == null) (if (l.peekType(x.e.*)) |t| elemOf(t) else null) else null,
|
||
.array_rep => |x| if (l.peekType(x.e.*)) |t| (l.arrayOf(t, x.len) catch null) else null,
|
||
.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.functionSig(n, e.span)) |sig| sig.ret else null,
|
||
.variant => |v| l.enumType(v.@"enum", e.span),
|
||
else => if (l.calleeSig(x.callee.*)) |sig| sig.ret else if (pathOf(x.callee.*)) |p| l.peekPath(p, x.args) else null,
|
||
},
|
||
.move => |n| if (l.lookup(n)) |b| b.ty else null,
|
||
.variant => |v| l.enumType(v.@"enum", e.span),
|
||
.struct_lit => |x| l.enumOrStruct(x.name, e.span),
|
||
.field => |x| blk: {
|
||
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: {
|
||
const sig = l.calleeSig(x.callee.*) orelse break :blk null;
|
||
for (x.args, 0..) |a, i| {
|
||
const pt: ?Ty = if (i < sig.params.len) sig.params[i] else null;
|
||
if (l.useIn(n, a, pt)) |t| break :blk t;
|
||
}
|
||
break :blk null;
|
||
},
|
||
.if_expr => |x| l.useIn(n, x.cond, .bool) orelse l.usesInBlock(n, x.then) orelse if (x.@"else") |els| switch (els) {
|
||
.block => |b| l.usesInBlock(n, b),
|
||
.@"if" => |inner| l.useIn(n, .{ .span = e.span, .kind = .{ .if_expr = inner } }, want),
|
||
} else null,
|
||
.block => |b| l.usesInBlock(n, b.*),
|
||
else => null,
|
||
};
|
||
}
|
||
|
||
fn typeOfNoFail(l: *Lowerer, 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, t.span),
|
||
else => null,
|
||
};
|
||
}
|
||
|
||
fn enumOrStruct(l: *Lowerer, name: []const u8, span: Span) ?Ty {
|
||
const n = l.boundName(name, span) orelse return null;
|
||
for (l.m.types, 0..) |d, i| if (std.mem.eql(u8, d.name, n)) return .{ .named = @intCast(i) };
|
||
return null;
|
||
}
|
||
|
||
fn enumType(l: *Lowerer, n: []const u8, span: Span) ?Ty {
|
||
const t = l.enumOrStruct(n, span) orelse return null;
|
||
return if (l.m.types[t.named].kind == .@"enum") t else null;
|
||
}
|
||
|
||
fn expr(l: *Lowerer, e: ast.Expr, want: ?Ty) Error!Value {
|
||
switch (e.kind) {
|
||
.specialize => return l.fail("E7006", e.span, "explicit type arguments require a generic function", &.{}),
|
||
.int => |x| {
|
||
const ty: Ty = if (parse_mod.intSuffix(x.text)) |s| .{ .int = s } else want orelse
|
||
return l.fail("E7007", e.span, "the type of this integer literal cannot be determined; add a suffix such as `0u64` or a type annotation", &.{});
|
||
if (ty != .int) return l.fail("E7005", e.span, "an integer literal where another type is expected", &.{.{ .name = "expected", .value = l.diagnosticTyText(ty) }});
|
||
const v = parse_mod.parseIntText(x.text) orelse return l.fail("E7001", e.span, "malformed integer literal", &.{});
|
||
const n = ty.int;
|
||
const bits = intBits(n);
|
||
const max: u128 = if (isSigned(n)) (@as(u128, 1) << @intCast(bits - 1)) - 1 else if (bits == 128) std.math.maxInt(u128) else (@as(u128, 1) << @intCast(bits)) - 1;
|
||
if (v > max) return l.fail("E7005", e.span, "integer literal out of range for its type", &.{ .{ .name = "type", .value = n }, .{ .name = "literal", .value = x.text } });
|
||
return l.def("c", ty, try l.fmt("const.{s} {d}", .{ n, v }), e.span);
|
||
},
|
||
.boolean => |b| return l.def("c", .bool, if (b) "const.bool true" else "const.bool false", e.span),
|
||
.name => |n| {
|
||
const b = 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.diagnosticTyText(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 `*`", &.{});
|
||
// The verifier's code (spec 15 §1 rule 2, spec 04 §28).
|
||
if (in == .atomic) return l.fail("E4202", e.span, "an atomic cell is read only by atomic operations: use `atomic.load(r, ordering)`", &.{});
|
||
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);
|
||
if (v.ty != .int) return l.fail("E7005", x.e.span, "casts convert between integer types", &.{.{ .name = "found", .value = l.diagnosticTyText(v.ty) }});
|
||
// `as` widens without loss, by the verifier's own rule (spec 02 §2).
|
||
if (x.mode == .widen) {
|
||
const a = std.meta.stringToEnum(air_module.IntType, v.ty.int).?;
|
||
const b = std.meta.stringToEnum(air_module.IntType, to.int).?;
|
||
if (a != b and !verifier_types.lossless(a, b))
|
||
return l.fail("E7005", e.span, "`as` only widens without loss; use `as!` (checked, traps T0006 when the value does not fit) or `as%` (wrapping)", &.{ .{ .name = "from", .value = v.ty.int }, .{ .name = "to", .value = to.int } });
|
||
}
|
||
const mode = switch (x.mode) {
|
||
.widen => "widen",
|
||
.checked => "checked",
|
||
.wrap => "wrap",
|
||
};
|
||
return l.def("cast", to, try l.fmt("cast.{s}.{s} %{s}", .{ mode, to.int, v.name }), e.span);
|
||
},
|
||
.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.diagnosticTyText(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);
|
||
// `iref` identity (spec 03 §22): equal graph and slot; never a trap.
|
||
if (ty == .iref) {
|
||
if (op != .eq and op != .ne) return l.fail("E7005", e.span, "`iref` handles are compared with `==` and `!=` only", &.{});
|
||
const c = try l.def("cmp", .bool, try l.fmt("iref.eq %{s}, %{s}", .{ lv.name, rv.name }), e.span);
|
||
if (op == .eq) return c;
|
||
const t = try l.def("c", .bool, "const.bool true", e.span);
|
||
return l.def("cmp", .bool, try l.fmt("xor.bool %{s}, %{s}", .{ c.name, t.name }), e.span);
|
||
}
|
||
if (ty == .bool and !(op == .eq or op == .ne or op == .bit_and or op == .bit_or or op == .bit_xor))
|
||
return l.fail("E7005", e.span, "this operation needs integer operands", &.{});
|
||
if (ty != .bool and ty != .int) return l.fail("E7005", e.span, "this operation needs integer or boolean operands", &.{});
|
||
const t = 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 (try l.moduleCall(callee)) |name| {
|
||
// Reuse ordinary call typing/borrowing/lowering, including E7002.
|
||
const owned_name = try l.arena.dupe(u8, name);
|
||
return l.call(e, .{ .span = callee.span, .kind = .{ .name = owned_name } }, args);
|
||
}
|
||
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.diagnosticTyText(o.ty) }});
|
||
return l.def("v", o.ty.own.*, try l.fmt("own.take %{s}", .{o.name}), e.span);
|
||
}
|
||
if (std.mem.eql(u8, p, "own.free") or std.mem.eql(u8, p, "region.destroy")) {
|
||
if (args.len != 1) return l.fail("E7005", e.span, "this operation takes one linear value", &.{});
|
||
const o = try l.consuming(args[0], null);
|
||
const ok = if (std.mem.eql(u8, p, "own.free")) (o.ty == .own or o.ty == .own_array) else o.ty == .region;
|
||
if (!ok) return l.fail("E7005", args[0].span, if (std.mem.eql(u8, p, "own.free")) "`own.free` takes an `own<T>` or `own_array<T>`" else "`region.destroy` takes a region", &.{.{ .name = "found", .value = l.diagnosticTyText(o.ty) }});
|
||
try l.emit(try l.fmt("{s} %{s}", .{ p, o.name }), e.span);
|
||
return .{ .name = "", .ty = .void };
|
||
}
|
||
if (std.mem.eql(u8, p, "region.reset")) {
|
||
if (args.len != 1 or args[0].kind != .name) return l.fail("E7005", e.span, "`region.reset` takes the region by name", &.{});
|
||
const r = l.lookup(args[0].kind.name) orelse return l.unknown(args[0].span, args[0].kind.name);
|
||
if (r.ty != .region) return l.fail("E7005", args[0].span, "`region.reset` takes a region", &.{.{ .name = "found", .value = l.diagnosticTyText(r.ty) }});
|
||
try l.emit(try l.fmt("region.reset %{s}", .{r.value}), e.span);
|
||
return .{ .name = "", .ty = .void };
|
||
}
|
||
if (try l.concurrencyCall(e, p, args)) |v| return v;
|
||
if (std.mem.startsWith(u8, p, "atomic.")) return l.atomicCall(e, p, args);
|
||
if (authority.intrinsicIndex(p)) |ix| {
|
||
const x = authority.intrinsics[ix];
|
||
var temps: std.ArrayList([]const u8) = .empty;
|
||
const ops = try l.intrinsicOperands(e, x, args, &temps);
|
||
l.uses.insert(.capabilities);
|
||
const text = try l.fmt("intrinsic {s}({s})", .{ x.name, ops });
|
||
const v: Value = if (x.results.len == 0) blk: {
|
||
try l.emit(text, e.span);
|
||
break :blk .{ .name = "", .ty = .void };
|
||
} else try l.def("r", resultTy(x.results[0]), text, e.span);
|
||
try l.endNow(temps.items, e.span);
|
||
return v;
|
||
}
|
||
return l.notYet(callee.span, "this built-in operation (later layers)");
|
||
}
|
||
if (callee.kind == .field and std.mem.eql(u8, callee.kind.field.name, "split_at"))
|
||
return l.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.functionSig(name, callee.span) orelse return l.unknown(callee.span, name);
|
||
if (args.len != sig.params.len) return l.fail("E7005", e.span, "wrong number of arguments", &.{ .{ .name = "function", .value = sig.display_name }, .{ .name = "expected", .value = try l.fmt("{d}", .{sig.params.len}) }, .{ .name = "found", .value = try l.fmt("{d}", .{args.len}) } });
|
||
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})", .{ sig.air_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(if (callee.span.resolved) "generic_call" else if (std.mem.startsWith(u8, name, "std.")) "std_call" else if (std.mem.indexOfScalar(u8, name, '.') != null) "module_call" else name, sig.ret, text, e.span);
|
||
}
|
||
|
||
/// `Name { f: e, … }`: every field exactly once; initializers are
|
||
/// evaluated in declaration order, so the AIR does not depend on the
|
||
/// order the fields are written in (spec 15 §5).
|
||
fn structLit(l: *Lowerer, e: ast.Expr, name: []const u8, inits: []const ast.FieldInit) Error!Value {
|
||
const t = l.enumOrStruct(name, e.span) orelse return l.fail("E7002", e.span, "unknown type", &.{.{ .name = "name", .value = name }});
|
||
const d = l.m.types[t.named];
|
||
if (d.kind != .@"struct") return l.fail("E7005", e.span, "`Name { … }` constructs a struct; this is an enum (use `Enum::Variant`)", &.{.{ .name = "type", .value = d.display_name orelse name }});
|
||
const fields = d.kind.@"struct";
|
||
for (inits, 0..) |fi, i| {
|
||
for (inits[0..i]) |prev| if (std.mem.eql(u8, prev.name, fi.name)) return l.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 = d.display_name orelse name }, .{ .name = "field", .value = fi.name } });
|
||
}
|
||
var args: std.ArrayList(u8) = .empty;
|
||
for (fields, 0..) |f, i| {
|
||
const fi = for (inits) |x| {
|
||
if (std.mem.eql(u8, x.name, f.name)) break x;
|
||
} else return l.fail("E7006", e.span, "missing field", &.{ .{ .name = "type", .value = d.display_name orelse name }, .{ .name = "field", .value = f.name } });
|
||
const ft = try l.typeOf(f.ty);
|
||
const v = try l.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})", .{ l.tyText(t), args.items }), e.span);
|
||
}
|
||
|
||
fn variantValue(l: *Lowerer, e: ast.Expr, enum_name: []const u8, variant: []const u8, args: []const ast.Expr) Error!Value {
|
||
const t = l.enumType(enum_name, e.span) orelse return l.fail("E7002", e.span, "unknown enum", &.{.{ .name = "name", .value = enum_name }});
|
||
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})", .{ l.tyText(t), variant, names.items }), e.span);
|
||
}
|
||
|
||
/// `v.f` on a struct value: `struct.get` (borrows come in layer 4).
|
||
fn fieldValue(l: *Lowerer, e: ast.Expr, base: ast.Expr, name: []const u8) Error!Value {
|
||
var bt = l.peekType(base) orelse return l.fail("E7007", base.span, "the type of this expression cannot be determined", &.{});
|
||
if (bt.isBorrow()) bt = bt.inner().?;
|
||
const d = l.decl(bt) orelse return l.fail("E7005", e.span, "field access on a value that is not a struct", &.{.{ .name = "found", .value = l.diagnosticTyText(bt) }});
|
||
if (d.kind != .@"struct") return l.fail("E7005", e.span, "field access on an enum; use `match`", &.{.{ .name = "type", .value = d.display_name orelse d.name }});
|
||
const f = for (d.kind.@"struct") |x| {
|
||
if (std.mem.eql(u8, x.name, name)) break x;
|
||
} else return l.fail("E7002", e.span, "no such field", &.{ .{ .name = "type", .value = d.display_name orelse d.name }, .{ .name = "field", .value = name } });
|
||
// Through a borrow: borrow the field and load it.
|
||
if (l.rootBinding(base)) |rb| if (rb.kind == .borrow) {
|
||
const p = try l.placeBorrow(e, false, false, e.span);
|
||
const v = try l.def(name, p.v.ty.inner().?, try l.fmt("load %{s}", .{p.v.name}), e.span);
|
||
try l.endNow(p.ends, e.span);
|
||
return v;
|
||
};
|
||
const v = try l.expr(base, bt);
|
||
return l.def(name, try l.typeOf(f.ty), try l.fmt("struct.get @{s}.{s}, %{s}", .{ d.air_name orelse d.name, name, v.name }), e.span);
|
||
}
|
||
|
||
/// One branch of a conditional or `match`: where it ended (null if it
|
||
/// diverged), its value and the variables' values there.
|
||
const ArmEnd = struct { block: ?usize, value: ?Value, values: []const []const u8, span: Span };
|
||
|
||
/// Joins branches that reach the end: one block with a parameter for
|
||
/// the result (if any) and one per carried variable (spec 15 §4).
|
||
fn mergeArms(l: *Lowerer, _: Span, 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.diagnosticTyText(prev) }, .{ .name = "found", .value = l.diagnosticTyText(vt) } });
|
||
} else result_ty = vt;
|
||
};
|
||
if (result_ty == null) {
|
||
l.cur = null;
|
||
return .{ .name = "", .ty = .never };
|
||
}
|
||
const join = try l.newBlock(join_kind);
|
||
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, .{ .match = m });
|
||
const before = try l.snapshot();
|
||
var ends: std.ArrayList(ArmEnd) = .empty;
|
||
|
||
if (l.decl(st)) |d| {
|
||
if (d.kind != .@"enum") return l.fail("E7005", m.scrutinee.span, "`match` over a struct; use field access", &.{.{ .name = "type", .value = d.display_name orelse d.name }});
|
||
const vs = d.kind.@"enum";
|
||
const blocks = try l.arena.alloc(usize, m.arms.len);
|
||
var head: std.ArrayList(u8) = .empty;
|
||
try head.appendSlice(l.arena, try l.fmt("enum.switch {s} %{s}", .{ l.tyText(st), sv.name }));
|
||
for (m.arms, blocks, 0..) |arm, *blk, i| {
|
||
if (arm.pattern.kind != .ctor or arm.pattern.kind.ctor.qualifier == null)
|
||
return l.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.display_name orelse d.name }});
|
||
const c = arm.pattern.kind.ctor;
|
||
const pattern_type = l.enumType(c.qualifier.?, arm.pattern.span);
|
||
if (std.mem.indexOfScalar(u8, c.qualifier.?, '.') != null and pattern_type == null) return l.unknown(arm.pattern.span, c.qualifier.?);
|
||
if (pattern_type == null or !Ty.eql(st, pattern_type.?)) return l.fail("E7005", arm.pattern.span, "variant of a different enum", &.{ .{ .name = "expected", .value = d.display_name orelse d.name }, .{ .name = "found", .value = c.qualifier.? } });
|
||
const vi = for (vs, 0..) |v, k| {
|
||
if (std.mem.eql(u8, v.name, c.name)) break k;
|
||
} else return l.fail("E7002", arm.pattern.span, "no such variant", &.{ .{ .name = "enum", .value = d.display_name orelse d.name }, .{ .name = "variant", .value = c.name } });
|
||
for (m.arms[0..i]) |prev| if (std.mem.eql(u8, prev.pattern.kind.ctor.name, c.name)) return l.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.diagnosticTyText(st) }});
|
||
var head: std.ArrayList(u8) = .empty;
|
||
try head.appendSlice(l.arena, try l.fmt("switch.{s} %{s}, ", .{ st.int, sv.name }));
|
||
const blocks = try l.arena.alloc(usize, m.arms.len);
|
||
var default: ?usize = null;
|
||
var seen: std.ArrayList(u128) = .empty;
|
||
for (m.arms, blocks, 0..) |arm, *blk, i| {
|
||
switch (arm.pattern.kind) {
|
||
.wildcard => {
|
||
if (default != null) return l.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, .{ .match = m });
|
||
const before = try l.snapshot();
|
||
const blocks = try l.arena.alloc(usize, m.arms.len);
|
||
var head: std.ArrayList(u8) = .empty;
|
||
try head.appendSlice(l.arena, try l.fmt("enum.switch {s} %{s}", .{ name, sv.name }));
|
||
for (m.arms, blocks, 0..) |arm, *blk, i| {
|
||
if (arm.pattern.kind != .ctor or arm.pattern.kind.ctor.qualifier == null or !std.mem.eql(u8, arm.pattern.kind.ctor.qualifier.?, name))
|
||
return l.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 (std.mem.startsWith(u8, p, "atomic.") and args.len >= 1) {
|
||
if (eq(u8, p, "atomic.new")) return if (l.peekType(args[0])) |t| (l.wrap(.atomic, t) catch null) else null;
|
||
if (eq(u8, p, "atomic.take")) return if (l.peekType(args[0])) |t| t.inner() else null;
|
||
if (eq(u8, p, "atomic.store") or eq(u8, p, "atomic.fence") or eq(u8, p, "atomic.compare_exchange")) return null;
|
||
// A `ref a` argument, or a `ref<atomic<T>>` binding: the cell's T.
|
||
const cell: ?Ty = if (args[0].kind == .borrow) l.peekType(args[0].kind.borrow.place.*) else if (l.peekType(args[0])) |t| t.inner() else null;
|
||
return if (cell) |c| (if (c == .atomic) c.inner() else null) else null;
|
||
}
|
||
if ((eq(u8, p, "island.root") or eq(u8, p, "frozen.root") or eq(u8, p, "arc.root")) and args.len == 1)
|
||
return if (l.peekType(args[0])) |t| (if (t.inner()) |o| (if (o.inner()) |root| l.wrap(.iref, root) catch null else null) else null) else null;
|
||
if (eq(u8, p, "island.freeze") and args.len == 1) return if (l.peekType(args[0])) |t| (if (t == .island) l.wrap(.frozen, t.inner().?) catch null else null) else null;
|
||
if (eq(u8, p, "arc.from_frozen") and args.len == 1) return if (l.peekType(args[0])) |t| (if (t == .frozen) l.wrap(.arc, t.inner().?) catch null else null) else null;
|
||
if (eq(u8, p, "arc.clone") and args.len == 1) return if (l.peekType(args[0])) |t| (if (t == .arc) t else if (t.inner()) |in| (if (in == .arc) in else null) else null) else null;
|
||
if (eq(u8, p, "channel.dup") and args.len == 1) return if (l.peekType(args[0])) |t| (if (t == .sender) t else if (t.inner()) |in| (if (in == .sender) in else null) else null) else null;
|
||
if (eq(u8, p, "task.spawn") and args.len >= 2) {
|
||
const sig = l.calleeSig(args[1]) orelse return null;
|
||
return l.wrap(.task, sig.ret) catch null;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
fn armBody(l: *Lowerer, body: ast.Expr, want: ?Ty) Error!?Value {
|
||
const v = try l.expr(body, want);
|
||
if (v.ty == .void) return null;
|
||
if (v.ty == .never) {
|
||
l.cur = null;
|
||
return v;
|
||
}
|
||
return v;
|
||
}
|
||
|
||
// ------------------------------------------------------------ places, storage and borrows (layers 3–4)
|
||
|
||
fn endNowIfLive(l: *Lowerer, names: []const []const u8, span: Span) Error!void {
|
||
if (l.cur != null) try l.endNow(names, span);
|
||
}
|
||
|
||
/// Index of the first binding of the innermost lexical scope.
|
||
fn scopeBindingStart(l: *Lowerer) usize {
|
||
return l.scope_binding_start;
|
||
}
|
||
|
||
/// Frame storage for a variable, allocated in the entry block.
|
||
fn storageFor(l: *Lowerer, name: []const u8, ty: Ty, span: Span) Error![]const u8 {
|
||
const st = try l.freshName(name);
|
||
try l.allocs.append(l.arena, .{ .text = try l.fmt("%{s} = local.alloc {s}", .{ st, 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);
|
||
// `ref place` reached through a `mut` borrow (`ref s.buf` with
|
||
// `s: mut<S>`) is a shared reborrow of it (spec 07a `borrow.ref`).
|
||
if (want_slice and !mutable and (p.v.ty == .mut or p.v.ty == .slice_mut)) {
|
||
const t = if (p.v.ty == .mut) try l.wrap(.ref, p.v.ty.inner().?) else try l.wrap(.slice, p.v.ty.inner().?);
|
||
const r = try l.def("r", t, try l.fmt("borrow.ref %{s}", .{p.v.name}), span);
|
||
p = .{ .v = r, .ends = try l.concat(p.ends, r.name) };
|
||
}
|
||
if (want_slice and (p.v.ty == .ref or p.v.ty == .mut) and p.v.ty.inner().? == .array) {
|
||
const elem = p.v.ty.inner().?.array.elem;
|
||
const sl = try l.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, .mutex, .sender, .receiver, .task, .island => if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty),
|
||
.frozen, .arc => if (mutable) return l.fail("E7005", place.span, "frozen graphs and arcs are immutable: borrow them with `ref`", &.{.{ .name = "name", .value = n }}) else try l.wrap(.ref, b.ty),
|
||
// Atomic operations go through a shared borrow (spec 04 §23).
|
||
.atomic => if (mutable) return l.fail("E7005", place.span, "an atomic cell is borrowed with `ref`: every atomic operation goes through a shared borrow", &.{.{ .name = "name", .value = n }}) else try l.wrap(.ref, b.ty),
|
||
else => null,
|
||
};
|
||
const t = bt orelse return l.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.diagnosticTyText(st) }});
|
||
if (d.kind != .@"struct") return l.fail("E7005", place.span, "field of an enum; use `match`", &.{});
|
||
const fd = for (d.kind.@"struct") |x| {
|
||
if (std.mem.eql(u8, x.name, f.name)) break x;
|
||
} else return l.fail("E7002", place.span, "no such field", &.{ .{ .name = "type", .value = d.display_name orelse d.name }, .{ .name = "field", .value = f.name } });
|
||
const ft = try l.typeOf(fd.ty);
|
||
const v = try l.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.air_name orelse 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.diagnosticTyText(bt) }});
|
||
if (x.hi) |hi| {
|
||
// `s[a..b]`: slice.sub with start a and length b - a (checked).
|
||
var sl = base.v;
|
||
var ends = base.ends;
|
||
if (bt == .ref or bt == .mut) {
|
||
sl = try l.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.diagnosticTyText(bt) }});
|
||
const s_ = try l.expr(base, bt);
|
||
return l.def("len", .{ .int = "usize" }, try l.fmt("slice.len %{s}", .{s_.name}), e.span);
|
||
}
|
||
|
||
/// `let (left, right) = s.split_at(k);`: two disjoint borrows of `s`,
|
||
/// bound for the rest of the block (spec 15 §5).
|
||
fn 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.diagnosticTyText(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);
|
||
if (d.ty != .slice_mut) return l.fail("E7005", args[0].span, "`slice.copy` writes to `mut dst` (a `slice_mut<T>`)", &.{.{ .name = "found", .value = l.diagnosticTyText(d.ty) }});
|
||
if (src.ty != .slice and src.ty != .slice_mut) return l.fail("E7005", args[1].span, "`slice.copy` reads from `ref src` (a `slice<T>`)", &.{.{ .name = "found", .value = l.diagnosticTyText(src.ty) }});
|
||
if (!d.ty.inner().?.eql(src.ty.inner().?)) return l.fail("E7005", args[1].span, "`slice.copy` copies between slices of the same element type", &.{ .{ .name = "expected", .value = l.diagnosticTyText(d.ty.inner().?) }, .{ .name = "found", .value = l.diagnosticTyText(src.ty.inner().?) } });
|
||
try l.emit(try l.fmt("slice.copy %{s}, %{s}", .{ d.name, src.name }), e.span);
|
||
try l.endNow(temps.items, e.span);
|
||
return .{ .name = "", .ty = .void };
|
||
}
|
||
|
||
/// Names that need frame storage in this function: every variable that is
|
||
/// borrowed, indexed, or written through a field or element (spec 15 §9).
|
||
/// Deterministic and by name.
|
||
fn findAddressable(l: *Lowerer, body: ast.Block) Error!void {
|
||
try l.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", "task.check_cancel", "task.join_cancel", "island.create", "island.alloc", "arc.new" };
|
||
for (ops) |o| if (std.mem.eql(u8, o, path)) return {};
|
||
if (authority.intrinsicIndex(path)) |i| if (authority.intrinsics[i].fallible) return {};
|
||
return null;
|
||
}
|
||
|
||
// ------------------------------------------------------------ tasks and channels (layer 7)
|
||
|
||
// ------------------------------------------------------------ atomics (spec 15 §12, spec 04 §42)
|
||
|
||
/// An ordering, written as a bare word (spec 15 §12).
|
||
fn ordering(l: *Lowerer, a: ast.Expr) Error![]const u8 {
|
||
const words = [_][]const u8{ "relaxed", "acquire", "release", "acq_rel", "seq_cst" };
|
||
if (a.kind == .name) for (words) |w| if (std.mem.eql(u8, a.kind.name, w)) return w;
|
||
return l.fail("E7006", a.span, "an ordering is one of the words relaxed, acquire, release, acq_rel, seq_cst, written in place", &.{});
|
||
}
|
||
|
||
/// The cell operand of an atomic operation: a `ref<atomic<T>>` binding or
|
||
/// parameter, or `ref a` of an atomic, borrowed for the operation.
|
||
fn cellOperand(l: *Lowerer, a: ast.Expr, temps: *std.ArrayList([]const u8)) Error!Value {
|
||
if (a.kind == .borrow) {
|
||
const br = a.kind.borrow;
|
||
if (br.mutable) return l.fail("E7005", a.span, "atomic operations take `ref` of the cell, never `mut`", &.{});
|
||
const b = try l.bindingOf(br.place.*, "an atomic cell");
|
||
if (b.ty != .atomic) return l.fail("E7005", a.span, "an atomic operation takes `ref` of an `atomic<T>`", &.{.{ .name = "found", .value = l.diagnosticTyText(b.ty) }});
|
||
const r = try l.def(br.place.kind.name, try l.wrap(.ref, b.ty), try l.fmt("borrow.ref %{s}", .{b.value}), a.span);
|
||
try temps.append(l.arena, r.name);
|
||
return r;
|
||
}
|
||
const b = try l.bindingOf(a, "an atomic cell");
|
||
if (b.ty == .atomic) return l.fail("E7005", a.span, "pass the cell as `ref a` (or a `ref` binding of it): atomic operations go through a shared borrow", &.{.{ .name = "suggestion", .value = try l.fmt("ref {s}", .{a.kind.name}) }});
|
||
if (b.ty == .ref and b.ty.inner().? == .atomic) return .{ .name = b.value, .ty = b.ty };
|
||
return l.fail("E7005", a.span, "an atomic operation takes a `ref<atomic<T>>`", &.{.{ .name = "found", .value = l.diagnosticTyText(b.ty) }});
|
||
}
|
||
|
||
fn atomicCall(l: *Lowerer, e: ast.Expr, p: []const u8, args: []const ast.Expr) Error!Value {
|
||
const eq = std.mem.eql;
|
||
if (eq(u8, p, "atomic.new")) {
|
||
if (args.len != 1) return l.fail("E7005", e.span, "`atomic.new` takes the initial value", &.{});
|
||
const v = try l.expr(args[0], null);
|
||
if (!atomicScalar(v.ty)) return l.fail("E7005", args[0].span, "atomic<T> needs bool or an integer of at most 64 bits", &.{.{ .name = "found", .value = l.diagnosticTyText(v.ty) }});
|
||
return l.def("atomic", try l.wrap(.atomic, v.ty), try l.fmt("atomic.new %{s}", .{v.name}), e.span);
|
||
}
|
||
if (eq(u8, p, "atomic.take")) {
|
||
if (args.len != 1) return l.fail("E7005", e.span, "`atomic.take` takes one cell", &.{});
|
||
const c = try l.consuming(args[0], null);
|
||
if (c.ty != .atomic) return l.fail("E7005", args[0].span, "`atomic.take` takes an `atomic<T>`", &.{.{ .name = "found", .value = l.diagnosticTyText(c.ty) }});
|
||
return l.def("v", c.ty.inner().?, try l.fmt("atomic.take %{s}", .{c.name}), e.span);
|
||
}
|
||
if (eq(u8, p, "atomic.fence")) {
|
||
if (args.len != 1) return l.fail("E7005", e.span, "`atomic.fence` takes one ordering", &.{});
|
||
try l.emit(try l.fmt("atomic.fence.{s}", .{try l.ordering(args[0])}), e.span);
|
||
return .{ .name = "", .ty = .void };
|
||
}
|
||
if (eq(u8, p, "atomic.compare_exchange"))
|
||
return l.fail("E7006", e.span, "`atomic.compare_exchange` has two results: `let (old, exchanged) = atomic.compare_exchange(c, expected, desired, success, failure);`", &.{});
|
||
var temps: std.ArrayList([]const u8) = .empty;
|
||
const want: usize = if (eq(u8, p, "atomic.load")) 2 else 3;
|
||
if (args.len != want) return l.fail("E7005", e.span, "wrong number of operands", &.{ .{ .name = "operation", .value = p }, .{ .name = "expected", .value = try l.fmt("{d}", .{want}) } });
|
||
const c = try l.cellOperand(args[0], &temps);
|
||
const t = c.ty.inner().?.inner().?;
|
||
const ord = try l.ordering(args[want - 1]);
|
||
if (eq(u8, p, "atomic.load")) {
|
||
const v = try l.def("v", t, try l.fmt("atomic.load.{s} %{s}", .{ ord, c.name }), e.span);
|
||
try l.endNow(temps.items, e.span);
|
||
return v;
|
||
}
|
||
const operand = try l.expr(args[1], t);
|
||
try l.checkTy(args[1].span, operand.ty, t);
|
||
if (eq(u8, p, "atomic.store")) {
|
||
try l.emit(try l.fmt("atomic.store.{s} %{s}, %{s}", .{ ord, c.name, operand.name }), e.span);
|
||
try l.endNow(temps.items, e.span);
|
||
return .{ .name = "", .ty = .void };
|
||
}
|
||
const op: []const u8 = if (eq(u8, p, "atomic.swap")) "xchg" else p["atomic.".len..];
|
||
if ((eq(u8, op, "add.wrap") or eq(u8, op, "sub.wrap")) and t != .int) return l.fail("E7005", args[1].span, "`atomic.add.wrap` and `atomic.sub.wrap` need an integer cell", &.{.{ .name = "found", .value = l.diagnosticTyText(t) }});
|
||
const v = try l.def("old", t, try l.fmt("atomic.{s}.{s} %{s}, %{s}", .{ op, ord, c.name, operand.name }), e.span);
|
||
try l.endNow(temps.items, e.span);
|
||
return v;
|
||
}
|
||
|
||
/// `let (old, exchanged) = atomic.compare_exchange(c, expected, desired,
|
||
/// success, failure);` (spec 15 §12): the second multi-result binding.
|
||
fn compareExchangeLet(l: *Lowerer, s: ast.Stmt, names: []const []const u8, e: ast.Expr) Error!void {
|
||
const args = e.kind.call.args;
|
||
if (args.len != 5) return l.fail("E7005", e.span, "`atomic.compare_exchange` takes a cell, the expected and the desired value, and two orderings", &.{});
|
||
var temps: std.ArrayList([]const u8) = .empty;
|
||
const c = try l.cellOperand(args[0], &temps);
|
||
const t = c.ty.inner().?.inner().?;
|
||
const expected = try l.expr(args[1], t);
|
||
try l.checkTy(args[1].span, expected.ty, t);
|
||
const desired = try l.expr(args[2], t);
|
||
try l.checkTy(args[2].span, desired.ty, t);
|
||
const succ = try l.ordering(args[3]);
|
||
const failure = try l.ordering(args[4]);
|
||
const old = try l.freshName(names[0]);
|
||
const ok = try l.freshName(names[1]);
|
||
try l.emit(try l.fmt("%{s}, %{s} = atomic.cmpxchg.{s}.{s} %{s}, %{s}, %{s}", .{ old, ok, succ, failure, c.name, expected.name, desired.name }), s.span);
|
||
try l.endNow(temps.items, s.span);
|
||
try l.bindings.append(l.arena, .{ .name = names[0], .mutable = false, .value = old, .ty = t, .kind = .ssa });
|
||
try l.bindings.append(l.arena, .{ .name = names[1], .mutable = false, .value = ok, .ty = .bool, .kind = .ssa });
|
||
}
|
||
|
||
fn bindingOf(l: *Lowerer, a: ast.Expr, what: []const u8) Error!*Binding {
|
||
if (a.kind != .name) return l.fail("E7005", a.span, try l.fmt("{s} is expected here, by name", .{what}), &.{});
|
||
return l.lookup(a.kind.name) orelse l.unknown(a.span, a.kind.name);
|
||
}
|
||
|
||
/// An endpoint operand the operation borrows (`mut` or `ref`): the
|
||
/// endpoint by name, borrowed for the operation, or a borrow binding of it.
|
||
fn endpointOperand(l: *Lowerer, a: ast.Expr, tag: std.meta.Tag(Ty), mutable: bool, temps: *std.ArrayList([]const u8)) Error!Value {
|
||
const what = if (tag == .sender) "a sender" else "a receiver";
|
||
if (a.kind == .borrow) return l.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.diagnosticTyText(b.ty) }});
|
||
}
|
||
|
||
/// The task and channel operations that are plain calls; null for any
|
||
/// other path.
|
||
fn concurrencyCall(l: *Lowerer, e: ast.Expr, p: []const u8, args: []const ast.Expr) Error!?Value {
|
||
const eq = struct {
|
||
fn f(a: []const u8, b: []const u8) bool {
|
||
return std.mem.eql(u8, a, b);
|
||
}
|
||
}.f;
|
||
if (eq(p, "task.spawn")) {
|
||
if (args.len < 2) return l.fail("E7005", e.span, "`task.spawn` takes a scope, a function and its arguments", &.{});
|
||
const sb = try l.bindingOf(args[0], "a task scope");
|
||
if (sb.ty != .scope) return l.fail("E7005", args[0].span, "`task.spawn` spawns into a scope: `scope s { … task.spawn(s, f, …) … }`", &.{.{ .name = "found", .value = l.diagnosticTyText(sb.ty) }});
|
||
const scope_name = sb.value;
|
||
const fname = try expressionPath(l.arena, args[1]) orelse return l.fail("E7005", args[1].span, "the function to spawn is named", &.{});
|
||
const sig = l.functionSig(fname, args[1].span) orelse return l.unknown(args[1].span, fname);
|
||
const fargs = args[2..];
|
||
if (fargs.len != sig.params.len) return l.fail("E7005", e.span, "wrong number of arguments", &.{ .{ .name = "function", .value = sig.display_name }, .{ .name = "expected", .value = try l.fmt("{d}", .{sig.params.len}) }, .{ .name = "found", .value = try l.fmt("{d}", .{fargs.len}) } });
|
||
var names: std.ArrayList(u8) = .empty;
|
||
for (fargs, sig.params, 0..) |a, pt, i| {
|
||
// A borrow is lent to the task until its join, so it is bound
|
||
// by the program, not made for the call (spec 15 §7).
|
||
if (a.kind == .borrow or a.kind == .bytes) return l.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, sig.air_name, names.items }), e.span);
|
||
}
|
||
if (eq(p, "task.join")) {
|
||
if (args.len != 1) return l.fail("E7005", e.span, "`task.join` takes one task", &.{});
|
||
const t = try l.consuming(args[0], null);
|
||
if (t.ty != .task) return l.fail("E7005", args[0].span, "`task.join` takes a `task<T>`", &.{.{ .name = "found", .value = l.diagnosticTyText(t.ty) }});
|
||
const rt = t.ty.task.*;
|
||
if (rt == .void) {
|
||
try l.emit(try l.fmt("task.join %{s}", .{t.name}), e.span);
|
||
return .{ .name = "", .ty = .void };
|
||
}
|
||
return try l.def("r", rt, try l.fmt("task.join %{s}", .{t.name}), e.span);
|
||
}
|
||
if (eq(p, "task.cancel")) {
|
||
if (args.len != 1) return l.fail("E7005", e.span, "`task.cancel` takes one task, by name", &.{});
|
||
const b = try l.bindingOf(args[0], "a task");
|
||
if (b.ty != .task) return l.fail("E7005", args[0].span, "`task.cancel` takes a `task<T>`", &.{.{ .name = "found", .value = l.diagnosticTyText(b.ty) }});
|
||
try l.emit(try l.fmt("task.cancel %{s}", .{b.value}), e.span);
|
||
return .{ .name = "", .ty = .void };
|
||
}
|
||
if (eq(p, "task.cancelled")) {
|
||
if (args.len != 0) return l.fail("E7005", e.span, "`task.cancelled()` takes no operands", &.{});
|
||
return try l.def("c", .bool, "task.cancelled", e.span);
|
||
}
|
||
if (eq(p, "channel.dup")) {
|
||
if (args.len != 1) return l.fail("E7005", e.span, "`channel.dup` takes one sender", &.{});
|
||
var temps: std.ArrayList([]const u8) = .empty;
|
||
const tx = try l.endpointOperand(args[0], .sender, false, &temps);
|
||
const st = tx.ty.inner().?;
|
||
const v = try l.def("tx", st, try l.fmt("channel.sender.dup %{s}", .{tx.name}), e.span);
|
||
try l.endNow(temps.items, e.span);
|
||
return v;
|
||
}
|
||
if (eq(p, "island.root") or eq(p, "frozen.root") or eq(p, "arc.root")) {
|
||
if (args.len != 1) return l.fail("E7005", e.span, "`.root` takes the graph's borrow binding", &.{});
|
||
const g = try l.graphBorrow(args[0], p[0..std.mem.indexOfScalar(u8, p, '.').?], false);
|
||
return try l.def("root", try l.wrap(.iref, g.ty.inner().?.inner().?), try l.fmt("{s} %{s}", .{ p, g.name }), e.span);
|
||
}
|
||
if (eq(p, "island.freeze") or eq(p, "arc.from_frozen")) {
|
||
if (args.len != 1) return l.fail("E7005", e.span, "this operation takes one graph owner", &.{});
|
||
const o = try l.consuming(args[0], null);
|
||
const want: std.meta.Tag(Ty) = if (eq(p, "island.freeze")) .island else .frozen;
|
||
if (std.meta.activeTag(o.ty) != want) return l.fail("E7005", args[0].span, if (want == .island) "`island.freeze` takes an `island<T>`" else "`arc.from_frozen` takes a `frozen<T>`", &.{.{ .name = "found", .value = l.diagnosticTyText(o.ty) }});
|
||
const out = if (want == .island) try l.wrap(.frozen, o.ty.inner().?) else try l.wrap(.arc, o.ty.inner().?);
|
||
return try l.def(if (want == .island) "frozen" else "arc", out, try l.fmt("{s} %{s}", .{ p, o.name }), e.span);
|
||
}
|
||
if (eq(p, "island.destroy") or eq(p, "frozen.release") or eq(p, "arc.release")) {
|
||
if (args.len != 1) return l.fail("E7005", e.span, "this operation takes one graph owner", &.{});
|
||
const o = try l.consuming(args[0], null);
|
||
const want: std.meta.Tag(Ty) = if (eq(p, "island.destroy")) .island else if (eq(p, "frozen.release")) .frozen else .arc;
|
||
if (std.meta.activeTag(o.ty) != want) return l.fail("E7005", args[0].span, "this operation takes another graph owner", &.{ .{ .name = "operation", .value = p }, .{ .name = "found", .value = l.diagnosticTyText(o.ty) } });
|
||
try l.emit(try l.fmt("{s} %{s}", .{ p, o.name }), e.span);
|
||
return .{ .name = "", .ty = .void };
|
||
}
|
||
if (eq(p, "arc.clone")) {
|
||
if (args.len != 1 or args[0].kind != .name) return l.fail("E7005", e.span, "`arc.clone` takes an arc by name", &.{});
|
||
const b = l.lookup(args[0].kind.name) orelse return l.unknown(args[0].span, args[0].kind.name);
|
||
if (b.ty == .arc) {
|
||
const r = try l.def(args[0].kind.name, try l.wrap(.ref, b.ty), try l.fmt("borrow.ref %{s}", .{b.value}), args[0].span);
|
||
const v = try l.def("arc", b.ty, try l.fmt("arc.clone %{s}", .{r.name}), e.span);
|
||
try l.emit(try l.fmt("borrow.end %{s}", .{r.name}), e.span);
|
||
return v;
|
||
}
|
||
if (b.ty == .ref and b.ty.inner().? == .arc) return try l.def("arc", b.ty.inner().?, try l.fmt("arc.clone %{s}", .{b.value}), e.span);
|
||
return l.fail("E7005", args[0].span, "`arc.clone` takes an `arc<T>`", &.{.{ .name = "found", .value = l.diagnosticTyText(b.ty) }});
|
||
}
|
||
if (eq(p, "island.at") or eq(p, "frozen.at") or eq(p, "arc.at"))
|
||
return l.fail("E7006", e.span, "a graph access is a borrow: bind it with `ref x = island.at(g, r);` or `mut x = island.at(g, r);`", &.{});
|
||
if (eq(p, "mutex.make")) {
|
||
if (args.len != 1) return l.fail("E7005", e.span, "`mutex.make` takes the initial value", &.{});
|
||
const v = try l.consuming(args[0], null);
|
||
try l.elementRule(v.ty, args[0].span, "a mutex's content");
|
||
return try l.def("m", try l.wrap(.mutex, v.ty), try l.fmt("mutex.make %{s}", .{v.name}), e.span);
|
||
}
|
||
if (eq(p, "mutex.take")) {
|
||
if (args.len != 1) return l.fail("E7005", e.span, "`mutex.take` takes one mutex", &.{});
|
||
const m = try l.consuming(args[0], null);
|
||
if (m.ty != .mutex) return l.fail("E7005", args[0].span, "`mutex.take` takes a `mutex<T>`", &.{.{ .name = "found", .value = l.diagnosticTyText(m.ty) }});
|
||
return try l.def("v", m.ty.mutex.*, try l.fmt("mutex.take %{s}", .{m.name}), e.span);
|
||
}
|
||
if (eq(p, "channel.close_sender")) {
|
||
if (args.len != 1) return l.fail("E7005", e.span, "`channel.close_sender` takes one sender", &.{});
|
||
const tx = try l.consuming(args[0], null);
|
||
if (tx.ty != .sender) return l.fail("E7005", args[0].span, "`channel.close_sender` takes a `sender<T>`", &.{.{ .name = "found", .value = l.diagnosticTyText(tx.ty) }});
|
||
try l.emit(try l.fmt("channel.close_sender %{s}", .{tx.name}), e.span);
|
||
return .{ .name = "", .ty = .void };
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/// `lock ref m as x { body } cancelled { cb }` (spec 15 §7): `mutex.lock`
|
||
/// on a shared borrow of the mutex; on `ok`, `mutex.borrow` of the guard
|
||
/// bound as `x: mut<T>`, and at every normal exit of the body
|
||
/// `borrow.end x` then `mutex.unlock`. The guard is never a source value.
|
||
fn lockStmt(l: *Lowerer, s: ast.Stmt, place: ast.Expr, name: []const u8, body: ast.Block, cancelled: ast.Block) Error!void {
|
||
// The mutex: a `ref<mutex<T>>` binding, or a mutex borrowed for the lock.
|
||
var temps: std.ArrayList([]const u8) = .empty;
|
||
if (place.kind != .name) return l.fail("E7005", place.span, "`lock ref m`: the mutex or a `ref<mutex<T>>` binding, by name", &.{});
|
||
const b = l.lookup(place.kind.name) orelse return l.unknown(place.span, place.kind.name);
|
||
const mr: Value = switch (b.ty) {
|
||
.mutex => blk: {
|
||
const v = try l.def(place.kind.name, try l.wrap(.ref, b.ty), try l.fmt("borrow.ref %{s}", .{b.value}), place.span);
|
||
try temps.append(l.arena, v.name);
|
||
break :blk v;
|
||
},
|
||
.ref => if (b.ty.ref.* == .mutex) .{ .name = b.value, .ty = b.ty } else return l.fail("E7005", place.span, "`lock` needs a mutex", &.{.{ .name = "found", .value = l.diagnosticTyText(b.ty) }}),
|
||
else => return l.fail("E7005", place.span, "`lock` needs a mutex", &.{.{ .name = "found", .value = l.diagnosticTyText(b.ty) }}),
|
||
};
|
||
const elem = mr.ty.ref.mutex.*;
|
||
const depth = l.bindings.items.len;
|
||
const vars = try l.carriedLive(depth, s.span, .{ .lock = .{ body, cancelled } });
|
||
const before = try l.snapshot();
|
||
const locked = try l.newBlock("locked");
|
||
const guard = try l.freshName("guard");
|
||
try l.blocks.items[locked].params.append(l.arena, .{ .name = guard, .ty = try l.wrap(.guard, elem) });
|
||
const canc = try l.newBlock("lock_cancelled");
|
||
try l.term(try l.fmt("mutex.lock %{s}, ok -> @{s}, cancelled -> @{s}", .{ mr.name, l.blocks.items[locked].name, l.blocks.items[canc].name }), s.span);
|
||
var ends: std.ArrayList(ArmEnd) = .empty;
|
||
|
||
l.cur = locked;
|
||
const x = try l.def(name, try l.wrap(.mut, elem), try l.fmt("mutex.borrow %{s}", .{guard}), s.span);
|
||
for (temps.items) |t| try l.pending_ends.append(l.arena, .{ .name = t, .span = body.span });
|
||
try l.pending_ends.append(l.arena, .{ .name = guard, .span = body.span, .op = "mutex.unlock" });
|
||
try l.pending_ends.append(l.arena, .{ .name = x.name, .span = body.span });
|
||
try l.pending_bindings.append(l.arena, .{ .name = name, .mutable = false, .value = x.name, .ty = x.ty, .kind = .borrow });
|
||
const bv = try l.blockBody(body);
|
||
try ends.append(l.arena, .{ .block = l.cur, .value = bv, .values = try l.snapshot(), .span = body.span });
|
||
|
||
l.restore(before);
|
||
l.cur = canc;
|
||
try l.endNow(temps.items, cancelled.span);
|
||
const cv = try l.blockBody(cancelled);
|
||
try ends.append(l.arena, .{ .block = l.cur, .value = cv, .values = try l.snapshot(), .span = cancelled.span });
|
||
_ = try l.mergeArms(s.span, "lock", ends.items, vars, before, "endlock");
|
||
}
|
||
|
||
/// `select { recv(rx) { … } send(tx, v) { … } cancelled(…) => … }`
|
||
/// (spec 15 §7, spec 04 §39). Each endpoint is borrowed once for the
|
||
/// operation. `V` is the distinct send values in order of first
|
||
/// appearance; every edge binds its own value (a received `T`) and then
|
||
/// the values of `V` not sent on it.
|
||
fn selectStmt(l: *Lowerer, s: ast.Stmt, sel: ast.Select) Error!void {
|
||
if (sel.arms.len == 0) return l.fail("E7006", s.span, "a `select` has at least one `recv` or `send` arm", &.{});
|
||
const Sent = struct { key: ?[]const u8, v: Value };
|
||
var values: std.ArrayList(Sent) = .empty;
|
||
const arm_value = try l.arena.alloc(?usize, sel.arms.len);
|
||
// Values first (as for an assignment), then the endpoint borrows.
|
||
for (sel.arms, arm_value) |a, *av| {
|
||
av.* = null;
|
||
const ve = a.value orelse continue;
|
||
const key: ?[]const u8 = switch (ve.kind) {
|
||
.move, .name => |n| n,
|
||
else => null,
|
||
};
|
||
if (key) |k| for (values.items, 0..) |x, i| if (x.key != null and std.mem.eql(u8, x.key.?, k)) {
|
||
av.* = i;
|
||
break;
|
||
};
|
||
if (av.* == null) {
|
||
const v = try l.consuming(ve, null);
|
||
try values.append(l.arena, .{ .key = key, .v = v });
|
||
av.* = values.items.len - 1;
|
||
}
|
||
}
|
||
var temps: std.ArrayList([]const u8) = .empty;
|
||
const Ep = struct { name: []const u8, v: Value };
|
||
var eps: std.ArrayList(Ep) = .empty;
|
||
const arm_ep = try l.arena.alloc(Value, sel.arms.len);
|
||
for (sel.arms, arm_ep, 0..) |a, *ae, ai| {
|
||
const found = for (eps.items) |x| {
|
||
if (std.mem.eql(u8, x.name, a.endpoint)) break x.v;
|
||
} else null;
|
||
ae.* = found orelse blk: {
|
||
const ex: ast.Expr = .{ .span = a.span, .kind = .{ .name = a.endpoint } };
|
||
const v = try l.endpointOperand(ex, if (a.send) .sender else .receiver, true, &temps);
|
||
try eps.append(l.arena, .{ .name = a.endpoint, .v = v });
|
||
break :blk v;
|
||
};
|
||
if (a.send) {
|
||
const et = ae.ty.inner().?.sender.*;
|
||
try l.checkTy(a.value.?.span, values.items[arm_value[ai].?].v.ty, et);
|
||
}
|
||
}
|
||
// Edges: per arm `ok` and `closed`, then `cancelled`.
|
||
const Edge = struct { arm: ?usize, role: []const u8, params: []const Ty, values: []const usize, block: usize = 0 };
|
||
var edges: std.ArrayList(Edge) = .empty;
|
||
const notSent = struct {
|
||
fn f(lw: *Lowerer, n: usize, sent: ?usize) Error![]const usize {
|
||
var out: std.ArrayList(usize) = .empty;
|
||
for (0..n) |i| if (sent == null or sent.? != i) try out.append(lw.arena, i);
|
||
return out.items;
|
||
}
|
||
}.f;
|
||
for (sel.arms, 0..) |a, i| {
|
||
if (a.send) {
|
||
try edges.append(l.arena, .{ .arm = i, .role = "ok", .params = &.{}, .values = try notSent(l, values.items.len, arm_value[i]) });
|
||
} else {
|
||
try edges.append(l.arena, .{ .arm = i, .role = "ok", .params = try l.arena.dupe(Ty, &.{arm_ep[i].ty.inner().?.receiver.*}), .values = try notSent(l, values.items.len, null) });
|
||
}
|
||
try edges.append(l.arena, .{ .arm = i, .role = "closed", .params = &.{}, .values = try notSent(l, values.items.len, null) });
|
||
}
|
||
try edges.append(l.arena, .{ .arm = null, .role = "cancelled", .params = &.{}, .values = try notSent(l, values.items.len, null) });
|
||
|
||
// Every outcome of every arm is matched exactly once.
|
||
for (sel.arms) |a| {
|
||
for (a.arms, 0..) |arm, k| {
|
||
if (arm.pattern.kind != .ctor or arm.pattern.kind.ctor.qualifier != null) return l.fail("E7006", arm.pattern.span, "a `select` arm names its outcomes: `ok(…)` and `closed(…)`", &.{});
|
||
const c = arm.pattern.kind.ctor;
|
||
if (!std.mem.eql(u8, c.name, "ok") and !std.mem.eql(u8, c.name, "closed")) return l.fail("E7002", arm.pattern.span, "a `select` arm has the outcomes `ok` and `closed`; `cancelled` is the `select`'s own arm", &.{.{ .name = "outcome", .value = c.name }});
|
||
for (a.arms[0..k]) |prev| if (std.mem.eql(u8, prev.pattern.kind.ctor.name, c.name)) return l.fail("E7006", arm.pattern.span, "outcome matched twice", &.{.{ .name = "outcome", .value = c.name }});
|
||
}
|
||
for ([_][]const u8{ "ok", "closed" }) |role| {
|
||
const covered = for (a.arms) |arm| {
|
||
if (std.mem.eql(u8, arm.pattern.kind.ctor.name, role)) break true;
|
||
} else false;
|
||
if (!covered) return l.fail("E7004", a.span, "the arm does not handle every outcome", &.{.{ .name = "missing", .value = role }});
|
||
}
|
||
}
|
||
|
||
const depth = l.bindings.items.len;
|
||
const vars = try l.carriedLive(depth, s.span, .{ .select = sel });
|
||
const before = try l.snapshot();
|
||
var text: std.ArrayList(u8) = .empty;
|
||
try text.appendSlice(l.arena, "select ");
|
||
for (edges.items) |*ed| {
|
||
ed.block = try l.newBlock(ed.role);
|
||
for (ed.params) |pt| try l.blocks.items[ed.block].params.append(l.arena, .{ .name = try l.freshName(ed.role), .ty = pt });
|
||
for (ed.values) |vi| try l.blocks.items[ed.block].params.append(l.arena, .{ .name = try l.freshName(ed.role), .ty = values.items[vi].v.ty });
|
||
}
|
||
for (sel.arms, 0..) |a, i| {
|
||
const okb = edges.items[2 * i].block;
|
||
const clb = edges.items[2 * i + 1].block;
|
||
if (a.send) {
|
||
try text.appendSlice(l.arena, try l.fmt("[send %{s}, %{s}, ok -> @{s}, closed -> @{s}], ", .{ arm_ep[i].name, values.items[arm_value[i].?].v.name, l.blocks.items[okb].name, l.blocks.items[clb].name }));
|
||
} else {
|
||
try text.appendSlice(l.arena, try l.fmt("[recv %{s}, ok -> @{s}, closed -> @{s}], ", .{ arm_ep[i].name, l.blocks.items[okb].name, l.blocks.items[clb].name }));
|
||
}
|
||
}
|
||
try text.appendSlice(l.arena, try l.fmt("cancelled -> @{s}", .{l.blocks.items[edges.items[edges.items.len - 1].block].name}));
|
||
try l.term(text.items, s.span);
|
||
|
||
var ends: std.ArrayList(ArmEnd) = .empty;
|
||
for (edges.items) |ed| {
|
||
const binds: []const []const u8, const body: ast.Expr, const pspan: Span = if (ed.arm) |ai| blk: {
|
||
const a = sel.arms[ai];
|
||
const arm = for (a.arms) |x| {
|
||
if (std.mem.eql(u8, x.pattern.kind.ctor.name, ed.role)) break x;
|
||
} else unreachable;
|
||
break :blk .{ arm.pattern.kind.ctor.binds, arm.body, arm.pattern.span };
|
||
} else .{ sel.cancelled_binds, sel.cancelled, sel.span };
|
||
const params = l.blocks.items[ed.block].params.items;
|
||
if (binds.len != params.len) return l.fail("E7005", pspan, "the edge binds its own value, then the values not sent on it, in order of first appearance", &.{ .{ .name = "outcome", .value = ed.role }, .{ .name = "expected", .value = try l.fmt("{d}", .{params.len}) } });
|
||
l.restore(before);
|
||
l.cur = ed.block;
|
||
try l.endNow(temps.items, pspan);
|
||
try l.scopes.append(l.arena, .empty);
|
||
for (binds, params) |bn, prm| {
|
||
if (std.mem.eql(u8, bn, "_")) continue;
|
||
if (l.lookup(bn)) |old| if (old.mutable and old.kind == .ssa and old.ty.eql(prm.ty)) {
|
||
old.value = prm.name;
|
||
continue;
|
||
};
|
||
try l.bindings.append(l.arena, .{ .name = bn, .mutable = false, .value = prm.name, .ty = prm.ty });
|
||
}
|
||
const v = try l.armBody(body, null);
|
||
if (l.cur != null) try l.endScopes(l.scopes.items.len - 1, body.span);
|
||
_ = l.scopes.pop();
|
||
l.bindings.shrinkRetainingCapacity(before.len);
|
||
try ends.append(l.arena, .{ .block = l.cur, .value = v, .values = try l.snapshot(), .span = body.span });
|
||
}
|
||
_ = try l.mergeArms(s.span, "select", ends.items, vars, before, "endselect");
|
||
}
|
||
|
||
/// Element rules of channels and mutexes (spec 04 §38.1): no borrow,
|
||
/// scope, task, shield or guard, at any depth. Endpoints inside are the
|
||
/// reserved `channel_transfer`, left to the verifier (`E0006`).
|
||
fn elementRule(l: *Lowerer, t: Ty, span: Span, what: []const u8) Error!void {
|
||
if (try l.forbiddenIn(t, 0)) |bad| return l.fail("E7005", span, try l.fmt("{s} contains no borrow, scope, task, shield or guard", .{what}), &.{ .{ .name = "type", .value = l.diagnosticTyText(t) }, .{ .name = "found", .value = l.diagnosticTyText(bad) } });
|
||
}
|
||
|
||
fn forbiddenIn(l: *Lowerer, t: Ty, depth: u32) Error!?Ty {
|
||
if (depth > 32) return null;
|
||
return switch (t) {
|
||
.ref, .mut, .slice, .slice_mut, .scope, .task, .shield, .guard => t,
|
||
.array => |a| l.forbiddenIn(a.elem, depth + 1),
|
||
.own, .own_array, .mutex => |x| l.forbiddenIn(x.*, depth + 1),
|
||
.named => |i| blk: {
|
||
const d = l.m.types[i];
|
||
switch (d.kind) {
|
||
.@"struct" => |fs| for (fs) |f| if (try l.forbiddenIn(try l.typeOf(f.ty), depth + 1)) |bad| break :blk bad,
|
||
.@"enum" => |vs| for (vs) |v| for (v.payload) |pt| if (try l.forbiddenIn(try l.typeOf(pt), depth + 1)) |bad| break :blk bad,
|
||
}
|
||
break :blk null;
|
||
},
|
||
else => null,
|
||
};
|
||
}
|
||
|
||
/// The named borrow binding of a graph owner that `.root`, `.at` and
|
||
/// `island.alloc` take (spec 15 §8: container borrows are explicit).
|
||
fn graphBorrow(l: *Lowerer, a: ast.Expr, owner: []const u8, mutable: bool) Error!Value {
|
||
if (a.kind == .borrow) return l.fail("E7006", a.span, "the graph's borrow is bound first (`mut g = isl;`), so it outlives the borrows taken from it", &.{});
|
||
if (a.kind != .name) return l.fail("E7005", a.span, "the graph's borrow binding is expected here, by name", &.{});
|
||
const b = l.lookup(a.kind.name) orelse return l.unknown(a.span, a.kind.name);
|
||
const tag = std.meta.stringToEnum(std.meta.Tag(Ty), owner).?;
|
||
if (std.meta.activeTag(b.ty) == tag) return l.fail("E7005", a.span, try l.fmt("this takes a borrow of the {s}, not the owner: bind `{s} g = {s};` in an enclosing block and pass `g`", .{ owner, if (mutable) "mut" else "ref", a.kind.name }), &.{.{ .name = "name", .value = a.kind.name }});
|
||
const ok = (b.ty == .ref or (b.ty == .mut and !mutable) or (b.ty == .mut and mutable)) and std.meta.activeTag(b.ty.inner().?) == tag;
|
||
if (!ok or (mutable and b.ty != .mut)) return l.fail("E7005", a.span, try l.fmt("a {s} borrow of an `{s}<T>` is expected here", .{ if (mutable) "`mut`" else "`ref` or `mut`", owner }), &.{.{ .name = "found", .value = l.diagnosticTyText(b.ty) }});
|
||
return .{ .name = b.value, .ty = b.ty };
|
||
}
|
||
|
||
/// `ref x = island.at(g, r);` / `mut x = island.at(g, r);`, and
|
||
/// `frozen.at`, `arc.at` (`ref` only): a child borrow of `g`.
|
||
fn graphAccess(l: *Lowerer, s: ast.Stmt, name: []const u8, mutable: bool, place: ast.Expr) Error!void {
|
||
const ac = place.kind.call;
|
||
const p = pathOf(ac.callee.*).?;
|
||
const owner = p[0..std.mem.indexOfScalar(u8, p, '.').?];
|
||
if (mutable and !std.mem.eql(u8, owner, "island")) return l.fail("E7005", s.span, "frozen graphs and arcs give `ref` access only", &.{});
|
||
if (ac.args.len != 2) return l.fail("E7005", place.span, "`.at` takes the graph's borrow binding and an `iref`", &.{});
|
||
const g = try l.graphBorrow(ac.args[0], owner, mutable);
|
||
const r = try l.expr(ac.args[1], null);
|
||
if (r.ty != .iref) return l.fail("E7005", ac.args[1].span, "an `iref` is expected here", &.{.{ .name = "found", .value = l.diagnosticTyText(r.ty) }});
|
||
const op = if (std.mem.eql(u8, owner, "island")) "island.borrow" else if (std.mem.eql(u8, owner, "frozen")) "frozen.borrow" else "arc.borrow";
|
||
const target = r.ty.inner().?;
|
||
const v = try l.def(name, if (mutable) try l.wrap(.mut, target) else try l.wrap(.ref, target), try l.fmt("{s} %{s}, %{s}", .{ op, g.name, r.name }), s.span);
|
||
try l.scopeEnds(&.{v.name}, s.span);
|
||
try l.bindings.append(l.arena, .{ .name = name, .mutable = false, .value = v.name, .ty = v.ty, .kind = .borrow });
|
||
}
|
||
|
||
fn resultTy(r: authority.ResultType) Ty {
|
||
return switch (r) {
|
||
.usize => .{ .int = "usize" },
|
||
.u64 => .{ .int = "u64" },
|
||
.resource => |x| .{ .resource = x },
|
||
};
|
||
}
|
||
|
||
/// Operands of an intrinsic in registry order (`reference/intrinsics.md`).
|
||
/// A capability is passed plainly; a resource operand that is borrowed
|
||
/// is named and borrowed for the operation; a consumed one is `move`d;
|
||
/// data borrows are written (`ref`/`mut`, or a byte string).
|
||
fn intrinsicOperands(l: *Lowerer, e: ast.Expr, x: authority.Intrinsic, args: []const ast.Expr, temps: *std.ArrayList([]const u8)) Error![]const u8 {
|
||
if (args.len != x.operands.len) return l.fail("E7005", e.span, "wrong number of operands", &.{ .{ .name = "operation", .value = x.name }, .{ .name = "expected", .value = try l.fmt("{d}", .{x.operands.len}) } });
|
||
var text: std.ArrayList(u8) = .empty;
|
||
for (x.operands, args, 0..) |o, a, i| {
|
||
const v: Value = switch (o) {
|
||
.cap => |k| try l.expectCap(a, k),
|
||
.bytes, .buffer => blk: {
|
||
const want: Ty = if (o == .bytes) try l.wrap(.slice, .{ .int = "u8" }) else try l.wrap(.slice_mut, .{ .int = "u8" });
|
||
if (o == .buffer and a.kind == .bytes) return l.fail("E7005", a.span, "this operand is a buffer the operation writes: pass `mut buf`", &.{});
|
||
const v = try l.argument(a, want, temps);
|
||
if (!v.ty.eql(want)) return l.fail("E7005", a.span, if (o == .bytes) "bytes are passed as a borrow: `ref buf`, `ref buf[a..b]` or a byte string `b\"…\"`" else "a buffer is passed as `mut buf` or `mut buf[a..b]`", &.{ .{ .name = "expected", .value = l.diagnosticTyText(want) }, .{ .name = "found", .value = l.diagnosticTyText(v.ty) } });
|
||
break :blk v;
|
||
},
|
||
.borrowed => |rs| try l.resourceOperand(a, rs, temps),
|
||
.consumed => |rs| blk: {
|
||
const v = try l.consuming(a, null);
|
||
if (v.ty != .resource or std.mem.indexOfScalar(authority.Resource, rs, v.ty.resource) == null)
|
||
return l.fail("E7005", a.span, "this operation consumes a resource of another type", &.{ .{ .name = "operation", .value = x.name }, .{ .name = "found", .value = l.diagnosticTyText(v.ty) } });
|
||
break :blk v;
|
||
},
|
||
};
|
||
try text.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", v.name }));
|
||
}
|
||
return text.items;
|
||
}
|
||
|
||
/// A resource operand the operation borrows: the resource by name
|
||
/// (borrowed `mut` for the operation) or a `mut` borrow binding of one.
|
||
fn resourceOperand(l: *Lowerer, a: ast.Expr, rs: []const authority.Resource, temps: *std.ArrayList([]const u8)) Error!Value {
|
||
const expected = try l.resourceList(rs);
|
||
if (a.kind == .borrow) return l.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.diagnosticTyText(b.ty) } });
|
||
if (b.ty == .mut) return .{ .name = b.value, .ty = b.ty };
|
||
const v = try l.def(a.kind.name, try l.wrap(.mut, b.ty), try l.fmt("borrow.mut %{s}", .{b.value}), a.span);
|
||
try temps.append(l.arena, v.name);
|
||
return v;
|
||
}
|
||
|
||
fn resourceList(l: *Lowerer, rs: []const authority.Resource) Error![]const u8 {
|
||
var out: std.ArrayList(u8) = .empty;
|
||
for (rs, 0..) |r, i| try out.appendSlice(l.arena, try l.fmt("{s}{s}", .{ if (i == 0) "" else " or ", r.text() }));
|
||
return out.items;
|
||
}
|
||
|
||
fn expectCap(l: *Lowerer, a: ast.Expr, kind: []const u8) Error!Value {
|
||
const c = try l.expr(a, null);
|
||
if (c.ty != .cap) return l.fail("E7005", a.span, "a capability is expected here", &.{ .{ .name = "expected", .value = try l.fmt("cap<{s}>", .{kind}) }, .{ .name = "found", .value = l.diagnosticTyText(c.ty) } });
|
||
return c;
|
||
}
|
||
|
||
/// The region borrow of `region.new`/`region.array` must be an explicit
|
||
/// borrow binding, so that it outlives the allocation borrows derived
|
||
/// from it (spec 15 §8).
|
||
fn regionBorrow(l: *Lowerer, a: ast.Expr) Error!Value {
|
||
if (a.kind == .name) if (l.lookup(a.kind.name)) |b| {
|
||
if (b.kind == .borrow and (b.ty == .ref or b.ty == .mut) and b.ty.inner().? == .region) return .{ .name = b.value, .ty = b.ty };
|
||
if (b.ty == .region) return l.fail("E7005", a.span, "allocation in a region takes a borrow of it that outlives the allocations: bind `ref arena = region;` in an enclosing block and pass `arena`", &.{.{ .name = "name", .value = a.kind.name }});
|
||
};
|
||
return l.fail("E7005", a.span, "allocation in a region takes a `ref<region>` borrow binding", &.{});
|
||
}
|
||
|
||
fn lowerFallible(l: *Lowerer, e: ast.Expr) Error!Fallible {
|
||
if (e.kind != .call) return l.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 (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, "island.create") or std.mem.eql(u8, path, "arc.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");
|
||
const owner = if (std.mem.eql(u8, path, "arc.new")) try l.wrap(.arc, v.ty) else try l.wrap(.island, v.ty);
|
||
return .{ .text = try l.fmt("{s} %{s}, %{s}", .{ path, v.name, c.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{owner} }, .{ .role = "err", .params = &.{alloc_err} } }) };
|
||
}
|
||
if (std.mem.eql(u8, path, "island.alloc")) {
|
||
try want(l, e.span, args, 2, path);
|
||
const g = try l.graphBorrow(args[0], "island", true);
|
||
const v = try l.consuming(args[1], null);
|
||
return .{ .text = try l.fmt("island.alloc %{s}, %{s}", .{ g.name, v.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{try l.wrap(.iref, v.ty)} }, .{ .role = "err", .params = &.{alloc_err} } }) };
|
||
}
|
||
if (std.mem.eql(u8, path, "task.check_cancel")) {
|
||
try want(l, e.span, args, 0, path);
|
||
return .{ .text = "task.check_cancel", .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{} }, .{ .role = "cancelled", .params = &.{} } }) };
|
||
}
|
||
if (std.mem.eql(u8, path, "task.join_cancel")) {
|
||
try want(l, e.span, args, 1, path);
|
||
const t = try l.consuming(args[0], null);
|
||
if (t.ty != .task) return l.fail("E7005", args[0].span, "`task.join_cancel` takes a `task<T>`", &.{.{ .name = "found", .value = l.diagnosticTyText(t.ty) }});
|
||
const rt = t.ty.task.*;
|
||
const ok: []const Ty = if (rt == .void) &.{} else &.{rt};
|
||
return .{ .text = try l.fmt("task.join.cancel %{s}", .{t.name}), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = ok }, .{ .role = "cancelled", .params = &.{t.ty} } }) };
|
||
}
|
||
if (std.mem.eql(u8, path, "channel.make")) {
|
||
try want(l, e.span, args, 2, path);
|
||
const ta = e.kind.call.type_arg orelse return l.fail("E7005", e.span, "`channel.make` names its element type: `channel.make<T>(n, mem)`", &.{});
|
||
const et = try l.memberType(ta);
|
||
try l.elementRule(et, ta.span, "a channel element");
|
||
const n = try l.expr(args[0], usize_ty);
|
||
try l.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<T>`", &.{.{ .name = "found", .value = l.diagnosticTyText(rx.ty) }});
|
||
return .{ .text = try l.fmt("channel.close_receiver %{s}", .{rx.name}), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{} }, .{ .role = "pending", .params = &.{rx.ty} } }) };
|
||
}
|
||
if (std.mem.eql(u8, path, "cap.narrow.prefix")) {
|
||
try want(l, e.span, args, 2, path);
|
||
const c = try l.expr(args[0], null);
|
||
if (c.ty != .cap) return l.fail("E7005", args[0].span, "a capability is expected here", &.{.{ .name = "found", .value = l.diagnosticTyText(c.ty) }});
|
||
var temps: std.ArrayList([]const u8) = .empty;
|
||
const bytes = try l.wrap(.slice, .{ .int = "u8" });
|
||
const p = try l.argument(args[1], bytes, &temps);
|
||
if (!p.ty.eql(bytes)) return l.fail("E7005", args[1].span, "the path is a byte string or a `ref` borrow of bytes", &.{.{ .name = "found", .value = l.diagnosticTyText(p.ty) }});
|
||
return .{ .text = try l.fmt("cap.narrow.prefix %{s}, %{s}", .{ c.name, p.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{c.ty} }, .{ .role = "err", .params = &.{.{ .builtin = .cap_error }} } }), .temps = temps.items };
|
||
}
|
||
if (std.mem.eql(u8, path, "cap.narrow.budget")) {
|
||
try want(l, e.span, args, 2, path);
|
||
const c = try l.expr(args[0], null);
|
||
if (c.ty != .cap) return l.fail("E7005", args[0].span, "a capability is expected here", &.{.{ .name = "found", .value = l.diagnosticTyText(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);
|
||
// 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, .{ .match = m });
|
||
const before = try l.snapshot();
|
||
const blocks = try l.outcomeBlocks(f, m.scrutinee.span);
|
||
var ends: std.ArrayList(ArmEnd) = .empty;
|
||
for (f.outcomes, blocks) |o, blk| {
|
||
const arm = for (m.arms) |a| {
|
||
if (std.mem.eql(u8, a.pattern.kind.ctor.name, o.role)) break a;
|
||
} else unreachable;
|
||
l.restore(before);
|
||
l.cur = blk;
|
||
// The outcome's values are bound in the arm; a borrow among them
|
||
// (a region allocation) ends with the arm.
|
||
try l.scopes.append(l.arena, .empty);
|
||
for (arm.pattern.kind.ctor.binds, l.blocks.items[blk].params.items) |bn, prm| {
|
||
if (prm.ty.isBorrow()) try l.scopeEnds(&.{prm.name}, arm.pattern.span);
|
||
if (std.mem.eql(u8, bn, "_")) continue;
|
||
// Rebinding (spec 15 §6): a value that comes back on an edge
|
||
// under the name of a variable of its type is that variable's
|
||
// new value (`pending(rx)`, `closed(v)`).
|
||
if (l.lookup(bn)) |old| if (old.mutable and old.kind == .ssa and old.ty.eql(prm.ty)) {
|
||
old.value = prm.name;
|
||
continue;
|
||
};
|
||
try l.bindings.append(l.arena, .{ .name = bn, .mutable = false, .value = prm.name, .ty = prm.ty, .kind = if (prm.ty.isBorrow()) .borrow else .ssa });
|
||
}
|
||
const v = try l.armBody(arm.body, want);
|
||
if (l.cur != null) try l.endScopes(l.scopes.items.len - 1, arm.body.span);
|
||
_ = l.scopes.pop();
|
||
l.bindings.shrinkRetainingCapacity(before.len);
|
||
try ends.append(l.arena, .{ .block = l.cur, .value = v, .values = try l.snapshot(), .span = arm.body.span });
|
||
}
|
||
return l.mergeArms(m.span, "match", ends.items, vars, before, "endmatch");
|
||
}
|
||
|
||
/// `op(…) or trap`: the `ok` value; every other outcome traps.
|
||
fn orTrap(l: *Lowerer, e: ast.Expr, inner_e: ast.Expr) Error!Value {
|
||
const f = try l.lowerFallible(inner_e);
|
||
const blocks = try l.outcomeBlocks(f, e.span);
|
||
for (f.outcomes, blocks) |o, blk| if (!std.mem.eql(u8, o.role, "ok")) {
|
||
l.cur = blk;
|
||
try l.term("trap", e.span);
|
||
};
|
||
const ok = for (f.outcomes, blocks) |o, blk| {
|
||
if (std.mem.eql(u8, o.role, "ok")) break blk;
|
||
} else unreachable;
|
||
l.cur = ok;
|
||
const ps = l.blocks.items[ok].params.items;
|
||
if (ps.len == 0) return .{ .name = "", .ty = .void };
|
||
if (ps.len != 1) return l.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, .{ .@"if" = x });
|
||
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,
|
||
};
|
||
}
|
||
|
||
/// 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", "mutex.make", "mutex.take", "task.check_cancel",
|
||
"task.join_cancel", "island.create", "island.alloc", "island.root", "island.at",
|
||
"island.freeze", "island.destroy", "frozen.root", "frozen.at", "frozen.release",
|
||
"arc.from_frozen", "arc.new", "arc.clone", "arc.release", "arc.root",
|
||
"arc.at", "atomic.new", "atomic.take", "atomic.load", "atomic.store",
|
||
"atomic.swap", "atomic.add.wrap", "atomic.sub.wrap", "atomic.and", "atomic.or",
|
||
"atomic.xor", "atomic.compare_exchange", "atomic.fence",
|
||
};
|
||
var buf: [64]u8 = undefined;
|
||
const text = dotted(e, &buf) orelse return null;
|
||
for (known) |k| if (std.mem.eql(u8, k, text)) return k;
|
||
if (authority.intrinsicIndex(text)) |i| return authority.intrinsics[i].name;
|
||
return null;
|
||
}
|
||
|
||
fn dotted(e: ast.Expr, buf: []u8) ?[]const u8 {
|
||
switch (e.kind) {
|
||
.name => |n| {
|
||
if (n.len > buf.len) return null;
|
||
@memcpy(buf[0..n.len], n);
|
||
return buf[0..n.len];
|
||
},
|
||
.field => |f| {
|
||
const base = dotted(f.e.*, buf) orelse return null;
|
||
const len = base.len + 1 + f.name.len;
|
||
if (len > buf.len) return null;
|
||
buf[base.len] = '.';
|
||
@memcpy(buf[base.len + 1 .. len], f.name);
|
||
return buf[0..len];
|
||
},
|
||
else => return null,
|
||
}
|
||
}
|
||
|
||
fn standardPath(e: ast.Expr) bool {
|
||
if (e.kind != .field) return false;
|
||
var root = e;
|
||
while (root.kind == .field) root = root.kind.field.e.*;
|
||
return root.kind == .name and std.mem.eql(u8, root.kind.name, "std");
|
||
}
|
||
|
||
fn box(arena: Allocator, e: ast.Expr) Error!*const ast.Expr {
|
||
const b = try arena.create(ast.Expr);
|
||
b.* = e;
|
||
return b;
|
||
}
|
||
|
||
// ---------------------------------------------------------------- liveness (pruned joins)
|
||
|
||
fn spanEq(a: Span, b: Span) bool {
|
||
return a.start.line == b.start.line and a.start.col == b.start.col and a.end.line == b.end.line and a.end.col == b.end.col;
|
||
}
|
||
|
||
const Use = enum { read, kill, none };
|
||
|
||
/// The first use of `name` in statements executed in order: a read, a
|
||
/// whole-variable assignment that does not read it (`name = e;`), or none.
|
||
fn firstUse(stmts: []const ast.Stmt, tail: ?*const ast.Expr, name: []const u8) Use {
|
||
for (stmts) |st| {
|
||
if (st.kind == .assign and st.kind.assign.place.kind == .name and std.mem.eql(u8, st.kind.assign.place.kind.name, name)) {
|
||
if (exprReads(st.kind.assign.e, name, null)) return .read;
|
||
return .kill;
|
||
}
|
||
if (stmtReads(st, name, null)) return .read;
|
||
}
|
||
if (tail) |t| if (exprReads(t.*, name, null)) return .read;
|
||
return .none;
|
||
}
|
||
|
||
fn loopReads(lp: LoopAst, name: []const u8) bool {
|
||
if (lp.step) |st| if (std.mem.eql(u8, st, name)) return true;
|
||
if (lp.cond) |c| if (exprReads(c, name, null)) return true;
|
||
return blockReads(lp.body, name, null);
|
||
}
|
||
|
||
fn blockReads(b: ast.Block, name: []const u8, skip: ?Span) bool {
|
||
for (b.stmts) |st| if (stmtReads(st, name, skip)) return true;
|
||
if (b.tail) |t| if (exprReads(t.*, name, skip)) return true;
|
||
return false;
|
||
}
|
||
|
||
/// Whether the statement mentions `name` other than as the target of a
|
||
/// whole-variable assignment. `skip`: a construct whose own reads happen
|
||
/// before the join being decided.
|
||
fn stmtReads(st: ast.Stmt, name: []const u8, skip: ?Span) bool {
|
||
return switch (st.kind) {
|
||
.let => |x| exprReads(x.e, name, skip),
|
||
.@"var" => |x| if (x.init) |e| exprReads(e, name, skip) else false,
|
||
.assign => |x| exprReads(x.e, name, skip) or (x.place.kind != .name and exprReads(x.place, name, skip)),
|
||
.borrow => |x| exprReads(x.place, name, skip),
|
||
.@"return" => |e| if (e) |x| exprReads(x, name, skip) else false,
|
||
.expr => |e| exprReads(e, name, skip),
|
||
.@"while" => |x| exprReads(x.cond, name, skip) or blockReads(x.body, name, skip),
|
||
.@"for" => |x| exprReads(x.lo, name, skip) or exprReads(x.hi, name, skip) or blockReads(x.body, name, skip),
|
||
.loop, .shield => |b| blockReads(b, name, skip),
|
||
.scope => |x| blockReads(x.body, name, skip),
|
||
.lock => |x| exprReads(x.place, name, skip) or blockReads(x.body, name, skip) or blockReads(x.cancelled, name, skip),
|
||
.select => |x| selectReads(x, name, skip),
|
||
.@"break", .@"continue", .trap => false,
|
||
};
|
||
}
|
||
|
||
fn exprReads(e: ast.Expr, name: []const u8, skip: ?Span) bool {
|
||
if (skip) |sk| if (spanEq(e.span, sk)) return false;
|
||
return switch (e.kind) {
|
||
.name => |n| std.mem.eql(u8, n, name),
|
||
.move => |n| std.mem.eql(u8, n, name),
|
||
.int, .boolean, .bytes, .variant, .specialize => false,
|
||
.neg, .not, .deref, .or_trap => |x| exprReads(x.*, name, skip),
|
||
.borrow => |x| exprReads(x.place.*, name, skip),
|
||
.binary => |x| exprReads(x.l.*, name, skip) or exprReads(x.r.*, name, skip),
|
||
.cast => |x| exprReads(x.e.*, name, skip),
|
||
.call => |x| blk: {
|
||
if (exprReads(x.callee.*, name, skip)) break :blk true;
|
||
for (x.args) |a| if (exprReads(a, name, skip)) break :blk true;
|
||
break :blk false;
|
||
},
|
||
.field => |x| exprReads(x.e.*, name, skip),
|
||
.index => |x| exprReads(x.e.*, name, skip) or exprReads(x.lo.*, name, skip) or (if (x.hi) |h| exprReads(h.*, name, skip) else false),
|
||
.struct_lit => |x| blk: {
|
||
for (x.fields) |f| if (exprReads(f.e, name, skip)) break :blk true;
|
||
break :blk false;
|
||
},
|
||
.array_rep => |x| exprReads(x.e.*, name, skip),
|
||
.if_expr => |x| ifReads(x.*, name, skip),
|
||
.match_expr => |x| blk: {
|
||
if (exprReads(x.scrutinee, name, skip)) break :blk true;
|
||
for (x.arms) |a| if (exprReads(a.body, name, skip)) break :blk true;
|
||
break :blk false;
|
||
},
|
||
.block => |b| blockReads(b.*, name, skip),
|
||
};
|
||
}
|
||
|
||
fn selectReads(x: ast.Select, name: []const u8, skip: ?Span) bool {
|
||
for (x.arms) |a| {
|
||
if (std.mem.eql(u8, a.endpoint, name)) return true;
|
||
if (a.value) |v| if (exprReads(v, name, skip)) return true;
|
||
for (a.arms) |arm| if (exprReads(arm.body, name, skip)) return true;
|
||
}
|
||
return exprReads(x.cancelled, name, skip);
|
||
}
|
||
|
||
fn ifReads(x: ast.If, name: []const u8, skip: ?Span) bool {
|
||
if (exprReads(x.cond, name, skip) or blockReads(x.then, name, skip)) return true;
|
||
if (x.@"else") |els| return switch (els) {
|
||
.block => |b| blockReads(b, name, skip),
|
||
.@"if" => |inner| ifReads(inner.*, name, skip),
|
||
};
|
||
return false;
|
||
}
|
||
|
||
/// Reads of `name` after `construct`, in evaluation order, within the
|
||
/// statement or expression that contains it. Once the construct is found in
|
||
/// one arm of an `if` or `match`, the other arms are not "after" it; once it
|
||
/// is found in a loop, the whole loop is (the back edge).
|
||
const After = struct {
|
||
name: []const u8,
|
||
construct: Span,
|
||
seen: bool = false,
|
||
|
||
fn expr(w: *After, e: ast.Expr) bool {
|
||
if (!w.seen and spanEq(e.span, w.construct)) {
|
||
w.seen = true;
|
||
return false;
|
||
}
|
||
return switch (e.kind) {
|
||
.name, .move => |n| w.seen and std.mem.eql(u8, n, w.name),
|
||
.int, .boolean, .bytes, .variant, .specialize => false,
|
||
.neg, .not, .deref, .or_trap => |x| w.expr(x.*),
|
||
.borrow => |x| w.expr(x.place.*),
|
||
.binary => |x| w.expr(x.l.*) or w.expr(x.r.*),
|
||
.cast => |x| w.expr(x.e.*),
|
||
.call => |x| blk: {
|
||
if (w.expr(x.callee.*)) break :blk true;
|
||
for (x.args) |a| if (w.expr(a)) break :blk true;
|
||
break :blk false;
|
||
},
|
||
.field => |x| w.expr(x.e.*),
|
||
.index => |x| w.expr(x.e.*) or w.expr(x.lo.*) or (if (x.hi) |h| w.expr(h.*) else false),
|
||
.struct_lit => |x| blk: {
|
||
for (x.fields) |f| if (w.expr(f.e)) break :blk true;
|
||
break :blk false;
|
||
},
|
||
.array_rep => |x| w.expr(x.e.*),
|
||
.if_expr => |x| w.ifExpr(x.*),
|
||
.match_expr => |x| blk: {
|
||
if (w.expr(x.scrutinee)) break :blk true;
|
||
if (w.seen) {
|
||
for (x.arms) |a| if (w.expr(a.body)) break :blk true;
|
||
break :blk false;
|
||
}
|
||
for (x.arms) |a| {
|
||
const r = w.expr(a.body);
|
||
if (w.seen) break :blk r; // found in this arm: siblings are not after it
|
||
}
|
||
break :blk false;
|
||
},
|
||
.block => |b| w.block(b.*),
|
||
};
|
||
}
|
||
|
||
fn select(w: *After, x: ast.Select) bool {
|
||
for (x.arms) |a| {
|
||
if (w.seen and std.mem.eql(u8, a.endpoint, w.name)) return true;
|
||
if (a.value) |v| if (w.expr(v)) return true;
|
||
}
|
||
var bodies: std.ArrayList(ast.Expr) = .empty;
|
||
defer bodies.deinit(std.heap.page_allocator);
|
||
for (x.arms) |a| for (a.arms) |arm| bodies.append(std.heap.page_allocator, arm.body) catch return true;
|
||
bodies.append(std.heap.page_allocator, x.cancelled) catch return true;
|
||
if (w.seen) {
|
||
for (bodies.items) |b| if (w.expr(b)) return true;
|
||
return false;
|
||
}
|
||
for (bodies.items) |b| {
|
||
const r = w.expr(b);
|
||
if (w.seen) return r;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
fn ifExpr(w: *After, x: ast.If) bool {
|
||
if (w.expr(x.cond)) return true;
|
||
if (w.seen) return w.block(x.then) or (if (x.@"else") |els| w.elseBranch(els) else false);
|
||
const r = w.block(x.then);
|
||
if (w.seen) return r;
|
||
if (x.@"else") |els| return w.elseBranch(els);
|
||
return false;
|
||
}
|
||
|
||
fn elseBranch(w: *After, els: ast.Else) bool {
|
||
return switch (els) {
|
||
.block => |b| w.block(b),
|
||
.@"if" => |inner| w.ifExpr(inner.*),
|
||
};
|
||
}
|
||
|
||
fn block(w: *After, b: ast.Block) bool {
|
||
for (b.stmts) |st| if (w.stmt(st)) return true;
|
||
if (b.tail) |t| if (w.expr(t.*)) return true;
|
||
return false;
|
||
}
|
||
|
||
fn loopBody(w: *After, cond: ?ast.Expr, body: ast.Block, step: ?[]const u8) bool {
|
||
const was = w.seen;
|
||
if (cond) |c| if (w.expr(c)) return true;
|
||
const r = w.block(body);
|
||
if (r) return true;
|
||
// Found inside this loop: everything in it can run again.
|
||
if (!was and w.seen) return loopReads(.{ .cond = cond, .body = body, .step = step }, w.name);
|
||
return false;
|
||
}
|
||
|
||
fn stmt(w: *After, st: ast.Stmt) bool {
|
||
if (!w.seen and spanEq(st.span, w.construct)) {
|
||
w.seen = true;
|
||
return false;
|
||
}
|
||
return switch (st.kind) {
|
||
.let => |x| w.expr(x.e),
|
||
.@"var" => |x| if (x.init) |e| w.expr(e) else false,
|
||
.assign => |x| w.expr(x.e) or (x.place.kind != .name and w.expr(x.place)),
|
||
.borrow => |x| w.expr(x.place),
|
||
.@"return" => |e| if (e) |x| w.expr(x) else false,
|
||
.expr => |e| w.expr(e),
|
||
.@"while" => |x| w.loopBody(x.cond, x.body, null),
|
||
.@"for" => |x| w.expr(x.lo) or w.expr(x.hi) or w.loopBody(null, x.body, x.name),
|
||
.loop => |b| w.loopBody(null, b, null),
|
||
.shield => |b| w.block(b),
|
||
.scope => |x| w.block(x.body),
|
||
.lock => |x| w.expr(x.place) or w.block(x.body) or w.block(x.cancelled),
|
||
.select => |x| w.select(x),
|
||
.@"break", .@"continue", .trap => false,
|
||
};
|
||
}
|
||
};
|
||
|
||
/// The code of a branching construct, for deciding which variables it
|
||
/// assigns: a join carries only variables that may change inside.
|
||
const Region = union(enum) {
|
||
loop: LoopAst,
|
||
@"if": ast.If,
|
||
match: ast.Match,
|
||
lock: struct { ast.Block, ast.Block },
|
||
select: ast.Select,
|
||
|
||
fn assigns(r: Region, name: []const u8) bool {
|
||
return switch (r) {
|
||
.loop => |lp| (if (lp.step) |st| std.mem.eql(u8, st, name) else false) or (if (lp.cond) |c| exprAssigns(c, name) else false) or blockAssigns(lp.body, name),
|
||
.@"if" => |x| ifAssigns(x, name),
|
||
.match => |m| matchAssigns(m, name),
|
||
.lock => |b| blockAssigns(b[0], name) or blockAssigns(b[1], name),
|
||
.select => |x| selectAssigns(x, name),
|
||
};
|
||
}
|
||
};
|
||
|
||
/// Whether code assigns variable `name`: `name = e;`, or a pattern of an
|
||
/// outcome or `select` edge rebinding it (spec 15 §6).
|
||
fn blockAssigns(b: ast.Block, name: []const u8) bool {
|
||
for (b.stmts) |st| if (stmtAssigns(st, name)) return true;
|
||
if (b.tail) |t| if (exprAssigns(t.*, name)) return true;
|
||
return false;
|
||
}
|
||
|
||
fn stmtAssigns(st: ast.Stmt, name: []const u8) bool {
|
||
return switch (st.kind) {
|
||
.assign => |x| (x.place.kind == .name and std.mem.eql(u8, x.place.kind.name, name)) or exprAssigns(x.e, name),
|
||
.let => |x| exprAssigns(x.e, name),
|
||
.@"var" => |x| if (x.init) |e| exprAssigns(e, name) else false,
|
||
.borrow => |x| exprAssigns(x.place, name),
|
||
.@"return" => |e| if (e) |x| exprAssigns(x, name) else false,
|
||
.expr => |e| exprAssigns(e, name),
|
||
.@"while" => |x| exprAssigns(x.cond, name) or blockAssigns(x.body, name),
|
||
.@"for" => |x| std.mem.eql(u8, x.name, name) or blockAssigns(x.body, name),
|
||
.loop, .shield => |b| blockAssigns(b, name),
|
||
.scope => |x| blockAssigns(x.body, name),
|
||
.lock => |x| blockAssigns(x.body, name) or blockAssigns(x.cancelled, name),
|
||
.select => |x| selectAssigns(x, name),
|
||
.@"break", .@"continue", .trap => false,
|
||
};
|
||
}
|
||
|
||
fn exprAssigns(e: ast.Expr, name: []const u8) bool {
|
||
return switch (e.kind) {
|
||
.if_expr => |x| ifAssigns(x.*, name),
|
||
.match_expr => |x| matchAssigns(x.*, name),
|
||
.block => |b| blockAssigns(b.*, name),
|
||
.neg, .not, .deref, .or_trap => |x| exprAssigns(x.*, name),
|
||
.binary => |x| exprAssigns(x.l.*, name) or exprAssigns(x.r.*, name),
|
||
.cast => |x| exprAssigns(x.e.*, name),
|
||
.call => |x| blk: {
|
||
for (x.args) |a| if (exprAssigns(a, name)) break :blk true;
|
||
break :blk false;
|
||
},
|
||
.struct_lit => |x| blk: {
|
||
for (x.fields) |f| if (exprAssigns(f.e, name)) break :blk true;
|
||
break :blk false;
|
||
},
|
||
.field => |x| exprAssigns(x.e.*, name),
|
||
.index => |x| exprAssigns(x.e.*, name) or exprAssigns(x.lo.*, name) or (if (x.hi) |h| exprAssigns(h.*, name) else false),
|
||
.array_rep => |x| exprAssigns(x.e.*, name),
|
||
else => false,
|
||
};
|
||
}
|
||
|
||
fn ifAssigns(x: ast.If, name: []const u8) bool {
|
||
if (exprAssigns(x.cond, name) or blockAssigns(x.then, name)) return true;
|
||
if (x.@"else") |els| return switch (els) {
|
||
.block => |b| blockAssigns(b, name),
|
||
.@"if" => |inner| ifAssigns(inner.*, name),
|
||
};
|
||
return false;
|
||
}
|
||
|
||
fn matchAssigns(m: ast.Match, name: []const u8) bool {
|
||
if (exprAssigns(m.scrutinee, name)) return true;
|
||
for (m.arms) |a| {
|
||
if (a.pattern.kind == .ctor) for (a.pattern.kind.ctor.binds) |b| if (std.mem.eql(u8, b, name)) return true;
|
||
if (exprAssigns(a.body, name)) return true;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
fn selectAssigns(x: ast.Select, name: []const u8) bool {
|
||
for (x.arms) |a| for (a.arms) |arm| {
|
||
if (arm.pattern.kind == .ctor) for (arm.pattern.kind.ctor.binds) |b| if (std.mem.eql(u8, b, name)) return true;
|
||
if (exprAssigns(arm.body, name)) return true;
|
||
};
|
||
for (x.cancelled_binds) |b| if (std.mem.eql(u8, b, name)) return true;
|
||
return exprAssigns(x.cancelled, name);
|
||
}
|
||
|
||
fn localName(full: []const u8, module: []const u8, short: []const u8) bool {
|
||
return full.len == module.len + 1 + short.len and std.mem.startsWith(u8, full, module) and full[module.len] == '.' and std.mem.eql(u8, full[module.len + 1 ..], short);
|
||
}
|
||
|
||
fn expressionPath(arena: Allocator, e: ast.Expr) Allocator.Error!?[]const u8 {
|
||
return switch (e.kind) {
|
||
.name => |name| name,
|
||
.field => |field| if (try expressionPath(arena, field.e.*)) |base| try std.fmt.allocPrint(arena, "{s}.{s}", .{ base, field.name }) else null,
|
||
else => null,
|
||
};
|
||
}
|
||
|
||
// Bound property queries before invoking recursive verifier derivations.
|
||
fn boundedType(m: air_module.Module, t: air_module.Type, depth: usize) bool {
|
||
if (depth >= 64) return false;
|
||
if (t == .named) return switch (m.types[t.named].kind) {
|
||
.@"struct" => |fs| for (fs) |f| {
|
||
if (!boundedType(m, f.ty, depth + 1)) break false;
|
||
} else true,
|
||
.@"enum" => |vs| blk: {
|
||
for (vs) |v| for (v.payload) |p| if (!boundedType(m, p, depth + 1)) break :blk false;
|
||
break :blk true;
|
||
},
|
||
};
|
||
return if (t.inner()) |inner| boundedType(m, inner, depth + 1) else true;
|
||
}
|