diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index 49ce36a..e10fac4 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -24,16 +24,29 @@ Targets and the evaluation order are in `README.md`. Phase 6A is specified by RF | ID | Status | Task | Depends | Output | Done when | |---|---|---|---|---|---| | P6A-1 | done | Spec 15, grammar, `E7xxx`, `E3101` `suggested_effects`, `E0006` `canonical_header`, Quick Reference | — | spec 15, `reference/grammar.ebnf`, `docs/agent/quick-reference.md` | RFC 0013 accepted | -| P6A-2 | todo | Lexer and parser with spans | P6A-1 | `src/frontend/{lex,parse}.zig` | every spec 15 example parses; syntax errors are `E7001` | -| P6A-3 | todo | Names and source types: variables, functions, types, built-in operations, outcome arms | P6A-2 | `src/frontend/check.zig` | `E7002`–`E7007` accept/reject tests | -| P6A-4 | todo | Lowering: control flow, variables → SSA/block parameters, frame storage, lexical borrow ends, outcome matches, block forms (`scope`, `shield`, `lock`), `select`, byte literals, feature closure | P6A-3 | `src/frontend/lower.zig` | lowered AIR verifies; lowering is a pure function | -| P6A-5 | todo | Source spans on lowered AIR; verifier diagnostics and trap records carry `source_location` and `air_location` | P6A-4 | `src/frontend/spans.zig`, `src/diag.zig` | every diagnostic of a `.aji` file points at source | -| P6A-6 | todo | CLI: `aji check/run/lower file.aji` | P6A-4 | `src/main.zig` | same flags and run record as for `.air` | +| P6A-2 | done | Lexer and parser with spans (full 6A grammar; one precise `E7001`, no recovery) | P6A-1 | `src/frontend/{lex,parse}.zig` | every spec 15 example parses; syntax errors are `E7001` | +| P6A-3 | doing | Names and source types: variables, functions, types, built-in operations, outcome arms | P6A-2 | `src/frontend/check.zig` | `E7002`–`E7007` accept/reject tests | +| P6A-4 | doing | Lowering: control flow, variables → SSA/block parameters, frame storage, lexical borrow ends, outcome matches, block forms (`scope`, `shield`, `lock`), `select`, byte literals, feature closure | P6A-3 | `src/frontend/lower.zig` | lowered AIR verifies; lowering is a pure function | +| P6A-5 | done | Source spans on lowered AIR; verifier diagnostics and trap records carry `source_location` and `air_location` | P6A-4 | `src/frontend/spans.zig`, `src/diag.zig` | every diagnostic of a `.aji` file points at source | +| P6A-6 | done | CLI: `aji check/run/lower file.aji` | P6A-4 | `src/main.zig` | same flags and run record as for `.air` | | P6A-7 | todo | `.aji` twins for the Phase 0–3 conformance tests (same outcome or code) and the reference programs | P6A-5 | `tests/conformance/*/source/` | twins pass; the reference programs in `.aji` pass `--stress` | | P6A-8 | todo | Source bundle and harness profile `aji_source` (Quick Reference first, full material indexed) | P6A-6 | `docs/agent/`, `tools/eval/languages/aji_source.json` | bundle measured | | P6A-9 | todo | Dev regression on tasks M and C: `Aji/AIR` vs `Aji/source` (size, output tokens, tool calls, bundle use, diagnostics) | P6A-8 | results note | targets checked (≤ 1.5× Rust size, ≤ 2× output tokens, no SSA/CFG or `E0006` diagnostics) | | P6A-10 | todo | Phase 6A exit review | all | plan status | targets reported | +Lowering layers (P6A-3/4), each with accepted (golden AIR), rejected (`E7xxx`) and verifier-caught tests in `tests/conformance/source/`: + +| 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 | +| 3 | arrays, slices, byte strings | todo | +| 4 | lexical borrows, frame storage, `move`, places | todo | +| 5 | `own`, regions, resources, unsafe | todo | +| 6 | capabilities, intrinsics, I/O | todo | +| 7 | tasks, channels | todo | +| 8 | `lock`, `select`, cancellation, shields | todo | + ## Tasks (full Phase 6) | ID | Status | Task | Depends | Output | Done when | diff --git a/docs/spec/15-source-language.md b/docs/spec/15-source-language.md index 876a189..edac9df 100644 --- a/docs/spec/15-source-language.md +++ b/docs/spec/15-source-language.md @@ -269,9 +269,9 @@ A byte string or array used where a `slice` is expected is materialized in f | Problem | Code | |---|---| -| found by the verifier on the lowered AIR | the AIR code, reported with `source_location` (file, line, column of the construct the instruction came from) and `air_location` (function, block, instruction) | +| 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 | -| trap at run time | the trap record also carries `source_location` | +| trap at run time | the trap record also carries `source_location` (`file`, `line`, `col`) | | Code | Kind | Meaning | |---|---|---| @@ -290,3 +290,6 @@ A byte string or array used where a `slice` 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 --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. diff --git a/src/check.zig b/src/check.zig index ce9df9e..70258c5 100644 --- a/src/check.zig +++ b/src/check.zig @@ -5,6 +5,7 @@ const std = @import("std"); const air = @import("air.zig"); const diag = @import("diag.zig"); const verifier = @import("verifier.zig"); +const frontend = @import("frontend.zig"); pub const Status = enum { /// Module verified; no error diagnostics. @@ -22,8 +23,27 @@ pub const Report = struct { module: ?air.Module = null, /// Pipeline stage that is missing when `status == .unimplemented`. missing_stage: []const u8 = "", + /// For `.aji` input: the lowered AIR and its line map (spec 15 §10). + lowered: ?frontend.lower_mod.Output = null, }; +/// Checks a `.aji` module (frontend, then the AIR pipeline, with every +/// diagnostic at its source location) or a text AIR module. +pub fn checkFile(arena: std.mem.Allocator, file_name: []const u8, source: []const u8) !Report { + if (!std.mem.endsWith(u8, file_name, ".aji")) return checkAir(arena, file_name, source); + const lowered = switch (try frontend.compile(arena, file_name, source)) { + .ok => |o| o, + .err => |d| return .{ .status = .rejected, .diagnostics = try arena.dupe(diag.Diagnostic, &.{d}) }, + .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; + r.lowered = lowered; + return r; +} + /// Checks a text AIR module. All allocations go into `arena`. pub fn checkAir(arena: std.mem.Allocator, file_name: []const u8, source: []const u8) !Report { const parsed = try air.parse.parse(arena, file_name, source); diff --git a/src/frontend.zig b/src/frontend.zig new file mode 100644 index 0000000..3063a71 --- /dev/null +++ b/src/frontend.zig @@ -0,0 +1,71 @@ +//! `.aji` frontend (spec 15): source → canonical text AIR + line map. +//! Outside the trusted computing base: its output is checked by the +//! normative verifier like any other AIR. + +const std = @import("std"); +const diag = @import("diag.zig"); +pub const lex = @import("frontend/lex.zig"); +pub const ast = @import("frontend/ast.zig"); +pub const parse = @import("frontend/parse.zig"); +pub const lower_mod = @import("frontend/lower.zig"); + +pub const Span = ast.Span; + +pub const Compiled = union(enum) { + /// Canonical AIR, its line map and the annotated form. + ok: lower_mod.Output, + /// One source diagnostic (`E7xxx`): the first problem only. + err: diag.Diagnostic, + unimplemented: []const u8, +}; + +pub fn compile(arena: std.mem.Allocator, file: []const u8, source: []const u8) std.mem.Allocator.Error!Compiled { + const parsed = try parse.parse(arena, source); + const m = switch (parsed) { + .ok => |m| m, + .err => |f| return .{ .err = .{ + .code = diag.lookup("E7001").?, + .span = .{ .file = file, .line = f.pos.line, .col = f.pos.col }, + .message = try std.fmt.allocPrint(arena, "expected {s}", .{f.expected}), + .fields = try arena.dupe(diag.Field, &.{ + .{ .name = "expected", .value = .{ .str = f.expected } }, + .{ .name = "found", .value = .{ .str = f.found } }, + }), + } }, + }; + return switch (try lower_mod.lower(arena, m)) { + .ok => |o| .{ .ok = o }, + .err => |p| blk: { + const fields = try arena.alloc(diag.Field, p.fields.len); + for (p.fields, fields) |pf, *f| f.* = .{ .name = pf.name, .value = .{ .str = pf.value } }; + break :blk .{ .err = .{ + .code = diag.lookup(p.code).?, + .span = .{ .file = file, .line = p.span.start.line, .col = p.span.start.col }, + .message = p.message, + .fields = fields, + } }; + }, + .unimplemented => |u| .{ .unimplemented = try std.fmt.allocPrint(arena, "{s}:{d}:{d}: {s}", .{ file, u.span.start.line, u.span.start.col, u.construct }) }, + }; +} + +/// Moves a diagnostic on lowered AIR to its source location; the AIR +/// location stays as `air_line`/`air_col` metadata (spec 15 §10). +pub fn mapDiagnostic(arena: std.mem.Allocator, d: diag.Diagnostic, file: []const u8, lines: []const ?Span) std.mem.Allocator.Error!diag.Diagnostic { + var out = d; + const sp = d.span orelse return out; + const fields = try arena.alloc(diag.Field, d.fields.len + 2); + @memcpy(fields[0..d.fields.len], d.fields); + fields[d.fields.len] = .{ .name = "air_line", .value = .{ .int = sp.line } }; + fields[d.fields.len + 1] = .{ .name = "air_col", .value = .{ .int = sp.col } }; + out.fields = fields; + const src: ?Span = if (sp.line >= 1 and sp.line <= lines.len) lines[sp.line - 1] else null; + out.span = .{ .file = file, .line = if (src) |s| s.start.line else 1, .col = if (src) |s| s.start.col else 1 }; + return out; +} + +test { + _ = lex; + _ = parse; + _ = lower_mod; +} diff --git a/src/frontend/ast.zig b/src/frontend/ast.zig new file mode 100644 index 0000000..640fe99 --- /dev/null +++ b/src/frontend/ast.zig @@ -0,0 +1,172 @@ +//! Syntax tree of `.aji` source 0.1 (spec 15). Produced by `parse.zig`; +//! every node carries the span it came from, so lowered AIR maps back to +//! source. + +const lex = @import("lex.zig"); + +pub const Pos = lex.Pos; + +pub const Span = struct { start: Pos, end: Pos }; + +pub const Type = struct { + span: Span, + kind: union(enum) { + /// A built-in or declared type name (`u8`, `bool`, `region`, `Pair`). + name: []const u8, + /// `[T; N]`. + array: struct { elem: *const Type, len: u64 }, + /// `ref`, `own`, `sender`, … (`wrapper` names the constructor). + wrapped: struct { wrapper: []const u8, inner: *const Type }, + /// `cap` with a dotted kind. + cap: []const u8, + /// `file`. + file: []const u8, + }, +}; + +pub const BinOp = enum { + add, + sub, + mul, + div, + rem, + add_wrap, + sub_wrap, + mul_wrap, + bit_and, + bit_or, + bit_xor, + shl, + shr, + eq, + ne, + lt, + le, + gt, + ge, + /// Short-circuit. + @"and", + /// Short-circuit. + @"or", +}; + +pub const CastMode = enum { widen, checked, wrap }; + +pub const Expr = struct { + span: Span, + kind: Kind, + + pub const Kind = union(enum) { + int: struct { text: []const u8 }, + boolean: bool, + bytes: []const u8, + name: []const u8, + neg: *const Expr, + not: *const Expr, + deref: *const Expr, + borrow: struct { mutable: bool, unchecked: bool, place: *const Expr }, + move: []const u8, + binary: struct { op: BinOp, l: *const Expr, r: *const Expr }, + cast: struct { mode: CastMode, e: *const Expr, ty: Type }, + /// `callee(args)`; `type_arg` only for `channel.make`. + call: struct { callee: *const Expr, type_arg: ?Type, args: []const Expr }, + field: struct { e: *const Expr, name: []const u8 }, + /// `e[lo]` or `e[lo..hi]`. + index: struct { e: *const Expr, lo: *const Expr, hi: ?*const Expr }, + struct_lit: struct { name: []const u8, fields: []const FieldInit }, + array_rep: struct { e: *const Expr, len: u64 }, + or_trap: *const Expr, + if_expr: *const If, + match_expr: *const Match, + block: *const Block, + }; +}; + +pub const FieldInit = struct { name: []const u8, span: Span, e: Expr }; + +pub const If = struct { cond: Expr, then: Block, @"else": ?Else }; + +pub const Else = union(enum) { block: Block, @"if": *const If }; + +pub const Pattern = struct { + span: Span, + 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 }, + }, +}; + +pub const Arm = struct { pattern: Pattern, body: Expr }; + +pub const Match = struct { scrutinee: Expr, arms: []const Arm, span: Span }; + +pub const SelectArm = struct { + span: Span, + /// `recv` or `send`. + send: bool, + endpoint: []const u8, + value: ?Expr, + arms: []const Arm, +}; + +pub const Select = struct { + arms: []const SelectArm, + cancelled_binds: []const []const u8, + cancelled: Expr, + span: Span, +}; + +pub const Stmt = struct { + span: Span, + kind: union(enum) { + let: struct { names: []const []const u8, ty: ?Type, e: Expr }, + /// `init == null` is `= zero`. + @"var": struct { name: []const u8, ty: Type, init: ?Expr }, + assign: struct { place: Expr, e: Expr }, + @"break", + @"continue", + @"return": ?Expr, + trap, + expr: Expr, + @"while": struct { cond: Expr, body: Block }, + @"for": struct { name: []const u8, lo: Expr, hi: Expr, body: Block }, + loop: Block, + scope: struct { name: []const u8, body: Block }, + shield: Block, + lock: struct { place: Expr, name: []const u8, body: Block, cancelled: Block }, + select: Select, + }, +}; + +pub const Block = struct { stmts: []const Stmt, tail: ?*const Expr, span: Span }; + +pub const Field = struct { name: []const u8, ty: Type, span: Span }; + +pub const Variant = struct { name: []const u8, payload: []const Type, span: Span }; + +pub const TypeDecl = struct { + name: []const u8, + span: Span, + kind: union(enum) { @"struct": []const Field, @"enum": []const Variant }, +}; + +pub const Param = struct { name: []const u8, ty: Type, span: Span }; + +pub const FnDecl = struct { + name: []const u8, + span: Span, + params: []const Param, + ret: Type, + from: ?[]const u8, + effects: []const []const u8, + trusted: ?[]const u8, + body: Block, +}; + +pub const Module = struct { + name: []const u8, + types: []const TypeDecl, + functions: []const FnDecl, +}; diff --git a/src/frontend/lex.zig b/src/frontend/lex.zig new file mode 100644 index 0000000..cd2bd69 --- /dev/null +++ b/src/frontend/lex.zig @@ -0,0 +1,209 @@ +//! Lexer for `.aji` source 0.1 (spec 15, reference/grammar.ebnf). + +const std = @import("std"); + +pub const Pos = struct { + /// 1-based. + line: u32, + /// 1-based, in bytes. + col: u32, +}; + +pub const Tag = enum { + ident, + int, + /// `b"…"`; `text` is the raw token including quotes. + bytes, + l_paren, + r_paren, + l_brace, + r_brace, + l_bracket, + r_bracket, + comma, + semicolon, + colon, + dot, + dot_dot, + arrow, + fat_arrow, + eq, + eq_eq, + bang_eq, + lt, + le, + gt, + ge, + plus, + minus, + star, + slash, + percent, + plus_pct, + minus_pct, + star_pct, + amp, + pipe, + caret, + shl, + shr, + /// `as!` (checked cast); `as` alone is an identifier keyword. + as_bang, + /// `as%` (wrapping cast). + as_pct, + underscore, + eof, + invalid, +}; + +pub const Token = struct { + tag: Tag, + text: []const u8, + pos: Pos, + /// Position just after the token. + end: Pos, +}; + +fn isIdentStart(c: u8) bool { + return std.ascii.isAlphabetic(c) or c == '_'; +} + +fn isIdentChar(c: u8) bool { + return std.ascii.isAlphanumeric(c) or c == '_'; +} + +pub fn tokenize(arena: std.mem.Allocator, src: []const u8) std.mem.Allocator.Error![]const Token { + var out: std.ArrayList(Token) = .empty; + var i: usize = 0; + var line: u32 = 1; + var line_start: usize = 0; + while (true) { + // Skip whitespace and comments. + while (i < src.len) { + const c = src[i]; + if (c == '\n') { + i += 1; + line += 1; + line_start = i; + } else if (c == ' ' or c == '\t' or c == '\r') { + i += 1; + } else if (c == '/' and i + 1 < src.len and src[i + 1] == '/') { + while (i < src.len and src[i] != '\n') i += 1; + } else break; + } + const start = i; + const pos: Pos = .{ .line = line, .col = @intCast(start - line_start + 1) }; + if (i >= src.len) { + try out.append(arena, .{ .tag = .eof, .text = "", .pos = pos, .end = pos }); + return out.items; + } + const c = src[i]; + var tag: Tag = .invalid; + if (c == 'b' and i + 1 < src.len and src[i + 1] == '"') { + i += 2; + while (i < src.len and src[i] != '"' and src[i] != '\n') { + if (src[i] == '\\' and i + 1 < src.len) i += 1; + i += 1; + } + if (i < src.len and src[i] == '"') { + i += 1; + tag = .bytes; + } + } else if (isIdentStart(c)) { + while (i < src.len and isIdentChar(src[i])) i += 1; + const word = src[start..i]; + if (std.mem.eql(u8, word, "_")) { + tag = .underscore; + } else if (std.mem.eql(u8, word, "as") and i < src.len and (src[i] == '!' or src[i] == '%')) { + tag = if (src[i] == '!') .as_bang else .as_pct; + i += 1; + } else tag = .ident; + } else if (std.ascii.isDigit(c)) { + while (i < src.len and (isIdentChar(src[i]))) i += 1; + tag = .int; + } else { + 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 }, + }; + const pair: ?Tag = for (pairs) |p| { + if (std.mem.eql(u8, two, p[0])) break p[1]; + } else null; + if (pair) |pt| { + tag = pt; + i += 2; + } else { + tag = switch (c) { + '(' => .l_paren, + ')' => .r_paren, + '{' => .l_brace, + '}' => .r_brace, + '[' => .l_bracket, + ']' => .r_bracket, + ',' => .comma, + ';' => .semicolon, + ':' => .colon, + '.' => .dot, + '=' => .eq, + '<' => .lt, + '>' => .gt, + '+' => .plus, + '-' => .minus, + '*' => .star, + '/' => .slash, + '%' => .percent, + '&' => .amp, + '|' => .pipe, + '^' => .caret, + else => .invalid, + }; + i += 1; + } + } + const end: Pos = .{ .line = line, .col = @intCast(i - line_start + 1) }; + try out.append(arena, .{ .tag = tag, .text = src[start..i], .pos = pos, .end = end }); + } +} + +/// Decodes the contents of a `b"…"` token; null on an invalid escape. +pub fn decodeBytes(arena: std.mem.Allocator, raw: []const u8) std.mem.Allocator.Error!?[]const u8 { + const body = raw[2 .. raw.len - 1]; + var out: std.ArrayList(u8) = .empty; + var i: usize = 0; + while (i < body.len) : (i += 1) { + if (body[i] != '\\') { + try out.append(arena, body[i]); + continue; + } + i += 1; + if (i >= body.len) return null; + switch (body[i]) { + 'n' => try out.append(arena, '\n'), + 't' => try out.append(arena, '\t'), + '\\' => try out.append(arena, '\\'), + '"' => try out.append(arena, '"'), + 'x' => { + if (i + 3 > body.len) return null; + const v = std.fmt.parseInt(u8, body[i + 1 .. i + 3], 16) catch return null; + try out.append(arena, v); + i += 2; + }, + else => return null, + } + } + return out.items; +} + +test "tokens" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const ts = try tokenize(arena.allocator(), "let x = a +% 1u8; // c\nx as! u64 b\"a\\n\" .."); + const want = [_]Tag{ .ident, .ident, .eq, .ident, .plus_pct, .int, .semicolon, .ident, .as_bang, .ident, .bytes, .dot_dot, .eof }; + try std.testing.expectEqual(want.len, ts.len); + for (want, ts) |w, t| try std.testing.expectEqual(w, t.tag); + try std.testing.expectEqual(@as(u32, 2), ts[7].pos.line); + try std.testing.expectEqualStrings("a\n", (try decodeBytes(arena.allocator(), ts[10].text)).?); +} diff --git a/src/frontend/lower.zig b/src/frontend/lower.zig new file mode 100644 index 0000000..3fd2706 --- /dev/null +++ b/src/frontend/lower.zig @@ -0,0 +1,873 @@ +//! Lowering of `.aji` source 0.1 to canonical text AIR (spec 15). +//! +//! The frontend is a thin layer: it resolves names and source types only as +//! far as needed to choose AIR instructions, and writes canonical AIR text +//! together with a line map (AIR line → source span). Every semantic +//! judgement — ownership, borrows, resources, effects, concurrency — is left +//! to the AIR verifier, which reports at the mapped source location. +//! +//! The frontend never repairs a program: it does not add `move`, effects, +//! closes or error handling. It generates only representation mechanics +//! (SSA, blocks, block parameters, the `features` header). +//! +//! Layers implemented here (spec 15 is implemented layer by layer; a +//! construct of a later layer is reported as not yet implemented): +//! 1. scalars, expressions, functions, control flow. + +const std = @import("std"); +const ast = @import("ast.zig"); +const parse_mod = @import("parse.zig"); + +const Allocator = std.mem.Allocator; +const Span = ast.Span; + +/// A source-level type: the subset of AIR types the implemented layers use. +pub const Ty = union(enum) { + int: []const u8, + bool, + void, + never, + + 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), + 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" }; + +fn isIntName(n: []const u8) bool { + for (int_types) |t| if (std.mem.eql(u8, t, n)) return true; + return false; +} + +fn isSigned(n: []const u8) bool { + return n[0] == 'i'; +} + +fn intBits(n: []const u8) u16 { + if (std.mem.endsWith(u8, n, "size")) return 64; + return std.fmt.parseInt(u16, n[1..], 10) catch 64; +} + +pub const Problem = struct { + code: []const u8, + span: Span, + message: []const u8, + fields: []const Field = &.{}, + + pub const Field = struct { name: []const u8, value: []const u8 }; +}; + +pub const Output = struct { + air: []const u8, + /// `lines[i]` is the source span of AIR line `i + 1`, if any. + lines: []const ?Span, + /// The same AIR with `; line:col-line:col` comments before each + /// instruction (not canonical; `aji lower --annotate`). + annotated: []const u8, +}; + +pub const Result = union(enum) { + ok: Output, + /// A source problem (`E7xxx`). + err: Problem, + /// A construct of a layer that is not implemented yet. + unimplemented: struct { span: Span, construct: []const u8 }, +}; + +const Error = error{ Lower, Unimplemented, OutOfMemory }; + +pub fn lower(arena: Allocator, m: ast.Module) Allocator.Error!Result { + var l: Lowerer = .{ .arena = arena, .m = m }; + l.run() catch |e| switch (e) { + error.Lower => return .{ .err = l.problem.? }, + error.Unimplemented => return .{ .unimplemented = l.unimpl.? }, + error.OutOfMemory => return error.OutOfMemory, + }; + return .{ .ok = .{ .air = l.out.items, .lines = l.lines.items, .annotated = l.annotated.items } }; +} + +const Inst = struct { text: []const u8, span: ?Span }; + +const Block = struct { + name: []const u8, + params: std.ArrayList(Param) = .empty, + insts: std.ArrayList(Inst) = .empty, + terminated: bool = false, +}; + +const Param = struct { name: []const u8, ty: Ty }; + +const Binding = struct { + name: []const u8, + mutable: bool, + value: []const u8, + ty: Ty, +}; + +const Loop = struct { + /// Target of `continue`. + @"continue": usize, + exit: usize, + /// Number of bindings visible when the loop started; the variables among + /// them are the loop's carried state. + depth: usize, +}; + +const Value = struct { name: []const u8, ty: Ty }; + +const Rest = struct { stmts: []const ast.Stmt, tail: ?*const ast.Expr }; + +const FnSig = struct { params: []const Ty, ret: Ty }; + +const Lowerer = struct { + arena: Allocator, + m: ast.Module, + out: std.ArrayList(u8) = .empty, + annotated: std.ArrayList(u8) = .empty, + lines: std.ArrayList(?Span) = .empty, + problem: ?Problem = null, + unimpl: ?@FieldType(Result, "unimplemented") = null, + sigs: std.StringHashMapUnmanaged(FnSig) = .empty, + + // Per function. + blocks: std.ArrayList(Block) = .empty, + cur: ?usize = null, + bindings: std.ArrayList(Binding) = .empty, + loops: std.ArrayList(Loop) = .empty, + counter: u32 = 0, + ret: Ty = .void, + /// Statements still to be lowered in each enclosing block (innermost + /// last), for inferring the type of an untyped `let` from its uses. + rest: std.ArrayList(Rest) = .empty, + + fn fail(l: *Lowerer, code: []const u8, span: Span, message: []const u8, fields: []const Problem.Field) Error { + // `fields` usually points at a temporary array: keep a copy. + l.problem = .{ .code = code, .span = span, .message = message, .fields = try l.arena.dupe(Problem.Field, fields) }; + return error.Lower; + } + + fn notYet(l: *Lowerer, span: Span, construct: []const u8) Error { + l.unimpl = .{ .span = span, .construct = construct }; + return error.Unimplemented; + } + + fn fmt(l: *Lowerer, comptime f: []const u8, args: anytype) Error![]const u8 { + return std.fmt.allocPrint(l.arena, f, args); + } + + // ------------------------------------------------------------ output + + fn line(l: *Lowerer, text: []const u8, span: ?Span) Error!void { + try l.out.appendSlice(l.arena, text); + try l.out.append(l.arena, '\n'); + try l.lines.append(l.arena, span); + if (span) |s| if (std.mem.startsWith(u8, text, " ")) { + try l.annotated.appendSlice(l.arena, try l.fmt(" ; {d}:{d}-{d}:{d}\n", .{ s.start.line, s.start.col, s.end.line, s.end.col })); + }; + try l.annotated.appendSlice(l.arena, text); + try l.annotated.append(l.arena, '\n'); + } + + // ------------------------------------------------------------ module + + fn run(l: *Lowerer) Error!void { + for (l.m.types) |t| return l.notYet(t.span, "type declarations (layer 2)"); + for (l.m.functions) |f| { + if (l.sigs.contains(f.name)) return l.fail("E7006", f.span, "function defined twice", &.{.{ .name = "name", .value = f.name }}); + const ps = try l.arena.alloc(Ty, f.params.len); + for (f.params, ps) |p, *t| t.* = try l.typeOf(p.ty); + try l.sigs.put(l.arena, f.name, .{ .params = ps, .ret = try l.typeOf(f.ret) }); + } + if (!l.sigs.contains("main")) return l.fail("E7002", .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 1 } }, "the module has no `main` function", &.{.{ .name = "name", .value = "main" }}); + + const whole: Span = if (l.m.functions.len != 0) l.m.functions[0].span else .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 1 } }; + 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); + for (l.m.functions) |f| try l.function(f); + } + + fn typeOf(l: *Lowerer, t: ast.Type) Error!Ty { + switch (t.kind) { + .name => |n| { + if (isIntName(n)) return .{ .int = n }; + if (std.mem.eql(u8, n, "bool")) return .bool; + if (std.mem.eql(u8, n, "void")) return .void; + if (std.mem.eql(u8, n, "never")) return .never; + return l.notYet(t.span, "this type (later layers)"); + }, + else => return l.notYet(t.span, "this type (later layers)"), + } + } + + // ------------------------------------------------------------ functions + + fn function(l: *Lowerer, f: ast.FnDecl) Error!void { + l.blocks = .empty; + l.bindings = .empty; + l.loops = .empty; + l.counter = 0; + const sig = l.sigs.get(f.name).?; + l.ret = sig.ret; + if (f.from != null) return l.notYet(f.span, "borrow returns (layer 4)"); + if (f.trusted != null) return l.notYet(f.span, "trusted functions (layer 5)"); + + var header: std.ArrayList(u8) = .empty; + try header.appendSlice(l.arena, try l.fmt("fn @{s}(", .{f.name})); + for (f.params, sig.params, 0..) |p, t, i| { + const v = try l.freshName(p.name); + 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}", .{sig.ret.text()})); + + _ = try l.newBlock("entry"); + l.cur = 0; + const tail = try l.blockBodyWant(f.body, sig.ret); + if (l.cur != null) { + if (tail != null and tail.?.ty == .void and sig.ret != .void) { + return l.fail("E7006", f.body.tail.?.span, "the function can end without returning a value", &.{.{ .name = "function", .value = f.name }}); + } + if (tail) |v| { + try l.checkTy(f.body.tail.?.span, v.ty, sig.ret); + try l.term(try l.fmt("ret %{s}", .{v.name}), f.body.tail.?.span); + } else if (sig.ret == .void) { + try l.term("ret", f.body.span); + } else return l.fail("E7006", f.body.span, "the function can end without returning a value", &.{.{ .name = "function", .value = f.name }}); + } + + 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| { + if (b.insts.items.len == 0) continue; // never reached + var head: std.ArrayList(u8) = .empty; + try head.appendSlice(l.arena, b.name); + if (b.params.items.len != 0) { + try head.append(l.arena, '('); + for (b.params.items, 0..) |p, i| try head.appendSlice(l.arena, try l.fmt("{s}%{s}: {s}", .{ if (i == 0) "" else ", ", p.name, p.ty.text() })); + try head.append(l.arena, ')'); + } + try head.appendSlice(l.arena, ":"); + try l.line(head.items, null); + for (b.insts.items) |inst| try l.line(try l.fmt(" {s}", .{inst.text}), inst.span); + } + } + + fn freshName(l: *Lowerer, base: []const u8) Error![]const u8 { + l.counter += 1; + return l.fmt("{s}_{d}", .{ base, l.counter }); + } + + fn newBlock(l: *Lowerer, kind: []const u8) Error!usize { + const name = if (l.blocks.items.len == 0) kind else blk: { + l.counter += 1; + break :blk try l.fmt("{s}_{d}", .{ kind, l.counter }); + }; + try l.blocks.append(l.arena, .{ .name = name }); + return l.blocks.items.len - 1; + } + + fn emit(l: *Lowerer, text: []const u8, span: Span) Error!void { + const b = &l.blocks.items[l.cur.?]; + try b.insts.append(l.arena, .{ .text = text, .span = span }); + } + + /// Emits `%name = text` and returns the value. + fn def(l: *Lowerer, base: []const u8, ty: Ty, text: []const u8, span: Span) Error!Value { + const name = try l.freshName(base); + try l.emit(try l.fmt("%{s} = {s}", .{ name, text }), span); + return .{ .name = name, .ty = ty }; + } + + fn term(l: *Lowerer, text: []const u8, span: Span) Error!void { + try l.emit(text, span); + l.blocks.items[l.cur.?].terminated = true; + l.cur = null; + } + + // ------------------------------------------------------------ variables and joins + + fn lookup(l: *Lowerer, name: []const u8) ?*Binding { + var i = l.bindings.items.len; + while (i > 0) { + i -= 1; + if (std.mem.eql(u8, l.bindings.items[i].name, name)) return &l.bindings.items[i]; + } + return null; + } + + /// Indices of the variables (mutable bindings) among the first `depth` + /// bindings: the state carried across joins. + fn carried(l: *Lowerer, depth: usize) Error![]const usize { + var out: std.ArrayList(usize) = .empty; + for (l.bindings.items[0..depth], 0..) |b, i| if (b.mutable) try out.append(l.arena, i); + return out.items; + } + + fn argsOf(l: *Lowerer, vars: []const usize, extra: ?[]const u8) Error![]const u8 { + var s: std.ArrayList(u8) = .empty; + try s.append(l.arena, '('); + var first = true; + if (extra) |e| { + try s.appendSlice(l.arena, try l.fmt("%{s}", .{e})); + first = false; + } + for (vars) |i| { + try s.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (first) "" else ", ", l.bindings.items[i].value })); + first = false; + } + try s.append(l.arena, ')'); + return s.items; + } + + /// Gives `block` one parameter per carried variable (after an optional + /// result parameter) and rebinds the variables to them. + fn joinParams(l: *Lowerer, block: usize, vars: []const usize) Error!void { + for (vars) |i| { + const b = &l.bindings.items[i]; + const name = try l.freshName(b.name); + try l.blocks.items[block].params.append(l.arena, .{ .name = name, .ty = b.ty }); + } + } + + fn rebindToParams(l: *Lowerer, block: usize, vars: []const usize, offset: usize) void { + for (vars, 0..) |i, k| l.bindings.items[i].value = l.blocks.items[block].params.items[offset + k].name; + } + + fn snapshot(l: *Lowerer) Error![]const []const u8 { + const s = try l.arena.alloc([]const u8, l.bindings.items.len); + for (l.bindings.items, s) |b, *o| o.* = b.value; + return s; + } + + fn restore(l: *Lowerer, s: []const []const u8) void { + l.bindings.shrinkRetainingCapacity(s.len); + for (l.bindings.items, s) |*b, v| b.value = v; + } + + // ------------------------------------------------------------ statements + + /// Lowers a block's statements in a new scope; returns the tail value. + fn blockBody(l: *Lowerer, b: ast.Block) Error!?Value { + return l.blockBodyWant(b, null); + } + + /// As `blockBody`, with the type expected of the tail expression. + fn blockBodyWant(l: *Lowerer, b: ast.Block, want: ?Ty) Error!?Value { + const depth = l.bindings.items.len; + defer l.bindings.shrinkRetainingCapacity(depth); + try l.rest.append(l.arena, .{ .stmts = b.stmts, .tail = b.tail }); + defer _ = l.rest.pop(); + 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); + } + if (b.tail) |t| { + if (l.cur == null) return l.fail("E7006", t.span, "unreachable expression", &.{}); + return try l.expr(t.*, want); + } + 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)"); + var want: ?Ty = if (x.ty) |t| try l.typeOf(t) else null; + // An untyped `let` takes its type from how the name is used + // later (`return`, arguments, operations, annotations). + if (want == null and l.peekType(x.e) == null) want = l.inferUses(x.names[0]); + 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 }); + }, + .@"var" => |x| { + const ty = try l.typeOf(x.ty); + 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", &.{}), + }; + 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)"); + const b = l.lookup(x.place.kind.name) orelse return l.unknown(x.place.span, x.place.kind.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 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; + }, + .@"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); + } 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() }}); + try l.term("ret", s.span); + } + }, + .trap => try l.term("trap", s.span), + .@"break", .@"continue" => { + if (l.loops.items.len == 0) return l.fail("E7006", s.span, "`break` or `continue` outside a loop", &.{}); + const lp = l.loops.items[l.loops.items.len - 1]; + const vars = try l.carried(lp.depth); + const target = if (s.kind == .@"break") lp.exit else lp.@"continue"; + try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[target].name, try l.argsOf(vars, null) }), s.span); + }, + .expr => |e| { + const v = try l.expr(e, null); + _ = v; + }, + .@"while" => |x| try l.whileLoop(s.span, x.cond, x.body, null), + .loop => |b| try l.whileLoop(s.span, null, b, null), + .@"for" => |x| try l.forLoop(s.span, x.name, x.lo, x.hi, x.body), + .scope => return l.notYet(s.span, "`scope` (layer 7)"), + .shield => return l.notYet(s.span, "`shield` (layer 8)"), + .lock => return l.notYet(s.span, "`lock` (layer 8)"), + .select => return l.notYet(s.span, "`select` (layer 8)"), + } + } + + fn unknown(l: *Lowerer, span: Span, name: []const u8) Error { + return l.fail("E7002", span, "unknown name", &.{.{ .name = "name", .value = name }}); + } + + fn checkTy(l: *Lowerer, span: Span, found: Ty, want: Ty) Error!void { + if (found == .never or found.eql(want)) return; + return l.fail("E7005", span, "type mismatch", &.{ .{ .name = "expected", .value = want.text() }, .{ .name = "found", .value = found.text() } }); + } + + /// `while cond { body }` (cond null: `loop { body }`). Carried state: + /// every variable visible at the loop. + fn whileLoop(l: *Lowerer, span: Span, cond: ?ast.Expr, body: ast.Block, step: ?ForStep) Error!void { + const depth = l.bindings.items.len; + const vars = try l.carried(depth); + const header = try l.newBlock(if (cond == null) "loop" else "while"); + const exit = try l.newBlock("after"); + const cont = if (step != null) try l.newBlock("step") else header; + try l.joinParams(header, vars); + try l.joinParams(exit, vars); + if (step != null) try l.joinParams(cont, vars); + try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[header].name, try l.argsOf(vars, null) }), span); + + l.cur = header; + l.rebindToParams(header, vars, 0); + if (cond) |c| { + const cv = try l.expr(c, .bool); + try l.checkTy(c.span, cv.ty, .bool); + const body_b = try l.newBlock("body"); + try l.term(try l.fmt("cbr %{s}, @{s}(), @{s}{s}", .{ cv.name, l.blocks.items[body_b].name, l.blocks.items[exit].name, try l.argsOf(vars, null) }), c.span); + l.cur = body_b; + } + try l.loops.append(l.arena, .{ .@"continue" = cont, .exit = exit, .depth = depth }); + _ = try l.blockBody(body); + _ = l.loops.pop(); + if (l.cur != null) try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[cont].name, try l.argsOf(vars, null) }), body.span); + if (step) |st| { + l.cur = cont; + l.rebindToParams(cont, vars, 0); + const i = l.lookup(st.name).?; + const one = try l.def("one", i.ty, try l.fmt("const.{s} 1", .{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); + l.lookup(st.name).?.value = next.name; + try l.term(try l.fmt("br @{s}{s}", .{ l.blocks.items[header].name, try l.argsOf(vars, null) }), st.span); + } + l.cur = exit; + l.rebindToParams(exit, vars, 0); + // A `loop` without `break` never reaches its exit. + if (!l.reaches(exit)) l.cur = null; + } + + const ForStep = struct { name: []const u8, span: Span }; + + /// `for i in lo..hi { body }`: `var i = lo; let end = hi; while i < end { body; i = i + 1 }`, + /// with `continue` going to the increment. + fn forLoop(l: *Lowerer, span: Span, name: []const u8, lo: ast.Expr, hi: ast.Expr, body: ast.Block) Error!void { + const depth = l.bindings.items.len; + defer l.bindings.shrinkRetainingCapacity(depth); + const ty = l.peekType(lo) orelse l.peekType(hi) orelse return l.fail("E7007", lo.span, "the type of the range cannot be determined; add a suffix such as `0usize`", &.{}); + if (ty != .int) return l.fail("E7005", lo.span, "a range needs an integer type", &.{.{ .name = "found", .value = ty.text() }}); + const a = try l.expr(lo, ty); + try l.checkTy(lo.span, a.ty, ty); + const b = try l.expr(hi, ty); + try l.checkTy(hi.span, b.ty, ty); + try l.bindings.append(l.arena, .{ .name = "end of range", .mutable = false, .value = b.name, .ty = ty }); + try l.bindings.append(l.arena, .{ .name = name, .mutable = true, .value = a.name, .ty = ty }); + const cond: ast.Expr = .{ .span = span, .kind = .{ .binary = .{ + .op = .lt, + .l = try box(l.arena, ast.Expr{ .span = lo.span, .kind = .{ .name = name } }), + .r = try box(l.arena, ast.Expr{ .span = hi.span, .kind = .{ .name = "end of range" } }), + } } }; + try l.whileLoop(span, cond, body, .{ .name = name, .span = span }); + } + + fn reaches(l: *Lowerer, block: usize) bool { + const name = l.blocks.items[block].name; + for (l.blocks.items) |b| for (b.insts.items) |inst| { + if (std.mem.indexOf(u8, inst.text, name)) |at| { + const end = at + name.len; + if (at > 0 and inst.text[at - 1] == '@' and (end == inst.text.len or inst.text[end] == '(')) return true; + } + }; + return false; + } + + // ------------------------------------------------------------ expressions + + /// The type of an expression without lowering it, where it follows + /// from names, suffixes, casts and calls; null otherwise. + fn peekType(l: *Lowerer, e: ast.Expr) ?Ty { + return switch (e.kind) { + .int => |x| if (parse_mod.intSuffix(x.text)) |s| Ty{ .int = s } else null, + .boolean => .bool, + .name => |n| if (l.lookup(n)) |b| b.ty else null, + .neg => |x| l.peekType(x.*), + .not => .bool, + .cast => |x| l.typeOfNoFail(x.ty), + .binary => |x| switch (x.op) { + .eq, .ne, .lt, .le, .gt, .ge, .@"and", .@"or" => .bool, + .shl, .shr => l.peekType(x.l.*), + else => l.peekType(x.l.*) orelse l.peekType(x.r.*), + }, + .call => |x| if (x.callee.kind == .name) (if (l.sigs.get(x.callee.kind.name)) |sig| sig.ret else null) else null, + .if_expr => |x| if (x.then.tail) |t| l.peekType(t.*) else null, + else => null, + }; + } + + /// The type the following code expects for the name `n`, if any use + /// determines one. Stops at a rebinding of `n`. + fn inferUses(l: *Lowerer, n: []const u8) ?Ty { + var i = l.rest.items.len; + while (i > 0) { + i -= 1; + const r = l.rest.items[i]; + for (r.stmts) |s| { + if (l.usesInStmt(n, s)) |t| return t; + if (s.kind == .let) for (s.kind.let.names) |bn| if (std.mem.eql(u8, bn, n)) return null; + } + if (r.tail) |t| if (l.useIn(n, t.*, if (i == 0) l.ret else null)) |ty| return ty; + } + return null; + } + + fn usesInStmt(l: *Lowerer, n: []const u8, s: ast.Stmt) ?Ty { + return switch (s.kind) { + .let => |x| l.useIn(n, x.e, if (x.ty) |t| l.typeOfNoFail(t) else null), + .@"var" => |x| if (x.init) |e| l.useIn(n, e, l.typeOfNoFail(x.ty)) else null, + .assign => |x| l.useIn(n, x.e, if (x.place.kind == .name) (if (l.lookup(x.place.kind.name)) |b| b.ty else null) else null), + .@"return" => |e| if (e) |x| l.useIn(n, x, l.ret) else null, + .expr => |e| l.useIn(n, e, null), + .@"while" => |x| l.useIn(n, x.cond, .bool) orelse l.usesInBlock(n, x.body), + .@"for" => |x| l.useIn(n, x.lo, l.peekType(x.hi)) orelse l.useIn(n, x.hi, l.peekType(x.lo)) orelse l.usesInBlock(n, x.body), + .loop, .shield => |b| l.usesInBlock(n, b), + .scope => |x| l.usesInBlock(n, x.body), + else => null, + }; + } + + fn usesInBlock(l: *Lowerer, n: []const u8, b: ast.Block) ?Ty { + for (b.stmts) |s| if (l.usesInStmt(n, s)) |t| return t; + if (b.tail) |t| return l.useIn(n, t.*, null); + return null; + } + + /// The expected type of `n` inside `e`, evaluated where `e` is expected + /// to have type `want`. + fn useIn(l: *Lowerer, n: []const u8, e: ast.Expr, want: ?Ty) ?Ty { + return switch (e.kind) { + .name => |x| if (std.mem.eql(u8, x, n)) want else null, + .neg => |x| l.useIn(n, x.*, want), + .not => |x| l.useIn(n, x.*, .bool), + .cast => |x| l.useIn(n, x.e.*, null), + .binary => |x| switch (x.op) { + .@"and", .@"or" => l.useIn(n, x.l.*, .bool) orelse l.useIn(n, x.r.*, .bool), + .eq, .ne, .lt, .le, .gt, .ge => l.useIn(n, x.l.*, l.peekType(x.r.*)) orelse l.useIn(n, x.r.*, l.peekType(x.l.*)), + .shl, .shr => l.useIn(n, x.l.*, want) orelse l.useIn(n, x.r.*, l.peekType(x.l.*) orelse want), + else => blk: { + const t = want orelse l.peekType(x.l.*) orelse l.peekType(x.r.*); + break :blk l.useIn(n, x.l.*, t) orelse l.useIn(n, x.r.*, t); + }, + }, + .call => |x| blk: { + if (x.callee.kind != .name) break :blk null; + const sig = l.sigs.get(x.callee.kind.name) orelse break :blk null; + for (x.args, 0..) |a, i| { + const pt: ?Ty = if (i < sig.params.len) sig.params[i] else null; + if (l.useIn(n, a, pt)) |t| break :blk t; + } + break :blk null; + }, + .if_expr => |x| l.useIn(n, x.cond, .bool) orelse l.usesInBlock(n, x.then) orelse if (x.@"else") |els| switch (els) { + .block => |b| l.usesInBlock(n, b), + .@"if" => |inner| l.useIn(n, .{ .span = e.span, .kind = .{ .if_expr = inner } }, want), + } else null, + .block => |b| l.usesInBlock(n, b.*), + else => null, + }; + } + + fn typeOfNoFail(l: *Lowerer, t: ast.Type) ?Ty { + _ = l; + return switch (t.kind) { + .name => |n| if (isIntName(n)) Ty{ .int = n } else if (std.mem.eql(u8, n, "bool")) .bool else null, + 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() }}); + const v = parse_mod.parseIntText(x.text) orelse return l.fail("E7001", e.span, "malformed integer literal", &.{}); + const n = ty.int; + const bits = intBits(n); + const max: u128 = if (isSigned(n)) (@as(u128, 1) << @intCast(bits - 1)) - 1 else if (bits == 128) std.math.maxInt(u128) else (@as(u128, 1) << @intCast(bits)) - 1; + if (v > max) return l.fail("E7005", e.span, "integer literal out of range for its type", &.{ .{ .name = "type", .value = n }, .{ .name = "literal", .value = x.text } }); + return l.def("c", ty, try l.fmt("const.{s} {d}", .{ n, v }), e.span); + }, + .boolean => |b| return l.def("c", .bool, if (b) "const.bool true" else "const.bool false", e.span), + .name => |n| { + const b = l.lookup(n) orelse return l.unknown(e.span, n); + return .{ .name = b.value, .ty = b.ty }; + }, + .neg => |x| { + const ty = want orelse l.peekType(x.*) orelse return l.fail("E7007", e.span, "the type of this negation cannot be determined", &.{}); + if (ty != .int) return l.fail("E7005", e.span, "negation of a non-integer", &.{}); + // `-literal` is the negative literal. + if (x.kind == .int) { + const v = parse_mod.parseIntText(x.kind.int.text) orelse return l.fail("E7001", e.span, "malformed integer literal", &.{}); + if (!isSigned(ty.int)) return l.fail("E7005", e.span, "negative literal of an unsigned type", &.{.{ .name = "type", .value = ty.int }}); + const min_mag: u128 = @as(u128, 1) << @intCast(intBits(ty.int) - 1); + if (v > min_mag) return l.fail("E7005", e.span, "integer literal out of range for its type", &.{.{ .name = "type", .value = ty.int }}); + return l.def("c", ty, try l.fmt("const.{s} -{d}", .{ ty.int, v }), e.span); + } + const z = try l.def("zero", ty, try l.fmt("const.{s} 0", .{ty.int}), e.span); + const v = try l.expr(x.*, ty); + try l.checkTy(x.span, v.ty, ty); + return l.def("neg", ty, try l.fmt("sub.checked.{s} %{s}, %{s}", .{ ty.int, z.name, v.name }), e.span); + }, + .not => |x| { + const v = try l.expr(x.*, .bool); + try l.checkTy(x.span, v.ty, .bool); + const t = try l.def("c", .bool, "const.bool true", e.span); + return l.def("not", .bool, try l.fmt("xor.bool %{s}, %{s}", .{ v.name, t.name }), e.span); + }, + .binary => |x| return l.binary(e, x.op, x.l.*, x.r.*, want), + .cast => |x| { + const to = try l.typeOf(x.ty); + if (to != .int) return l.fail("E7005", x.ty.span, "casts convert between integer types", &.{}); + const from = l.peekType(x.e.*) orelse to; + const v = try l.expr(x.e.*, from); + const mode = switch (x.mode) { + .widen => "widen", + .checked => "checked", + .wrap => "wrap", + }; + return l.def("cast", to, try l.fmt("cast.{s}.{s} %{s}", .{ mode, to.int, v.name }), e.span); + }, + .call => |x| return l.call(e, x.callee.*, x.args), + .if_expr => |x| return l.ifExpr(e.span, x.*, want), + .block => |b| { + const v = try l.blockBodyWant(b.*, want); + return v orelse .{ .name = "", .ty = if (l.cur == null) .never else .void }; + }, + .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)"), + .borrow, .deref, .move => return l.notYet(e.span, "borrows and moves (layer 4)"), + } + } + + fn binary(l: *Lowerer, e: ast.Expr, op: ast.BinOp, a: ast.Expr, b: ast.Expr, want: ?Ty) Error!Value { + switch (op) { + .@"and", .@"or" => { + // Short-circuit: the right operand runs only when needed. + const lv = try l.expr(a, .bool); + try l.checkTy(a.span, lv.ty, .bool); + const short = try l.def("c", .bool, if (op == .@"and") "const.bool false" else "const.bool true", e.span); + const rhs_b = try l.newBlock(if (op == .@"and") "and_rhs" else "or_rhs"); + const join = try l.newBlock(if (op == .@"and") "and_end" else "or_end"); + const rname = try l.freshName(if (op == .@"and") "and" else "or"); + try l.blocks.items[join].params.append(l.arena, .{ .name = rname, .ty = .bool }); + const jn = l.blocks.items[join].name; + if (op == .@"and") { + try l.term(try l.fmt("cbr %{s}, @{s}(), @{s}(%{s})", .{ lv.name, l.blocks.items[rhs_b].name, jn, short.name }), e.span); + } else try l.term(try l.fmt("cbr %{s}, @{s}(%{s}), @{s}()", .{ lv.name, jn, short.name, l.blocks.items[rhs_b].name }), e.span); + l.cur = rhs_b; + const rv = try l.expr(b, .bool); + try l.checkTy(b.span, rv.ty, .bool); + try l.term(try l.fmt("br @{s}(%{s})", .{ jn, rv.name }), e.span); + l.cur = join; + return .{ .name = rname, .ty = .bool }; + }, + else => {}, + } + const cmp = switch (op) { + .eq, .ne, .lt, .le, .gt, .ge => true, + else => false, + }; + const shift = op == .shl or op == .shr; + const operand: ?Ty = if (cmp) (l.peekType(a) orelse l.peekType(b)) else if (shift) (want orelse l.peekType(a)) else (want orelse l.peekType(a) orelse l.peekType(b)); + const ty = operand orelse return l.fail("E7007", e.span, "the type of this operation cannot be determined; add a suffix or annotation", &.{}); + const lv = try l.expr(a, ty); + try l.checkTy(a.span, lv.ty, ty); + const rv = try l.expr(b, ty); + try l.checkTy(b.span, rv.ty, ty); + if (ty == .bool and !(op == .eq or op == .ne or op == .bit_and or op == .bit_or or op == .bit_xor)) + return l.fail("E7005", e.span, "this operation needs integer operands", &.{}); + if (ty != .bool and ty != .int) return l.fail("E7005", e.span, "this operation needs integer or boolean operands", &.{}); + const t = ty.text(); + const text = switch (op) { + .add => try l.fmt("add.checked.{s}", .{t}), + .sub => try l.fmt("sub.checked.{s}", .{t}), + .mul => try l.fmt("mul.checked.{s}", .{t}), + .div => try l.fmt("div.checked.{s}", .{t}), + .rem => try l.fmt("rem.checked.{s}", .{t}), + .add_wrap => try l.fmt("add.wrap.{s}", .{t}), + .sub_wrap => try l.fmt("sub.wrap.{s}", .{t}), + .mul_wrap => try l.fmt("mul.wrap.{s}", .{t}), + .bit_and => try l.fmt("and.{s}", .{t}), + .bit_or => try l.fmt("or.{s}", .{t}), + .bit_xor => try l.fmt("xor.{s}", .{t}), + .shl => try l.fmt("shl.{s}", .{t}), + .shr => try l.fmt("shr.{s}", .{t}), + .eq => try l.fmt("eq.{s}", .{t}), + .ne => try l.fmt("ne.{s}", .{t}), + .lt => try l.fmt("lt.{s}", .{t}), + .le => try l.fmt("le.{s}", .{t}), + .gt => try l.fmt("gt.{s}", .{t}), + .ge => try l.fmt("ge.{s}", .{t}), + .@"and", .@"or" => unreachable, + }; + return l.def(if (cmp) "cmp" else "t", if (cmp) .bool else ty, try l.fmt("{s} %{s}, %{s}", .{ text, lv.name, rv.name }), e.span); + } + + fn call(l: *Lowerer, e: ast.Expr, callee: ast.Expr, args: []const ast.Expr) Error!Value { + if (callee.kind != .name) return l.notYet(callee.span, "built-in operations (later layers)"); + const name = callee.kind.name; + if (std.mem.eql(u8, name, "assert")) { + if (args.len != 1) return l.fail("E7005", e.span, "`assert` takes one boolean", &.{}); + const v = try l.expr(args[0], .bool); + try l.checkTy(args[0].span, v.ty, .bool); + try l.emit(try l.fmt("assert %{s}", .{v.name}), e.span); + return .{ .name = "", .ty = .void }; + } + 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; + for (args, sig.params, 0..) |a, pt, i| { + const v = try l.expr(a, pt); + 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 }); + if (sig.ret == .void or sig.ret == .never) { + try l.emit(text, e.span); + if (sig.ret == .never) { + try l.term("trap", e.span); // `never` returns do not come back + return .{ .name = "", .ty = .never }; + } + return .{ .name = "", .ty = .void }; + } + return l.def(name, sig.ret, text, e.span); + } + + 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); + const depth = l.bindings.items.len; + 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; + for (0..2) |k| { + l.restore(before); + l.cur = if (k == 0) then_b else else_b; + var v: ?Value = null; + 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() }; + } + 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.? }; + } +}; + +fn box(arena: Allocator, e: ast.Expr) Error!*const ast.Expr { + const b = try arena.create(ast.Expr); + b.* = e; + return b; +} diff --git a/src/frontend/parse.zig b/src/frontend/parse.zig new file mode 100644 index 0000000..cc625be --- /dev/null +++ b/src/frontend/parse.zig @@ -0,0 +1,796 @@ +//! Parser for `.aji` source 0.1 (reference/grammar.ebnf). Recursive +//! descent. On the first error it stops with exactly one `E7001` carrying +//! the span, what was expected and what was found: no recovery, no cascade. + +const std = @import("std"); +const lex = @import("lex.zig"); +const ast = @import("ast.zig"); + +const Allocator = std.mem.Allocator; +const Tag = lex.Tag; +const Token = lex.Token; + +pub const Failure = struct { pos: lex.Pos, expected: []const u8, found: []const u8 }; + +pub const Result = union(enum) { ok: ast.Module, err: Failure }; + +pub fn parse(arena: Allocator, src: []const u8) Allocator.Error!Result { + const tokens = try lex.tokenize(arena, src); + var p: Parser = .{ .arena = arena, .tokens = tokens }; + const m = p.module() catch |e| switch (e) { + error.Syntax => return .{ .err = p.failure.? }, + error.OutOfMemory => return error.OutOfMemory, + }; + return .{ .ok = m }; +} + +const Error = error{ Syntax, OutOfMemory }; + +const Parser = struct { + arena: Allocator, + tokens: []const Token, + pos: usize = 0, + failure: ?Failure = null, + /// Struct literals are not allowed where a `{` starts a block (conditions). + no_struct: bool = false, + + fn peek(p: *Parser) Token { + return p.tokens[p.pos]; + } + + fn peekAt(p: *Parser, n: usize) Token { + return p.tokens[@min(p.pos + n, p.tokens.len - 1)]; + } + + fn next(p: *Parser) Token { + const t = p.tokens[p.pos]; + if (t.tag != .eof) p.pos += 1; + return t; + } + + fn prevEnd(p: *Parser) lex.Pos { + return if (p.pos == 0) p.tokens[0].pos else p.tokens[p.pos - 1].end; + } + + fn fail(p: *Parser, t: Token, expected: []const u8) Error { + p.failure = .{ .pos = t.pos, .expected = expected, .found = if (t.tag == .eof) "end of file" else t.text }; + return error.Syntax; + } + + fn expect(p: *Parser, tag: Tag, what: []const u8) Error!Token { + const t = p.peek(); + if (t.tag != tag) return p.fail(t, what); + return p.next(); + } + + fn isWord(t: Token, w: []const u8) bool { + return t.tag == .ident and std.mem.eql(u8, t.text, w); + } + + fn atWord(p: *Parser, w: []const u8) bool { + return isWord(p.peek(), w); + } + + fn expectWord(p: *Parser, w: []const u8) Error!Token { + const t = p.peek(); + if (!isWord(t, w)) return p.fail(t, w); + return p.next(); + } + + fn ident(p: *Parser, what: []const u8) Error![]const u8 { + const t = p.peek(); + if (t.tag != .ident or isKeyword(t.text)) return p.fail(t, what); + return p.next().text; + } + + fn span(p: *Parser, start: lex.Pos) ast.Span { + return .{ .start = start, .end = p.prevEnd() }; + } + + fn box(p: *Parser, comptime T: type, v: T) Error!*const T { + const b = try p.arena.create(T); + b.* = v; + return b; + } + + // ------------------------------------------------------------ items + + fn module(p: *Parser) Error!ast.Module { + _ = try p.expectWord("module"); + const name = try p.path(); + var types: std.ArrayList(ast.TypeDecl) = .empty; + var fns: std.ArrayList(ast.FnDecl) = .empty; + while (p.peek().tag != .eof) { + if (p.atWord("type")) { + 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`"); + } + return .{ .name = name, .types = types.items, .functions = fns.items }; + } + + fn path(p: *Parser) Error![]const u8 { + var out: std.ArrayList(u8) = .empty; + try out.appendSlice(p.arena, try p.ident("a name")); + while (p.peek().tag == .dot and p.peekAt(1).tag == .ident) { + _ = p.next(); + try out.append(p.arena, '.'); + try out.appendSlice(p.arena, p.next().text); + } + return out.items; + } + + fn typeDecl(p: *Parser) Error!ast.TypeDecl { + const start = p.next().pos; // `type` + const name = try p.ident("type name"); + _ = try p.expect(.eq, "`=`"); + if (p.atWord("struct")) { + _ = p.next(); + _ = try p.expect(.l_brace, "`{`"); + var fields: std.ArrayList(ast.Field) = .empty; + while (p.peek().tag != .r_brace) { + const fs = p.peek().pos; + const fname = try p.ident("field name"); + _ = try p.expect(.colon, "`:`"); + const ty = try p.typeExpr(); + try fields.append(p.arena, .{ .name = fname, .ty = ty, .span = p.span(fs) }); + if (p.peek().tag != .comma) break; + _ = p.next(); + } + _ = 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; + _ = p.next(); + } + _ = try p.expect(.r_brace, "`}`"); + return .{ .name = name, .span = p.span(start), .kind = .{ .@"enum" = vs.items } }; + } + return p.fail(p.peek(), "`struct` or `enum`"); + } + + fn fnDecl(p: *Parser) Error!ast.FnDecl { + const start = p.next().pos; // `fn` + const name = try p.ident("function name"); + _ = try p.expect(.l_paren, "`(`"); + var params: std.ArrayList(ast.Param) = .empty; + while (p.peek().tag != .r_paren) { + const ps = p.peek().pos; + const pname = try p.ident("parameter name"); + _ = try p.expect(.colon, "`:`"); + const ty = try p.typeExpr(); + try params.append(p.arena, .{ .name = pname, .ty = ty, .span = p.span(ps) }); + if (p.peek().tag != .comma) break; + _ = p.next(); + } + _ = try p.expect(.r_paren, "`)`"); + _ = try p.expect(.arrow, "`->` and the return type"); + const ret = try p.typeExpr(); + var from: ?[]const u8 = null; + if (p.atWord("from")) { + _ = p.next(); + from = try p.ident("parameter name after `from`"); + } + _ = try p.expectWord("effects"); + _ = try p.expect(.l_bracket, "`[`"); + var effects: std.ArrayList([]const u8) = .empty; + while (p.peek().tag != .r_bracket) { + try effects.append(p.arena, try p.path()); + if (p.peek().tag != .comma) break; + _ = p.next(); + } + _ = try p.expect(.r_bracket, "`]`"); + var trusted: ?[]const u8 = null; + if (p.atWord("trusted")) { + _ = p.next(); + const t = try p.expect(.bytes, "an obligation string b\"…\""); + trusted = (try lex.decodeBytes(p.arena, t.text)) orelse return p.fail(t, "a valid string"); + } + const body = try p.block(); + return .{ .name = name, .span = p.span(start), .params = params.items, .ret = ret, .from = from, .effects = effects.items, .trusted = trusted, .body = body }; + } + + // ------------------------------------------------------------ types + + fn typeExpr(p: *Parser) Error!ast.Type { + const start = p.peek().pos; + if (p.peek().tag == .l_bracket) { + _ = p.next(); + const elem = try p.typeExpr(); + _ = try p.expect(.semicolon, "`;` in `[T; N]`"); + const n = try p.expect(.int, "array length"); + _ = try p.expect(.r_bracket, "`]`"); + const len = parseIntText(n.text) orelse return p.fail(n, "an array length"); + return .{ .span = p.span(start), .kind = .{ .array = .{ .elem = try p.box(ast.Type, elem), .len = @intCast(len) } } }; + } + const t = p.peek(); + if (t.tag != .ident) return p.fail(t, "a type"); + _ = p.next(); + if (p.peek().tag != .lt) return .{ .span = p.span(start), .kind = .{ .name = t.text } }; + _ = p.next(); + if (std.mem.eql(u8, t.text, "cap")) { + const k = try p.path(); + _ = try p.expect(.gt, "`>`"); + return .{ .span = p.span(start), .kind = .{ .cap = k } }; + } + if (std.mem.eql(u8, t.text, "file")) { + const m = try p.ident("`read`, `write` or `append`"); + _ = try p.expect(.gt, "`>`"); + return .{ .span = p.span(start), .kind = .{ .file = m } }; + } + const inner = try p.typeExpr(); + _ = try p.expect(.gt, "`>`"); + return .{ .span = p.span(start), .kind = .{ .wrapped = .{ .wrapper = t.text, .inner = try p.box(ast.Type, inner) } } }; + } + + // ------------------------------------------------------------ statements + + fn block(p: *Parser) Error!ast.Block { + const start = (try p.expect(.l_brace, "`{`")).pos; + var stmts: std.ArrayList(ast.Stmt) = .empty; + var tail: ?*const ast.Expr = null; + while (p.peek().tag != .r_brace) { + if (p.peek().tag == .eof) return p.fail(p.peek(), "`}`"); + if (try p.statement(&tail)) |s| { + try stmts.append(p.arena, s); + } else break; // a tail expression ends the block + } + _ = try p.expect(.r_brace, "`}`"); + return .{ .stmts = stmts.items, .tail = tail, .span = p.span(start) }; + } + + /// Parses one statement; returns null after setting `tail` when the + /// block ends with an expression without `;`. + fn statement(p: *Parser, tail: *?*const ast.Expr) Error!?ast.Stmt { + const start = p.peek().pos; + const t = p.peek(); + if (isWord(t, "let")) { + _ = p.next(); + var names: std.ArrayList([]const u8) = .empty; + if (p.peek().tag == .l_paren) { + _ = p.next(); + try names.append(p.arena, try p.ident("a name")); + _ = try p.expect(.comma, "`,`"); + try names.append(p.arena, try p.ident("a name")); + _ = try p.expect(.r_paren, "`)`"); + } else try names.append(p.arena, try p.ident("a name")); + var ty: ?ast.Type = null; + if (p.peek().tag == .colon) { + _ = p.next(); + ty = try p.typeExpr(); + } + _ = try p.expect(.eq, "`=`"); + const e = try p.expr(); + _ = try p.expect(.semicolon, "`;`"); + return .{ .span = p.span(start), .kind = .{ .let = .{ .names = names.items, .ty = ty, .e = e } } }; + } + if (isWord(t, "var")) { + _ = p.next(); + const name = try p.ident("a name"); + _ = try p.expect(.colon, "`:` and the variable's type"); + const ty = try p.typeExpr(); + _ = try p.expect(.eq, "`=`"); + var init: ?ast.Expr = null; + if (p.atWord("zero")) { + _ = p.next(); + } else init = try p.expr(); + _ = try p.expect(.semicolon, "`;`"); + return .{ .span = p.span(start), .kind = .{ .@"var" = .{ .name = name, .ty = ty, .init = init } } }; + } + if (isWord(t, "break") or isWord(t, "continue") or isWord(t, "trap")) { + _ = p.next(); + _ = try p.expect(.semicolon, "`;`"); + const k: @FieldType(ast.Stmt, "kind") = if (isWord(t, "break")) .@"break" else if (isWord(t, "continue")) .@"continue" else .trap; + return .{ .span = p.span(start), .kind = k }; + } + if (isWord(t, "return")) { + _ = p.next(); + var e: ?ast.Expr = null; + if (p.peek().tag != .semicolon) e = try p.expr(); + _ = try p.expect(.semicolon, "`;`"); + return .{ .span = p.span(start), .kind = .{ .@"return" = e } }; + } + if (isWord(t, "while")) { + _ = p.next(); + const cond = try p.condition(); + return .{ .span = p.span(start), .kind = .{ .@"while" = .{ .cond = cond, .body = try p.block() } } }; + } + if (isWord(t, "for")) { + _ = p.next(); + const name = try p.ident("loop variable"); + _ = try p.expectWord("in"); + const saved = p.no_struct; + p.no_struct = true; + const lo = try p.binary(0); + _ = try p.expect(.dot_dot, "`..`"); + const hi = try p.binary(0); + p.no_struct = saved; + return .{ .span = p.span(start), .kind = .{ .@"for" = .{ .name = name, .lo = lo, .hi = hi, .body = try p.block() } } }; + } + if (isWord(t, "loop")) { + _ = p.next(); + return .{ .span = p.span(start), .kind = .{ .loop = try p.block() } }; + } + if (isWord(t, "scope")) { + _ = p.next(); + const name = try p.ident("scope name"); + return .{ .span = p.span(start), .kind = .{ .scope = .{ .name = name, .body = try p.block() } } }; + } + if (isWord(t, "shield")) { + _ = p.next(); + return .{ .span = p.span(start), .kind = .{ .shield = try p.block() } }; + } + if (isWord(t, "lock")) { + _ = p.next(); + _ = try p.expectWord("ref"); + const saved = p.no_struct; + p.no_struct = true; + const place = try p.unary(); + p.no_struct = saved; + _ = try p.expectWord("as"); + const name = try p.ident("a name for the locked data"); + const body = try p.block(); + _ = try p.expectWord("cancelled"); + return .{ .span = p.span(start), .kind = .{ .lock = .{ .place = place, .name = name, .body = body, .cancelled = try p.block() } } }; + } + if (isWord(t, "select")) return .{ .span = p.span(start), .kind = .{ .select = try p.selectStmt() } }; + + // Expression statement, assignment or tail expression. + const e = try p.expr(); + if (p.peek().tag == .eq) { + _ = p.next(); + const rhs = try p.expr(); + _ = try p.expect(.semicolon, "`;`"); + return .{ .span = p.span(start), .kind = .{ .assign = .{ .place = e, .e = rhs } } }; + } + if (p.peek().tag == .semicolon) { + _ = p.next(); + return .{ .span = p.span(start), .kind = .{ .expr = e } }; + } + if (p.peek().tag == .r_brace) { + tail.* = try p.box(ast.Expr, e); + return null; + } + // Block-like expressions end without `;`. + switch (e.kind) { + .if_expr, .match_expr, .block => return .{ .span = p.span(start), .kind = .{ .expr = e } }, + else => return p.fail(p.peek(), "`;`"), + } + } + + fn condition(p: *Parser) Error!ast.Expr { + const saved = p.no_struct; + p.no_struct = true; + defer p.no_struct = saved; + return p.expr(); + } + + fn selectStmt(p: *Parser) Error!ast.Select { + const start = p.next().pos; // `select` + _ = try p.expect(.l_brace, "`{`"); + var sel_arms: std.ArrayList(ast.SelectArm) = .empty; + while (p.atWord("recv") or p.atWord("send")) { + const astart = p.peek().pos; + const is_send = p.atWord("send"); + _ = p.next(); + _ = try p.expect(.l_paren, "`(`"); + const ep = try p.ident("an endpoint name"); + var value: ?ast.Expr = null; + if (is_send) { + _ = try p.expect(.comma, "`,` and the value to send"); + value = try p.expr(); + } + _ = try p.expect(.r_paren, "`)`"); + _ = try p.expect(.l_brace, "`{` with the arm's outcomes"); + const outcomes = try p.arms(); + try sel_arms.append(p.arena, .{ .span = p.span(astart), .send = is_send, .endpoint = ep, .value = value, .arms = outcomes }); + } + _ = try p.expectWord("cancelled"); + var binds: std.ArrayList([]const u8) = .empty; + if (p.peek().tag == .l_paren) { + _ = p.next(); + while (p.peek().tag != .r_paren) { + try binds.append(p.arena, try p.ident("a name")); + if (p.peek().tag != .comma) break; + _ = p.next(); + } + _ = try p.expect(.r_paren, "`)`"); + } + _ = try p.expect(.fat_arrow, "`=>`"); + const body = try p.armBody(); + _ = try p.expect(.r_brace, "`}`"); + return .{ .arms = sel_arms.items, .cancelled_binds = binds.items, .cancelled = body, .span = p.span(start) }; + } + + /// Arms up to and including the closing `}`. + fn arms(p: *Parser) Error![]const ast.Arm { + var out: std.ArrayList(ast.Arm) = .empty; + while (p.peek().tag != .r_brace) { + const pat = try p.pattern(); + _ = try p.expect(.fat_arrow, "`=>`"); + try out.append(p.arena, .{ .pattern = pat, .body = try p.armBody() }); + } + _ = p.next(); + return out.items; + } + + fn armBody(p: *Parser) Error!ast.Expr { + if (p.peek().tag == .l_brace) { + const start = p.peek().pos; + const b = try p.block(); + if (p.peek().tag == .comma) _ = p.next(); + return .{ .span = p.span(start), .kind = .{ .block = try p.box(ast.Block, b) } }; + } + const e = try p.expr(); + if (p.peek().tag == .comma) { + _ = p.next(); + } else if (p.peek().tag != .r_brace) return p.fail(p.peek(), "`,` after the arm"); + return e; + } + + fn pattern(p: *Parser) Error!ast.Pattern { + const start = p.peek().pos; + const t = p.peek(); + if (t.tag == .underscore) { + _ = p.next(); + return .{ .span = p.span(start), .kind = .wildcard }; + } + if (t.tag == .int or (t.tag == .minus and p.peekAt(1).tag == .int)) { + var text = p.next().text; + 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 `_`)"); + _ = p.next(); + var binds: std.ArrayList([]const u8) = .empty; + if (p.peek().tag == .l_paren) { + _ = p.next(); + while (p.peek().tag != .r_paren) { + const b = p.peek(); + if (b.tag == .underscore) { + _ = p.next(); + try binds.append(p.arena, "_"); + } else try binds.append(p.arena, try p.ident("a name")); + if (p.peek().tag != .comma) break; + _ = p.next(); + } + _ = try p.expect(.r_paren, "`)`"); + } + return .{ .span = p.span(start), .kind = .{ .ctor = .{ .name = t.text, .binds = binds.items } } }; + } + + // ------------------------------------------------------------ expressions + + fn expr(p: *Parser) Error!ast.Expr { + return p.binary(0); + } + + const BinInfo = struct { prec: u8, op: ast.BinOp }; + + fn binInfo(t: Token) ?BinInfo { + if (isWord(t, "or")) return .{ .prec = 1, .op = .@"or" }; + if (isWord(t, "and")) return .{ .prec = 2, .op = .@"and" }; + return switch (t.tag) { + .eq_eq => .{ .prec = 3, .op = .eq }, + .bang_eq => .{ .prec = 3, .op = .ne }, + .lt => .{ .prec = 3, .op = .lt }, + .le => .{ .prec = 3, .op = .le }, + .gt => .{ .prec = 3, .op = .gt }, + .ge => .{ .prec = 3, .op = .ge }, + .amp => .{ .prec = 4, .op = .bit_and }, + .pipe => .{ .prec = 4, .op = .bit_or }, + .caret => .{ .prec = 4, .op = .bit_xor }, + .shl => .{ .prec = 5, .op = .shl }, + .shr => .{ .prec = 5, .op = .shr }, + .plus => .{ .prec = 6, .op = .add }, + .minus => .{ .prec = 6, .op = .sub }, + .plus_pct => .{ .prec = 6, .op = .add_wrap }, + .minus_pct => .{ .prec = 6, .op = .sub_wrap }, + .star => .{ .prec = 7, .op = .mul }, + .slash => .{ .prec = 7, .op = .div }, + .percent => .{ .prec = 7, .op = .rem }, + .star_pct => .{ .prec = 7, .op = .mul_wrap }, + else => null, + }; + } + + fn binary(p: *Parser, min_prec: u8) Error!ast.Expr { + const start = p.peek().pos; + var lhs = try p.castExpr(); + while (true) { + // `e or trap`: the fallible shorthand (spec 15 §6). + if (p.atWord("or") and isWord(p.peekAt(1), "trap") and min_prec <= 1) { + _ = p.next(); + _ = p.next(); + const inner = try p.box(ast.Expr, lhs); + lhs = .{ .span = p.span(start), .kind = .{ .or_trap = inner } }; + continue; + } + const info = binInfo(p.peek()) orelse break; + if (info.prec <= min_prec) break; + _ = p.next(); + const rhs = try p.binary(info.prec); + // Comparisons do not chain. + const lb = try p.box(ast.Expr, lhs); + const rb = try p.box(ast.Expr, rhs); + lhs = .{ .span = p.span(start), .kind = .{ .binary = .{ .op = info.op, .l = lb, .r = rb } } }; + if (info.prec == 3 and binInfo(p.peek()) != null and binInfo(p.peek()).?.prec == 3) return p.fail(p.peek(), "parentheses around a comparison"); + } + return lhs; + } + + fn castExpr(p: *Parser) Error!ast.Expr { + const start = p.peek().pos; + var e = try p.unary(); + while (true) { + const mode: ast.CastMode = if (p.atWord("as")) .widen else if (p.peek().tag == .as_bang) .checked else if (p.peek().tag == .as_pct) .wrap else break; + _ = p.next(); + const ty = try p.typeExpr(); + const inner = try p.box(ast.Expr, e); + e = .{ .span = p.span(start), .kind = .{ .cast = .{ .mode = mode, .e = inner, .ty = ty } } }; + } + return e; + } + + fn unary(p: *Parser) Error!ast.Expr { + const start = p.peek().pos; + const t = p.peek(); + if (t.tag == .minus) { + _ = p.next(); + return .{ .span = p.span(start), .kind = .{ .neg = try p.box(ast.Expr, try p.unary()) } }; + } + if (isWord(t, "not")) { + _ = p.next(); + return .{ .span = p.span(start), .kind = .{ .not = try p.box(ast.Expr, try p.unary()) } }; + } + if (t.tag == .star) { + _ = p.next(); + return .{ .span = p.span(start), .kind = .{ .deref = try p.box(ast.Expr, try p.unary()) } }; + } + if (isWord(t, "ref") or isWord(t, "mut")) { + _ = p.next(); + var unchecked = false; + if (p.atWord("unchecked")) { + _ = p.next(); + unchecked = true; + } + const place = try p.postfix(); + return .{ .span = p.span(start), .kind = .{ .borrow = .{ .mutable = isWord(t, "mut"), .unchecked = unchecked, .place = try p.box(ast.Expr, place) } } }; + } + if (isWord(t, "move")) { + _ = p.next(); + return .{ .span = p.span(start), .kind = .{ .move = try p.ident("the name of the value to move") } }; + } + return p.postfix(); + } + + fn postfix(p: *Parser) Error!ast.Expr { + const start = p.peek().pos; + var e = try p.primary(); + while (true) { + switch (p.peek().tag) { + .dot => { + _ = p.next(); + const name = try p.ident("a field, method or operation name"); + const base = try p.box(ast.Expr, e); + e = .{ .span = p.span(start), .kind = .{ .field = .{ .e = base, .name = name } } }; + // `channel.make(…)`: the only explicit type argument. + if (std.mem.eql(u8, name, "make") and p.peek().tag == .lt and e.kind.field.e.kind == .name and std.mem.eql(u8, e.kind.field.e.kind.name, "channel")) { + _ = p.next(); + const ty = try p.typeExpr(); + _ = try p.expect(.gt, "`>`"); + const args = try p.callArgs(); + const callee = try p.box(ast.Expr, e); + e = .{ .span = p.span(start), .kind = .{ .call = .{ .callee = callee, .type_arg = ty, .args = args } } }; + } + }, + .l_paren => { + const args = try p.callArgs(); + const callee = try p.box(ast.Expr, e); + e = .{ .span = p.span(start), .kind = .{ .call = .{ .callee = callee, .type_arg = null, .args = args } } }; + }, + .l_bracket => { + _ = p.next(); + const saved = p.no_struct; + p.no_struct = false; + const lo = try p.expr(); + var hi: ?*const ast.Expr = null; + if (p.peek().tag == .dot_dot) { + _ = p.next(); + hi = try p.box(ast.Expr, try p.expr()); + } + p.no_struct = saved; + _ = try p.expect(.r_bracket, "`]`"); + const base = try p.box(ast.Expr, e); + const lob = try p.box(ast.Expr, lo); + e = .{ .span = p.span(start), .kind = .{ .index = .{ .e = base, .lo = lob, .hi = hi } } }; + }, + else => return e, + } + } + } + + fn callArgs(p: *Parser) Error![]const ast.Expr { + _ = try p.expect(.l_paren, "`(`"); + const saved = p.no_struct; + p.no_struct = false; + defer p.no_struct = saved; + var args: std.ArrayList(ast.Expr) = .empty; + while (p.peek().tag != .r_paren) { + try args.append(p.arena, try p.expr()); + if (p.peek().tag != .comma) break; + _ = p.next(); + } + _ = try p.expect(.r_paren, "`)`"); + return args.items; + } + + fn primary(p: *Parser) Error!ast.Expr { + const start = p.peek().pos; + const t = p.peek(); + switch (t.tag) { + .int => { + _ = p.next(); + return .{ .span = p.span(start), .kind = .{ .int = .{ .text = t.text } } }; + }, + .bytes => { + _ = p.next(); + const b = (try lex.decodeBytes(p.arena, t.text)) orelse return p.fail(t, "a byte string with valid escapes"); + return .{ .span = p.span(start), .kind = .{ .bytes = b } }; + }, + .l_paren => { + _ = p.next(); + const saved = p.no_struct; + p.no_struct = false; + const e = try p.expr(); + p.no_struct = saved; + _ = try p.expect(.r_paren, "`)`"); + return e; + }, + .l_bracket => { + _ = p.next(); + const e = try p.expr(); + _ = try p.expect(.semicolon, "`;` in `[e; N]`"); + const n = try p.expect(.int, "array length"); + _ = try p.expect(.r_bracket, "`]`"); + const len = parseIntText(n.text) orelse return p.fail(n, "an array length"); + return .{ .span = p.span(start), .kind = .{ .array_rep = .{ .e = try p.box(ast.Expr, e), .len = @intCast(len) } } }; + }, + .l_brace => { + const b = try p.block(); + return .{ .span = p.span(start), .kind = .{ .block = try p.box(ast.Block, b) } }; + }, + .ident => { + if (isWord(t, "true") or isWord(t, "false")) { + _ = p.next(); + return .{ .span = p.span(start), .kind = .{ .boolean = isWord(t, "true") } }; + } + if (isWord(t, "if")) return .{ .span = p.span(start), .kind = .{ .if_expr = try p.box(ast.If, try p.ifExpr()) } }; + if (isWord(t, "match")) { + _ = p.next(); + const scrut = try p.condition(); + _ = try p.expect(.l_brace, "`{`"); + const as = try p.arms(); + return .{ .span = p.span(start), .kind = .{ .match_expr = try p.box(ast.Match, .{ .scrutinee = scrut, .arms = as, .span = p.span(start) }) } }; + } + if (isKeyword(t.text)) return p.fail(t, "an expression"); + _ = p.next(); + 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; + while (p.peek().tag != .r_brace) { + const fs = p.peek().pos; + const fname = try p.ident("a field name"); + _ = try p.expect(.colon, "`:`"); + const fe = try p.expr(); + try fields.append(p.arena, .{ .name = fname, .span = p.span(fs), .e = fe }); + if (p.peek().tag != .comma) break; + _ = p.next(); + } + _ = try p.expect(.r_brace, "`}`"); + return .{ .span = p.span(start), .kind = .{ .struct_lit = .{ .name = t.text, .fields = fields.items } } }; + } + return .{ .span = p.span(start), .kind = .{ .name = t.text } }; + }, + else => return p.fail(t, "an expression"), + } + } + + fn ifExpr(p: *Parser) Error!ast.If { + _ = p.next(); // `if` + const cond = try p.condition(); + const then = try p.block(); + var els: ?ast.Else = null; + if (p.atWord("else")) { + _ = p.next(); + if (p.atWord("if")) { + els = .{ .@"if" = try p.box(ast.If, try p.ifExpr()) }; + } else els = .{ .block = try p.block() }; + } + return .{ .cond = cond, .then = then, .@"else" = els }; + } +}; + +const keywords = [_][]const u8{ + "module", "type", "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", +}; + +pub fn isKeyword(w: []const u8) bool { + for (keywords) |k| if (std.mem.eql(u8, k, w)) return true; + return false; +} + +/// Value of an integer token without its type suffix; null if malformed. +pub fn parseIntText(text: []const u8) ?u128 { + const digits = stripSuffix(text); + var clean: [64]u8 = undefined; + var n: usize = 0; + for (digits) |c| { + if (c == '_') continue; + if (n == clean.len) return null; + clean[n] = c; + n += 1; + } + return std.fmt.parseInt(u128, clean[0..n], 0) catch null; +} + +/// The integer suffix (`u8`, `usize`, …) of an integer token, if any. +pub fn intSuffix(text: []const u8) ?[]const u8 { + const suffixes = [_][]const u8{ "usize", "isize", "u128", "i128", "u16", "u32", "u64", "i16", "i32", "i64", "u8", "i8" }; + for (suffixes) |s| if (text.len > s.len and std.mem.endsWith(u8, text, s)) { + const before = text[text.len - s.len - 1]; + if (std.ascii.isDigit(before) or before == '_' or (std.ascii.isHex(before) and std.mem.startsWith(u8, text, "0x"))) return s; + }; + return null; +} + +fn stripSuffix(text: []const u8) []const u8 { + if (intSuffix(text)) |s| return text[0 .. text.len - s.len]; + return text; +} + +test "parse a function" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const src = + \\module demo + \\fn main() -> u64 + \\effects [] + \\{ + \\ let a = 10; + \\ var i: u64 = 0; + \\ while i < a { i = i + 1; } + \\ return a + i * 2; + \\} + ; + const r = try parse(arena.allocator(), src); + try std.testing.expect(r == .ok); + try std.testing.expectEqual(@as(usize, 1), r.ok.functions.len); + try std.testing.expectEqual(@as(usize, 4), r.ok.functions[0].body.stmts.len); + const bad = try parse(arena.allocator(), "module demo\nfn main() -> u64 effects [] { let a = 1 }"); + try std.testing.expect(bad == .err); + try std.testing.expectEqualStrings("`;`", bad.err.expected); + try std.testing.expectEqual(@as(u32, 2), bad.err.pos.line); +} diff --git a/src/main.zig b/src/main.zig index 7273d42..d382855 100644 --- a/src/main.zig +++ b/src/main.zig @@ -29,6 +29,9 @@ 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] + \\ print the canonical AIR a source module lowers to; + \\ --annotate adds source spans as comments (not canonical) \\ report 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 @@ -83,6 +86,30 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s try out.writeByte('\n'); return .accepted; } + 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 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 }); + return .usage; + }; + switch (try aji.frontend.compile(arena, path, source)) { + .ok => |o| { + try out.writeAll(if (annotate) o.annotated else o.air); + return .accepted; + }, + .err => |d| { + try d.writeJson(out); + try out.writeByte('\n'); + return .rejected; + }, + .unimplemented => |what| { + std.debug.print("aji: not implemented yet: {s}\n", .{what}); + return .unimplemented; + }, + } + } if (std.mem.eql(u8, cmd, "features")) { var s: std.json.Stringify = .{ .writer = out }; try s.write(.{ @@ -188,7 +215,7 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s std.debug.print("aji: cannot read {s}: {t}\n", .{ path, err }); return .usage; }; - const report = try aji.check.checkAir(arena, path, source); + const report = try aji.check.checkFile(arena, path, source); for (report.diagnostics) |d| { try d.writeJson(out); try out.writeByte('\n'); @@ -208,7 +235,7 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s }; const captured: ?aji.interp.Output = if (hosted) null else output; if (!hosted) { - try aji.interp.writeOutcome(module, outcome, captured, out); + try writeRecord(arena, module, outcome, captured, report, path, out); try out.writeByte('\n'); } else if (result_file == null) { // Human summary only; the machine interface is --result-file (spec 11 §8). @@ -245,6 +272,34 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s return usageError("unknown command"); } +/// The run record; for a `.aji` module a trap also carries its +/// `source_location` (spec 15 §10). +fn writeRecord(arena: std.mem.Allocator, module: aji.air.Module, outcome: aji.interp.Outcome, captured: ?aji.interp.Output, report: aji.check.Report, path: []const u8, out: *std.Io.Writer) !void { + var rec: std.Io.Writer.Allocating = .init(arena); + try aji.interp.writeOutcome(module, outcome, captured, &rec.writer); + const text = rec.written(); + const lowered = report.lowered orelse return out.writeAll(text); + const t = switch (outcome) { + .trapped => |t| t, + else => return out.writeAll(text), + }; + var loc: ?aji.frontend.Span = null; + for (module.functions) |f| { + if (!std.mem.eql(u8, f.name, t.function)) continue; + for (f.blocks) |b| { + if (!std.mem.eql(u8, b.name, t.block)) continue; + const air_line = b.insts[t.inst].span.line; + if (air_line >= 1 and air_line <= lowered.lines.len) loc = lowered.lines[air_line - 1]; + } + } + const s = loc orelse return out.writeAll(text); + try out.writeAll(text[0 .. text.len - 1]); + var j: std.json.Stringify = .{ .writer = out }; + try out.writeAll(",\"source_location\":"); + try j.write(.{ .file = path, .line = s.start.line, .col = s.start.col }); + try out.writeAll("}"); +} + fn writeCode(out: *std.Io.Writer, c: aji.diag.Code) !void { var s: std.json.Stringify = .{ .writer = out }; try s.write(.{ .code = c.id, .kind = c.kind, .meaning = c.meaning }); diff --git a/src/root.zig b/src/root.zig index ac79a4d..172b5e9 100644 --- a/src/root.zig +++ b/src/root.zig @@ -15,6 +15,7 @@ pub const air = @import("air.zig"); pub const verifier = @import("verifier.zig"); pub const interp = @import("interp.zig"); pub const check = @import("check.zig"); +pub const frontend = @import("frontend.zig"); pub const report = @import("report.zig"); pub const manifest = @import("manifest.zig"); diff --git a/tests/conformance/source/layer1/calls.aji b/tests/conformance/source/layer1/calls.aji new file mode 100644 index 0000000..b68dacf --- /dev/null +++ b/tests/conformance/source/layer1/calls.aji @@ -0,0 +1,19 @@ +// Function calls and recursion. +// expect: run +// result: 3628800 +// phase: 6 +// spec: docs/spec/15-source-language.md +module demo.calls + +fn fact(n: u64) -> u64 +effects [] +{ + if n <= 1 { return 1; } + return n * fact(n - 1); +} + +fn main() -> u64 +effects [] +{ + return fact(10); +} diff --git a/tests/conformance/source/layer1/casts.aji b/tests/conformance/source/layer1/casts.aji new file mode 100644 index 0000000..f8c62bd --- /dev/null +++ b/tests/conformance/source/layer1/casts.aji @@ -0,0 +1,16 @@ +// Casts keep AIR's explicit modes: `as` widens, `as!` checks, `as%` wraps. +// expect: run +// result: 300 +// phase: 6 +// spec: docs/spec/15-source-language.md +module demo.casts + +fn main() -> u64 +effects [] +{ + let small: u8 = 200; + let wide = small as u64; + let back = 44u64 as! u8; + let wrapped = 300u64 as% u8; + return wide + back as u64 + wrapped as u64 + 12; +} diff --git a/tests/conformance/source/layer1/control_flow.aji b/tests/conformance/source/layer1/control_flow.aji new file mode 100644 index 0000000..be0e984 --- /dev/null +++ b/tests/conformance/source/layer1/control_flow.aji @@ -0,0 +1,29 @@ +// while, for, loop, break, continue, if as an expression and variables carried across joins. +// expect: run +// result: 1062 +// phase: 6 +// spec: docs/spec/15-source-language.md +module demo.control + +fn main() -> u64 +effects [] +{ + var evens: u64 = 0; + for i in 0..10u64 { + if i % 2 == 1 { continue; } + evens = evens + i; + } + var n: u64 = 0; + var steps: u64 = 0; + while n < 1000 { + n = n + 37; + steps = steps + 1; + } + var k: u64 = 0; + loop { + k = k + 1; + if k == 5 { break; } + } + let big = if steps > 20 { 1 } else { 0 }; + return evens + n + k + big; +} diff --git a/tests/conformance/source/layer1/overflow_trap.aji b/tests/conformance/source/layer1/overflow_trap.aji new file mode 100644 index 0000000..e9e2716 --- /dev/null +++ b/tests/conformance/source/layer1/overflow_trap.aji @@ -0,0 +1,13 @@ +// Checked arithmetic traps on overflow; the trap record carries the source location. +// expect: run +// trap: T0003 +// phase: 6 +// spec: docs/spec/15-source-language.md +module demo.overflow + +fn main() -> u8 +effects [] +{ + let a: u8 = 250; + return a + 10; +} diff --git a/tests/conformance/source/layer1/reject/ambiguous_literal.aji b/tests/conformance/source/layer1/reject/ambiguous_literal.aji new file mode 100644 index 0000000..012900e --- /dev/null +++ b/tests/conformance/source/layer1/reject/ambiguous_literal.aji @@ -0,0 +1,11 @@ +// The frontend never guesses an integer type. +// expect: reject E7007 +// phase: 6 +// spec: docs/spec/15-source-language.md +module demo.ambiguous + +fn main() -> void +effects [] +{ + let unused = 5; +} diff --git a/tests/conformance/source/layer1/reject/assign_let.aji b/tests/conformance/source/layer1/reject/assign_let.aji new file mode 100644 index 0000000..d2400cc --- /dev/null +++ b/tests/conformance/source/layer1/reject/assign_let.aji @@ -0,0 +1,13 @@ +// Only `var` can be reassigned. +// expect: reject E7006 +// phase: 6 +// spec: docs/spec/15-source-language.md +module demo.assign + +fn main() -> u64 +effects [] +{ + let x: u64 = 1; + x = 2; + return x; +} diff --git a/tests/conformance/source/layer1/reject/missing_return.aji b/tests/conformance/source/layer1/reject/missing_return.aji new file mode 100644 index 0000000..e2f6673 --- /dev/null +++ b/tests/conformance/source/layer1/reject/missing_return.aji @@ -0,0 +1,11 @@ +// expect: reject E7006 +// phase: 6 +// spec: docs/spec/15-source-language.md +module demo.noreturn + +fn main() -> u64 +effects [] +{ + let x: u64 = 1; + if x > 0 { return x; } +} diff --git a/tests/conformance/source/layer1/reject/syntax.aji b/tests/conformance/source/layer1/reject/syntax.aji new file mode 100644 index 0000000..c2ff0ac --- /dev/null +++ b/tests/conformance/source/layer1/reject/syntax.aji @@ -0,0 +1,12 @@ +// One precise syntax error, no cascade. +// expect: reject E7001 +// phase: 6 +// spec: docs/spec/15-source-language.md +module demo.syntax + +fn main() -> u64 +effects [] +{ + let a = 1 + return a; +} diff --git a/tests/conformance/source/layer1/reject/type_mismatch.aji b/tests/conformance/source/layer1/reject/type_mismatch.aji new file mode 100644 index 0000000..1b78370 --- /dev/null +++ b/tests/conformance/source/layer1/reject/type_mismatch.aji @@ -0,0 +1,11 @@ +// expect: reject E7005 +// phase: 6 +// spec: docs/spec/15-source-language.md +module demo.mismatch + +fn main() -> u64 +effects [] +{ + let ok = true; + return ok; +} diff --git a/tests/conformance/source/layer1/reject/unknown_name.aji b/tests/conformance/source/layer1/reject/unknown_name.aji new file mode 100644 index 0000000..047d640 --- /dev/null +++ b/tests/conformance/source/layer1/reject/unknown_name.aji @@ -0,0 +1,10 @@ +// expect: reject E7002 +// phase: 6 +// spec: docs/spec/15-source-language.md +module demo.unknown + +fn main() -> u64 +effects [] +{ + return missing + 1; +} diff --git a/tests/conformance/source/layer1/reject/verifier_effect.aji b/tests/conformance/source/layer1/reject/verifier_effect.aji new file mode 100644 index 0000000..c550c84 --- /dev/null +++ b/tests/conformance/source/layer1/reject/verifier_effect.aji @@ -0,0 +1,17 @@ +// Effects stay explicit: the verifier reports E3101 at the call, with suggested_effects. +// expect: reject E3101 +// phase: 6 +// spec: docs/spec/15-source-language.md +module demo.effects + +fn alloc_something() -> void +effects [mem.alloc] +{ + return; +} + +fn main() -> void +effects [] +{ + alloc_something(); +} diff --git a/tests/conformance/source/layer1/reject/verifier_widen.aji b/tests/conformance/source/layer1/reject/verifier_widen.aji new file mode 100644 index 0000000..d9e8c3a --- /dev/null +++ b/tests/conformance/source/layer1/reject/verifier_widen.aji @@ -0,0 +1,12 @@ +// The frontend does not duplicate the verifier: a lossy `as` lowers to cast.widen and the verifier rejects it (E1002). +// expect: reject E1002 +// phase: 6 +// spec: docs/spec/15-source-language.md +module demo.widen + +fn main() -> u8 +effects [] +{ + let big: u64 = 1; + return big as u8; +} diff --git a/tests/conformance/source/layer1/short_circuit.aji b/tests/conformance/source/layer1/short_circuit.aji new file mode 100644 index 0000000..a185a1e --- /dev/null +++ b/tests/conformance/source/layer1/short_circuit.aji @@ -0,0 +1,15 @@ +// `and` evaluates its right operand only when the left one is true, so this does not divide by zero. +// expect: run +// result: 7 +// phase: 6 +// spec: docs/spec/15-source-language.md +module demo.short + +fn main() -> u8 +effects [] +{ + let d: u8 = 0; + if d != 0 and 10 / d > 1 { return 1; } + if d == 0 or 10 / d > 1 { return 7; } + return 2; +} diff --git a/tests/conformance/source/layer1/sum.aji b/tests/conformance/source/layer1/sum.aji new file mode 100644 index 0000000..7ad287f --- /dev/null +++ b/tests/conformance/source/layer1/sum.aji @@ -0,0 +1,14 @@ +// The first end-to-end slice: untyped literals take their type from the return. +// expect: run +// result: 30 +// phase: 6 +// spec: docs/spec/15-source-language.md +module demo.sum + +fn main() -> u64 +effects [] +{ + let a = 10; + let b = 20; + return a + b; +} diff --git a/tests/conformance/source/layer1/sum.aji.expected b/tests/conformance/source/layer1/sum.aji.expected new file mode 100644 index 0000000..69d5c4f --- /dev/null +++ b/tests/conformance/source/layer1/sum.aji.expected @@ -0,0 +1,12 @@ +module demo.sum +air 0 +lang 0.1 +features [effects] + +fn @main() -> u64 +effects [] +entry: + %c_1 = const.u64 10 + %c_2 = const.u64 20 + %t_3 = add.checked.u64 %c_1, %c_2 + ret %t_3 diff --git a/tools/conformance.zig b/tools/conformance.zig index 1ade1ce..55a85a2 100644 --- a/tools/conformance.zig +++ b/tools/conformance.zig @@ -94,7 +94,7 @@ pub fn main(init: std.process.Init) !void { var walker = try dir.walk(arena); defer walker.deinit(); while (try walker.next(io)) |entry| { - if (entry.kind != .file or !std.mem.endsWith(u8, entry.path, ".air")) continue; + if (entry.kind != .file or !(std.mem.endsWith(u8, entry.path, ".air") or std.mem.endsWith(u8, entry.path, ".aji"))) continue; if (std.mem.indexOf(u8, entry.path, filter) == null) continue; try paths.append(arena, try arena.dupe(u8, entry.path)); } @@ -108,7 +108,7 @@ pub fn main(init: std.process.Init) !void { for (paths.items) |rel| { const source = try dir.readFileAlloc(io, rel, arena, .limited(16 << 20)); const display = try std.fs.path.join(arena, &.{ root, rel }); - const result = try runOne(arena, display, source); + const result = if (std.mem.endsWith(u8, rel, ".aji")) try runSource(arena, io, dir, rel, display, source) else try runOne(arena, display, source); counts.getPtr(result.outcome).* += 1; if (json) { var s: std.json.Stringify = .{ .writer = out }; @@ -136,6 +136,42 @@ var stress_seeds: ?u64 = null; /// and odd slices (spec 04 §36.3); the test's own quantum is added. const stress_quanta = [_]u64{ 1, 2, 7 }; +/// A `.aji` test (spec 15): the same header keys as AIR tests. Every +/// accepted module must also lower deterministically, survive the round +/// trip lower → parse → print unchanged, and match `.expected` if +/// that file exists (golden canonical AIR). +fn runSource(arena: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, rel: []const u8, path: []const u8, source: []const u8) !Result { + const header = parseHeader(arena, source) catch |err| + return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "bad header: {t}", .{err}) }; + const report = try aji.check.checkFile(arena, path, source); + if (report.status == .unimplemented) return .{ .outcome = .pending, .detail = report.missing_stage }; + if (report.lowered) |lowered| { + const again = try aji.frontend.compile(arena, path, source); + if (again != .ok or !std.mem.eql(u8, again.ok.air, lowered.air)) return .{ .outcome = .fail, .detail = "lowering is not deterministic" }; + const parsed = try aji.air.parse.parse(arena, path, lowered.air); + if (parsed.module) |m| { + var w: std.Io.Writer.Allocating = .init(arena); + try aji.air.print.print(m, &w.writer); + if (!std.mem.eql(u8, w.written(), lowered.air)) return .{ .outcome = .fail, .detail = "lowered AIR is not canonical (parse → print differs)" }; + } + const golden_path = try std.fmt.allocPrint(arena, "{s}.expected", .{rel}); + if (dir.readFileAlloc(io, golden_path, arena, .limited(16 << 20))) |golden| { + if (!std.mem.eql(u8, golden, lowered.air)) return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "lowered AIR differs from {s}", .{golden_path}) }; + } else |_| {} + } + var got: std.ArrayList([]const u8) = .empty; + for (report.diagnostics) |d| if (d.severity == .@"error") try got.append(arena, d.code.id); + std.mem.sort([]const u8, got.items, {}, lessThan); + switch (header.expect) { + .accept => if (report.status == .accepted) return .{ .outcome = .pass }, + .reject => |want| if (report.status == .rejected and eqlCodes(want, got.items)) return .{ .outcome = .pass }, + .run => |want| if (report.status == .accepted) return runModule(arena, path, report.module.?, want, header), + } + return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "expected {f}, got {t} {s}", .{ + fmtExpect(header.expect), report.status, try std.mem.join(arena, " ", got.items), + }) }; +} + fn lessThan(_: void, a: []const u8, b: []const u8) bool { return std.mem.lessThan(u8, a, b); } @@ -372,8 +408,9 @@ fn parseHeader(arena: std.mem.Allocator, source: []const u8) HeaderError!Header var lines = std.mem.splitScalar(u8, source, '\n'); while (lines.next()) |line| { - if (!std.mem.startsWith(u8, line, ";")) break; - const content = std.mem.trim(u8, line[1..], " \t\r"); + // `.air` tests use `;` comments, `.aji` tests `//`. + const prefix: usize = if (std.mem.startsWith(u8, line, "//")) 2 else if (std.mem.startsWith(u8, line, ";")) 1 else break; + const content = std.mem.trim(u8, line[prefix..], " \t\r"); const colon = std.mem.indexOfScalar(u8, content, ':') orelse continue; // free-form comment const key = content[0..colon]; if (!isKey(key)) continue; // free-form comment containing a colon