Files
2026-11-19 04:54:17 -06:00

511 lines
13 KiB
Plaintext

#! @file compiler.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the tests of lowering: small programs are checked and lowered, and
#! the code of their functions printed and compared with what is expected,
#! after the verifier has found nothing wrong with any of it.
import std::io;
import std::testing;
import sakura::analyzer;
module sakura::compiler;
#! Checks the files as one program, lowers every function of it, and gives the
#! code of those named, printed one after another, or what went wrong.
#! @param names The names of the functions, separated by spaces.
#! @param texts The files' texts.
#! @returns The code.
def lowered(names: strview, texts: strview...): string {
var held := names::new();
var notes := vector::<note>::new();
var sources := vector::<source>::new();
var syntaxes := vector::<syntax>::new();
var roots := vector::<u32>::new();
sources.reserve(texts.length);
syntaxes.reserve(texts.length);
for i in 0..texts.length {
sources.append(source::from(i == 0 ? "test.sakura" : "other.sakura", texts.at(i)));
syntaxes.append(syntax::new());
}
for i in 0..texts.length {
var lexing := lexer::new(sources.at(i), &mut held, &mut notes, i as u32);
lexing.tokenize_all(syntaxes.at(i));
var parsing := parser::new(syntaxes.at(i), &held, &mut notes, i as u32);
roots.append(parsing.parse());
}
var checker := checker::new(&mut held, &mut notes);
for i in 0..texts.length {
checker.add(sources.at(i), syntaxes.at(i), roots.at(i));
}
checker.check();
var out := string::new(nothing {});
if notes.length != 0 {
out.append("the program does not check");
return out;
}
var lowering := lowerer::new(&mut checker, lowering { verify = true, everything = true });
lowering.compile();
for &each in lowering.problems {
out.append(each.span);
out.append("\n");
}
var wanted := string::from(names, nothing {});
for name in wanted.split(' ') {
for &function in lowering.program.functions {
if function.name.span == name {
var text := function.body.print();
out.append(text.span);
}
}
}
return out;
}
#! Whether code printed is what is expected, but for the line breaks ending
#! them, printing what it is where it is not.
#! @param got The code printed.
#! @param want The code expected.
#! @returns Whether it is.
def lowers_as(got: &string, want: strview): bool {
var x := got.length;
var y := want.length;
while x > 0 && got.at(x - 1) == '\n' { x--; }
while y > 0 && want.at(y - 1) == '\n' { y--; }
val same := got.substr(0, x) == want.substr(0, y);
if !same {
println(got);
}
return same;
}
@test def arithmetic_narrows_to_its_type(t: &mut tester): void {
# Arithmetic on words wraps at 64 bits, so a result narrower than a word is
# narrowed again, and an `f32` is rounded to its precision.
val got := lowered("add neg mix", """
def add(a: u8, b: u8): u8 { return a + b; }
def neg(a: i16): i16 { return -a; }
def mix(a: i32, b: f32): f32 { return a as f32 * b; }
def clamp(a: i64): i64 { return a < 0 ? 0 : a; }
def both(a: bool, b: bool): bool { return a && !b; }
""");
t.expects(lowers_as(&got, """
b0(v0: i64, v1: i64):
v2 = add v0, v1
v3 = wrap v2, 8, unsigned
ret v3
b0(v0: i64):
v1 = neg v0
v2 = wrap v1, 16, signed
ret v2
b0(v0: i64, v1: f64):
v2 = itof v0
v3 = fsingle v2
v4 = fmul v3, v1
v5 = fsingle v4
ret v5
"""));
}
@test def and_or_branch_rather_than_compute(t: &mut tester): void {
# `&&` goes to its right only where its left holds, and `!` swaps where a
# condition goes rather than computing a value.
val got := lowered("both", """
def add(a: u8, b: u8): u8 { return a + b; }
def neg(a: i16): i16 { return -a; }
def mix(a: i32, b: f32): f32 { return a as f32 * b; }
def clamp(a: i64): i64 { return a < 0 ? 0 : a; }
def both(a: bool, b: bool): bool { return a && !b; }
""");
t.expects(lowers_as(&got, """
b0(v0: i64, v1: i64):
branch v0, b1, b3
b1:
branch v1, b3, b2
b2:
v2 = iconst 1
jump b4(v2)
b3:
v3 = iconst 0
jump b4(v3)
b4(v4: i64):
ret v4
"""));
}
@test def structs_live_in_cells_and_return_by_address(t: &mut tester): void {
# A struct is built in a cell, what its fields given do not write cleared
# and its default given; a local referred to where the reference cannot be
# kept is held in a cell, and a struct returned in memory is written where
# the call says.
val got := lowered("make main", """
struct pair { var a: i64; var b: i32 = 7; }
def sum(p: pair): i64 { return p.a + p.b as i64; }
def make(): pair { return pair { a = 1 }; }
def bump(x: &mut i64): void { x = x + 1; }
def main(): void {
var n: i64 = 1;
bump(&mut n);
val p := make();
sum(p);
}
""");
t.expects(lowers_as(&got, """
c0: 16, 8
b0:
v0 = cell c0
v1 = iconst 0
store.i64 v0+8, v1
v2 = iconst 1
store.i64 v0, v2
v3 = iconst 7
store.i32 v0+8, v3
ret v0
c0: 8, 8
c1: 16, 8
c2: 16, 8
b0:
v0 = cell c0
v1 = iconst 1
store.i64 v0, v1
call f4(v0)
v2 = cell c1
v3 = cell c2
call f3(v3)
copy v2, v3, 16
v4 = cell c2
copy v4, v2, 16
v5 = call f2(v4)
ret
"""));
}
@test def tests_and_matches_read_the_tag(t: &mut tester): void {
# A union's tag says which field it holds, which a test names and a match
# goes by; a match used as a value without `else` traps where none holds.
val got := lowered("size", """
union shape { var circle: f64; var square: i64; }
def size(s: &shape): i64 {
if s is square(w) {
return w;
}
return match s {
circle(r) => r as i64,
square(w) => w
};
}
""");
t.expects(lowers_as(&got, """
b0(v0: i64):
v1 = iconst 0
v2 = load.i64 v0
v3 = iconst 1
v4 = eq v2, v3
branch v4, b1, b2(v1)
b1:
v5 = load.i64 v0+8
jump b2(v5)
b2(v6: i64):
branch v4, b9, b3
b3:
v7 = load.i64 v0
v8 = iconst 0
v9 = eq v7, v8
branch v9, b7, b4
b4:
v10 = load.i64 v0
v11 = iconst 1
v12 = eq v10, v11
branch v12, b6, b5
b5:
trap not_member
b6:
v13 = load.i64 v0+8
jump b8(v13)
b7:
v14 = load.f64 v0+8
v15 = ftoi v14
jump b8(v15)
b8(v16: i64):
ret v16
b9:
ret v6
"""));
}
@test def traits_dispatch_through_vtables_and_closures_capture_where_they_can_be_reached(t: &mut tester): void {
# A call through a trait reference goes through its vtable, and a reference to
# a value becomes one to a trait by its vtable, the value known while compiling
# held where the statement holds it. A local an anonymous function captures is
# held where its environment refers to it, both cells of the frame.
val got := lowered("call main <lambda>", """
trait named { def name(&this): i64; }
struct one : named { var n: i64; }
def one::name(&this): i64 { return this.n; }
def call(x: &named): i64 { return x.name(); }
def main(): void {
val o := one { n = 3 };
call(&o);
var k: i64 = 5;
val f := def(x: i64): i64 { return x + k; };
f(1);
}
""");
t.expects(lowers_as(&got, """
b0(v0: i64, v1: i64):
v2 = call_trait s2[0](v0, v1)
ret v2
c0: 8, 8
c1: 8, 8
c2: 8, 8
c3: 8, 8
b0:
v0 = cell c0
v1 = cell c1
v2 = iconst 3
store.i64 v1, v2
copy v0, v1, 8
v3 = iconst 0
v4 = call f3(v0, v3)
v5 = cell c2
v6 = iconst 5
store.i64 v5, v6
v7 = iconst 5
v8 = cell c3
store.i64 v8, v5
v9 = iconst 1
v10 = call_value s3(v7, v8, v9)
ret
b0(v0: i64, v1: i64):
v2 = load.i64 v1
v3 = load.i64 v2
v4 = add v0, v3
ret v4
"""));
}
# What a walk of the escape tests walks.
struct escape_body {
var n: i64; # Its number.
}
# A walk holding a reference to what it walks.
struct escape_walk {
var of: &escape_body; # What it walks.
}
# A walk of a body, which holds a reference to it.
def escape_body::walk(&this): escape_walk {
return escape_walk { of = this };
}
# The number a walk of a body local to the frame reads.
def escape_walked(n: i64): i64 {
var made := escape_body { n = n };
val walk := made.walk();
return walk.of.n;
}
# Gives each element of a vector to a function.
def escape_each_of(xs: &vector<i64>, f: def(&i64): void): void {
for &x in xs {
f(x);
}
}
# The sum of a vector's elements, through a closure writing a local of the frame.
def escape_sum_of(xs: &vector<i64>): i64 {
var total: i64 = 0;
escape_each_of(xs, def(x: &i64): void { total += x; });
return total;
}
@test def references_and_closures_refer_to_what_their_frames_hold(t: &mut tester): void {
# A walk and a closure refer to what the frame making them holds, where it is,
# so each sees it changed, and those made in a function read and write its
# frame while it runs.
var held := escape_body { n = 4 };
val a := held.walk();
var k: i64 = 5;
val f := def(): i64 { return k; };
held.n = 11;
k = 9;
var xs := vector::<i64>::new();
xs.append(1);
xs.append(2);
xs.append(3);
t.expects(a.of.n == 11 && escape_walked(7) == 7 && f() == 9 && escape_sum_of(&xs) == 6);
}
@test def a_value_called_through_invoke_is_referred_to_where_it_is(t: &mut tester): void {
# A value called as `a(2)` is the `this` of its `invoke`, which cannot keep it,
# so it stays in a cell of the frame as it does for `a.invoke(2)`, and a
# function calling a parameter so keeps nothing of it.
val got := lowered("main apply", """
struct adder { var total: i64; }
def adder::invoke(&mut this, by: i64): i64 { this.total += by; return this.total; }
def apply(f: &mut adder): i64 { return f(1); }
def main(): void {
var a := adder { total = 0 };
a(2);
apply(&mut a);
}
""");
val text := got.span;
var boxed := false;
for i in 0..text.length {
boxed = boxed || text.substr(i, 3) == "box";
}
t.expects(text.substr(0, 4) == "c0: " && !boxed);
}
@test def values_made_down_one_branch_close_where_made(t: &mut tester): void {
# What a statement makes that closes is closed where it ends, where it was made,
# and a local where its scope ends.
val got := lowered("pick hold", """
import std;
struct handle : owning { var n: i64; }
def handle::close(&mut this): void { this.n = 0; }
def make(): handle { return handle { n = 1 }; }
def peek(h: &handle): i64 { return h.n; }
def pick(c: bool): i64 { return c ? peek(&make()) : 0; }
def hold(): void {
val h := make();
peek(&h);
}
""", """
module std; module core;
pub trait owning { def close(&mut this): void; }
""");
t.expects(lowers_as(&got, """
c0: 8, 8
b0(v0: i64):
v1 = iconst 0
branch v0, b2, b1
b1:
v2 = iconst 0
jump b3(v2, v1)
b2:
v3 = cell c0
call f2(v3)
v4 = iconst 1
v5 = call f3(v3)
jump b3(v5, v4)
b3(v6: i64, v7: i64):
branch v7, b4, b5
b4:
v8 = cell c0
call f1(v8)
v9 = iconst 0
jump b5
b5:
ret v6
c0: 8, 8
c1: 8, 8
b0:
v0 = cell c0
v1 = cell c1
call f2(v1)
v2 = iconst 1
copy v0, v1, 8
v3 = call f3(v0)
call f1(v0)
ret
"""));
}
@test def loops_lower_with_their_variables_at_their_heads(t: &mut tester): void {
# Variables a loop changes arrive at its head as parameters, and a loop over a
# fixed array walks its elements by address.
val got := lowered("steps total", """
def steps(start: u64): u64 {
var n := start;
var count: u64 = 0;
while n != 1 {
if n % 2 == 0 { n = n / 2; } else { n = 3 * n + 1; }
count += 1;
}
return count;
}
def total(xs: &i64[4]): i64 {
var sum: i64 = 0;
for x in xs {
sum += x;
}
return sum;
}
def first_even(xs: &i64[4]): i64 {
for i in 0..4 {
if xs[i] % 2 == 0 { return xs[i]; }
if xs[i] < 0 { break; }
}
return -1;
}
""");
t.expects(lowers_as(&got, """
b0(v0: i64):
v1 = iconst 0
jump b1(v0, v1)
b1(v2: i64, v3: i64):
v4 = iconst 1
v5 = ne v2, v4
branch v5, b3, b2
b2:
ret v3
b3:
v6 = iconst 2
v7 = remu v2, v6
v8 = iconst 0
v9 = eq v7, v8
branch v9, b5, b4
b4:
v10 = iconst 3
v11 = mul v10, v2
v12 = iconst 1
v13 = add v11, v12
jump b6(v13)
b5:
v14 = iconst 2
v15 = divu v2, v14
jump b6(v15)
b6(v16: i64):
v17 = iconst 1
v18 = add v3, v17
jump b7
b7:
jump b1(v16, v18)
b0(v0: i64):
v1 = iconst 0
v2 = iconst 4
v3 = iconst 0
jump b1(v3, v1)
b1(v4: i64, v5: i64):
v6 = ltu v4, v2
branch v6, b3, b2
b2:
ret v5
b3:
v7 = iconst 8
v8 = mul v4, v7
v9 = add v0, v8
v10 = load.i64 v9
v11 = add v5, v10
jump b4
b4:
v12 = iconst 1
v13 = add v4, v12
jump b1(v13, v11)
"""));
}