Phase 6A: .aji layers 3-4 (addressable values, lexical borrows, slices)

Owner rules: addressability is decided by lowering (a variable that is
borrowed, indexed or written through a place gets frame storage in the
entry block; otherwise SSA; by name, deterministic); borrows are bound
only by 'ref r = place;' / 'mut r = place;' and live to the end of the
block (borrow.end at every normal exit, including break/continue/return);
no shadowing of an active borrow in the same scope; ref/mut as call
arguments are temporaries ended after the call; *r only for scalar and
struct referents, slices via s[i], s[a..b], s.len; writes *r = v,
r.f = v, s[i] = v with the value evaluated first; split_at as the only
multi-result binding; slice.copy(mut dst, ref src) as the only copy;
[e; N] evaluates e once; byte strings as [u8; N] in frame storage with
a fixed escape set; borrow.index.proven only for the verifier's own
fact form (if i < s.len, same SSA values), otherwise checked.

Diagnostics on lowered AIR are deduplicated per code and source
location. aji lower --stats counts code only (no comment lines).

Tests: 10 run (architecture goldens: value-only has no local.alloc,
borrowed has local.alloc, proven indexing), 6 rejects incl.
verifier-caught E2101 (aliasing; parent used after split_at).
Expansion on these programs: 4-9x bytes, 2.2-6.6x lines.
This commit is contained in:
dev committed 2026-10-05 11:51:04 +03:00
1 parent 0fdd04179b
commit eca30f817a
28 files changed
+1157 -73

No files matched your search

