Phase 6A: .aji layer 2 (structs, enums, exhaustive match)
Owner rules: struct/enum declarations in Rust form; one construction form each (named struct literal, Enum::Variant); struct fields lowered in declaration order, so field order in the source does not change the AIR (golden test with two orders, one AIR); match over enums exhaustive with no '_' (E7004 lists missing variants, E7006 for '_'), integer match needs '_'; payload names scoped to their arm (enum.switch block parameters); match as an expression with a merge block; arm-level source map; no destructuring, guards or nested patterns. Type inference limits written into spec 15 (one function, monomorphic, no search, E7007). aji lower --stats: source/AIR size and expansion ratio. Tests: 4 run (one shared golden), 7 rejects incl. verifier-caught E1003.
This commit is contained in:
1 parent
ba3e9b3719
commit
0fdd04179b
22 files changed
+702
-121
No files matched your search
@@ -31,8 +31,8 @@ effects [io.read, io.write]
|
||||
|---|---|
|
||||
| `u8 … u128`, `usize`, `i8 … i128`, `isize`, `bool` | no implicit conversion |
|
||||
| `[T; N]` | array; `[e; N]` repeats `e` |
|
||||
| `type P = struct { a: u8, b: u8 }` | `P { a: 1, b: 2 }`, `p.a` |
|
||||
| `type E = enum { A, B(u64), C(u8, u8) }` | `E.B(4)`; `match` arms `A`, `B(x)`, `C(x, y)`, `_` |
|
||||
| `struct P { a: u8, b: u8 }` | `P { a: 1, b: 2 }` (every field, any order), `p.a` |
|
||||
| `enum E { A, B(u64), C(u8, u8) }` | `E::A`, `E::B(4)`; `match` with one arm per variant: `E::A => …`, `E::B(x) => …`, `E::C(x, y) => …` (no `_`) |
|
||||
| `ref<T>`, `mut<T>`, `slice<T>`, `slice_mut<T>` | borrows (§4) |
|
||||
| `own<T>`, `own_array<T>`, `region` | heap and regions (§6) |
|
||||
| `cap<K>` | authority; kinds below |
|
||||
@@ -54,6 +54,11 @@ for i in 0..n { … } // 0 ≤ i < n
|
||||
loop { … break; … continue; … }
|
||||
return v; trap; assert(c);
|
||||
let y = if c { 1 } else { 2 }; // value-producing if/match: tail expression without `;`
|
||||
let w: u64 = match m { // enum match: exhaustive, one arm per variant
|
||||
Message::Stop => 0,
|
||||
Message::Value(x) => x, // x exists only in this arm
|
||||
};
|
||||
match d { 0 => { … } 1 => { … } _ => { … } } // integer match: `_` required
|
||||
```
|
||||
|
||||
| Operation | Meaning |
|
||||
@@ -197,7 +202,7 @@ scope s { // every task spawned in s must
|
||||
| E7001 | syntax | check `;`, braces, `=>` in `match` |
|
||||
| E7002 | unknown name | spelling; declare the variable or function |
|
||||
| E7003 | linear value consumed without `move` | write `move x` (or borrow it with `ref`/`mut` if it must stay) |
|
||||
| E7004 | `match` not exhaustive | add the missing outcome/variant arm or `_` |
|
||||
| E7004 | `match` not exhaustive | add the arms listed in `missing` (integers: add `_`) |
|
||||
| E7005, E1001 | type mismatch | convert with `as`, `as!`, `as%`; check borrow vs value |
|
||||
| E7007 | ambiguous literal | add a suffix (`0u64`) or a type annotation |
|
||||
| E2101 | conflicting borrows | end the first borrow earlier with an inner `{ }` block |
|
||||
|
||||
@@ -39,7 +39,7 @@ Lowering layers (P6A-3/4), each with accepted (golden AIR), rejected (`E7xxx`) a
|
||||
| Layer | Content | Status |
|
||||
|---|---|---|
|
||||
| 1 | scalars, expressions, functions, control flow, variables carried across joins, short-circuit `and`/`or`, casts | done |
|
||||
| 2 | structs, enums, `match`, outcome matches, `or trap` | todo |
|
||||
| 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 |
|
||||
| 5 | `own`, regions, resources, unsafe | todo |
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
-------------------
|
||||
- `//` starts a comment that runs to the end of the line.
|
||||
- Whitespace and line breaks separate tokens and are otherwise insignificant.
|
||||
- Keywords: module type struct enum fn effects trusted from let var zero
|
||||
- Keywords: module struct enum fn effects trusted from let var zero
|
||||
if else while for in loop break continue return trap match select
|
||||
scope shield lock as cancelled ref mut move unchecked or and not
|
||||
true false recv send.
|
||||
@@ -16,10 +16,10 @@ module = "module" path { item } ;
|
||||
item = type_decl | fn_decl ;
|
||||
path = ident { "." ident } ;
|
||||
|
||||
type_decl = "type" ident "=" ( struct_body | enum_body ) ;
|
||||
struct_body = "struct" "{" [ field { "," field } [ "," ] ] "}" ;
|
||||
type_decl = struct_decl | enum_decl ;
|
||||
struct_decl = "struct" ident "{" [ field { "," field } [ "," ] ] "}" ;
|
||||
field = ident ":" type ;
|
||||
enum_body = "enum" "{" [ variant { "," variant } [ "," ] ] "}" ;
|
||||
enum_decl = "enum" ident "{" variant { "," variant } [ "," ] "}" ;
|
||||
variant = ident [ "(" type { "," type } ")" ] ;
|
||||
|
||||
fn_decl = "fn" ident "(" [ param { "," param } ] ")" "->" type [ "from" ident ]
|
||||
@@ -59,8 +59,9 @@ block_stmt = if_expr | match_expr | select_stmt | block
|
||||
if_expr = "if" expr block [ "else" ( if_expr | block ) ] ;
|
||||
match_expr = "match" expr "{" { arm } "}" ;
|
||||
arm = pattern "=>" ( block | expr "," ) ;
|
||||
pattern = "_" | int_lit
|
||||
| ident [ "(" ident { "," ident } ")" ] ; (* variant or outcome: ok(n), closed, Shape.Rect(w, h) is written Rect(w, h) *)
|
||||
pattern = "_" | int_lit (* integer matches only; `_` is required there *)
|
||||
| ident "::" ident [ "(" ident { "," ident } ")" ] (* enum variant: Shape::Rect(w, h); no `_` in enum matches *)
|
||||
| ident [ "(" ident { "," ident } ")" ] ; (* outcome of a fallible operation: ok(n), closed *)
|
||||
|
||||
select_stmt = "select" "{" { select_arm } "cancelled" [ "(" ident { "," ident } ")" ] "=>" ( block | expr "," ) "}" ;
|
||||
select_arm = "recv" "(" ident ")" "{" { arm } "}"
|
||||
@@ -83,6 +84,7 @@ postfix = primary { "." ident | "[" expr [ ".." expr ] "]" | call_args } ;
|
||||
call_args = [ "<" type ">" ] "(" [ expr { "," expr } ] ")" ;
|
||||
primary = int_lit | "true" | "false" | string
|
||||
| ident [ "{" field_init { "," field_init } [ "," ] "}" ] (* struct literal *)
|
||||
| ident "::" ident (* enum variant; applied by a call *)
|
||||
| "[" expr ";" int_lit "]"
|
||||
| "(" expr ")"
|
||||
| if_expr | match_expr | block ;
|
||||
|
||||
@@ -39,8 +39,16 @@ Rules:
|
||||
```aji
|
||||
module demo.echo
|
||||
|
||||
type Pair = struct { a: u8, b: u8 }
|
||||
type Shape = enum { Empty, Square(u64), Rect(u64, u64) }
|
||||
struct Pair {
|
||||
a: u8,
|
||||
b: u8,
|
||||
}
|
||||
|
||||
enum Shape {
|
||||
Empty,
|
||||
Square(u64),
|
||||
Rect(u64, u64),
|
||||
}
|
||||
|
||||
fn main(input: cap<io.read>, out: cap<io.write>) -> void
|
||||
effects [io.read, io.write]
|
||||
@@ -93,6 +101,13 @@ Statements end with `;`. Block constructs (`if`, `while`, `for`, `loop`, `match`
|
||||
|
||||
`if` and `match` are expressions when every branch yields a value of the same type through a tail expression (an expression without `;` at the end of a block) or diverges (`return`, `break`, `continue`, `trap`).
|
||||
|
||||
**Type inference is deliberately small.** It works within one function, it is monomorphic, and it does no overload resolution or search among several admissible types. An expression's type comes from:
|
||||
|
||||
- its own form: a literal suffix, a name, a call's declared return type, a cast, a struct or enum constructor;
|
||||
- otherwise its context: an annotation, the other operand, the parameter type of the function called, the function's return type.
|
||||
|
||||
An untyped `let x = <literal>` takes the type its first later use in the same function determines in that way. If nothing determines a type, the result is `E7007`: the frontend never picks a default.
|
||||
|
||||
Lowering: structured control flow becomes blocks and terminators. A variable assigned on several paths becomes a block parameter at the join.
|
||||
|
||||
## 5. Expressions
|
||||
@@ -122,7 +137,14 @@ Lowering: structured control flow becomes blocks and terminators. A variable ass
|
||||
- `true`, `false`;
|
||||
- `b"…"`: a byte string, of type `[u8; N]`, with escapes `\n`, `\t`, `\\`, `\"`, `\xHH`.
|
||||
|
||||
**Aggregates.** `Pair { a: 1, b: 2 }` (every field, in any order); `Shape.Square(4)`; `[e; N]` (`array.splat`). `v.f` on a struct value is `struct.get`.
|
||||
**Aggregates.**
|
||||
|
||||
- **Struct values.** `Pair { a: 1, b: 2 }` is the only way to build one: every field exactly once, in any order. A missing or repeated field is `E7006`, an unknown one `E7002`. The initializers are evaluated, and lowered, in **declaration order**, so the AIR does not depend on the order the fields are written in. There is no positional constructor.
|
||||
- **Enum values.** `Shape::Square(4)`, or `Shape::Empty` for a variant without payload, is the only form.
|
||||
- **Arrays.** `[e; N]` is `array.splat`.
|
||||
- **Field access.** `v.f` on a struct value is `struct.get`.
|
||||
|
||||
6A has no destructuring: no `let Point { x, y } = p`, no nested patterns, guards or or-patterns.
|
||||
|
||||
**Calls.** `f(args)` calls a function of the module. Built-in operations are called by their AIR names (§7, §8). Arguments are evaluated left to right.
|
||||
|
||||
@@ -176,7 +198,11 @@ match io.stdin_read(input, mut buf) {
|
||||
|
||||
- **Rebinding.** A value that comes back on an edge is rebound by the name in its arm: `closed(v)`, `pending(rx)`, `cancelled(t)`.
|
||||
- **`or trap`.** `op(args) or trap` is the expression of the `ok` value, or of `void`. Every other outcome traps (`T0001`). It is the only shorthand.
|
||||
- **Enums.** A `match` over a value of an enum type arms its variants, with `_` as default. A `match` over an integer arms literals, with `_` required.
|
||||
- **Enums.** A `match` over a value of an enum type has exactly one arm per variant, each written `Enum::Variant(names…)` (`Enum::Variant` without payload). It must be exhaustive (`E7004` lists the missing variants), and `_` is not allowed (`E7006`), so a new variant cannot slip through silently. Payload names are bound only inside their arm (they are the arm block's parameters in AIR). It lowers to `enum.switch`.
|
||||
- **Integers.** A `match` over an integer has literal arms and exactly one `_` arm, which is required (`E7004`). It lowers to `switch`.
|
||||
- **Booleans** use `if`.
|
||||
- **As expressions.** `match` and `if` are expressions when their arms yield values (§4). Every arm must have the type of the others, or diverge.
|
||||
- **Source map.** The switch maps to the `match`; each arm's code and its branch to the join map to that arm.
|
||||
|
||||
## 7. Tasks, cancellation, channels, select and mutex
|
||||
|
||||
@@ -290,6 +316,7 @@ A byte string or array used where a `slice<u8>` is expected is materialized in f
|
||||
| `aji check file.aji` | parse, lower, verify |
|
||||
| `aji run file.aji` | the same, then run (same flags and run record as for `.air`) |
|
||||
| `aji lower file.aji` | print the canonical AIR |
|
||||
| `aji lower --stats file.aji` | source and AIR size and the expansion ratio (bytes, non-empty lines): how much mechanical work the frontend took over |
|
||||
| `aji lower --annotate file.aji` | the same with `; line:col-line:col` source spans before each instruction (not canonical; for debugging) |
|
||||
|
||||
Lowering is deterministic: the same source and compiler give byte-identical AIR, and the lowered AIR is canonical (parse → print reproduces it). The conformance runner checks both for every accepted `.aji` test.
|
||||
@@ -61,6 +61,8 @@ pub const Expr = struct {
|
||||
boolean: bool,
|
||||
bytes: []const u8,
|
||||
name: []const u8,
|
||||
/// `Enum::Variant` (applied to payload arguments by a `call`).
|
||||
variant: struct { @"enum": []const u8, name: []const u8 },
|
||||
neg: *const Expr,
|
||||
not: *const Expr,
|
||||
deref: *const Expr,
|
||||
@@ -93,8 +95,9 @@ pub const Pattern = struct {
|
||||
kind: union(enum) {
|
||||
wildcard,
|
||||
int: []const u8,
|
||||
/// A variant or outcome name with bound names: `ok(n)`, `closed`, `Rect(w, h)`.
|
||||
ctor: struct { name: []const u8, binds: []const []const u8 },
|
||||
/// A variant with its enum (`Shape::Rect(w, h)`) or an outcome
|
||||
/// (`ok(n)`, `closed`; `qualifier == null`), with bound names.
|
||||
ctor: struct { qualifier: ?[]const u8, name: []const u8, binds: []const []const u8 },
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ pub const Tag = enum {
|
||||
comma,
|
||||
semicolon,
|
||||
colon,
|
||||
colon_colon,
|
||||
dot,
|
||||
dot_dot,
|
||||
arrow,
|
||||
@@ -125,9 +126,9 @@ pub fn tokenize(arena: std.mem.Allocator, src: []const u8) std.mem.Allocator.Err
|
||||
const two = if (i + 1 < src.len) src[i .. i + 2] else src[i .. i + 1];
|
||||
const Two = struct { []const u8, Tag };
|
||||
const pairs = [_]Two{
|
||||
.{ "..", .dot_dot }, .{ "->", .arrow }, .{ "=>", .fat_arrow }, .{ "==", .eq_eq },
|
||||
.{ "!=", .bang_eq }, .{ "<=", .le }, .{ ">=", .ge }, .{ "<<", .shl },
|
||||
.{ ">>", .shr }, .{ "+%", .plus_pct }, .{ "-%", .minus_pct }, .{ "*%", .star_pct },
|
||||
.{ "::", .colon_colon }, .{ "..", .dot_dot }, .{ "->", .arrow }, .{ "=>", .fat_arrow }, .{ "==", .eq_eq },
|
||||
.{ "!=", .bang_eq }, .{ "<=", .le }, .{ ">=", .ge }, .{ "<<", .shl }, .{ ">>", .shr },
|
||||
.{ "+%", .plus_pct }, .{ "-%", .minus_pct }, .{ "*%", .star_pct },
|
||||
};
|
||||
const pair: ?Tag = for (pairs) |p| {
|
||||
if (std.mem.eql(u8, two, p[0])) break p[1];
|
||||
|
||||
+332
-68
@@ -27,23 +27,17 @@ pub const Ty = union(enum) {
|
||||
bool,
|
||||
void,
|
||||
never,
|
||||
/// A declared struct or enum: index into the module's type declarations.
|
||||
named: u32,
|
||||
|
||||
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,
|
||||
else => true,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn text(t: Ty) []const u8 {
|
||||
return switch (t) {
|
||||
.int => |x| x,
|
||||
.bool => "bool",
|
||||
.void => "void",
|
||||
.never => "never",
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const int_types = [_][]const u8{ "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize" };
|
||||
@@ -142,6 +136,8 @@ const Lowerer = struct {
|
||||
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,
|
||||
@@ -165,6 +161,20 @@ const Lowerer = struct {
|
||||
return error.Unimplemented;
|
||||
}
|
||||
|
||||
fn tyText(l: *Lowerer, t: Ty) []const u8 {
|
||||
return switch (t) {
|
||||
.int => |x| x,
|
||||
.bool => "bool",
|
||||
.void => "void",
|
||||
.never => "never",
|
||||
.named => |i| l.typeNames[i],
|
||||
};
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -185,7 +195,12 @@ const Lowerer = struct {
|
||||
// ------------------------------------------------------------ module
|
||||
|
||||
fn run(l: *Lowerer) Error!void {
|
||||
for (l.m.types) |t| return l.notYet(t.span, "type declarations (layer 2)");
|
||||
const names = try l.arena.alloc([]const u8, l.m.types.len);
|
||||
for (l.m.types, names, 0..) |t, *n, i| {
|
||||
for (l.m.types[0..i]) |prev| if (std.mem.eql(u8, prev.name, t.name)) return l.fail("E7006", t.span, "type defined twice", &.{.{ .name = "name", .value = t.name }});
|
||||
n.* = try l.fmt("@{s}", .{t.name});
|
||||
}
|
||||
l.typeNames = names;
|
||||
for (l.m.functions) |f| {
|
||||
if (l.sigs.contains(f.name)) return l.fail("E7006", f.span, "function defined twice", &.{.{ .name = "name", .value = f.name }});
|
||||
const ps = try l.arena.alloc(Ty, f.params.len);
|
||||
@@ -201,9 +216,50 @@ const Lowerer = struct {
|
||||
// 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);
|
||||
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);
|
||||
}
|
||||
|
||||
/// `type @T = struct { … }` / `enum { … }` in canonical form.
|
||||
fn typeDeclLine(l: *Lowerer, t: ast.TypeDecl) Error!void {
|
||||
var w: std.ArrayList(u8) = .empty;
|
||||
try w.appendSlice(l.arena, try l.fmt("type @{s} = ", .{t.name}));
|
||||
switch (t.kind) {
|
||||
.@"struct" => |fields| {
|
||||
try w.appendSlice(l.arena, "struct {");
|
||||
for (fields, 0..) |f, i| {
|
||||
for (fields[0..i]) |prev| if (std.mem.eql(u8, prev.name, f.name)) return l.fail("E7006", f.span, "field declared twice", &.{.{ .name = "field", .value = f.name }});
|
||||
const ft = try l.memberType(f.ty);
|
||||
try w.appendSlice(l.arena, try l.fmt("{s}{s}: {s}", .{ if (i == 0) " " else ", ", f.name, l.tyText(ft) }));
|
||||
}
|
||||
try w.appendSlice(l.arena, if (fields.len == 0) "}" else " }");
|
||||
},
|
||||
.@"enum" => |vs| {
|
||||
if (vs.len == 0) return l.fail("E7006", t.span, "an enum needs at least one variant", &.{.{ .name = "type", .value = t.name }});
|
||||
try w.appendSlice(l.arena, "enum { ");
|
||||
for (vs, 0..) |v, i| {
|
||||
for (vs[0..i]) |prev| if (std.mem.eql(u8, prev.name, v.name)) return l.fail("E7006", v.span, "variant declared twice", &.{.{ .name = "variant", .value = v.name }});
|
||||
if (i != 0) try w.appendSlice(l.arena, ", ");
|
||||
try w.appendSlice(l.arena, v.name);
|
||||
if (v.payload.len != 0) {
|
||||
try w.append(l.arena, '(');
|
||||
for (v.payload, 0..) |pt, j| try w.appendSlice(l.arena, try l.fmt("{s}{s}", .{ if (j == 0) "" else ", ", l.tyText(try l.memberType(pt)) }));
|
||||
try w.append(l.arena, ')');
|
||||
}
|
||||
}
|
||||
try w.appendSlice(l.arena, " }");
|
||||
},
|
||||
}
|
||||
try l.line(w.items, t.span);
|
||||
}
|
||||
|
||||
fn memberType(l: *Lowerer, t: ast.Type) Error!Ty {
|
||||
const ty = try l.typeOf(t);
|
||||
if (ty == .void or ty == .never) return l.fail("E7005", t.span, "a field or payload needs a value type", &.{});
|
||||
return ty;
|
||||
}
|
||||
|
||||
fn typeOf(l: *Lowerer, t: ast.Type) Error!Ty {
|
||||
switch (t.kind) {
|
||||
.name => |n| {
|
||||
@@ -211,7 +267,10 @@ const Lowerer = struct {
|
||||
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;
|
||||
return l.notYet(t.span, "this type (later layers)");
|
||||
for (l.m.types, 0..) |d, i| if (std.mem.eql(u8, d.name, n)) return .{ .named = @intCast(i) };
|
||||
const later = [_][]const u8{ "region", "listener", "stream", "io_error", "alloc_error", "cap_error" };
|
||||
for (later) |x| if (std.mem.eql(u8, x, n)) return l.notYet(t.span, "this type (later layers)");
|
||||
return l.fail("E7002", t.span, "unknown type", &.{.{ .name = "name", .value = n }});
|
||||
},
|
||||
else => return l.notYet(t.span, "this type (later layers)"),
|
||||
}
|
||||
@@ -234,9 +293,9 @@ const Lowerer = struct {
|
||||
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 });
|
||||
try header.appendSlice(l.arena, try l.fmt("{s}%{s}: {s}", .{ if (i == 0) "" else ", ", v, t.text() }));
|
||||
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}", .{sig.ret.text()}));
|
||||
try header.appendSlice(l.arena, try l.fmt(") -> {s}", .{l.tyText(sig.ret)}));
|
||||
|
||||
_ = try l.newBlock("entry");
|
||||
l.cur = 0;
|
||||
@@ -264,7 +323,7 @@ const Lowerer = struct {
|
||||
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, p.ty.text() }));
|
||||
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, ":");
|
||||
@@ -432,7 +491,7 @@ const Lowerer = struct {
|
||||
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);
|
||||
} 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.ret.text() }});
|
||||
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.term("ret", s.span);
|
||||
}
|
||||
},
|
||||
@@ -464,7 +523,7 @@ const Lowerer = struct {
|
||||
|
||||
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 = want.text() }, .{ .name = "found", .value = found.text() } });
|
||||
return l.fail("E7005", span, "type mismatch", &.{ .{ .name = "expected", .value = l.tyText(want) }, .{ .name = "found", .value = l.tyText(found) } });
|
||||
}
|
||||
|
||||
/// `while cond { body }` (cond null: `loop { body }`). Carried state:
|
||||
@@ -497,8 +556,8 @@ const Lowerer = struct {
|
||||
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", .{i.ty.text()}), st.span);
|
||||
const next = try l.def(st.name, i.ty, try l.fmt("add.checked.{s} %{s}, %{s}", .{ i.ty.text(), i.value, one.name }), st.span);
|
||||
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);
|
||||
}
|
||||
@@ -516,7 +575,7 @@ const Lowerer = struct {
|
||||
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 = ty.text() }});
|
||||
if (ty != .int) return l.fail("E7005", lo.span, "a range needs an integer type", &.{.{ .name = "found", .value = l.tyText(ty) }});
|
||||
const a = try l.expr(lo, ty);
|
||||
try l.checkTy(lo.span, a.ty, ty);
|
||||
const b = try l.expr(hi, ty);
|
||||
@@ -559,8 +618,25 @@ const Lowerer = struct {
|
||||
.shl, .shr => l.peekType(x.l.*),
|
||||
else => l.peekType(x.l.*) orelse l.peekType(x.r.*),
|
||||
},
|
||||
.call => |x| if (x.callee.kind == .name) (if (l.sigs.get(x.callee.kind.name)) |sig| sig.ret else null) else null,
|
||||
.call => |x| switch (x.callee.kind) {
|
||||
.name => |n| if (l.sigs.get(n)) |sig| sig.ret else null,
|
||||
.variant => |v| l.enumType(v.@"enum"),
|
||||
else => null,
|
||||
},
|
||||
.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;
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -638,19 +714,28 @@ const Lowerer = struct {
|
||||
}
|
||||
|
||||
fn typeOfNoFail(l: *Lowerer, t: ast.Type) ?Ty {
|
||||
_ = l;
|
||||
return switch (t.kind) {
|
||||
.name => |n| if (isIntName(n)) Ty{ .int = n } else if (std.mem.eql(u8, n, "bool")) .bool else null,
|
||||
.name => |n| if (isIntName(n)) Ty{ .int = n } else if (std.mem.eql(u8, n, "bool")) .bool else l.enumOrStruct(n),
|
||||
else => null,
|
||||
};
|
||||
}
|
||||
|
||||
fn enumOrStruct(l: *Lowerer, n: []const u8) ?Ty {
|
||||
for (l.m.types, 0..) |d, i| if (std.mem.eql(u8, d.name, n)) return .{ .named = @intCast(i) };
|
||||
return null;
|
||||
}
|
||||
|
||||
fn enumType(l: *Lowerer, n: []const u8) ?Ty {
|
||||
const t = l.enumOrStruct(n) orelse return null;
|
||||
return if (l.m.types[t.named].kind == .@"enum") t else null;
|
||||
}
|
||||
|
||||
fn expr(l: *Lowerer, e: ast.Expr, want: ?Ty) Error!Value {
|
||||
switch (e.kind) {
|
||||
.int => |x| {
|
||||
const ty: Ty = if (parse_mod.intSuffix(x.text)) |s| .{ .int = s } else want orelse
|
||||
return l.fail("E7007", e.span, "the type of this integer literal cannot be determined; add a suffix such as `0u64` or a type annotation", &.{});
|
||||
if (ty != .int) return l.fail("E7005", e.span, "an integer literal where another type is expected", &.{.{ .name = "expected", .value = ty.text() }});
|
||||
if (ty != .int) return l.fail("E7005", e.span, "an integer literal where another type is expected", &.{.{ .name = "expected", .value = l.tyText(ty) }});
|
||||
const v = parse_mod.parseIntText(x.text) orelse return l.fail("E7001", e.span, "malformed integer literal", &.{});
|
||||
const n = ty.int;
|
||||
const bits = intBits(n);
|
||||
@@ -704,8 +789,12 @@ const Lowerer = struct {
|
||||
const v = try l.blockBodyWant(b.*, want);
|
||||
return v orelse .{ .name = "", .ty = if (l.cur == null) .never else .void };
|
||||
},
|
||||
.or_trap, .match_expr => return l.notYet(e.span, "`match` and `or trap` (layer 2)"),
|
||||
.bytes, .struct_lit, .array_rep, .field, .index => return l.notYet(e.span, "aggregates, arrays and byte strings (layers 2–3)"),
|
||||
.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),
|
||||
.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)"),
|
||||
}
|
||||
}
|
||||
@@ -748,7 +837,7 @@ const Lowerer = struct {
|
||||
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 = ty.text();
|
||||
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}),
|
||||
@@ -775,6 +864,7 @@ 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 (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")) {
|
||||
@@ -804,6 +894,208 @@ const Lowerer = struct {
|
||||
return l.def(name, sig.ret, text, e.span);
|
||||
}
|
||||
|
||||
/// `Name { f: e, … }`: every field exactly once; initializers are
|
||||
/// evaluated in declaration order, so the AIR does not depend on the
|
||||
/// order the fields are written in (spec 15 §5).
|
||||
fn structLit(l: *Lowerer, e: ast.Expr, name: []const u8, inits: []const ast.FieldInit) Error!Value {
|
||||
const t = l.enumOrStruct(name) orelse return l.fail("E7002", e.span, "unknown type", &.{.{ .name = "name", .value = name }});
|
||||
const d = l.m.types[t.named];
|
||||
if (d.kind != .@"struct") return l.fail("E7005", e.span, "`Name { … }` constructs a struct; this is an enum (use `Enum::Variant`)", &.{.{ .name = "type", .value = name }});
|
||||
const fields = d.kind.@"struct";
|
||||
for (inits, 0..) |fi, i| {
|
||||
for (inits[0..i]) |prev| if (std.mem.eql(u8, prev.name, fi.name)) return l.fail("E7006", fi.span, "field given twice", &.{.{ .name = "field", .value = fi.name }});
|
||||
const known = for (fields) |f| {
|
||||
if (std.mem.eql(u8, f.name, fi.name)) break true;
|
||||
} else false;
|
||||
if (!known) return l.fail("E7002", fi.span, "no such field", &.{ .{ .name = "type", .value = name }, .{ .name = "field", .value = fi.name } });
|
||||
}
|
||||
var args: std.ArrayList(u8) = .empty;
|
||||
for (fields, 0..) |f, i| {
|
||||
const fi = for (inits) |x| {
|
||||
if (std.mem.eql(u8, x.name, f.name)) break x;
|
||||
} else return l.fail("E7006", e.span, "missing field", &.{ .{ .name = "type", .value = name }, .{ .name = "field", .value = f.name } });
|
||||
const ft = try l.typeOf(f.ty);
|
||||
const v = try l.expr(fi.e, ft);
|
||||
try l.checkTy(fi.e.span, v.ty, ft);
|
||||
try args.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", v.name }));
|
||||
}
|
||||
return l.def("s", t, try l.fmt("struct.make @{s}({s})", .{ name, args.items }), e.span);
|
||||
}
|
||||
|
||||
fn variantValue(l: *Lowerer, e: ast.Expr, enum_name: []const u8, variant: []const u8, args: []const ast.Expr) Error!Value {
|
||||
const t = l.enumType(enum_name) orelse return l.fail("E7002", e.span, "unknown enum", &.{.{ .name = "name", .value = enum_name }});
|
||||
const vs = l.m.types[t.named].kind.@"enum";
|
||||
const v = for (vs) |x| {
|
||||
if (std.mem.eql(u8, x.name, variant)) break x;
|
||||
} else return l.fail("E7002", e.span, "no such variant", &.{ .{ .name = "enum", .value = enum_name }, .{ .name = "variant", .value = variant } });
|
||||
if (args.len != v.payload.len) return l.fail("E7005", e.span, "wrong number of payload values", &.{ .{ .name = "variant", .value = variant }, .{ .name = "expected", .value = try l.fmt("{d}", .{v.payload.len}) }, .{ .name = "found", .value = try l.fmt("{d}", .{args.len}) } });
|
||||
var names: std.ArrayList(u8) = .empty;
|
||||
for (args, v.payload, 0..) |a, pt, i| {
|
||||
const ty = try l.typeOf(pt);
|
||||
const av = try l.expr(a, ty);
|
||||
try l.checkTy(a.span, av.ty, ty);
|
||||
try names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", av.name }));
|
||||
}
|
||||
return l.def("e", t, try l.fmt("enum.make @{s}.{s}({s})", .{ enum_name, variant, names.items }), e.span);
|
||||
}
|
||||
|
||||
/// `v.f` on a struct value: `struct.get` (borrows come in layer 4).
|
||||
fn fieldValue(l: *Lowerer, e: ast.Expr, base: ast.Expr, name: []const u8) Error!Value {
|
||||
const bt = l.peekType(base) orelse return l.fail("E7007", base.span, "the type of this expression cannot be determined", &.{});
|
||||
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 } });
|
||||
const v = try l.expr(base, bt);
|
||||
return l.def(name, try l.typeOf(f.ty), try l.fmt("struct.get @{s}.{s}, %{s}", .{ d.name, name, v.name }), e.span);
|
||||
}
|
||||
|
||||
/// One branch of a conditional or `match`: where it ended (null if it
|
||||
/// diverged), its value and the variables' values there.
|
||||
const ArmEnd = struct { block: ?usize, value: ?Value, values: []const []const u8, span: Span };
|
||||
|
||||
/// Joins branches that reach the end: one block with a parameter for
|
||||
/// the result (if any) and one per carried variable (spec 15 §4).
|
||||
fn mergeArms(l: *Lowerer, _: Span, what: []const u8, arms: []const ArmEnd, vars: []const usize, before: []const []const u8, join_kind: []const u8) Error!Value {
|
||||
l.restore(before);
|
||||
var result_ty: ?Ty = null;
|
||||
for (arms) |a| if (a.block != null) {
|
||||
const vt: Ty = if (a.value) |v| v.ty else .void;
|
||||
if (vt == .never) continue;
|
||||
if (result_ty) |prev| {
|
||||
if (!prev.eql(vt)) return l.fail("E7005", a.span, try l.fmt("the branches of this `{s}` have different types", .{what}), &.{ .{ .name = "expected", .value = l.tyText(prev) }, .{ .name = "found", .value = l.tyText(vt) } });
|
||||
} else result_ty = vt;
|
||||
};
|
||||
if (result_ty == null) {
|
||||
l.cur = null;
|
||||
return .{ .name = "", .ty = .never };
|
||||
}
|
||||
const join = try l.newBlock(join_kind);
|
||||
const has_value = result_ty.? != .void;
|
||||
var result_name: []const u8 = "";
|
||||
if (has_value) {
|
||||
result_name = try l.freshName(what);
|
||||
try l.blocks.items[join].params.append(l.arena, .{ .name = result_name, .ty = result_ty.? });
|
||||
}
|
||||
try l.joinParams(join, vars);
|
||||
for (arms) |a| if (a.block) |b| {
|
||||
l.cur = b;
|
||||
l.restore(a.values);
|
||||
const vt: Ty = if (a.value) |v| v.ty else .void;
|
||||
if (vt == .never) continue;
|
||||
try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[join].name, try l.argsOf(vars, if (has_value) a.value.?.name else null) }), a.span);
|
||||
};
|
||||
l.restore(before);
|
||||
l.cur = join;
|
||||
l.rebindToParams(join, vars, if (has_value) 1 else 0);
|
||||
return .{ .name = result_name, .ty = result_ty.? };
|
||||
}
|
||||
|
||||
/// `match` over an enum (`enum.switch`; exhaustive, no `_`) or an
|
||||
/// integer (`switch`; `_` required). Payload names live in their arm.
|
||||
fn matchExpr(l: *Lowerer, m: ast.Match, want: ?Ty) Error!Value {
|
||||
const st = l.peekType(m.scrutinee) orelse return l.fail("E7007", m.scrutinee.span, "the type of this value cannot be determined", &.{});
|
||||
const sv = try l.expr(m.scrutinee, st);
|
||||
const depth = l.bindings.items.len;
|
||||
const vars = try l.carried(depth);
|
||||
const before = try l.snapshot();
|
||||
var ends: std.ArrayList(ArmEnd) = .empty;
|
||||
|
||||
if (l.decl(st)) |d| {
|
||||
if (d.kind != .@"enum") return l.fail("E7005", m.scrutinee.span, "`match` over a struct; use field access", &.{.{ .name = "type", .value = d.name }});
|
||||
const vs = d.kind.@"enum";
|
||||
const blocks = try l.arena.alloc(usize, m.arms.len);
|
||||
var head: std.ArrayList(u8) = .empty;
|
||||
try head.appendSlice(l.arena, try l.fmt("enum.switch @{s} %{s}", .{ d.name, sv.name }));
|
||||
for (m.arms, blocks, 0..) |arm, *blk, i| {
|
||||
if (arm.pattern.kind != .ctor or arm.pattern.kind.ctor.qualifier == null)
|
||||
return l.fail("E7006", arm.pattern.span, "an arm of a `match` over an enum names one variant as `Enum::Variant`; `_` is not allowed", &.{.{ .name = "enum", .value = d.name }});
|
||||
const c = arm.pattern.kind.ctor;
|
||||
if (!std.mem.eql(u8, c.qualifier.?, d.name)) return l.fail("E7005", arm.pattern.span, "variant of a different enum", &.{ .{ .name = "expected", .value = d.name }, .{ .name = "found", .value = c.qualifier.? } });
|
||||
const vi = for (vs, 0..) |v, k| {
|
||||
if (std.mem.eql(u8, v.name, c.name)) break k;
|
||||
} else return l.fail("E7002", arm.pattern.span, "no such variant", &.{ .{ .name = "enum", .value = d.name }, .{ .name = "variant", .value = c.name } });
|
||||
for (m.arms[0..i]) |prev| if (std.mem.eql(u8, prev.pattern.kind.ctor.name, c.name)) return l.fail("E7006", arm.pattern.span, "variant matched twice", &.{.{ .name = "variant", .value = c.name }});
|
||||
if (c.binds.len != vs[vi].payload.len) return l.fail("E7005", arm.pattern.span, "the pattern binds a different number of payload values", &.{ .{ .name = "variant", .value = c.name }, .{ .name = "expected", .value = try l.fmt("{d}", .{vs[vi].payload.len}) } });
|
||||
blk.* = try l.newBlock(try l.fmt("case_{s}", .{c.name}));
|
||||
for (vs[vi].payload, c.binds) |pt, bn| {
|
||||
const pname = try l.freshName(if (std.mem.eql(u8, bn, "_")) "unused" else bn);
|
||||
try l.blocks.items[blk.*].params.append(l.arena, .{ .name = pname, .ty = try l.typeOf(pt) });
|
||||
}
|
||||
try head.appendSlice(l.arena, try l.fmt(", {s} -> @{s}", .{ c.name, l.blocks.items[blk.*].name }));
|
||||
}
|
||||
var missing: std.ArrayList(u8) = .empty;
|
||||
for (vs) |v| {
|
||||
const covered = for (m.arms) |arm| {
|
||||
if (std.mem.eql(u8, arm.pattern.kind.ctor.name, v.name)) break true;
|
||||
} else false;
|
||||
if (!covered) try missing.appendSlice(l.arena, try l.fmt("{s}{s}::{s}", .{ if (missing.items.len == 0) "" else ", ", d.name, v.name }));
|
||||
}
|
||||
if (missing.items.len != 0) return l.fail("E7004", m.span, "`match` does not cover every variant", &.{.{ .name = "missing", .value = missing.items }});
|
||||
try l.term(head.items, m.span);
|
||||
for (m.arms, blocks) |arm, blk| {
|
||||
l.restore(before);
|
||||
l.cur = blk;
|
||||
const c = arm.pattern.kind.ctor;
|
||||
for (c.binds, l.blocks.items[blk].params.items) |bn, prm| {
|
||||
if (!std.mem.eql(u8, bn, "_")) try l.bindings.append(l.arena, .{ .name = bn, .mutable = false, .value = prm.name, .ty = prm.ty });
|
||||
}
|
||||
const v = try l.armBody(arm.body, want);
|
||||
// Payload names end with their arm.
|
||||
l.bindings.shrinkRetainingCapacity(before.len);
|
||||
try ends.append(l.arena, .{ .block = l.cur, .value = v, .values = try l.snapshot(), .span = arm.body.span });
|
||||
}
|
||||
return l.mergeArms(m.span, "match", ends.items, vars, before, "endmatch");
|
||||
}
|
||||
|
||||
if (st != .int) return l.fail("E7005", m.scrutinee.span, "`match` needs an enum or integer value; use `if` for booleans", &.{.{ .name = "found", .value = l.tyText(st) }});
|
||||
var head: std.ArrayList(u8) = .empty;
|
||||
try head.appendSlice(l.arena, try l.fmt("switch.{s} %{s}, ", .{ st.int, sv.name }));
|
||||
const blocks = try l.arena.alloc(usize, m.arms.len);
|
||||
var default: ?usize = null;
|
||||
var seen: std.ArrayList(u128) = .empty;
|
||||
for (m.arms, blocks, 0..) |arm, *blk, i| {
|
||||
switch (arm.pattern.kind) {
|
||||
.wildcard => {
|
||||
if (default != null) return l.fail("E7006", arm.pattern.span, "`_` given twice", &.{});
|
||||
default = i;
|
||||
blk.* = try l.newBlock("case_default");
|
||||
},
|
||||
.int => |text| {
|
||||
const neg = text[0] == '-';
|
||||
const mag = parse_mod.parseIntText(if (neg) text[1..] else text) orelse return l.fail("E7001", arm.pattern.span, "malformed integer pattern", &.{});
|
||||
const bits: u128 = if (neg) (0 -% mag) else mag;
|
||||
for (seen.items) |prev| if (prev == bits) return l.fail("E7006", arm.pattern.span, "integer matched twice", &.{.{ .name = "value", .value = text }});
|
||||
try seen.append(l.arena, bits);
|
||||
blk.* = try l.newBlock("case");
|
||||
try head.appendSlice(l.arena, try l.fmt("{s} -> @{s}(), ", .{ text, l.blocks.items[blk.*].name }));
|
||||
},
|
||||
.ctor => return l.fail("E7005", arm.pattern.span, "an arm of a `match` over an integer is an integer literal or `_`", &.{}),
|
||||
}
|
||||
}
|
||||
const d = default orelse return l.fail("E7004", m.span, "a `match` over an integer needs a `_` arm", &.{});
|
||||
try head.appendSlice(l.arena, try l.fmt("default -> @{s}()", .{l.blocks.items[blocks[d]].name}));
|
||||
try l.term(head.items, m.span);
|
||||
for (m.arms, blocks) |arm, blk| {
|
||||
l.restore(before);
|
||||
l.cur = blk;
|
||||
const v = try l.armBody(arm.body, want);
|
||||
try ends.append(l.arena, .{ .block = l.cur, .value = v, .values = try l.snapshot(), .span = arm.body.span });
|
||||
}
|
||||
return l.mergeArms(m.span, "match", ends.items, vars, before, "endmatch");
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
fn ifExpr(l: *Lowerer, span: Span, x: ast.If, want: ?Ty) Error!Value {
|
||||
const cv = try l.expr(x.cond, .bool);
|
||||
try l.checkTy(x.cond.span, cv.ty, .bool);
|
||||
@@ -811,58 +1103,30 @@ const Lowerer = struct {
|
||||
const vars = try l.carried(depth);
|
||||
const then_b = try l.newBlock("then");
|
||||
const else_b = try l.newBlock("else");
|
||||
const join = try l.newBlock("endif");
|
||||
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();
|
||||
|
||||
// Each branch either reaches the join with its values or diverges.
|
||||
const Arm = struct { block: ?usize, value: ?Value, values: []const []const u8 };
|
||||
var arms: [2]Arm = undefined;
|
||||
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) {
|
||||
v = try l.blockBodyWant(x.then, want);
|
||||
} else if (x.@"else") |els| switch (els) {
|
||||
.block => |b| v = try l.blockBodyWant(b, want),
|
||||
.@"if" => |inner| v = try l.ifExpr(span, inner.*, want),
|
||||
};
|
||||
arms[k] = .{ .block = l.cur, .value = v, .values = try l.snapshot() };
|
||||
.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 };
|
||||
}
|
||||
l.restore(before);
|
||||
|
||||
const result_ty: ?Ty = blk: {
|
||||
var t: ?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 (t) |prev| {
|
||||
if (!prev.eql(vt)) return l.fail("E7005", span, "the branches of this `if` have different types", &.{ .{ .name = "then", .value = prev.text() }, .{ .name = "else", .value = vt.text() } });
|
||||
} else t = vt;
|
||||
};
|
||||
break :blk t;
|
||||
};
|
||||
if (result_ty == null) {
|
||||
l.cur = null;
|
||||
return .{ .name = "", .ty = .never };
|
||||
}
|
||||
const has_value = result_ty.? != .void;
|
||||
var result_name: []const u8 = "";
|
||||
if (has_value) {
|
||||
result_name = try l.freshName("if");
|
||||
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);
|
||||
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) }), span);
|
||||
};
|
||||
l.restore(before);
|
||||
l.cur = join;
|
||||
l.rebindToParams(join, vars, if (has_value) 1 else 0);
|
||||
return .{ .name = result_name, .ty = result_ty.? };
|
||||
return l.mergeArms(span, "if", &ends, vars, before, "endif");
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
+39
-31
@@ -101,11 +101,11 @@ const Parser = struct {
|
||||
var types: std.ArrayList(ast.TypeDecl) = .empty;
|
||||
var fns: std.ArrayList(ast.FnDecl) = .empty;
|
||||
while (p.peek().tag != .eof) {
|
||||
if (p.atWord("type")) {
|
||||
if (p.atWord("struct") or p.atWord("enum")) {
|
||||
try types.append(p.arena, try p.typeDecl());
|
||||
} else if (p.atWord("fn")) {
|
||||
try fns.append(p.arena, try p.fnDecl());
|
||||
} else return p.fail(p.peek(), "`type` or `fn`");
|
||||
} else return p.fail(p.peek(), "`struct`, `enum` or `fn`");
|
||||
}
|
||||
return .{ .name = name, .types = types.items, .functions = fns.items };
|
||||
}
|
||||
@@ -121,13 +121,14 @@ const Parser = struct {
|
||||
return out.items;
|
||||
}
|
||||
|
||||
/// `struct Name { field: T, … }` or `enum Name { A, B(T, …), … }`.
|
||||
fn typeDecl(p: *Parser) Error!ast.TypeDecl {
|
||||
const start = p.next().pos; // `type`
|
||||
const start = p.peek().pos;
|
||||
const is_struct = p.atWord("struct");
|
||||
_ = p.next();
|
||||
const name = try p.ident("type name");
|
||||
_ = try p.expect(.eq, "`=`");
|
||||
if (p.atWord("struct")) {
|
||||
_ = p.next();
|
||||
_ = try p.expect(.l_brace, "`{`");
|
||||
_ = try p.expect(.l_brace, "`{`");
|
||||
if (is_struct) {
|
||||
var fields: std.ArrayList(ast.Field) = .empty;
|
||||
while (p.peek().tag != .r_brace) {
|
||||
const fs = p.peek().pos;
|
||||
@@ -141,31 +142,26 @@ const Parser = struct {
|
||||
_ = try p.expect(.r_brace, "`}`");
|
||||
return .{ .name = name, .span = p.span(start), .kind = .{ .@"struct" = fields.items } };
|
||||
}
|
||||
if (p.atWord("enum")) {
|
||||
_ = p.next();
|
||||
_ = try p.expect(.l_brace, "`{`");
|
||||
var vs: std.ArrayList(ast.Variant) = .empty;
|
||||
while (p.peek().tag != .r_brace) {
|
||||
const vstart = p.peek().pos;
|
||||
const vname = try p.ident("variant name");
|
||||
var payload: std.ArrayList(ast.Type) = .empty;
|
||||
if (p.peek().tag == .l_paren) {
|
||||
_ = p.next();
|
||||
while (true) {
|
||||
try payload.append(p.arena, try p.typeExpr());
|
||||
if (p.peek().tag != .comma) break;
|
||||
_ = p.next();
|
||||
}
|
||||
_ = try p.expect(.r_paren, "`)`");
|
||||
}
|
||||
try vs.append(p.arena, .{ .name = vname, .payload = payload.items, .span = p.span(vstart) });
|
||||
if (p.peek().tag != .comma) break;
|
||||
var vs: std.ArrayList(ast.Variant) = .empty;
|
||||
while (p.peek().tag != .r_brace) {
|
||||
const vstart = p.peek().pos;
|
||||
const vname = try p.ident("variant name");
|
||||
var payload: std.ArrayList(ast.Type) = .empty;
|
||||
if (p.peek().tag == .l_paren) {
|
||||
_ = p.next();
|
||||
while (true) {
|
||||
try payload.append(p.arena, try p.typeExpr());
|
||||
if (p.peek().tag != .comma) break;
|
||||
_ = p.next();
|
||||
}
|
||||
_ = try p.expect(.r_paren, "`)`");
|
||||
}
|
||||
_ = try p.expect(.r_brace, "`}`");
|
||||
return .{ .name = name, .span = p.span(start), .kind = .{ .@"enum" = vs.items } };
|
||||
try vs.append(p.arena, .{ .name = vname, .payload = payload.items, .span = p.span(vstart) });
|
||||
if (p.peek().tag != .comma) break;
|
||||
_ = p.next();
|
||||
}
|
||||
return p.fail(p.peek(), "`struct` or `enum`");
|
||||
_ = try p.expect(.r_brace, "`}`");
|
||||
return .{ .name = name, .span = p.span(start), .kind = .{ .@"enum" = vs.items } };
|
||||
}
|
||||
|
||||
fn fnDecl(p: *Parser) Error!ast.FnDecl {
|
||||
@@ -459,8 +455,15 @@ const Parser = struct {
|
||||
if (t.tag == .minus) text = try std.mem.concat(p.arena, u8, &.{ "-", p.next().text });
|
||||
return .{ .span = p.span(start), .kind = .{ .int = text } };
|
||||
}
|
||||
if (t.tag != .ident) return p.fail(t, "a pattern (variant, outcome, integer or `_`)");
|
||||
if (t.tag != .ident) return p.fail(t, "a pattern (`Enum::Variant`, an outcome, an integer or `_`)");
|
||||
_ = p.next();
|
||||
var qualifier: ?[]const u8 = null;
|
||||
var name = t.text;
|
||||
if (p.peek().tag == .colon_colon) {
|
||||
_ = p.next();
|
||||
qualifier = t.text;
|
||||
name = try p.ident("a variant name");
|
||||
}
|
||||
var binds: std.ArrayList([]const u8) = .empty;
|
||||
if (p.peek().tag == .l_paren) {
|
||||
_ = p.next();
|
||||
@@ -475,7 +478,7 @@ const Parser = struct {
|
||||
}
|
||||
_ = try p.expect(.r_paren, "`)`");
|
||||
}
|
||||
return .{ .span = p.span(start), .kind = .{ .ctor = .{ .name = t.text, .binds = binds.items } } };
|
||||
return .{ .span = p.span(start), .kind = .{ .ctor = .{ .qualifier = qualifier, .name = name, .binds = binds.items } } };
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ expressions
|
||||
@@ -694,6 +697,11 @@ const Parser = struct {
|
||||
}
|
||||
if (isKeyword(t.text)) return p.fail(t, "an expression");
|
||||
_ = p.next();
|
||||
if (p.peek().tag == .colon_colon) {
|
||||
_ = p.next();
|
||||
const v = try p.ident("a variant name");
|
||||
return .{ .span = p.span(start), .kind = .{ .variant = .{ .@"enum" = t.text, .name = v } } };
|
||||
}
|
||||
if (p.peek().tag == .l_brace and !p.no_struct and std.ascii.isUpper(t.text[0])) {
|
||||
_ = p.next();
|
||||
var fields: std.ArrayList(ast.FieldInit) = .empty;
|
||||
|
||||
+29
-3
@@ -29,9 +29,10 @@ const usage =
|
||||
\\ --seed N; scheduler: --quantum N, --task-limit N,
|
||||
\\ --schedule-seed N; --profile hosted uses the real OS and
|
||||
\\ writes the record only to --result-file PATH
|
||||
\\ lower [--annotate] <file.aji>
|
||||
\\ lower [--annotate | --stats] <file.aji>
|
||||
\\ print the canonical AIR a source module lowers to;
|
||||
\\ --annotate adds source spans as comments (not canonical)
|
||||
\\ --annotate adds source spans as comments (not canonical);
|
||||
\\ --stats prints source/AIR size and expansion ratio
|
||||
\\ report <file.air> verify, then print the audit report (spec 10 §6.1)
|
||||
\\ codes list diagnostic codes as JSON Lines
|
||||
\\ features print supported AIR format, language version and features
|
||||
@@ -88,7 +89,8 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
|
||||
}
|
||||
if (std.mem.eql(u8, cmd, "lower")) {
|
||||
const annotate = args.len == 4 and std.mem.eql(u8, args[2], "--annotate");
|
||||
if (args.len != 3 and !annotate) return usageError("lower takes [--annotate] and one .aji file");
|
||||
const stats = args.len == 4 and std.mem.eql(u8, args[2], "--stats");
|
||||
if (args.len != 3 and !annotate and !stats) return usageError("lower takes [--annotate | --stats] and one .aji file");
|
||||
const path = args[args.len - 1];
|
||||
const source = std.Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(64 << 20)) catch |err| {
|
||||
std.debug.print("aji: cannot read {s}: {t}\n", .{ path, err });
|
||||
@@ -96,6 +98,30 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
|
||||
};
|
||||
switch (try aji.frontend.compile(arena, path, source)) {
|
||||
.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;
|
||||
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;
|
||||
}
|
||||
}.count;
|
||||
const sl = lines(source);
|
||||
const al = lines(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))),
|
||||
});
|
||||
try out.writeByte('\n');
|
||||
return .accepted;
|
||||
}
|
||||
try out.writeAll(if (annotate) o.annotated else o.air);
|
||||
return .accepted;
|
||||
},
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
// Enum construction with Enum::Variant, exhaustive match as an expression, payloads scoped to their arm.
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.messages
|
||||
|
||||
enum Message {
|
||||
Stop,
|
||||
Value(u64),
|
||||
Pair(u64, u64),
|
||||
}
|
||||
|
||||
fn weight(m: Message) -> u64
|
||||
effects []
|
||||
{
|
||||
let w: u64 = match m {
|
||||
Message::Stop => 0,
|
||||
Message::Value(x) => x,
|
||||
Message::Pair(a, b) => a * b,
|
||||
};
|
||||
return w;
|
||||
}
|
||||
|
||||
fn main() -> u64
|
||||
effects []
|
||||
{
|
||||
return weight(Message::Stop) + weight(Message::Value(12)) + weight(Message::Pair(5, 6));
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// An integer match needs `_`; arms may diverge; variables are carried across the arms.
|
||||
// expect: run
|
||||
// result: 111
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.digits
|
||||
|
||||
fn main() -> u64
|
||||
effects []
|
||||
{
|
||||
var total: u64 = 0;
|
||||
for d in 0..4u8 {
|
||||
match d {
|
||||
0 => { total = total + 1; }
|
||||
1 => { total = total + 10; }
|
||||
2 => { total = total + 100; }
|
||||
_ => { continue; }
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// expect: reject E7004
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.nodefault
|
||||
|
||||
fn main() -> u64
|
||||
effects []
|
||||
{
|
||||
let d: u8 = 1;
|
||||
return match d {
|
||||
0 => 10,
|
||||
1 => 20,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// expect: reject E7006
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.missing
|
||||
|
||||
struct Point {
|
||||
x: i64,
|
||||
y: i64,
|
||||
}
|
||||
|
||||
fn main() -> i64
|
||||
effects []
|
||||
{
|
||||
let p = Point { x: 1 };
|
||||
return p.x;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// Every variant must be covered; the diagnostic names the missing ones.
|
||||
// expect: reject E7004
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.partial
|
||||
|
||||
enum State {
|
||||
Ready,
|
||||
Busy(u64),
|
||||
Done,
|
||||
}
|
||||
|
||||
fn main() -> u64
|
||||
effects []
|
||||
{
|
||||
let s = State::Busy(3);
|
||||
return match s {
|
||||
State::Ready => 0,
|
||||
State::Busy(n) => n,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// expect: reject E7005
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.otherenum
|
||||
|
||||
enum A {
|
||||
One,
|
||||
}
|
||||
|
||||
enum B {
|
||||
One,
|
||||
}
|
||||
|
||||
fn main() -> u8
|
||||
effects []
|
||||
{
|
||||
let a = A::One;
|
||||
return match a {
|
||||
B::One => 1,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// expect: reject E7002
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.unknownfield
|
||||
|
||||
struct Point {
|
||||
x: i64,
|
||||
y: i64,
|
||||
}
|
||||
|
||||
fn main() -> i64
|
||||
effects []
|
||||
{
|
||||
let p = Point { x: 1, y: 2 };
|
||||
return p.z;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// The verifier, not the frontend, rejects a struct that contains itself by value (E1003).
|
||||
// expect: reject E1003
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.recursive
|
||||
|
||||
struct Node {
|
||||
value: u64,
|
||||
next: Node,
|
||||
}
|
||||
|
||||
fn main() -> u64
|
||||
effects []
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// `_` is not allowed in a match over an enum: a new variant must not slip through silently.
|
||||
// expect: reject E7006
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.wild
|
||||
|
||||
enum State {
|
||||
Ready,
|
||||
Done,
|
||||
}
|
||||
|
||||
fn main() -> u64
|
||||
effects []
|
||||
{
|
||||
let s = State::Done;
|
||||
return match s {
|
||||
State::Ready => 0,
|
||||
_ => 1,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// Fields are lowered in declaration order: this file and struct_order_b.aji write the
|
||||
// fields in different orders and share one golden AIR.
|
||||
// expect: run
|
||||
// result: 3
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.point
|
||||
|
||||
struct Point {
|
||||
x: i64,
|
||||
y: i64,
|
||||
}
|
||||
|
||||
fn main() -> i64
|
||||
effects []
|
||||
{
|
||||
let p = Point { x: 1, y: 2 };
|
||||
return p.x + p.y;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
module demo.point
|
||||
air 0
|
||||
lang 0.1
|
||||
features [effects]
|
||||
|
||||
type @Point = struct { x: i64, y: i64 }
|
||||
|
||||
fn @main() -> i64
|
||||
effects []
|
||||
entry:
|
||||
%c_1 = const.i64 1
|
||||
%c_2 = const.i64 2
|
||||
%s_3 = struct.make @Point(%c_1, %c_2)
|
||||
%x_4 = struct.get @Point.x, %s_3
|
||||
%y_5 = struct.get @Point.y, %s_3
|
||||
%t_6 = add.checked.i64 %x_4, %y_5
|
||||
ret %t_6
|
||||
@@ -0,0 +1,18 @@
|
||||
// The same program as struct_order_a.aji with the fields written in the other order.
|
||||
// expect: run
|
||||
// result: 3
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.point
|
||||
|
||||
struct Point {
|
||||
x: i64,
|
||||
y: i64,
|
||||
}
|
||||
|
||||
fn main() -> i64
|
||||
effects []
|
||||
{
|
||||
let p = Point { y: 2, x: 1 };
|
||||
return p.x + p.y;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
module demo.point
|
||||
air 0
|
||||
lang 0.1
|
||||
features [effects]
|
||||
|
||||
type @Point = struct { x: i64, y: i64 }
|
||||
|
||||
fn @main() -> i64
|
||||
effects []
|
||||
entry:
|
||||
%c_1 = const.i64 1
|
||||
%c_2 = const.i64 2
|
||||
%s_3 = struct.make @Point(%c_1, %c_2)
|
||||
%x_4 = struct.get @Point.x, %s_3
|
||||
%y_5 = struct.get @Point.y, %s_3
|
||||
%t_6 = add.checked.i64 %x_4, %y_5
|
||||
ret %t_6
|
||||
Reference in new issue
Block a user