Phase 6A: .aji frontend, layer 1 (scalars, expressions, functions, control flow)
src/frontend: lexer, AST, parser for the full 6A grammar (first error only: one E7001 with span, expected and found), lowering to canonical text AIR with a line map. Variables become SSA with block parameters carried across if/while/for/loop joins; short-circuit and/or; checked, wrapping and cast forms; calls; untyped let literals typed from later uses, never guessed (E7007). The frontend repairs nothing. check.checkFile: .aji → frontend → existing AIR parser and verifier; every diagnostic at its source location, AIR location kept as air_line/air_col; trap records gain source_location. CLI: check/run on .aji, aji lower [--annotate]. Runner: .aji tests with the same headers; every accepted module must lower deterministically, be canonical (lower → parse → print unchanged) and match <file>.expected if present. Layer-1 tests: 6 run, 6 E7xxx rejects, 2 verifier-caught (E1002, E3101).
This commit is contained in:
1 parent
bfb4c445cd
commit
ba3e9b3719
26 files changed
+2478
-13
No files matched your search
@@ -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;
|
||||
}
|
||||
Reference in new issue
Block a user