+9 -8
View File
@@ -79,19 +79,20 @@ There is one spelling per construct: no `+=`, no alternative syntax.
```aji
var data: [u64; 8] = zero;
let s = mut data; // exclusive borrow (here: slice_mut<u64>)
let e = mut s[i]; // element borrow; out of range traps T0008
*e = 7; // store through mut
let v = *e; // load
data[0] = 7; // element write (array variables get frame storage automatically)
mut s = data; // bind an exclusive borrow (an array is borrowed as slice_mut<u64>)
s[1] = s[0] + 1; // checked index; out of range traps T0008
let n = s.len;
let (l, r) = s.split_at(4); // two disjoint halves
copy(dst, ref src); // element-wise copy, same element type
let first = ref p.a; // field borrow; r.f reads a field through a borrow
if i < s.len { s[i] = 0; } // no runtime check here: the verifier proves i < s.len
let (l, r) = s.split_at(4); // two disjoint halves of s
slice.copy(mut out[0..4], ref data[4..8]); // borrows as arguments end after the call
ref q = p; // shared borrow of a struct; q.a reads a field
*c = *c + 1; // through mut<u64>
```
Rules (checked by the verifier):
- **A borrow lives until the end of the block where it was `let`-bound.** A borrow written directly as an argument lives until the end of the statement. To end one early, put it in an inner `{ … }` block.
- **A borrow lives until the end of the block where it was bound** (`ref r = …;` / `mut r = …;`). A borrow written as an argument (`f(mut buf)`) lives for that call. To end one early, put it in an inner `{ … }` block.
- **Exclusive XOR shared.** While a `mut` borrow of a place is live, no other borrow of the same place, and no direct use of it, is allowed (`E2101`). Disjoint fields and `split_at` halves are independent.
- A borrow cannot outlive what it borrows from (`E2102`). A function returns a borrow only with `-> ref<T> from param`.
- **Moves are explicit:** a named linear value is consumed only as `move x` (otherwise `E7003`). A fresh temporary needs no `move`: `consume(make())`. Copyable values are passed plainly; `move` on them is `E7006`.
+1 -2
View File
@@ -40,8 +40,7 @@ Lowering layers (P6A-3/4), each with accepted (golden AIR), rejected (`E7xxx`) a
|---|---|---|
| 1 | scalars, expressions, functions, control flow, variables carried across joins, short-circuit `and`/`or`, casts | done |
| 2 | structs (named construction, declaration-order lowering), enums (`Enum::Variant`), exhaustive `match` over enums (no `_`) and integers (`_` required), `match` as an expression; outcome matches and `or trap` move to layer 5 with the fallible operations | done |
| 3 | arrays, slices, byte strings | todo |
| 4 | lexical borrows, frame storage, `move`, places | todo |
| 3–4 | addressable values (frame storage chosen by lowering), lexical borrows (`ref r = …;`/`mut r = …;`), places and writes, arrays, slices, `split_at`, `slice.copy`, byte strings, proven indexing for the verifier's fact form; `move` comes with linear values in layer 5 | done |
| 5 | `own`, regions, resources, unsafe | todo |
| 6 | capabilities, intrinsics, I/O | todo |
| 7 | tasks, channels | todo |
+33 -11
View File
@@ -158,16 +158,37 @@ Lowering: structured control flow becomes blocks and terminators. A variable ass
| Source | Meaning |
|---|---|
| `ref place` | shared borrow (`borrow.ref`, `borrow.field`, `borrow.index`, `slice.make`, `slice.sub` as the place requires) |
| `mut place` | exclusive borrow |
| `*r` | load through `ref<T>`/`mut<T>` |
| `r.f` | load of a field through a borrow of a struct |
| `s.len` | `slice.len` of a slice, or the static length of an array |
| `s.split_at(k)` | `slice.split`; bound with `let (left, right) = …;` |
| `copy(dst, src)` | `slice.copy` |
| `ref r = place;` / `mut r = place;` | **the only way to bind a borrow**: a statement, valid to the end of the enclosing block. `let r = mut x;` is `E7006`. An active borrow cannot be shadowed by the same name in the same scope (`E7006`). Borrowing a whole array binds a slice (`slice<T>` / `slice_mut<T>`). Borrowing a borrow binding reborrows it. |
| `ref place` / `mut place` as an argument | a temporary borrow for that call (ended right after it); allowed only as an argument |
| `*r` | load through `ref<T>`/`mut<T>` of a scalar or struct; slices and arrays use `s[i]` (`E7006`) |
| `r.f` | field through a borrow of a struct (borrow, load, end) |
| `s[i]` | element value (borrow, load, end) |
| `s.len` | `slice.len`, or the static length of an array |
| `s[a..b]` | a sub-slice (`slice.sub` with start `a`, length `b - a`); a borrow, so it is bound or passed, never a value |
| `let (left, right) = s.split_at(k);` | `slice.split`: two disjoint borrows of `s`; the only multi-result binding. There is no general tuple destructuring. |
| `slice.copy(mut dst, ref src)` | `slice.copy`, the only copy form |
- **Indexing.** `s[i]` is a checked index (`T0008`). Inside the true branch of `if i < s.len`, with `i` and `s` unchanged, the frontend emits `borrow.index.proven`. The verifier confirms the fact; otherwise the index stays checked.
- **Unsafe indexing.** `ref unchecked s[i]` and `mut unchecked s[i]` are `borrow.index.unchecked`, and `assume(c)` is `assume`. Both are allowed only under spec 13 §6.
**Writes.**
- `*r = v;` for a scalar or struct referent;
- `r.f = v;`, `x.f = v;`;
- `s[i] = v;`, `x[i] = v;`.
The value is evaluated first, then the place is borrowed for the store and the borrow ends. So `s[i] = s[i] + 1;` reads before it writes.
**Bounds.** These follow AIR exactly:
- `s[i]` is a checked `borrow.index` (`T0008`);
- inside the true branch of `if i < s.len`, with `i` and `s` the unchanged SSA values, the frontend emits `borrow.index.proven`. This is the fact the verifier proves (spec 08 §12, "fact on the same slice");
- in every other case the index stays checked. The frontend never knows more about bounds than the verifier.
**Unsafe indexing.** `ref unchecked s[i]` and `mut unchecked s[i]` are `borrow.index.unchecked`, and `assume(c)` is `assume`. Both are allowed only under spec 13 §6.
**Arrays and byte strings.**
- `[e; N]` evaluates `e` once and copies the value N times (`array.splat`). The element must be copyable; a linear element is `E7006`.
- `b"…"` is an immutable `[u8; N]` value held in frame storage, written there byte by byte, with no heap. The escapes are exactly `\n \r \t \\ \" \0 \xNN`.
- Used where a `slice<u8>` is expected, it is borrowed for the operation.
**Moves.**
@@ -286,8 +307,8 @@ A byte string or array used where a `slice<u8>` is expected is materialized in f
## 9. Frame storage, borrow scopes and features
- **Frame storage.** A variable whose place is borrowed lowers to `local<T>` storage allocated in the entry block (spec 08 §11.5). Every other variable is an SSA value. The frame-size limit applies to the lowered AIR. There is no implicit heap allocation.
- **Borrow scopes.** A borrow bound by `let` ends at the end of the block that contains the `let`. A temporary borrow, used directly as an operand, ends at the end of its statement. Both end at every normal exit from their scope. The frontend emits `borrow.end` in reverse order of creation. A borrow that must end earlier is placed in an inner block. Borrows lent to tasks end at the join (spec 04 §34).
- **Frame storage.** Addressability is a property of lowering, not of source types. A variable whose name is borrowed, indexed, or written through a field or element anywhere in the function lowers to `local<T>` storage, allocated in the entry block (spec 08 §11.5). Every other variable is an SSA value. The decision is by name, so the same source always gives the same placement. The frame-size limit applies to the lowered AIR. There is no implicit heap allocation.
- **Borrow scopes.** A borrow bound by `ref`/`mut` ends at the end of the block that contains the binding. Because a borrow's name is not visible after its scope, a use after the borrow ended (`E2106`) cannot be written in source. A temporary borrow, used directly as an operand, ends at the end of its statement. Both end at every normal exit from their scope. The frontend emits `borrow.end` in reverse order of creation. A borrow that must end earlier is placed in an inner block. Borrows lent to tasks end at the join (spec 04 §34).
- **Features.** The frontend emits the `features [...]` header as the dependency closure of the constructs used, always including `effects`.
- **Effects.** They are declared by the programmer. `E3101` names the missing effect and suggests the complete effect list (`suggested_effects`).
@@ -297,6 +318,7 @@ A byte string or array used where a `slice<u8>` is expected is materialized in f
|---|---|
| found by the verifier on the lowered AIR | the AIR code; the diagnostic's `file`, `line` and `col` are the source location of the construct the instruction came from, and `air_line`/`air_col` locate it in the lowered AIR (`aji lower`); the verifier's own fields (`function`, `block`, `inst`) are kept |
| syntax, name resolution, lowering and invalid source constructs | `E7xxx`, below |
| several AIR instructions of one construct reporting the same code | one diagnostic (the first) per code and source location |
| trap at run time | the trap record also carries `source_location` (`file`, `line`, `col`) |
| Code | Kind | Meaning |
+12 -3
View File
@@ -37,9 +37,18 @@ pub fn checkFile(arena: std.mem.Allocator, file_name: []const u8, source: []cons
.unimplemented => |what| return .{ .status = .unimplemented, .diagnostics = &.{}, .missing_stage = what },
};
var r = try checkAir(arena, file_name, lowered.air);
const mapped = try arena.alloc(diag.Diagnostic, r.diagnostics.len);
for (r.diagnostics, mapped) |d, *m| m.* = try frontend.mapDiagnostic(arena, d, file_name, lowered.lines);
r.diagnostics = mapped;
// One source construct often lowers to several AIR instructions that the
// verifier reports separately: keep one diagnostic per code and source
// location (the first).
var mapped: std.ArrayList(diag.Diagnostic) = .empty;
for (r.diagnostics) |d| {
const m = try frontend.mapDiagnostic(arena, d, file_name, lowered.lines);
const dup = for (mapped.items) |prev| {
if (prev.code == m.code and prev.span.?.line == m.span.?.line and prev.span.?.col == m.span.?.col) break true;
} else false;
if (!dup) try mapped.append(arena, m);
}
r.diagnostics = mapped.items;
r.lowered = lowered;
return r;
}
+2
View File
@@ -128,6 +128,8 @@ pub const Stmt = struct {
/// `init == null` is `= zero`.
@"var": struct { name: []const u8, ty: Type, init: ?Expr },
assign: struct { place: Expr, e: Expr },
/// `ref r = place;` / `mut r = place;`: a borrow bound for the rest of the block.
borrow: struct { mutable: bool, name: []const u8, place: Expr },
@"break",
@"continue",
@"return": ?Expr,
+2
View File
@@ -184,6 +184,8 @@ pub fn decodeBytes(arena: std.mem.Allocator, raw: []const u8) std.mem.Allocator.
switch (body[i]) {
'n' => try out.append(arena, '\n'),
't' => try out.append(arena, '\t'),
'r' => try out.append(arena, '\r'),
'0' => try out.append(arena, 0),
'\\' => try out.append(arena, '\\'),
'"' => try out.append(arena, '"'),
'x' => {
+687 -36
View File
@@ -12,7 +12,10 @@
//!
//! 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.
//! 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.
const std = @import("std");
const ast = @import("ast.zig");
@@ -29,15 +32,40 @@ pub const Ty = union(enum) {
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,
pub const Arr = struct { elem: Ty, len: u64 };
fn eql(a: Ty, b: Ty) bool {
if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false;
return switch (a) {
.int => |x| std.mem.eql(u8, x, b.int),
.named => |i| i == b.named,
.array => |x| x.len == b.array.len and x.elem.eql(b.array.elem),
.ref, .mut, .slice, .slice_mut => |x| x.eql(inner(b).?),
else => true,
};
}
fn inner(t: Ty) ?Ty {
return switch (t) {
.ref, .mut, .slice, .slice_mut => |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" };
@@ -107,11 +135,30 @@ 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).
const BorrowEnd = struct { name: []const u8, span: Span };
/// 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,
@@ -119,6 +166,16 @@ const Loop = struct {
/// 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,
};
const FnOut = struct {
header: []const u8,
effects: []const u8,
span: Span,
blocks: []const Block,
};
const Value = struct { name: []const u8, ty: Ty };
@@ -149,6 +206,16 @@ const Lowerer = struct {
/// 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,
/// 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.
@@ -168,9 +235,23 @@ const Lowerer = struct {
.void => "void",
.never => "never",
.named => |i| l.typeNames[i],
.array => |a| std.fmt.allocPrint(l.arena, "array<{s}, {d}>", .{ l.tyText(a.elem), a.len }) catch "array",
.ref, .mut, .slice, .slice_mut => |x| std.fmt.allocPrint(l.arena, "{s}<{s}>", .{ @tagName(t), l.tyText(x.*) }) catch "borrow",
};
}
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;
}
@@ -210,19 +291,57 @@ const Lowerer = struct {
if (!l.sigs.contains("main")) return l.fail("E7002", .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 1 } }, "the module has no `main` function", &.{.{ .name = "name", .value = "main" }});
const whole: Span = if (l.m.functions.len != 0) l.m.functions[0].span else .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 1 } };
// Type lines are built first (they can fail); functions are lowered
// before the header is written, because the `features` header is the
// closure of what the lowered AIR uses (spec 15 §9).
var type_lines: std.ArrayList(Inst) = .empty;
for (l.m.types) |t| try type_lines.append(l.arena, .{ .text = try l.typeDeclText(t), .span = t.span });
for (l.m.functions) |f| try l.fns.append(l.arena, try l.function(f));
var features: std.ArrayList(u8) = .empty;
const uses = l.featureUse(type_lines.items);
if (uses.arrays) try features.appendSlice(l.arena, "arrays, ");
try features.appendSlice(l.arena, "effects");
if (uses.ownership) try features.appendSlice(l.arena, ", ownership");
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);
// The features header is the closure of what the module uses; the
// implemented layers need nothing beyond `effects` (spec 15 §9).
try l.line("features [effects]", whole);
try l.line(try l.fmt("features [{s}]", .{features.items}), whole);
if (l.m.types.len != 0) try l.line("", null);
for (l.m.types) |t| try l.typeDeclLine(t);
for (l.m.functions) |f| try l.function(f);
for (type_lines.items) |t| try l.line(t.text, t.span);
for (l.fns.items) |f| try l.emitFunction(f);
}
/// Which features the lowered AIR uses: `arrays` (and so `ownership`)
/// for arrays and slices, `ownership` for frame storage and borrows.
fn featureUse(l: *Lowerer, type_lines: []const Inst) struct { arrays: bool, ownership: bool } {
var arrays = false;
var ownership = false;
const scan = struct {
fn has(text: []const u8, word: []const u8) bool {
return std.mem.indexOf(u8, text, word) != null;
}
}.has;
var texts: std.ArrayList([]const u8) = .empty;
for (type_lines) |t| texts.append(l.arena, t.text) catch {};
for (l.fns.items) |f| {
texts.append(l.arena, f.header) catch {};
for (f.blocks) |b| {
for (b.params.items) |p| texts.append(l.arena, l.tyText(p.ty)) catch {};
for (b.insts.items) |inst| texts.append(l.arena, inst.text) catch {};
}
}
for (texts.items) |t| {
if (scan(t, "array<") or scan(t, "slice") or scan(t, "array.splat") or scan(t, "borrow.index")) arrays = true;
if (scan(t, "local.") or scan(t, "borrow.") or scan(t, " load ") or scan(t, "= load ") or std.mem.startsWith(u8, t, "store ") or scan(t, "ref<") or scan(t, "mut<")) ownership = true;
}
if (arrays) ownership = true;
return .{ .arrays = arrays, .ownership = ownership };
}
/// `type @T = struct { … }` / `enum { … }` in canonical form.
fn typeDeclLine(l: *Lowerer, t: ast.TypeDecl) Error!void {
fn typeDeclText(l: *Lowerer, t: ast.TypeDecl) Error![]const u8 {
var w: std.ArrayList(u8) = .empty;
try w.appendSlice(l.arena, try l.fmt("type @{s} = ", .{t.name}));
switch (t.kind) {
@@ -251,7 +370,7 @@ const Lowerer = struct {
try w.appendSlice(l.arena, " }");
},
}
try l.line(w.items, t.span);
return w.items;
}
fn memberType(l: *Lowerer, t: ast.Type) Error!Ty {
@@ -272,17 +391,34 @@ const Lowerer = struct {
for (later) |x| if (std.mem.eql(u8, x, n)) return l.notYet(t.span, "this type (later layers)");
return l.fail("E7002", t.span, "unknown type", &.{.{ .name = "name", .value = n }});
},
.array => |a| return l.arrayOf(try l.memberType(a.elem.*), a.len),
.wrapped => |w| {
const Wr = enum { ref, mut, slice, slice_mut };
const 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),
};
},
else => return l.notYet(t.span, "this type (later layers)"),
}
}
// ------------------------------------------------------------ functions
fn function(l: *Lowerer, f: ast.FnDecl) Error!void {
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;
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)");
@@ -292,7 +428,8 @@ const Lowerer = struct {
try header.appendSlice(l.arena, try l.fmt("fn @{s}(", .{f.name}));
for (f.params, sig.params, 0..) |p, t, i| {
const v = try l.freshName(p.name);
try l.bindings.append(l.arena, .{ .name = p.name, .mutable = false, .value = v, .ty = t });
// 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)}));
@@ -312,12 +449,21 @@ const Lowerer = struct {
} else return l.fail("E7006", f.body.span, "the function can end without returning a value", &.{.{ .name = "function", .value = f.name }});
}
try l.line("", null);
try l.line(header.items, f.span);
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 }));
try l.line(try l.fmt("effects [{s}]", .{eff.items}), f.span);
for (l.blocks.items) |b| {
// 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);
@@ -379,7 +525,7 @@ const Lowerer = struct {
/// 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) try out.append(l.arena, i);
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;
}
@@ -437,22 +583,65 @@ const Lowerer = struct {
defer l.bindings.shrinkRetainingCapacity(depth);
try l.rest.append(l.arena, .{ .stmts = b.stmts, .tail = b.tail });
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;
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 ..];
try l.stmt(s);
}
var result: ?Value = null;
if (b.tail) |t| {
if (l.cur == null) return l.fail("E7006", t.span, "unreachable expression", &.{});
return try l.expr(t.*, want);
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("borrow.end %{s}", .{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);
}
return null;
}
fn stmt(l: *Lowerer, s: ast.Stmt) Error!void {
switch (s.kind) {
.let => |x| {
if (x.names.len != 1) return l.notYet(s.span, "`let (a, b)` (layer 3)");
if (x.names.len == 2) return l.splitLet(s, x.names, x.e);
if (x.e.kind == .borrow) return l.fail("E7006", x.e.span, "bind a borrow with `ref name = place;` or `mut name = place;`", &.{});
if (x.e.kind == .bytes) {
const st = try l.materializeBytes(x.e.kind.bytes, x.e.span);
try l.bindings.append(l.arena, .{ .name = x.names[0], .mutable = false, .value = st.name, .ty = st.ty, .kind = .storage });
return;
}
var want: ?Ty = if (x.ty) |t| try l.typeOf(t) else null;
// An untyped `let` takes its type from how the name is used
// later (`return`, arguments, operations, annotations).
@@ -460,38 +649,77 @@ const Lowerer = struct {
const v = try l.expr(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", &.{});
try l.bindings.append(l.arena, .{ .name = x.names[0], .mutable = false, .value = v.name, .ty = v.ty });
if (v.ty.isBorrow()) return l.fail("E7006", x.e.span, "bind a borrow with `ref name = place;` or `mut name = place;`", &.{});
if (l.addressable.contains(x.names[0])) {
const st = try l.storageFor(x.names[0], v.ty, s.span);
try l.emit(try l.fmt("local.store %{s}, %{s}", .{ st, v.name }), s.span);
try l.bindings.append(l.arena, .{ .name = x.names[0], .mutable = false, .value = st, .ty = v.ty, .kind = .storage });
} else try l.bindings.append(l.arena, .{ .name = x.names[0], .mutable = false, .value = v.name, .ty = v.ty });
},
.@"var" => |x| {
const ty = try l.typeOf(x.ty);
if (ty.isBorrow()) return l.fail("E7006", s.span, "a `var` holds a value; bind a borrow with `ref` or `mut`", &.{});
if (l.addressable.contains(x.name)) {
const st = try l.storageFor(x.name, ty, s.span);
if (x.init) |e| {
const v = try l.expr(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.expr(e, ty);
try l.checkTy(e.span, v.ty, ty);
break :blk v;
} else switch (ty) {
.int => |n| try l.def(x.name, ty, try l.fmt("const.{s} 0", .{n}), s.span),
.bool => try l.def(x.name, ty, "const.bool false", s.span),
else => return l.fail("E7006", s.span, "`zero` needs a zeroable type", &.{}),
};
} 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.notYet(x.place.span, "assignment through a place (layer 4)");
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.expr(x.e, ty);
try l.checkTy(x.e.span, v.ty, ty);
// `expr` may have created bindings and blocks; look the binding up again.
l.lookup(x.place.kind.name).?.value = v.name;
if (kind == .storage) {
try l.emit(try l.fmt("local.store %{s}, %{s}", .{ storage, v.name }), s.span);
} else {
// `expr` may have created bindings and blocks; look the binding up again.
l.lookup(x.place.kind.name).?.value = v.name;
}
},
.borrow => |x| {
// No shadowing of an active borrow by the same name in the same scope.
const scope_start = l.scopeBindingStart();
for (l.bindings.items[scope_start..]) |b| if (b.kind == .borrow and std.mem.eql(u8, b.name, x.name))
return l.fail("E7006", s.span, "a borrow of this name is already active in this scope", &.{.{ .name = "name", .value = x.name }});
const p = try l.placeBorrow(x.place, x.mutable, true, 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.expr(x, l.ret);
try l.checkTy(x.span, v.ty, l.ret);
if (l.cur != null) try l.term(try l.fmt("ret %{s}", .{v.name}), s.span);
if (l.cur != null) {
try l.endScopes(0, s.span);
try l.term(try l.fmt("ret %{s}", .{v.name}), s.span);
}
} else {
if (l.ret != .void) return l.fail("E7005", s.span, "`return` without a value in a function that returns one", &.{.{ .name = "expected", .value = l.tyText(l.ret) }});
try l.endScopes(0, s.span);
try l.term("ret", s.span);
}
},
@@ -501,6 +729,7 @@ const Lowerer = struct {
const lp = l.loops.items[l.loops.items.len - 1];
const vars = try l.carried(lp.depth);
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| {
@@ -548,7 +777,7 @@ const Lowerer = struct {
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(vars, null) }), c.span);
l.cur = body_b;
}
try l.loops.append(l.arena, .{ .@"continue" = cont, .exit = exit, .depth = depth });
try l.loops.append(l.arena, .{ .@"continue" = cont, .exit = exit, .depth = depth, .scope_depth = l.scopes.items.len });
_ = 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);
@@ -610,6 +839,9 @@ const Lowerer = struct {
.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),
@@ -626,7 +858,9 @@ const Lowerer = struct {
.variant => |v| l.enumType(v.@"enum"),
.struct_lit => |x| l.enumOrStruct(x.name),
.field => |x| blk: {
const base = l.peekType(x.e.*) orelse break :blk null;
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);
@@ -746,8 +980,31 @@ const Lowerer = struct {
.boolean => |b| return l.def("c", .bool, if (b) "const.bool true" else "const.bool false", e.span),
.name => |n| {
const b = l.lookup(n) orelse return l.unknown(e.span, n);
if (b.kind == .storage) return l.def(n, b.ty, try l.fmt("local.load %{s}", .{b.value}), e.span);
return .{ .name = b.value, .ty = b.ty };
},
.deref => |x| {
const r = try l.expr(x.*, null);
const in = r.ty.inner() orelse return l.fail("E7005", e.span, "`*` reads through a borrow", &.{.{ .name = "found", .value = l.tyText(r.ty) }});
if (r.ty == .slice or r.ty == .slice_mut or in == .array) return l.fail("E7006", e.span, "read slice and array elements with `s[i]`, not `*`", &.{});
return l.def("v", in, try l.fmt("load %{s}", .{r.name}), e.span);
},
.index => |x| {
if (x.hi != null) return l.fail("E7006", e.span, "a range `s[a..b]` is a borrow: bind it with `ref r = s[a..b];` or pass `ref s[a..b]`", &.{});
const p = try l.placeBorrow(e, false, false, e.span);
const v = try l.def("v", p.v.ty.inner().?, try l.fmt("load %{s}", .{p.v.name}), e.span);
try l.endNow(p.ends, e.span);
return v;
},
.array_rep => |x| {
const want_elem: ?Ty = if (want) |w| (if (w == .array) w.array.elem else null) else null;
const v = try l.expr(x.e.*, want_elem);
if (v.ty.isBorrow()) return l.fail("E7006", x.e.span, "an array element cannot be a borrow", &.{});
const at = try l.arrayOf(v.ty, x.len);
return l.def("arr", at, try l.fmt("array.splat {s} %{s}", .{ l.tyText(at), v.name }), e.span);
},
.bytes => return l.fail("E7006", e.span, "a byte string is an array in storage: bind it with `let`/`ref`, or pass it where a slice is expected", &.{}),
.borrow => return l.fail("E7006", e.span, "`ref`/`mut` here: borrows are bound with `ref name = place;` / `mut name = place;` or passed as arguments", &.{}),
.neg => |x| {
const ty = want orelse l.peekType(x.*) orelse return l.fail("E7007", e.span, "the type of this negation cannot be determined", &.{});
if (ty != .int) return l.fail("E7005", e.span, "negation of a non-integer", &.{});
@@ -792,10 +1049,12 @@ const Lowerer = struct {
.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| return l.fieldValue(e, x.e.*, x.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 => return l.notYet(e.span, "`or trap` (layer 5, with fallible operations)"),
.bytes, .array_rep, .index => return l.notYet(e.span, "arrays and byte strings (layer 3)"),
.borrow, .deref, .move => return l.notYet(e.span, "borrows and moves (layer 4)"),
.move => return l.notYet(e.span, "`move` (layer 5, with linear values)"),
}
}
@@ -865,6 +1124,9 @@ const Lowerer = struct {
fn call(l: *Lowerer, e: ast.Expr, callee: ast.Expr, args: []const ast.Expr) Error!Value {
if (callee.kind == .variant) return l.variantValue(e, callee.kind.variant.@"enum", callee.kind.variant.name, args);
if (pathOf(callee)) |p| if (std.mem.eql(u8, p, "slice.copy")) return l.sliceCopy(e, args);
if (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")) {
@@ -877,12 +1139,14 @@ const Lowerer = struct {
const sig = l.sigs.get(name) orelse return l.unknown(callee.span, name);
if (args.len != sig.params.len) return l.fail("E7005", e.span, "wrong number of arguments", &.{ .{ .name = "function", .value = name }, .{ .name = "expected", .value = try l.fmt("{d}", .{sig.params.len}) }, .{ .name = "found", .value = try l.fmt("{d}", .{args.len}) } });
var arg_names: std.ArrayList(u8) = .empty;
var temps: std.ArrayList([]const u8) = .empty;
for (args, sig.params, 0..) |a, pt, i| {
const v = try l.expr(a, pt);
const v = try l.argument(a, pt, &temps);
try l.checkTy(a.span, v.ty, pt);
try arg_names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", v.name }));
}
const text = try l.fmt("call @{s}({s})", .{ name, arg_names.items });
defer l.endNowIfLive(temps.items, e.span) catch {};
if (sig.ret == .void or sig.ret == .never) {
try l.emit(text, e.span);
if (sig.ret == .never) {
@@ -941,12 +1205,20 @@ const Lowerer = struct {
/// `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 {
const bt = l.peekType(base) orelse return l.fail("E7007", base.span, "the type of this expression cannot be determined", &.{});
var bt = l.peekType(base) orelse return l.fail("E7007", base.span, "the type of this expression cannot be determined", &.{});
if (bt.isBorrow()) bt = bt.inner().?;
const d = l.decl(bt) orelse return l.fail("E7005", e.span, "field access on a value that is not a struct", &.{.{ .name = "found", .value = l.tyText(bt) }});
if (d.kind != .@"struct") return l.fail("E7005", e.span, "field access on an enum; use `match`", &.{.{ .name = "type", .value = d.name }});
const f = for (d.kind.@"struct") |x| {
if (std.mem.eql(u8, x.name, name)) break x;
} else return l.fail("E7002", e.span, "no such field", &.{ .{ .name = "type", .value = d.name }, .{ .name = "field", .value = name } });
// Through a borrow: borrow the field and load it.
if (l.rootBinding(base)) |rb| if (rb.kind == .borrow) {
const p = try l.placeBorrow(e, false, false, e.span);
const v = try l.def(name, p.v.ty.inner().?, try l.fmt("load %{s}", .{p.v.name}), e.span);
try l.endNow(p.ends, e.span);
return v;
};
const v = try l.expr(base, bt);
return l.def(name, try l.typeOf(f.ty), try l.fmt("struct.get @{s}.{s}, %{s}", .{ d.name, name, v.name }), e.span);
}
@@ -1096,8 +1368,365 @@ const Lowerer = struct {
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);
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.placeBorrow(x.place.*, x.mutable, true, 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.expr(a, want),
}
}
fn rootBinding(l: *Lowerer, e: ast.Expr) ?*Binding {
var x = e;
while (true) switch (x.kind) {
.name => |n| return l.lookup(n),
.field => |f| x = f.e.*,
.index => |i| x = i.e.*,
.deref => |d| x = d.*,
else => return null,
};
}
/// Borrows a place (spec 15 §5). `want_slice`: a borrow of a whole
/// array becomes a slice. A place that is itself a borrow binding is
/// returned as is (`ends` empty).
fn placeBorrow(l: *Lowerer, place: ast.Expr, mutable: bool, want_slice: bool, span: Span) Error!Placed {
var p = try l.placeRaw(place, mutable, span);
if (want_slice and (p.v.ty == .ref or p.v.ty == .mut) and p.v.ty.inner().? == .array) {
const elem = p.v.ty.inner().?.array.elem;
const sl = try l.def("s", (if (mutable) try l.wrap(.slice_mut, elem) else try l.wrap(.slice, elem)), try l.fmt("slice.make %{s}", .{p.v.name}), span);
var ends: std.ArrayList([]const u8) = .empty;
try ends.appendSlice(l.arena, p.ends);
try ends.append(l.arena, sl.name);
p = .{ .v = sl, .ends = ends.items };
}
return p;
}
fn placeRaw(l: *Lowerer, place: ast.Expr, mutable: bool, span: Span) Error!Placed {
const op = if (mutable) "borrow.mut" else "borrow.ref";
switch (place.kind) {
.name => |n| {
const b = l.lookup(n) orelse return l.unknown(place.span, n);
switch (b.kind) {
.storage => {
const v = try l.def(n, if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty), try l.fmt("{s} %{s}", .{ op, b.value }), span);
return .{ .v = v, .ends = try l.arena.dupe([]const u8, &.{v.name}) };
},
.borrow => return .{ .v = .{ .name = b.value, .ty = b.ty }, .ends = &.{} },
.ssa => return l.fail("E7006", place.span, "this value is not addressable here; borrow a variable, a field or an element", &.{.{ .name = "name", .value = n }}),
}
},
.bytes => |bytes| {
const st = try l.materializeBytes(bytes, place.span);
const v = try l.def("b", if (mutable) try l.wrap(.mut, st.ty) else try l.wrap(.ref, st.ty), try l.fmt("{s} %{s}", .{ op, st.name }), span);
return .{ .v = v, .ends = try l.arena.dupe([]const u8, &.{v.name}) };
},
.deref => |d| {
const r = try l.expr(d.*, null);
if (!r.ty.isBorrow()) return l.fail("E7005", place.span, "`*` needs a borrow", &.{});
return .{ .v = r, .ends = &.{} };
},
.field => |f| {
const base = try l.placeRaw(f.e.*, mutable, span);
const st = base.v.ty.inner() orelse return l.fail("E7005", place.span, "field of a value that is not a struct", &.{});
const d = l.decl(st) orelse return l.fail("E7005", place.span, "field of a value that is not a struct", &.{.{ .name = "found", .value = l.tyText(st) }});
if (d.kind != .@"struct") return l.fail("E7005", place.span, "field of an enum; use `match`", &.{});
const fd = for (d.kind.@"struct") |x| {
if (std.mem.eql(u8, x.name, f.name)) break x;
} else return l.fail("E7002", place.span, "no such field", &.{ .{ .name = "type", .value = d.name }, .{ .name = "field", .value = f.name } });
const ft = try l.typeOf(fd.ty);
const v = try l.def(f.name, if (base.v.ty.isMutBorrow()) try l.wrap(.mut, ft) else try l.wrap(.ref, ft), try l.fmt("borrow.field @{s}.{s}, %{s}", .{ d.name, f.name, base.v.name }), span);
return .{ .v = v, .ends = try l.concat(base.ends, v.name) };
},
.index => |x| {
const base = try l.placeRaw(x.e.*, mutable, span);
const bt = base.v.ty;
const elem = elemOf(bt) orelse return l.fail("E7005", place.span, "indexing needs an array or a slice", &.{.{ .name = "found", .value = l.tyText(bt) }});
if (x.hi) |hi| {
// `s[a..b]`: slice.sub with start a and length b - a (checked).
var sl = base.v;
var ends = base.ends;
if (bt == .ref or bt == .mut) {
sl = try l.def("s", (if (bt == .mut) try l.wrap(.slice_mut, elem) else try l.wrap(.slice, elem)), try l.fmt("slice.make %{s}", .{base.v.name}), span);
ends = try l.concat(ends, sl.name);
}
const a = try l.expr(x.lo.*, .{ .int = "usize" });
try l.checkTy(x.lo.span, a.ty, .{ .int = "usize" });
const b = try l.expr(hi.*, .{ .int = "usize" });
try l.checkTy(hi.span, b.ty, .{ .int = "usize" });
const len = try l.def("len", .{ .int = "usize" }, try l.fmt("sub.checked.usize %{s}, %{s}", .{ b.name, a.name }), span);
const sub_ = try l.def("s", sl.ty, try l.fmt("slice.sub %{s}, %{s}, %{s}", .{ sl.name, a.name, len.name }), span);
return .{ .v = sub_, .ends = try l.concat(ends, sub_.name) };
}
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;
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}", .{ if (proven) "borrow.index.proven" else "borrow.index", base.v.name, i.name }), span);
return .{ .v = v, .ends = try l.concat(base.ends, v.name) };
},
else => return l.fail("E7006", place.span, "not a place: borrow a variable, a field `x.f`, an element `s[i]` or a range `s[a..b]`", &.{}),
}
}
fn concat(l: *Lowerer, a: []const []const u8, b: []const u8) Error![]const []const u8 {
const out = try l.arena.alloc([]const u8, a.len + 1);
@memcpy(out[0..a.len], a);
out[a.len] = b;
return out;
}
/// `*r = v`, `r.f = v`, `x.f = v`, `s[i] = v`, `x[i] = v`.
fn assignPlace(l: *Lowerer, span: Span, place: ast.Expr, value: ast.Expr) Error!void {
switch (place.kind) {
.deref, .field, .index => {},
else => return l.fail("E7006", place.span, "cannot assign to this expression", &.{}),
}
if (place.kind == .index and place.kind.index.hi != null) return l.fail("E7006", place.span, "assign elements one by one, or use `slice.copy(mut dst, ref src)`", &.{});
// The value is evaluated first, then the place is borrowed for the
// store (spec 15 §4), so `s[i] = s[i] + 1` reads before it writes.
const v = try l.expr(value, l.placeType(place));
const p = try l.placeBorrow(place, true, false, span);
const in = p.v.ty.inner() orelse return l.fail("E7005", place.span, "assignment needs a mutable place", &.{});
if (in == .array and place.kind == .deref) return l.fail("E7006", place.span, "write array elements with `s[i] = …`", &.{});
try l.checkTy(value.span, v.ty, in);
try l.emit(try l.fmt("store %{s}, %{s}", .{ p.v.name, v.name }), span);
try l.endNow(p.ends, span);
}
/// The type stored at a place, without lowering it.
fn placeType(l: *Lowerer, place: ast.Expr) ?Ty {
return switch (place.kind) {
.deref => |d| if (l.peekType(d.*)) |t| t.inner() else null,
.field, .index => l.peekType(place),
else => null,
};
}
/// `x.len`: `slice.len` of a slice, the static length of an array.
fn lenOf(l: *Lowerer, e: ast.Expr, base: ast.Expr) Error!Value {
const bt = l.peekType(base) orelse return l.fail("E7007", base.span, "the type of this expression cannot be determined", &.{});
const arr: ?u64 = switch (bt) {
.array => |a| a.len,
.ref, .mut => |x| if (x.* == .array) x.array.len else null,
else => null,
};
if (arr) |n| return l.def("len", .{ .int = "usize" }, try l.fmt("const.usize {d}", .{n}), e.span);
if (bt != .slice and bt != .slice_mut) return l.fail("E7005", e.span, "`.len` needs an array or a slice", &.{.{ .name = "found", .value = l.tyText(bt) }});
const s_ = try l.expr(base, bt);
return l.def("len", .{ .int = "usize" }, try l.fmt("slice.len %{s}", .{s_.name}), e.span);
}
/// `let (left, right) = s.split_at(k);`: two disjoint borrows of `s`,
/// bound for the rest of the block (spec 15 §5).
fn splitLet(l: *Lowerer, s: ast.Stmt, names: []const []const u8, e: ast.Expr) Error!void {
if (e.kind != .call or e.kind.call.callee.kind != .field or !std.mem.eql(u8, e.kind.call.callee.kind.field.name, "split_at") or e.kind.call.args.len != 1)
return l.fail("E7006", e.span, "`let (a, b) = …` is only for `s.split_at(k)`", &.{});
const base = e.kind.call.callee.kind.field.e.*;
const rb = l.rootBinding(base) orelse return l.fail("E7002", base.span, "unknown name", &.{});
const mutable = rb.ty.isMutBorrow() or rb.kind == .storage and rb.mutable;
const p = try l.placeBorrow(base, mutable, true, s.span);
if (p.v.ty != .slice and p.v.ty != .slice_mut) return l.fail("E7005", base.span, "`split_at` splits a slice", &.{.{ .name = "found", .value = l.tyText(p.v.ty) }});
const k = try l.expr(e.kind.call.args[0], .{ .int = "usize" });
try l.checkTy(e.kind.call.args[0].span, k.ty, .{ .int = "usize" });
const left = try l.freshName(names[0]);
const right = try l.freshName(names[1]);
try l.emit(try l.fmt("%{s}, %{s} = slice.split %{s}, %{s}", .{ left, right, p.v.name, k.name }), s.span);
try l.scopeEnds(p.ends, s.span);
try l.scopeEnds(&.{ left, right }, s.span);
try l.bindings.append(l.arena, .{ .name = names[0], .mutable = false, .value = left, .ty = p.v.ty, .kind = .borrow });
try l.bindings.append(l.arena, .{ .name = names[1], .mutable = false, .value = right, .ty = p.v.ty, .kind = .borrow });
}
/// `slice.copy(mut dst, ref src)`: the only copy form (spec 15 §5).
fn sliceCopy(l: *Lowerer, e: ast.Expr, args: []const ast.Expr) Error!Value {
if (args.len != 2) return l.fail("E7005", e.span, "`slice.copy` takes `mut dst` and `ref src`", &.{});
var temps: std.ArrayList([]const u8) = .empty;
const d = try l.argument(args[0], null, &temps);
const src = try l.argument(args[1], null, &temps);
try l.emit(try l.fmt("slice.copy %{s}, %{s}", .{ d.name, src.name }), e.span);
try l.endNow(temps.items, e.span);
return .{ .name = "", .ty = .void };
}
/// Names that need frame storage in this function: every variable that is
/// borrowed, indexed, or written through a field or element (spec 15 §9).
/// Deterministic and by name.
fn findAddressable(l: *Lowerer, body: ast.Block) Error!void {
try l.markBlock(body);
}
fn markBlock(l: *Lowerer, b: ast.Block) Error!void {
for (b.stmts) |s| try l.markStmt(s);
if (b.tail) |t| try l.markExpr(t.*);
}
fn markRoot(l: *Lowerer, e: ast.Expr) Error!void {
var x = e;
while (true) switch (x.kind) {
.name => |n| return l.addressable.put(l.arena, n, {}),
.field => |f| x = f.e.*,
.index => |i| {
try l.markExpr(i.lo.*);
if (i.hi) |h| try l.markExpr(h.*);
x = i.e.*;
},
else => return l.markExpr(x),
};
}
fn markStmt(l: *Lowerer, s: ast.Stmt) Error!void {
switch (s.kind) {
.let => |x| try l.markExpr(x.e),
.@"var" => |x| if (x.init) |e| try l.markExpr(e),
.assign => |x| {
if (x.place.kind != .name) try l.markRoot(x.place);
try l.markExpr(x.e);
},
.borrow => |x| try l.markRoot(x.place),
.@"return" => |e| if (e) |x| try l.markExpr(x),
.expr => |e| try l.markExpr(e),
.@"while" => |x| {
try l.markExpr(x.cond);
try l.markBlock(x.body);
},
.@"for" => |x| {
try l.markExpr(x.lo);
try l.markExpr(x.hi);
try l.markBlock(x.body);
},
.loop, .shield => |b| try l.markBlock(b),
.scope => |x| try l.markBlock(x.body),
.lock => |x| {
try l.markBlock(x.body);
try l.markBlock(x.cancelled);
},
else => {},
}
}
fn markExpr(l: *Lowerer, e: ast.Expr) Error!void {
switch (e.kind) {
.borrow => |x| try l.markRoot(x.place.*),
.index => try l.markRoot(e),
.neg, .not, .deref, .or_trap => |x| try l.markExpr(x.*),
.binary => |x| {
try l.markExpr(x.l.*);
try l.markExpr(x.r.*);
},
.cast => |x| try l.markExpr(x.e.*),
.call => |x| {
try l.markExpr(x.callee.*);
for (x.args) |a| try l.markExpr(a);
if (x.callee.kind == .field and std.mem.eql(u8, x.callee.kind.field.name, "split_at")) try l.markRoot(x.callee.kind.field.e.*);
},
.field => |x| try l.markExpr(x.e.*),
.struct_lit => |x| for (x.fields) |f| try l.markExpr(f.e),
.array_rep => |x| try l.markExpr(x.e.*),
.if_expr => |x| {
try l.markExpr(x.cond);
try l.markBlock(x.then);
if (x.@"else") |els| switch (els) {
.block => |b| try l.markBlock(b),
.@"if" => |inner| try l.markExpr(.{ .span = e.span, .kind = .{ .if_expr = inner } }),
};
},
.match_expr => |x| {
try l.markExpr(x.scrutinee);
for (x.arms) |a| try l.markExpr(a.body);
},
.block => |b| try l.markBlock(b.*),
else => {},
}
}
fn ifExpr(l: *Lowerer, span: Span, x: ast.If, want: ?Ty) Error!Value {
const cv = try l.expr(x.cond, .bool);
// `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.carried(depth);
@@ -1112,7 +1741,9 @@ const Lowerer = struct {
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;
@@ -1130,6 +1761,26 @@ const Lowerer = struct {
}
};
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,
};
}
/// `a.b.c` for a callee made of names and fields.
fn pathOf(e: ast.Expr) ?[]const u8 {
return switch (e.kind) {
.field => |f| switch (f.e.kind) {
.name => |n| if (std.mem.eql(u8, n, "slice") and std.mem.eql(u8, f.name, "copy")) "slice.copy" else null,
else => null,
},
else => null,
};
}
fn box(arena: Allocator, e: ast.Expr) Error!*const ast.Expr {
const b = try arena.create(ast.Expr);
b.* = e;
+8
View File
@@ -279,6 +279,14 @@ const Parser = struct {
_ = try p.expect(.semicolon, "`;`");
return .{ .span = p.span(start), .kind = .{ .let = .{ .names = names.items, .ty = ty, .e = e } } };
}
if ((isWord(t, "ref") or isWord(t, "mut")) and p.peekAt(1).tag == .ident and p.peekAt(2).tag == .eq) {
_ = p.next();
const name = try p.ident("a name for the borrow");
_ = try p.expect(.eq, "`=`");
const place = try p.expr();
_ = try p.expect(.semicolon, "`;`");
return .{ .span = p.span(start), .kind = .{ .borrow = .{ .mutable = isWord(t, "mut"), .name = name, .place = place } } };
}
if (isWord(t, "var")) {
_ = p.next();
const name = try p.ident("a name");
+20 -13
View File
@@ -100,24 +100,31 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
.ok => |o| {
if (stats) {
// How much mechanical work the frontend took over.
const lines = struct {
fn count(t: []const u8) usize {
var n: usize = 0;
// Code only: blank lines and `//` / `;` comment lines are not counted.
const Code = struct { bytes: usize, lines: usize };
const code = struct {
fn count(t: []const u8) Code {
var c: Code = .{ .bytes = 0, .lines = 0 };
var it = std.mem.splitScalar(u8, t, '\n');
while (it.next()) |ln| n += @intFromBool(std.mem.trim(u8, ln, " \t\r").len != 0);
return n;
while (it.next()) |ln| {
const tr = std.mem.trim(u8, ln, " \t\r");
if (tr.len == 0 or std.mem.startsWith(u8, tr, "//") or std.mem.startsWith(u8, tr, ";")) continue;
c.bytes += ln.len + 1;
c.lines += 1;
}
return c;
}
}.count;
const sl = lines(source);
const al = lines(o.air);
const sc = code(source);
const ac = code(o.air);
var s: std.json.Stringify = .{ .writer = out };
try s.write(.{
.source_bytes = source.len,
.source_lines = sl,
.air_bytes = o.air.len,
.air_lines = al,
.expansion_bytes = @as(f64, @floatFromInt(o.air.len)) / @as(f64, @floatFromInt(@max(source.len, 1))),
.expansion_lines = @as(f64, @floatFromInt(al)) / @as(f64, @floatFromInt(@max(sl, 1))),
.source_bytes = sc.bytes,
.source_lines = sc.lines,
.air_bytes = ac.bytes,
.air_lines = ac.lines,
.expansion_bytes = @as(f64, @floatFromInt(ac.bytes)) / @as(f64, @floatFromInt(@max(sc.bytes, 1))),
.expansion_lines = @as(f64, @floatFromInt(ac.lines)) / @as(f64, @floatFromInt(@max(sc.lines, 1))),
});
try out.writeByte('\n');
return .accepted;
@@ -0,0 +1,17 @@
// Architecture: a borrowed variable gets frame storage (local.alloc in the entry block, local.store).
// expect: run
// result: 7
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.addressable
fn main() -> u64
effects []
{
var x: u64 = 5;
{
mut r = x;
*r = 7;
}
return x;
}
@@ -0,0 +1,17 @@
module demo.addressable
air 0
lang 0.1
features [effects, ownership]
fn @main() -> u64
effects []
entry:
%x_1 = local.alloc u64
%c_2 = const.u64 5
local.store %x_1, %c_2
%x_3 = borrow.mut %x_1
%c_4 = const.u64 7
store %x_3, %c_4
borrow.end %x_3
%x_5 = local.load %x_1
ret %x_5
@@ -0,0 +1,20 @@
// Element writes and reads on an array variable: the frontend gives it frame storage.
// expect: run
// result: 140
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.arraysum
fn main() -> u64
effects []
{
var buf: [u64; 8] = zero;
for i in 0..buf.len {
buf[i] = i as! u64 * 5;
}
var total: u64 = 0;
for i in 0..8usize {
total = total + buf[i];
}
return total;
}
@@ -0,0 +1,23 @@
// [e; N] evaluates e once and copies it; an array that is only passed around stays an SSA value.
// expect: run
// result: 28
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.arrayvalue
fn total(a: ref<[u8; 4]>) -> u64
effects []
{
return 0;
}
fn main() -> u64
effects []
{
var a: [u8; 4] = [7u8; 4];
var sum: u64 = 0;
for i in 0..4usize {
sum = sum + a[i] as u64;
}
return sum;
}
@@ -0,0 +1,35 @@
// Functions take borrows; the caller lends them for the call (temporaries end after it).
// expect: run
// result: 12
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.params
fn sum(s: slice<u64>) -> u64
effects []
{
var t: u64 = 0;
for i in 0..s.len {
t = t + s[i];
}
return t;
}
fn bump(c: mut<u64>) -> void
effects []
{
*c = *c + 1;
}
fn main() -> u64
effects []
{
var counter: u64 = 0;
bump(mut counter);
bump(mut counter);
var data: [u64; 3] = zero;
data[0] = 3;
data[1] = 3;
data[2] = 4;
return sum(ref data) + counter;
}
@@ -0,0 +1,14 @@
// A checked index out of range traps T0008 at run time, with the source location.
// expect: run
// trap: T0008
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.bounds
fn main() -> u64
effects []
{
var d: [u64; 2] = zero;
let i: usize = 2;
return d[i];
}
@@ -0,0 +1,19 @@
// A byte string is an array in frame storage; escapes \n and \x41.
// expect: run
// result: 3
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.bytes
fn main() -> u64
effects []
{
let msg = b"hi\nA\x41";
var count: u64 = 0;
for i in 0..msg.len {
if msg[i] == 65 or msg[i] == 10 {
count = count + 1;
}
}
return count;
}
@@ -0,0 +1,23 @@
// Architecture: under `if i < s.len` with i and s unchanged the index is borrow.index.proven.
// expect: run
// result: 9
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.proven
fn get(s: slice<u64>, i: usize) -> u64
effects []
{
if i < s.len {
return s[i];
}
return 0;
}
fn main() -> u64
effects []
{
var d: [u64; 2] = zero;
d[1] = 9;
return get(ref d, 1) + get(ref d, 5);
}
@@ -0,0 +1,48 @@
module demo.proven
air 0
lang 0.1
features [arrays, effects, ownership]
fn @get(%s_1: slice<u64>, %i_2: usize) -> u64
effects []
entry:
%len_3 = slice.len %s_1
%cmp_4 = lt.usize %i_2, %len_3
cbr %cmp_4, @then_5(), @else_6()
then_5:
%e_7 = borrow.index.proven %s_1, %i_2
%v_8 = load %e_7
borrow.end %e_7
ret %v_8
else_6:
br @endif_9()
endif_9:
%c_10 = const.u64 0
ret %c_10
fn @main() -> u64
effects []
entry:
%d_1 = local.alloc array<u64, 2>
local.zero %d_1
%c_2 = const.u64 9
%d_3 = borrow.mut %d_1
%c_4 = const.usize 1
%e_5 = borrow.index %d_3, %c_4
store %e_5, %c_2
borrow.end %e_5
borrow.end %d_3
%d_6 = borrow.ref %d_1
%s_7 = slice.make %d_6
%c_8 = const.usize 1
%get_9 = call @get(%s_7, %c_8)
borrow.end %s_7
borrow.end %d_6
%d_10 = borrow.ref %d_1
%s_11 = slice.make %d_10
%c_12 = const.usize 5
%get_13 = call @get(%s_11, %c_12)
borrow.end %s_11
borrow.end %d_10
%t_14 = add.checked.u64 %get_9, %get_13
ret %t_14
@@ -0,0 +1,14 @@
// The frontend does not check aliasing: the verifier reports E2101 at the second borrow.
// expect: reject E2101
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.conflict
fn main() -> u64
effects []
{
var buf: [u64; 2] = zero;
mut a = buf;
ref b = buf;
return 0;
}
@@ -0,0 +1,13 @@
// One spelling: borrows are bound with `ref r = …;` / `mut r = …;`.
// expect: reject E7006
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.letborrow
fn main() -> u64
effects []
{
var x: u64 = 1;
let r = mut x;
return 0;
}
@@ -0,0 +1,17 @@
// `*` is for scalar and struct referents; slices use s[i].
// expect: reject E7006
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.derefslice
fn first(s: slice<u64>) -> u64
effects []
{
return *s;
}
fn main() -> u64
effects []
{
return 0;
}
@@ -0,0 +1,11 @@
// expect: reject E7005
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.indexscalar
fn main() -> u64
effects []
{
var x: u64 = 1;
return x[0];
}
@@ -0,0 +1,15 @@
// An active borrow cannot be shadowed by the same name in the same scope.
// expect: reject E7006
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.shadow
fn main() -> u64
effects []
{
var x: u64 = 1;
var y: u64 = 2;
ref r = x;
ref r = y;
return *r;
}
@@ -0,0 +1,16 @@
// After split_at the parent slice cannot be used while the halves live: E2101 from the verifier.
// expect: reject E2101
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.splitparent
fn main() -> u64
effects []
{
var buf: [u64; 4] = zero;
mut s = buf;
let (l, r) = s.split_at(2);
s[0] = 1;
l[0] = 2;
return 0;
}
@@ -0,0 +1,27 @@
// mut binding, proven indexing under `if i < s.len`, split_at into disjoint halves, ranges and slice.copy.
// expect: run
// result: 4321
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.slices
fn main() -> u64
effects []
{
var buf: [u64; 4] = zero;
{
mut s = buf;
for i in 0..4usize {
if i < s.len {
s[i] = i as! u64 + 1;
}
}
let (left, right) = s.split_at(2);
left[0] = left[0] * 1;
right[1] = right[1] * 1;
}
var out: [u64; 4] = zero;
slice.copy(mut out[0..2], ref buf[2..4]);
slice.copy(mut out[2..4], ref buf[0..2]);
return out[1] * 1000 + out[0] * 100 + out[3] * 10 + out[2];
}
@@ -0,0 +1,28 @@
// Writes through a mut borrow of a struct, a field borrow, reads through a shared borrow.
// expect: run
// result: 57
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.structborrow
struct Pair {
a: u64,
b: u64,
}
fn main() -> u64
effects []
{
var p: Pair = Pair { a: 1, b: 2 };
{
mut r = p;
r.a = 5;
r.b = r.a + 2;
}
{
mut f = p.b;
*f = *f * 7;
}
ref q = p;
return q.a + q.b + 3;
}
@@ -0,0 +1,15 @@
// Architecture: a variable used only by value stays SSA (the golden AIR has no local.alloc).
// expect: run
// result: 10
// phase: 6
// spec: docs/spec/15-source-language.md
module demo.valueonly
fn main() -> u64
effects []
{
let x = 5u64;
var y: u64 = x;
y = y + x;
return y;
}
@@ -0,0 +1,11 @@
module demo.valueonly
air 0
lang 0.1
features [effects]
fn @main() -> u64
effects []
entry:
%c_1 = const.u64 5
%t_2 = add.checked.u64 %c_1, %c_1
ret %t_2