Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-10-28 22:13:49 -05:00
commit 05756094ac
706 files changed
+135430

No files matched your search

File diff suppressed because it is too large. Load diff
+94
View File
@@ -0,0 +1,94 @@
#! @file keymap.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the tests of the key map and the ID index: keys set, replaced, and
#! taken, as many as make it grow, and IDs found by their hash.
import std::testing;
module sakura::analyzer;
@test def key_maps_find_what_they_were_given(t: &mut tester): void {
var made := keymap::new();
t.expects(made.length == 0 && made.get(&7) is none && made.get_or(&7, 3) == 3);
# Enough keys to grow it several times, of IDs paired as the checker pairs
# them, and 0, which is a key like any other.
var fresh := true;
for i in 1..2001 {
fresh = made.insert(pair_key(i as u32, (i * 7) as u32), i as u32) && fresh;
}
t.expects(fresh && made.insert(0, 99));
t.expects(made.length == 2001 && made.capacity * 3 >= made.length * 4);
var found := true;
for i in 1..2001 {
found = found && made.get_or(&pair_key(i as u32, (i * 7) as u32), 0xFFFFFFFF) == i as u32;
}
t.expects(found && made.get_or(&0, 0) == 99);
# Inserting keeps the value held, and setting replaces it.
t.expects(!made.insert(pair_key(5, 35), 1) && made.get_or(&pair_key(5, 35), 0) == 5);
made.set(pair_key(5, 35), 1);
t.expects(made.get_or(&pair_key(5, 35), 0) == 1 && made.length == 2001);
}
@test def key_maps_find_the_rest_once_one_is_taken(t: &mut tester): void {
var made := keymap::new();
for i in 0..3000 {
made.set(i as u64 * 16, i as u32);
}
# Every third key is taken, and the rest are still found, wherever the keys
# after each taken one moved back to.
for i in 0..3000 {
if i % 3 == 0 {
made.remove(&(i as u64 * 16));
}
}
t.expects(made.length == 2000);
var right := true;
for i in 0..3000 {
val found := made.get(&(i as u64 * 16));
right = right && (i % 3 == 0 ? found is none : found.unwrap_or(0xFFFFFFFF) == i as u32);
}
t.expects(right);
made.clear();
t.expects(made.length == 0 && !made.contains(&16));
made.set(16, 4);
t.expects(made.get_or(&16, 0) == 4);
}
@test def id_indexes_walk_the_ids_of_a_hash(t: &mut tester): void {
var made := id_index::new();
t.expects(made.next(&mut made.walk(7 << 32)) == 0);
made.add(7 << 32, 1);
made.add(9 << 32, 2);
made.add(7 << 32 | 5, 4);
# A walk gives one more than each ID whose hash shares its top half, in the
# order they were added, then 0.
var walk := made.walk(7 << 32);
t.expects(made.next(&mut walk) == 2 && made.next(&mut walk) == 5 && made.next(&mut walk) == 0);
walk = made.walk(9 << 32);
t.expects(made.next(&mut walk) == 3 && made.next(&mut walk) == 0);
walk = made.walk(8 << 32);
t.expects(made.next(&mut walk) == 0);
# As many as make it grow are each still found.
for i in 0..5000 {
made.add(mix(0, i as u64), (i + 10) as u32);
}
var found := true;
for i in 0..5000 {
var each := made.walk(mix(0, i as u64));
var at := made.next(&mut each);
while at != 0 && at != (i + 11) as u32 {
at = made.next(&mut each);
}
found = found && at == (i + 11) as u32;
}
t.expects(found && made.length == 5003);
}
+204
View File
@@ -0,0 +1,204 @@
#! @file lexer.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the tests of the lexer: the kinds of tokens text makes, where they
#! are, and what it reports.
import std::testing;
module sakura::analyzer;
@test def keywords_lex_as_their_kinds(t: &mut tester): void {
t.expects(lexes_as("def mut import continue null", tk::kw_def, tk::kw_mut, tk::kw_imp, tk::kw_cont, tk::kw_null));
t.expects(lexes_as("is not as where when", tk::kw_is, tk::kw_not, tk::kw_as, tk::kw_where, tk::kw_when));
}
@test def words_keep_their_ids(t: &mut tester): void {
val lexing := lex("this get set type_of thing thing");
val syntax := &lexing.syntax;
t.expects(syntax.token(0, &lexing.names).kind == tk::name && syntax.token(0, &lexing.names).name == names::this_id);
t.expects(syntax.token(1, &lexing.names).name == names::get_id);
t.expects(syntax.token(2, &lexing.names).name == names::set_id);
t.expects(syntax.token(3, &lexing.names).name == names::type_of_id);
# A name is interned once, so each place it is written has the same ID.
t.expects(syntax.token(4, &lexing.names).name == syntax.token(5, &lexing.names).name && syntax.token(4, &lexing.names).name > names::type_of_id);
t.expects(syntax.token(6, &lexing.names).kind == tk::eof);
}
@test def tokens_know_where_they_are(t: &mut tester): void {
val lexing := lex("val name\n >>= 12u");
val syntax := &lexing.syntax;
t.expects(syntax.token(0, &lexing.names).offset == 0 && syntax.token(0, &lexing.names).length == 3);
t.expects(syntax.token(1, &lexing.names).offset == 5 && syntax.token(1, &lexing.names).length == 4);
t.expects(syntax.token(2, &lexing.names).offset == 12 && syntax.token(2, &lexing.names).length == 3);
# `>>=` is followed by tokens of what is left of it, `>=` and `=`.
t.expects(syntax.token(3, &lexing.names).offset == 13 && syntax.token(3, &lexing.names).length == 2);
t.expects(syntax.token(4, &lexing.names).offset == 14 && syntax.token(4, &lexing.names).length == 1);
t.expects(syntax.token(5, &lexing.names).offset == 16 && syntax.token(5, &lexing.names).length == 3);
t.expects(lexing.source.lines.length == 2);
}
@test def sources_find_where_their_lines_begin(t: &mut tester): void {
val made := source::from("lines.sakura", "one\n\nthree\n");
t.expects(made.lines.length == 4);
t.expects(made.lines.at(1) == 4 && made.lines.at(2) == 5 && made.lines.at(3) == 11);
val at := made.lines.place_of(6);
t.expects(at.line == 3 && at.column == 2);
}
@test def windows_line_breaks_read_as_those_of_other_systems(t: &mut tester): void {
val made := source::from("lines.sakura", "one\r\n\r\nthree\r\n");
t.expects(made.length == 11);
t.expects(made.lines.length == 4);
t.expects(made.lines.at(1) == 4 && made.lines.at(2) == 5 && made.lines.at(3) == 11);
# A CR on its own is no line break, and stays.
val alone := source::from("alone.sakura", "a\rb\r");
t.expects(alone.length == 4 && alone.lines.length == 1);
# A literal spanning lines holds the LF alone, wherever its text came from.
val crlf := lex("val a := \"\"\"\r\n x\r\n \"\"\";\r\n# note\r\nval b := 1;\r\n");
val lf := lex("val a := \"\"\"\n x\n \"\"\";\n# note\nval b := 1;\n");
t.expects(crlf.syntax.token_kinds.length == lf.syntax.token_kinds.length);
for i in 0..lf.syntax.token_kinds.length {
val ours := crlf.syntax.token(i as u32, &crlf.names);
val theirs := lf.syntax.token(i as u32, &lf.names);
t.expects(ours.kind == theirs.kind && ours.offset == theirs.offset
&& crlf.source.make_lexeme(ours.offset as u64, ours.length as u64) == lf.source.make_lexeme(theirs.offset as u64, theirs.length as u64));
}
}
@test def numbers(t: &mut tester): void {
t.expects(lexes_as("1 12u 1.5 2f 0xff 0o17 0b101", tk::signed, tk::unsigned, tk::float, tk::float, tk::signed, tk::signed, tk::signed));
t.expects(lexes_as("0xFFu 0o17u 0b101u", tk::unsigned, tk::unsigned, tk::unsigned));
# An exponent makes a float, with or without a fraction or a sign, and `e` among
# hexadecimal digits is a digit.
t.expects(lexes_as("6.02e23 1e-9 2E+10 3e5f 0x1e5", tk::float, tk::float, tk::float, tk::float, tk::signed));
t.expects(lexes_as("1e", tk::bad_number));
t.expects(lexes_as("2ex", tk::bad_number));
t.expects(lexes_as("1e5u", tk::bad_number));
# A fraction cannot be unsigned, and a suffix comes once.
t.expects(lexes_as("1.5u", tk::bad_number));
t.expects(lexes_as("1uf", tk::bad_number));
t.expects(lexes_as("2fu", tk::bad_number));
# `0..n` is a range, not a number with a fraction.
t.expects(lexes_as("0..n", tk::signed, tk::cascade, tk::name));
val bad := lex("val a := 0x;\nval b := 12ab;");
t.expects(bad.syntax.token_kinds.at(4) == tk::bad_number);
t.expects(lex_noted(&bad, 1, 10, ec::token));
t.expects(lex_noted(&bad, 2, 10, ec::token));
}
@test def operators_munch_as_much_as_they_can(t: &mut tester): void {
t.expects(lexes_as("... .. :: := => <<= <", tk::spread, tk::cascade, tk::scope, tk::colon, tk::assign, tk::arrow, tk::lshifteq, tk::less));
t.expects(lexes_as("a++ && b-- || !c != d", tk::name, tk::increment, tk::logand, tk::name, tk::decrement, tk::logor, tk::negate, tk::name, tk::noteq, tk::name));
}
@test def a_greater_than_is_followed_by_what_is_left_of_it(t: &mut tester): void {
# Each `>` and `=` after the first `>` of an operator begins a token of what is
# left of it, so a `>` closing type arguments always has a token of its own.
t.expects(lexes_as(">", tk::more));
t.expects(lexes_as(">>", tk::rshift, tk::more));
t.expects(lexes_as(">=", tk::moreeq, tk::assign));
t.expects(lexes_as(">>=", tk::rshifteq, tk::moreeq, tk::assign));
t.expects(lexes_as(">>>=", tk::rshift, tk::more, tk::moreeq, tk::assign));
# What is left ends where the operator does.
t.expects(lexes_as(">==", tk::moreeq, tk::assign, tk::assign));
t.expects(lexes_as("> > =", tk::more, tk::more, tk::assign));
}
@test def comments_are_skipped(t: &mut tester): void {
t.expects(lexes_as("a # a comment\n#! documentation\nb", tk::name, tk::name));
# Both are kept for the token after them, documentation apart from the rest.
val lexing := lex("a # a comment\n#! documentation\nb");
val syntax := &lexing.syntax;
t.expects(syntax.comments.length == 1 && syntax.docs.length == 1);
t.expects(lexing.source.make_lexeme(syntax.comments.at(0).offset, syntax.comments.at(0).length) == "# a comment");
t.expects(syntax.comments.at(0).token == 1 && syntax.docs.at(0).token == 1);
}
@test def strings_and_characters(t: &mut tester): void {
t.expects(lexes_as("\"text\" 'c' '\\n' \"\\x41\\{\"", tk::string, tk::char, tk::char, tk::string));
val lexing := lex("\"\\q\" 'ab' '' 'é'");
t.expects(lex_noted(&lexing, 1, 2, ec::escape));
t.expects(lex_noted(&lexing, 1, 6, ec::char));
t.expects(lex_noted(&lexing, 1, 11, ec::char));
t.expects(lexing.notes.length == 3);
}
@test def text_that_is_never_closed(t: &mut tester): void {
val lexing := lex("val s := \"open\nval c := 'x\n");
t.expects(lexing.syntax.token_kinds.at(4) == tk::bad_quote);
t.expects(lex_noted(&lexing, 1, 10, ec::token));
t.expects(lex_noted(&lexing, 2, 10, ec::token));
}
@test def text_spanning_lines(t: &mut tester): void {
val good := lex("val s := \"\"\"\n one\n\n two\n \"\"\";");
t.expects(good.notes.length == 0);
t.expects(good.syntax.token_kinds.at(4) == tk::string);
# Text on the opening line, the closing quotes after text, and a line indented
# less than the closing quotes.
t.expects(lex_noted(&lex("val s := \"\"\" x\n \"\"\";"), 1, 10, ec::block));
t.expects(lex_noted(&lex("val s := \"\"\"\n x \"\"\";"), 2, 1, ec::block));
t.expects(lex_noted(&lex("val s := \"\"\"\n x\n \"\"\";"), 2, 1, ec::block));
}
@test def interpolated_strings_split_at_their_holes(t: &mut tester): void {
t.expects(lexes_as("$\"plain\"", tk::istring));
t.expects(lexes_as("$\"a{b}c{d}e\"", tk::istring_beg, tk::name, tk::istring_mid, tk::name, tk::istring_end));
# Braces within a hole are counted, so a struct literal there closes nothing.
t.expects(lexes_as("$\"{p{ x = 1 }}\"", tk::istring_beg, tk::name, tk::lbrace, tk::name, tk::assign, tk::signed, tk::rbrace, tk::istring_end));
# A string within a hole holds holes of its own.
t.expects(lexes_as("$\"a{$\"b{c}\"}\"", tk::istring_beg, tk::istring_beg, tk::name, tk::istring_end, tk::istring_end));
# A block's holes may span lines, where a line's may not.
t.expects(lexes_as("$\"\"\"\n {a +\n b}\n \"\"\"", tk::istring_beg, tk::name, tk::plus, tk::name, tk::istring_end));
t.expects(lex("$\"\"\"\n {a}\n \"\"\"").notes.length == 0);
}
@test def escapes_within_interpolated_strings(t: &mut tester): void {
val lexing := lex("$\"\\{ {a} \\q\"");
t.expects(lexing.notes.length == 1);
t.expects(lex_noted(&lexing, 1, 10, ec::escape));
}
@test def unknown_characters_are_reported_and_dropped(t: &mut tester): void {
val lexing := lex("a ` b");
t.expects(lex_noted(&lexing, 1, 3, ec::token));
t.expects(lexes_as("a ` b", tk::name, tk::name));
# A character beyond ASCII is reported once, however many bytes it takes.
val wide := lex("a é b");
t.expects(wide.notes.length == 1 && lex_noted(&wide, 1, 3, ec::token));
t.expects(wide.notes.at(0).length == 2);
t.expects(lexes_as("a é b", tk::name, tk::name));
}
@test def names_outlive_the_text_they_were_read_in(t: &mut tester): void {
var table := names::new();
var text := string::from("fresh_name", nothing {});
val view := text.view();
val id := table.intern(&view);
# The text a name was read in may change or go, as an editor's does.
text.at(0) = 'X';
val again: strview = "fresh_name";
t.expects(table.intern(&again) == id);
}
+19
View File
@@ -0,0 +1,19 @@
#! @file names.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the test that the reserved words follow the keywords, where the
#! names table interns them.
import std::testing;
module sakura::analyzer;
@test def reserved_words_follow_the_keywords(t: &mut tester): void {
var table := names::new();
t.expects(table.is_keyword(table.intern("while")) && !table.is_keyword(table.intern("this")));
t.expects(table.is_reserved(table.intern("this")) && table.is_reserved(table.intern("_")));
t.expects(!table.is_reserved(table.intern("get")) && !table.is_reserved(table.intern("thing")));
}
+285
View File
@@ -0,0 +1,285 @@
#! @file parser.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the tests of the parser: the trees declarations, statements, and
#! expressions parse into, as `syntax::print` writes them.
import std::testing;
module sakura::analyzer;
# What each test expects is the tree `syntax::print` gives, where a node is
# `(kind:text slots...)`, or `kind:text` where its slots hold nothing.
@test def assignment_else_and_ternaries_group_to_the_right(t: &mut tester): void {
t.expects(expression("a = b += c").view() ==
"(assign:= name:a (assign:+= name:b name:c))");
t.expects(expression("c ? d : e ? f : g").view() ==
"(ternary name:c name:d (ternary name:e name:f name:g))");
t.expects(expression("p else q else r").view() ==
"(fallback name:p _ (fallback name:q _ name:r))");
t.expects(expression("x = p else q").view() ==
"(assign:= name:x (fallback name:p _ name:q))");
# The branch taken where the condition holds ends at `:`, so it may be a
# fallback, and one after `:` takes the whole ternary, as before.
t.expects(expression("c ? p else q : r").view() ==
"(ternary name:c (fallback name:p _ name:q) name:r)");
t.expects(expression("c ? p else q ? s : t : r").view() ==
"(ternary name:c (fallback name:p _ (ternary name:q name:s name:t)) name:r)");
t.expects(expression("c ? p else (e) { return; } : r").view() ==
"(ternary name:c (fallback name:p name:e (block [return_stmt])) name:r)");
t.expects(expression("c ? p : q else r").view() ==
"(fallback (ternary name:c name:p name:q) _ name:r)");
}
@test def binary_operators_group_by_precedence(t: &mut tester): void {
t.expects(expression("a || b && c | d ^ e & f == g < h << i + j * k").view() ==
"(binary:|| name:a (binary:&& name:b (binary:| name:c (binary:^ name:d (binary:& name:e (binary:== name:f (binary:< name:g (binary:<< name:h (binary:+ name:i (binary:* name:j name:k))))))))))");
t.expects(expression("-m as u8 + n").view() ==
"(binary:+ (cast (unary:- name:m) type_name:u8) name:n)");
t.expects(expression("true != null").view() ==
"(binary:!= boolean:true null_lit:null)");
}
@test def is_tests_values_fields_and_types(t: &mut tester): void {
t.expects(expression("!k is not value(&mut v)").view() ==
"(is_test (unary:! name:k) type_name:value (reference:& name:v {mutable}) {negated})");
t.expects(expression("r is error(why)").view() ==
"(is_test name:r type_name:error name:why)");
t.expects(expression("x is (d)").view() ==
"(is_test name:x name:d _ {computed})");
t.expects(expression("T is copyable && T is not moveable").view() ==
"(binary:&& (is_test name:T type_name:copyable _) (is_test name:T type_name:moveable _ {negated}))");
t.expects(expression("type_of(d) is numeric").view() ==
"(is_test (type_of:type_of name:d) type_name:numeric _)");
t.expects(expression("box::<T> is Shown").view() ==
"(is_test (path:box [(segment:box [type_name:T])]) type_name:Shown _)");
}
@test def postfix_operators_bind_tightest(t: &mut tester): void {
t.expects(expression("w.f(1)[2]++").view() ==
"(postfix:++ (index (call (member:f name:w []) [number:1]) number:2))");
t.expects(expression("xs[a:] + xs[:n] + xs[a:n]").view() ==
"(binary:+ (binary:+ (slice name:xs name:a _) (slice name:xs _ name:n)) (slice name:xs name:a name:n))");
t.expects(expression("x.(d)").view() ==
"(member_of name:x name:d)");
t.expects(expression("value_of(d)::<i64>").view() ==
"(type_args (call name:value_of [name:d]) [type_name:i64])");
t.expects(expression("max::<u8>(a, ...xs)").view() ==
"(call (path:max [(segment:max [type_name:u8])]) [name:a (unary name:xs)])");
t.expects(expression("std::io::print").view() ==
"(path:std [segment:std segment:io segment:print])");
t.expects(expression("*p = &mut x").view() ==
"(assign:= (unary:* name:p) (reference:& name:x {mutable}))");
}
@test def else_names_the_error_only_before_a_block(t: &mut tester): void {
t.expects(expression("f(1) else 0").view() ==
"(fallback (call name:f [number:1]) _ number:0)");
t.expects(expression("f(1) else (e) { return; }").view() ==
"(fallback (call name:f [number:1]) name:e (block [return_stmt]))");
t.expects(expression("f(1) else (e) + 1").view() ==
"(fallback (call name:f [number:1]) _ (binary:+ name:e number:1))");
t.expects(expression("f(1) else { return; }").view() ==
"(fallback (call name:f [number:1]) _ (block [return_stmt]))");
}
@test def literals_lambdas_and_matches(t: &mut tester): void {
t.expects(expression("point{ x = 1, 2 }").view() ==
"(construct type_name:point [(field_init:x number:1 {named}) (field_init:2 number:2)])");
t.expects(expression("[1, 2, 3,]").view() ==
"(array [number:1 number:2 number:3])");
t.expects(expression("def(a, b: i64) => a + b").view() ==
"(lambda [param:a (param:b type_name:i64 _)] _ (binary:+ name:a name:b))");
t.expects(expression("def(): i64 { return 1; }").view() ==
"(lambda [] type_name:i64 (block [(return_stmt number:1)]))");
t.expects(statements("val v := match k { 1, 2 => a, else => b };").view() ==
"(variable:v [] _ _ (match_value name:k [(match_arm:1 [number:1 number:2] name:a) (match_arm [] name:b)]))");
t.expects(expression("$\"a{b}c{d + 1}e\"").view() ==
"(istring:$\"a{ [string:$\"a{ name:b string:}c{ (binary:+ name:d number:1) string:}e\"])");
t.expects(expression("$\"plain\"").view() ==
"(istring:$\"plain\" [string:$\"plain\"])");
}
@test def conditions_and_jumps(t: &mut tester): void {
t.expects(statements("if a {} else if b {} else {}").view() ==
"(if_stmt name:a block (if_stmt name:b block block))");
t.expects(statements("if const T is integer {}").view() ==
"(if_const (is_test name:T type_name:integer _) block _)");
t.expects(statements("if x == y { }").view() ==
"(if_stmt (binary:== name:x name:y) block _)");
t.expects(statements("return x if a;").view() ==
"(if_stmt name:a (block [(return_stmt name:x)]) _)");
t.expects(statements("break if const n > 1;").view() ==
"(if_const (binary:> name:n number:1) (block [break_stmt]) _)");
}
@test def loops_and_matches(t: &mut tester): void {
t.expects(statements("for i, &mut x in xs {}").view() ==
"(for_stmt name:i name:x name:xs _ {mutable,reference} block)");
t.expects(statements("for const x in args {}").view() ==
"(for_stmt _ name:x name:args _ {constant} block)");
t.expects(statements("for i in 0..n {}").view() ==
"(for_stmt _ name:i number:0 name:n block)");
# A loop counts through a range written in place itself, and walks one
# made as a value otherwise.
t.expects(statements("for i in 0..=n {}").view() ==
"(for_stmt _ name:i number:0 name:n {inclusive} block)");
t.expects(statements("for i in (0..n).rev() {}").view() ==
"(for_stmt _ name:i (call (member:rev (range:.. number:0 name:n) []) []) _ block)");
t.expects(statements("while a { continue; }").view() ==
"(while_stmt name:a (block [continue_stmt]))");
t.expects(statements("match k { 1 => a(); else => { b(); } }").view() ==
"(match_stmt name:k [(match_arm:1 [number:1] (block:a [(expr_stmt:a (call name:a []))])) (match_arm [] (block [(expr_stmt:b (call name:b []))]))])");
}
@test def ranges_are_written_as_values(t: &mut tester): void {
# `..` and `..=` bind looser than every binary operator, and tighter than
# `?:`.
t.expects(expression("a + 1..b * 2").view() == "(range:.. (binary:+ name:a number:1) (binary:* name:b number:2))");
t.expects(expression("lo..=hi").view() == "(range:..= name:lo name:hi)");
t.expects(expression("f(0..n, 1..=2)").view() == "(call name:f [(range:.. number:0 name:n) (range:..= number:1 number:2)])");
}
@test def locals_and_local_functions(t: &mut tester): void {
t.expects(statements("val x := 1; var y: i64; const z: u8 = 2;").view() ==
"(variable:x [] _ _ number:1) (variable:y [] _ type_name:i64 _ {mutable}) (variable:z [] _ type_name:u8 number:2 {constant})");
t.expects(statements("def local(a: i64): i64 { return a; }").view() ==
"(variable:local [] _ _ (lambda [(param:a type_name:i64 _)] type_name:i64 (block [(return_stmt name:a)])) {function})");
t.expects(statements("when os == linux { f(); } else when !(arch != x86_64) {} else {}").view() ==
"(when_block (binary:== name:os name:linux) (block [(expr_stmt:f (call name:f []))]) (when_block (unary:! (binary:!= name:arch name:x86_64)) block block))");
}
@test def contracts_are_statements_their_words_begin(t: &mut tester): void {
t.expects(statements("expects(b != 0); asserts(ok, \"Fine.\"); ensures(r: r > old(n));").view() ==
"(contract:expects (binary:!= name:b number:0) _ _) (contract:asserts name:ok _ string:\"Fine.\") (contract:ensures (binary:> name:r (old_value:old name:n)) name:r _)");
# Anywhere else, each word is a name, and `old` is one outside an `ensures`.
t.expects(statements("t.expects(x); f(asserts); ensures = 1; val v := old(2); asserts + 1;").view() ==
"(expr_stmt:t (call (member:expects name:t []) [name:x])) (expr_stmt:f (call name:f [name:asserts])) (expr_stmt:ensures (assign:= name:ensures number:1)) (variable:v [] _ _ (call name:old [number:2])) (expr_stmt:asserts (binary:+ name:asserts number:1))");
}
@test def undefined_is_a_variables_value_alone(t: &mut tester): void {
# Anywhere but as the whole of a variable's value, the word is a name.
t.expects(statements("var b: u8[4] = undefined; var u := undefined + 1; val undefined := 2;").view() ==
"(variable:b [] _ (type_fixed type_name:u8 number:4) undefined:undefined {mutable}) (variable:u [] _ _ (binary:+ name:undefined number:1) {mutable}) (variable:undefined [] _ _ number:2)");
}
@test def imports_modules_and_when(t: &mut tester): void {
t.expects(tree("import std::io;").view() ==
"(document [(import_decl (path:std [segment:std segment:io]))])");
t.expects(tree("module a::b when os == linux && backend == vm;").view() ==
"(document [(module_decl (path:a [segment:a segment:b]) (binary:&& (binary:== name:os name:linux) (binary:== name:backend name:vm)))])");
t.expects(tree("when os == linux { def f(): void {} } else { val x := 1; }").view() ==
"(document [(when_block (binary:== name:os name:linux) (block [(function:f [] _ [] [] type_name:void block)]) (block [(variable:x [] _ _ number:1)]))])");
}
@test def extern_names_libraries_and_sections_of_c(t: &mut tester): void {
t.expects(tree("extern import \"libc.so.6\" when os == linux; extern module c when os == linux; extern module d;").view() ==
"(document [(extern_import string:\"libc.so.6\" (binary:== name:os name:linux)) (extern_module path:c (binary:== name:os name:linux)) (extern_module path:d _)])");
# `extern` begins an import of a library or a section, and a library is text.
val stray := parse("extern def f(): void;");
t.expects(noted(&stray, 1, 8, ec::token));
val unnamed := parse("extern import libc;");
t.expects(noted(&unnamed, 1, 15, ec::token));
}
@test def functions(t: &mut tester): void {
t.expects(tree("@doc{ text = \"x\" } pub def box<T>::map<U>(&mut this, f: def(T): U, n: u64 = 0, xs: U...): box<U> where T: copyable where U: equatable, hashable;").view() ==
"(document [(function:map [(attribute type_name:doc [(field_init:text string:\"x\" {named})])] (type_name:box [(segment:box [(type_param:T [type_name:copyable])])]) [(type_param:U [type_name:equatable type_name:hashable])] [(param:this _ _ {mutable}) (param:f (type_func [type_name:T] type_name:U) _) (param:n type_name:u64 number:0) (param:xs type_name:U _ {variadic})] (type_name:box [(segment:box [type_name:U])]) _ {exported})])");
t.expects(tree("const def zero(): i64 { return 0; }").view() ==
"(document [(function:zero [] _ [] [] type_name:i64 (block [(return_stmt number:0)]) {constant})])");
}
@test def structs_unions_and_traits(t: &mut tester): void {
t.expects(tree("struct pair<A, Bs...> : copyable { var a: A; val b: ...base{ x as y }; }").view() ==
"(document [(struct_decl:pair [] _ [type_param:A (type_param:Bs [] {packed})] [type_name:copyable] [(field:a [] _ type_name:A _ {mutable}) (field:b [] _ (spread type_name:base [(rename:x name:y)]) _)])])");
t.expects(tree("union either { var l: i64; var r: str; }").view() ==
"(document [(union_decl:either [] _ [] [] [(field:l [] _ type_name:i64 _ {mutable}) (field:r [] _ type_name:str _ {mutable})])])");
t.expects(tree("trait shown : equatable { def show(&this): str; type cursor: iterator<&T> = span<T>::cursor; val n: u64 { get; } const k: u8; }").view() ==
"(document [(trait_decl:shown [] _ [] [type_name:equatable] [(function:show [] _ [] [param:this] type_name:str _) (assoc_type:cursor [] [(type_name:iterator [(segment:iterator [(type_ref:& type_name:T)])])] (type_name:span [(segment:span [type_name:T]) segment:cursor])) (property:n [] _ type_name:u64 [(accessor:get [(param:this _ _ {implied})] _)]) (variable:k [] _ type_name:u8 _ {constant})])])");
}
@test def trait_methods_bound_the_traits_parameters_and_self(t: &mut tester): void {
# A trait's method may bound the trait's parameters or `self` beyond what the
# trait does, which the record keeps apart from its own parameters.
t.expects(tree("trait shelf<T> { def total(&this): T where T: numeric; def tagged<U>(&this): U where self: labeled where U: shown; }").view() ==
"(document [(trait_decl:shelf [] _ [type_param:T] [] [(function:total [] _ [] [param:this] type_name:T _ [(type_param:T [type_name:numeric])]) (function:tagged [] _ [(type_param:U [type_name:shown])] [param:this] type_name:U _ [(type_param:self [type_name:labeled])])])])");
}
@test def fields_are_pub_where_marked(t: &mut tester): void {
t.expects(tree("struct s { pub var a: i64; @x pub val b: u8; var c: u8; }").view() ==
"(document [(struct_decl:s [] _ [] [] [(field:a [] _ type_name:i64 _ {exported,mutable}) (field:b [(attribute type_name:x [])] _ type_name:u8 _ {exported}) (field:c [] _ type_name:u8 _ {mutable})])])");
val twice := parse("struct s { pub pub var a: i64; }");
t.expects(noted(&twice, 1, 16, ec::token));
}
@test def properties_enums_and_aliases(t: &mut tester): void {
t.expects(tree("pub var rect::area: u64 { get => 1; pub set {} }").view() ==
"(document [(property:area [] (type_name:rect [segment:rect]) type_name:u64 {exported,mutable} [(accessor:get [(param:this _ _ {implied})] (block [(return_stmt number:1)])) (accessor:set [(param:this _ _ {mutable,implied}) (param:value _ _ {implied})] block {exported})])])");
# `=>` gives what a `get` returns, and is what a `set` does; the parameters
# are implied, and written ones refused.
t.expects(tree("var r::w: i64 { get => this.n; set => this.n = value; }").view() ==
"(document [(property:w [] (type_name:r [segment:r]) type_name:i64 {mutable} [(accessor:get [(param:this _ _ {implied})] (block [(return_stmt (member:n name:this []))])) (accessor:set [(param:this _ _ {mutable,implied}) (param:value _ _ {implied})] (block [(expr_stmt (assign:= (member:n name:this []) name:value))]))])])");
val written := parse("var r::w: i64 { get(&this) { return 1; } }");
t.expects(noted(&written, 1, 20, ec::token));
t.expects(tree("enum color : u8 { red, @old green = 2, blue, }").view() ==
"(document [(enumeration:color [] _ type_name:u8 [enumerator:red (enumerator:green [(attribute type_name:old [])] number:2) enumerator:blue])])");
t.expects(tree("type list<T>::cursor = span<T>::cursor where T: copyable;").view() ==
"(document [(alias:cursor [] (type_name:list [(segment:list [type_param:T])]) [] (type_name:span [(segment:span [type_name:T]) segment:cursor]))])");
}
@test def types(t: &mut tester): void {
t.expects(tree("val m: dict<str, vec<i64>> = make();").view() ==
"(document [(variable:m [] _ (type_name:dict [(segment:dict [type_name:str (type_name:vec [(segment:vec [type_name:i64])])])]) (call name:make []))])");
t.expects(tree("val p: *mut u8[4][2] = null; val r: &mut def(u8): bool = f;").view() ==
"(document [(variable:p [] _ (type_ptr:* (type_fixed (type_fixed type_name:u8 number:4) number:2) {mutable}) null_lit:null) (variable:r [] _ (type_ref:& (type_func [type_name:u8] type_name:bool) {mutable}) name:f)])");
t.expects(tree("val t: type_of(d) = x;").view() ==
"(document [(variable:t [] _ (type_of:type_of name:d) name:x)])");
}
@test def spreads_and_patterns_among_types(t: &mut tester): void {
t.expects(tree("val f: def(i64, bool...): u8 = g; val b: box<i64, Ts...> = x;").view() ==
"(document [(variable:f [] _ (type_func [type_name:i64 (type_spread type_name:bool)] type_name:u8) name:g) (variable:b [] _ (type_name:box [(segment:box [type_name:i64 (type_spread type_name:Ts)])]) name:x)])");
t.expects(tree("trait t<def(A, Ts...): R> { type p...; }").view() ==
"(document [(trait_decl:t [] _ [(type_pattern [type_param:A (type_param:Ts [] {packed})] type_param:R)] [] [(assoc_type:p [] [] {packed} _)])])");
}
# A pattern of a fixed array, `L[N]`, names its element's type parameter and its
# length's constant one, among a declaration's type parameters and a receiver's.
@test def array_patterns_among_type_parameters(t: &mut tester): void {
t.expects(tree("struct simd<L[N]> where L: numeric { var lanes: L[N]; }").view() ==
"(document [(struct_decl:simd [] _ [(array_pattern:L (type_param:L [type_name:numeric]) const_param:N)] [] [(field:lanes [] _ (type_fixed type_name:L name:N) _ {mutable})])])");
t.expects(tree("def simd<L[N]>::count(&this): u64 { return N; }").view() ==
"(document [(function:count [] (type_name:simd [(segment:simd [(array_pattern:L type_param:L const_param:N)])]) [] [param:this] type_name:u64 (block [(return_stmt name:N)]))])");
}
@test def a_greater_than_closes_type_arguments_or_operates(t: &mut tester): void {
t.expects(expression("a >> b >= c").view() ==
"(binary:>= (binary:>> name:a name:b) name:c)");
t.expects(expression("a >>= b").view() ==
"(assign:>>= name:a name:b)");
# `>>` and `>>=` close nested type arguments a `>` at a time, and what is left
# after the last is what follows them.
t.expects(expression("x as box<u8>> y").view() ==
"(binary:> (cast name:x (type_name:box [(segment:box [type_name:u8])])) name:y)");
t.expects(expression("x as box<box<u8>>>= y").view() ==
"(binary:>= (cast name:x (type_name:box [(segment:box [(type_name:box [(segment:box [type_name:u8])])])])) name:y)");
t.expects(statements("var v: box<box<u8>>= w;").view() ==
"(variable:v [] _ (type_name:box [(segment:box [(type_name:box [(segment:box [type_name:u8])])])]) name:w {mutable})");
}
# A constant parameter is written `const N: u64`, and is given a value: a literal,
# a name, or an expression of them, within which `>` closes the arguments.
@test def constant_parameters_and_arguments(t: &mut tester): void {
t.expects(tree("struct buffer<T, const N: u64> { var items: T[N]; }").view() ==
"(document [(struct_decl:buffer [] _ [type_param:T (const_param:N [] type_name:u64)] [] [(field:items [] _ (type_fixed type_name:T name:N) _ {mutable})])])");
t.expects(tree("val b: grid<N * 2, M> = x;").view() ==
"(document [(variable:b [] _ (type_name:grid [(segment:grid [(binary:* name:N number:2) type_name:M])]) name:x)])");
t.expects(tree("val p: at<point { x = 1 }, \"t\", -1, [1, 2]> = x;").view() ==
"(document [(variable:p [] _ (type_name:at [(segment:at [(construct type_name:point [(field_init:x number:1 {named})]) string:\"t\" (unary:- number:1) (array [number:1 number:2])])]) name:x)])");
t.expects(expression("make::<N + 1, (a > b)>()").view() ==
"(call (path:make [(segment:make [(binary:+ name:N number:1) (binary:> name:a name:b)])]) [])");
}
+477
View File
@@ -0,0 +1,477 @@
#! @file queries.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the tests of the queries an editor asks of a checked program: what
#! hovering a name shows, what it refers to and where that is written, what
#! may be written at a place, what a call being written calls, and what each
#! name of a file is.
import std::testing;
module sakura::analyzer;
@test def hovering_a_declaration_shows_how_it_is_declared(t: &mut tester): void {
val text := """
#! A point on the plane.
pub struct point {
pub var x: i64; #! Across.
var y: i64 = 7;
}
#! How far across.
#! @param p The point.
pub def across(p: &point): i64 { return p.x; }
def point::moved(&this, by: i64): point { return point { x = this.x + by, y = this.y }; }
enum color: u8 { red, green = 4 }
const limit: u32 = 9;
def f(): void {
var p := point { x = 1 };
val q := p.moved(2);
val c := color::green;
val n := across(&q) + limit as i64;
}
""";
t.expects(hover_of(text, "point {", 0).view() == "pub struct point {\n pub var x: int;\n var y: int;\n}\n\nA point on the plane.");
t.expects(hover_of(text, "x: i64").view() == "pub var x: int\n\nAcross.");
t.expects(hover_of(text, "across(p").view() == "pub def across(p: &point): int\n\nHow far across.\n@param p The point.");
t.expects(hover_of(text, "p: &point").view() == "p: &point\n\nThe point.");
t.expects(hover_of(text, "moved(2)").view() == "def point::moved(this: &point, by: int): point");
t.expects(hover_of(text, "color: u8").view() == "enum color: u8 {\n red = 0,\n green = 4,\n}");
t.expects(hover_of(text, "green;").view() == "color::green = 4");
t.expects(hover_of(text, "limit as").view() == "const limit: u32");
t.expects(hover_of(text, "p := point").view() == "var p: point");
t.expects(hover_of(text, "q := p").view() == "val q: point");
t.expects(hover_of(text, "y = this", 0).view() == "var y: int");
t.expects(hover_of(text, "i64; #!").view() == "type int");
t.expects(hover_of(text, "return p.x").view() == "");
}
@test def hovering_names_through_modules_and_generics(t: &mut tester): void {
val lib := """
module shapes;
pub struct box<T> { pub var item: T; }
pub def box<T>::get(&this): T { return this.item; }
""";
val text := """
import shapes;
def f(b: shapes::box<u8>): u8 { return b.item + b.get(); }
""";
t.expects(asked(def(c: &mut checker): string {
var made := string::new(nothing {});
var at := c.hover(0, place_in(text, "shapes::box", 0)) else { return made; };
made.append(at.signature.view());
made.append("|");
var box := c.hover(0, place_in(text, "box<u8>")) else { return made; };
made.append(box.signature.view());
made.append("|");
var item := c.hover(0, place_in(text, "item +")) else { return made; };
made.append(item.signature.view());
return made;
}, text, lib).view() == "module shapes|pub struct box<T> {\n pub var item: T;\n}|pub var item: u8");
}
@test def hovering_a_call_writes_a_pack_as_the_types_it_gives(t: &mut tester): void {
val text := """
def count<Ts...>(xs: Ts...): i64 { return 0; }
def f(): i64 { return count(1, true); }
""";
# The pack given for `Ts` is written as notes write it, rather than as `(int, bool)`.
val shown := hover_of(text, "count(1");
t.expects(shown.view().starts_with("def count<int, bool>("));
}
#! Where each place a query gives is, as `line:column` of the file it is in,
#! each file named by its index, joined by spaces.
#! @param c The checker.
#! @param places The places.
#! @returns The text.
def places_text(c: &mut checker, places: &vector<spot>): string {
var made := string::new(nothing {});
for &each in places {
val at := c.units[each.file].source.lines.place_of(each.offset);
val text := $"{each.file}:{at.line}:{at.column}";
if made.length != 0 {
made.append(" ");
}
made.append(text.view());
}
return made;
}
@test def names_go_to_where_they_are_declared(t: &mut tester): void {
val lib := """
module shapes;
pub struct box { pub var w: i64; }
pub def area(b: &box): i64 { return b.w; }
""";
val text := """
import shapes;
def f(n: i64): i64 {
val b := box { w = n };
return area(&b) + b.w + n;
}
""";
t.expects(asked(def(c: &mut checker): string {
var made := string::new(nothing {});
for &needle in ["area(&b)", "w + n", "b.w", "n;", "box {", "w = n", "shapes;", "i64 {"] {
var named := c.name_at(0, place_in(text, needle)) else {
made.append("none|");
continue;
};
var places := vector::<spot>::new();
if named.declared {
places.append(named.declaration);
}
var shown := places_text(c, &places);
made.append(shown.view());
if named.refusal.length != 0 {
made.append("!");
}
made.append("|");
}
return made;
}, text, lib).view() == "1:3:9|1:2:26|0:3:7|0:2:7|1:2:12|1:2:26|1:1:8!|!|");
}
@test def references_are_every_place_a_name_is_written(t: &mut tester): void {
val lib := """
module shapes;
pub struct box { pub var w: i64; }
pub def area(b: &box): i64 { return b.w; }
""";
val text := """
import shapes;
def f(n: i64): i64 {
val b := box { w = n };
return area(&b) + b.w + n;
}
def g(): i64 { return area(&box { w = 2 }); }
""";
t.expects(asked(def(c: &mut checker): string {
var made := string::new(nothing {});
for &needle in ["area(&b)", "w + n", "n;", "b :="] {
var found := c.references(0, place_in(text, needle));
var shown := places_text(c, &found);
made.append(shown.view());
made.append("|");
}
return made;
}, text, lib).view() == "1:3:9 0:4:10 0:6:23|1:2:26 1:3:39 0:3:18 0:4:23 0:6:35|0:2:7 0:3:22 0:4:27|0:3:7 0:4:16 0:4:21|");
}
@test def a_trait_method_is_renamed_with_those_implementing_it(t: &mut tester): void {
val text := """
trait shape { def area(&this): i64; }
struct square : shape { var w: i64; }
def square::area(&this): i64 { return this.w * this.w; }
struct dot {}
def dot::area(&this): i64 { return 0; }
def f(s: &square): i64 { return s.area(); }
""";
t.expects(asked(def(c: &mut checker): string {
var found := c.references(0, place_in(text, "area(&this): i64;"));
return places_text(c, &found);
}, text).view() == "0:1:19 0:3:13 0:6:35");
}
@test def renaming_refuses_what_the_compiler_finds_by_name(t: &mut tester): void {
val text := """
def main(): void { val n: i64 = 1; }
struct box {}
def box::get(&this): i64 { return 0; }
""";
t.expects(asked(def(c: &mut checker): string {
var made := string::new(nothing {});
for &needle in ["main", "i64", "this)", "box {}"] {
var named := c.name_at(0, place_in(text, needle)) else {
made.append("none|");
continue;
};
made.append(named.refusal);
made.append("|");
}
return made;
}, text).view() == "A program begins at the function named `main`.|It is built into the language.|`this` is what every method calls its receiver.||");
}
@test def accessors_name_this_and_value_where_they_are_used(t: &mut tester): void {
val text := """
struct r { var w: i64; }
var r::width: i64 {
get => this.w;
set => this.w = value;
}
""";
t.expects(hover_of(text, "value;").view() == "value: int");
t.expects(hover_of(text, "this.w;").view() == "this: &r");
t.expects(asked(def(c: &mut checker): string {
var made := string::new(nothing {});
for &needle in ["value;", "set =>"] {
var named := c.name_at(0, place_in(text, needle)) else {
made.append("none|");
continue;
};
made.append(named.refusal);
made.append("|");
}
return made;
}, text).view() == "`value` is what every `set` calls what it is given.|none|");
}
@test def renaming_refuses_the_methods_operators_call(t: &mut tester): void {
# A type has `+` by its `add`, so renaming the method would lose the operator,
# but one of the name taking something else than an operand is only a method.
val text := """
struct box { var w: i64; }
def box::add(&this, other: &box): box { return box { w = this.w + other.w }; }
def box::negate(&this): box { return box { w = -this.w }; }
def box::mul(&this, by: &i64, more: &i64): box { return box { w = this.w * by * more }; }
def box::grown(&this): box { return this + this; }
""";
t.expects(asked(def(c: &mut checker): string {
var made := string::new(nothing {});
for &needle in ["add(&this", "negate(&this", "mul(&this", "grown(&this"] {
var named := c.name_at(0, place_in(text, needle)) else {
made.append("none|");
continue;
};
made.append(named.refusal.length != 0 ? "refused|" : "renamed|");
}
return made;
}, text).view() == "refused|refused|renamed|renamed|");
}
@test def hovering_a_function_shows_the_contract_its_body_begins_with(t: &mut tester): void {
val text := """
#! Divides.
def divide(a: i64, b: i64): i64 {
expects(b != 0,
"Nothing is divided by zero.");
ensures(q: q * b + a % b == a);
asserts(b > 0);
return a / b;
}
def f(): void { val q := divide(7, 2); }
""";
t.expects(hover_of(text, "divide(7").view() ==
"def divide(a: int, b: int): int\nexpects(b != 0, \"Nothing is divided by zero.\")\nensures(q: q * b + a % b == a)\n\nDivides.");
}
@test def contracts_are_coloured_as_words_of_the_language(t: &mut tester): void {
val text := "def f(n: i64): i64 { expects(n > 0); ensures(r: r > old(n)); return n + 1; }";
t.expects(asked(def(c: &mut checker): string {
var made := string::new(nothing {});
for &each in c.highlights(0) {
continue if each.kind != symbol::keyword;
made.append(text.substr(each.offset as u64, each.length as u64));
made.append(" ");
}
return made;
}, text).view() == "expects ensures old ");
}
@test def undefined_is_coloured_as_a_word_of_the_language_where_it_is_one(t: &mut tester): void {
val text := "def f(): u64 { var b: u64[2] = undefined; val undefined: u64 = 1; return undefined; }";
t.expects(asked(def(c: &mut checker): string {
var made := string::new(nothing {});
for &each in c.highlights(0) {
continue if text.substr(each.offset as u64, each.length as u64) != "undefined";
made.append($"{each.offset}:{each.kind == symbol::keyword} ");
}
return made;
}, text).view() == "31:true 46:false 73:false ");
}
@test def names_are_coloured_by_what_they_are(t: &mut tester): void {
val text := "struct p { var x: i64; }\ndef f(a: p): i64 { val y := a.x; return y; }";
t.expects(asked(def(c: &mut checker): string {
var made := string::new(nothing {});
val found := c.highlights(0);
for &each in found {
val name := text.substr(each.offset as u64, each.length as u64);
val line := $"{name}:{each.kind as u32}{each.declared ? "+" : ""}{each.readonly ? "r" : ""} ";
made.append(line.view());
}
return made;
}, text).view() == "p:8+ x:7+ i64:12r f:2+ a:6+ p:8r i64:12r y:4+r a:6 x:7 y:4r ");
}
#! The names completion offers at a place, joined by spaces.
#! @param text The program's text, of one file.
#! @param needle Where in it the place is.
#! @param skip How far into the needle the place is.
#! @param others The other files.
#! @returns The names.
def completed(text: strview, needle: strview, skip: u32, others: strview...): string {
var texts := vector::<strview>::new();
texts.append(text);
for &each in others {
texts.append(each);
}
return asked(def(c: &mut checker): string {
var made := string::new(nothing {});
val found := c.complete(0, place_in(text, needle, skip));
for &each in found {
break if each.kind == symbol::keyword && each.name.view() != "else";
if made.length != 0 {
made.append(" ");
}
made.append(each.name.view());
if each.insert.length != 0 {
made.append("=");
made.append(each.insert.view());
}
}
return made;
}, ...texts.view());
}
@test def completion_offers_what_the_place_takes(t: &mut tester): void {
val text := """
struct point { var x: i64; var y: i64; }
def point::norm(&this): i64 { return this.x; }
enum color { red, green }
def f(p: point, c: color): i64 {
val q := point { x = 1, };
val n := p.sakura__completion;
match c { red => {} }
return 0;
}
""";
t.expects(completed(text, ".sakura__completion", 1).view() == "x y norm");
t.expects(completed(text, "x = 1, ", 7).view().starts_with("y=y = p c point color f "));
t.expects(completed(text, "red => {} }", 10).view() == "green=green => else=else => ");
val locals := completed(text, "return 0", 7);
t.expects(locals.view().starts_with("q n p c point color f "));
}
@test def completion_offers_the_names_a_pattern_binds(t: &mut tester): void {
val text := """
struct lanes<L[N]> { var items: L[N]; }
def lanes<L[N]>::count(&this): u64 {
return N;
}
""";
t.expects(completed(text, "return N", 7).view().starts_with("this L N "));
}
@test def signature_help_shows_what_is_called(t: &mut tester): void {
val text := """
#! Adds.
#! @param a The first.
def add(a: i64, b: i64): i64 { return a + b; }
def add(a: i64): i64 { return a; }
def f(): i64 { return add(1, 2); }
""";
t.expects(asked(def(c: &mut checker): string {
var made := string::new(nothing {});
var help := c.calls_at(0, place_in(text, "2);")) else { return made; };
for &each in help.overloads {
made.append(each.signature.view());
made.append("|");
}
val line := $"{help.parameter}";
made.append(line.view());
return made;
}, text).view() == "def add(a: int, b: int): int|def add(a: int): int|1");
}
@test def an_edit_parsing_a_file_whole_again_checks_it_anew(t: &mut tester): void {
# Taking away the `}` of the first function has it swallow the last, which has
# the file parsed whole again and every node made anew, so what was kept of
# the old ones, as the nodes of the functions taken away, is let go of.
val before := """
def a(): i64 { return 1; }
def b(): i64 { return a() + 2; }
def c(): i64 { return b() + 3; }
def d(): i64 { return c() + 4; }
def e(): i64 { return 5; }
""";
t.expects(hovers_after_edits(before, "def a(): i64 { return 1;\ndef e(): i64 { return 5; }\n").view() == "");
t.expects(hovers_after_edits(before, "def a(): i64 { return 1;\ndef e(): i64 { return 5; }\n", before).view() == "");
}
@test def an_edit_keeps_what_was_worked_out_of_each_file_apart(t: &mut tester): void {
# Another file whose top-level declaration has the same node as one the edit
# keeps, but whose nodes begin elsewhere, leaves what is kept of this one as
# it was.
val before := """
def f(n: i64): i64 { return n; }
def g(n: i64): i64 { val m := n + 1; return m * f(m); }
""";
val after := """
def f(n: i64): i64 { return n + 0; }
def g(n: i64): i64 { val m := n + 1; return m * f(m); }
""";
val kept: u64 = top_nodes(before)[1];
var other := string::new(nothing {});
for pad in 0u..24u {
var text := string::from("def p(): void { ", nothing {});
for _ in 0..(pad / 3) {
text.append("val x := 1; ");
}
for _ in 0..(pad % 3) {
text.append("1; ");
}
text.append("}\n");
for _ in 0..8 {
text.append("def q(): void {}\n");
}
for &each in top_nodes(text.view()) {
if each >> 32 == kept >> 32 && (each & 0xFFFFFFFF) > (kept & 0xFFFFFFFF) {
other = move(&mut text);
break;
}
}
break if other.length != 0;
}
t.expects(other.length != 0);
var others := vector::<strview>::new();
others.append(other.view());
t.expects(hovers_after_edits_with(others.view(), before, after).view() == "");
}
@test def queries_after_edits_answer_as_a_whole_check_does(t: &mut tester): void {
val before := """
struct adder { var calls: i64; }
def adder::add(&mut this, a: i64, b: i64): i64 { this.calls++; return a + b; }
def make(): adder { return adder {}; }
def main(): void {
var a := adder {};
val n := a.add(1, 2);
}
""";
val typing := """
struct adder { var calls: i64; }
def adder::add(&mut this, a: i64, b: i64): i64 { this.calls++; return a + b; }
def make(): adder { return adder {}; }
def main(): void {
var a := adder {};
val q := a.
val n := a.add(1, 2);
}
""";
val completing := """
struct adder { var calls: i64; }
def adder::add(&mut this, a: i64, b: i64): i64 { this.calls++; return a + b; }
def make(): adder { return adder {}; }
def main(): void {
var a := adder {};
val q := a.sakura__completion
val n := a.add(1, 2);
}
""";
val wrong := """
struct adder { var calls: i64; }
def adder::add(&mut this, a: i64, b: i64): i64 { this.calls++; return a + b; }
def make(): u8 { return adder {}; }
def main(): void {
var a := adder {};
val q := a.calls;
val r: bool = 5;
val n := a.add(1, 2) + make();
}
""";
t.expects(hovers_after_edits(before, typing, completing, wrong, before).view() == "");
}
+146
View File
@@ -0,0 +1,146 @@
#! @file reading.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the tests of reading files on threads, which must read them as one
#! thread does: each word given the same ID, each file the same tokens and
#! nodes, and the same notes heard of each, and of hearing notes as they are
#! made, rather than finding them kept.
import std::testing;
module sakura::analyzer;
#! What reading files made: the names, each file's syntax and `document` node,
#! what was noted of each, and how many times each was heard read whole.
struct read_whole {
var names: names;
var sources: vector<source>;
var syntaxes: vector<syntax>;
var roots: vector<u32>;
var notes: vector<vector<note>>;
var reads: vector<u32>;
}
#! Reads files on a number of threads.
#! @param threads How many threads read them.
#! @param texts The files' texts.
#! @returns What reading them made.
def read_on(threads: u32, texts: span<strview>): read_whole {
var made := read_whole {
names = names::new(),
sources = vector::<source>::new(),
syntaxes = vector::<syntax>::new(),
roots = vector::<u32>::new(),
notes = vector::<vector<note>>::new(),
reads = vector::<u32>::new()
};
made.sources.reserve(texts.length);
made.syntaxes.reserve(texts.length);
for i in 0..texts.length {
made.sources.append(source::from("test.sakura", texts[i]));
made.syntaxes.append(syntax::new());
}
made.notes.resize(texts.length);
made.reads.resize(texts.length);
# What is heard of a file is heard on the thread reading it, so each file's
# vector is written by one thread alone.
val notes := &mut made.notes;
val reads := &mut made.reads;
val heard := listener {
noted = def(each: &mut note): void { notes[each.file as u64].append(move(each)); },
read = def(file: u32): void { reads[file as u64] += 1; }
};
read_files(&made.sources, &mut made.syntaxes, &mut made.roots, &mut made.names, threads, &heard, 0, texts.length);
return made;
}
#! Whether two readings made the same: names, tokens, nodes, and notes.
#! @param a One reading.
#! @param b The other.
#! @returns Whether they did.
def read_alike(a: &read_whole, b: &read_whole): bool {
return false if a.names.count != b.names.count;
for id in 0..a.names.count {
return false if a.names.text(id as u32) != b.names.text(id as u32);
}
for j in 0..a.syntaxes.length {
val x := &a.syntaxes.at(j);
val y := &b.syntaxes.at(j);
return false if a.roots.at(j) != b.roots.at(j) || x.token_count != y.token_count || x.node_count != y.node_count;
for k in 0..x.token_count {
val p := x.token(k as u32, &a.names);
val q := y.token(k as u32, &b.names);
return false if p.kind != q.kind || p.offset != q.offset || p.name != q.name;
}
for k in 0..x.node_count {
return false if x.node_kinds.at(k) != y.node_kinds.at(k) || x.node_tokens.at(k) != y.node_tokens.at(k);
}
return false if a.notes.at(j).length != b.notes.at(j).length || a.reads.at(j) != 1 || b.reads.at(j) != 1;
for k in 0..a.notes.at(j).length {
val p := &a.notes.at(j).at(k);
val q := &b.notes.at(j).at(k);
return false if p.offset != q.offset || p.code != q.code || p.length != q.length;
}
}
return true;
}
@test def files_read_on_threads_are_read_as_one_thread_reads_them(t: &mut tester): void {
# The files share some names and not others, and first use them in other
# orders, and some have mistakes, so what joins the names when, and what is
# heard of which file, would show.
val texts: strview[9] = [
"def alpha(beta: i64): i64 { return beta + gamma; }\nval gamma: i64 = 3;\n",
"struct point { var x: f64; var y: f64; }\ndef length(p: point): f64 { return p.x * p.x + p.y * p.y; }\n",
"def gamma2(): void { var delta := alpha(1); delta = delta * 2; }\n",
"def broken(: i64 { return 1 }\nval ok := 1;\n",
"enum colour { red, green, blue }\ndef pick(c: colour): u8 { return c == colour::red ? 1 : 2; }\n",
"def lexed(): void { val a := 1 @ 2; }\n",
"def x(): i64 { return y() + z(); }\ndef y(): i64 { return 1; }\ndef z(): i64 { return 2; }\n",
"def words(): strview { return $\"{alpha(2)} and {beta}\"; }\n",
"val last := point { x = 1.0, y = 2.0 };\ndef zeta(): void {}\n"
];
val one := read_on(1, texts[:]);
t.expects(one.notes.at(3).length != 0 && one.notes.at(5).length != 0);
for threads in 2..6u {
val many := read_on(threads as u32, texts[:]);
t.expects(read_alike(&one, &many));
}
}
@test def notes_heard_as_they_are_made_are_not_kept(t: &mut tester): void {
var names := names::new();
var notes := vector::<note>::new();
var heard := vector::<note>::new();
var syntax := syntax::new();
val source := source::from("test.sakura", "def f(): void {}\ndef g(): void { val a := 1 @ 2; }\ndef f(): void {}\n");
val hear := def(each: &mut note): void { heard.append(move(each)); };
var lexing := lexer::new(&source, &mut names, &mut notes, 0);
lexing.sink.heard = hear;
lexing.tokenize_all(&mut syntax);
var parsing := parser::new(&mut syntax, &names, &mut notes, 0);
parsing.sink.heard = hear;
val root := parsing.parse();
var checker := checker::new(&mut names, &mut notes);
checker.sink.heard = hear;
checker.add(&source, &syntax, root);
val read := heard.length;
checker.check();
# The lexer's note first, and the checker's of `f` declared twice, which says
# where it was first declared, as one kept would.
t.expects(notes.length == 0 && read != 0 && heard.length > read);
t.expects(heard.at(0).code == ec::token);
var related := false;
for &each in heard {
if each.code == ec::duplicate {
related = each.related.length != 0 && each.related_length != 0 && each.related_offset < each.offset;
}
}
t.expects(related);
t.expects(checker.notes_made as u64 == heard.length - read);
}
+141
View File
@@ -0,0 +1,141 @@
#! @file recovery.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the tests of how the parser recovers from mistakes: going on past an
#! item, a parameter, a statement, or a declaration that fails, with one note
#! for each mistake.
import std::testing;
module sakura::analyzer;
@test def a_list_goes_on_past_an_item_that_fails(t: &mut tester): void {
val made := parse("def f(): void { g(1 +, 2, h(3 *), [4, , 5]); }\nval ok := 1;\n");
t.expects(made.notes.length == 3);
t.expects(noted(&made, 1, 22, ec::expr));
t.expects(noted(&made, 1, 32, ec::expr));
t.expects(noted(&made, 1, 39, ec::expr));
t.expects(made.syntax.print(made.root, &made.source, &made.names).view() ==
"(document [(function:f [] _ [] [] type_name:void (block [(expr_stmt:g (call name:g [(binary:+ number:1 error) number:2 (call name:h [(binary:* number:3 error)]) (array [number:4 error number:5])]))])) (variable:ok [] _ _ number:1)])");
}
@test def parameters_go_on_past_one_that_fails(t: &mut tester): void {
val made := parse("def f(a: , b: i64, 7, c: u8): void {}");
t.expects(made.notes.length == 2);
t.expects(noted(&made, 1, 10, ec::kind));
t.expects(noted(&made, 1, 20, ec::ident));
}
@test def statements_and_declarations_resume_after_errors(t: &mut tester): void {
val made := parse("def f(): void { val x := 1 }\ndef g(): void { y = ; z(); }\nstruct s { var a: i64 }\nval ok := 1;\n");
t.expects(made.notes.length == 3);
t.expects(noted(&made, 1, 28, ec::token));
t.expects(noted(&made, 2, 21, ec::expr));
t.expects(noted(&made, 3, 23, ec::token));
t.expects(made.syntax.print(made.root, &made.source, &made.names).view() ==
"(document [(function:f [] _ [] [] type_name:void (block [(variable:x [] _ _ number:1)])) (function:g [] _ [] [] type_name:void (block [(expr_stmt:y (assign:= name:y error))])) (struct_decl:s [] _ [] [] [(field:a [] _ type_name:i64 _ {mutable})]) (variable:ok [] _ _ number:1)])");
}
@test def members_resume_after_errors(t: &mut tester): void {
val made := parse("trait t { pub def f(): void; var x: i64; }\nenum e { a = , b, 3, c }\n");
t.expects(noted(&made, 1, 11, ec::token));
t.expects(noted(&made, 1, 30, ec::token));
t.expects(noted(&made, 2, 14, ec::expr));
t.expects(noted(&made, 2, 19, ec::ident));
}
@test def what_belongs_nowhere_is_kept_within_errors(t: &mut tester): void {
# A trait's `var` that is no property, attributes before no member, and those
# within a function, each kept under an `error` node rather than dropped.
t.expects(tree("trait t { var x: i64; }").view() ==
"(document [(trait_decl:t [] _ [] [] [(error [(variable:x [] _ type_name:i64 _ {mutable})])])])");
t.expects(tree("struct s { @a }").view() ==
"(document [(struct_decl:s [] _ [] [] [(error [(attribute type_name:a [])])])])");
t.expects(statements("@a val x := 1;").view() ==
"(error [(attribute type_name:a []) (variable:x [] _ _ number:1)])");
}
@test def declarations_are_pub_once_and_after_their_attributes(t: &mut tester): void {
val made := parse("pub pub def f(): void {}\n@a pub @b def g(): void {}\nimport x\nmodule m;\n");
t.expects(noted(&made, 1, 5, ec::token));
t.expects(noted(&made, 2, 8, ec::token));
t.expects(noted(&made, 4, 1, ec::token));
# The attributes written after `pub` still describe the function.
t.expects(tree("@a pub @b def g(): void {}").view() ==
"(document [(function:g [(attribute type_name:a []) (attribute type_name:b [])] _ [] [] type_name:void block {exported})])");
}
@test def nothing_is_nullable(t: &mut tester): void {
val made := parse("def f(p: ?i64): void { g(p!); }\n");
t.expects(made.notes.length == 2);
t.expects(noted(&made, 1, 10, ec::kind));
t.expects(noted(&made, 1, 27, ec::token));
}
@test def else_takes_a_value_in_parentheses_before_anything_but_a_block(t: &mut tester): void {
val made := parse("val n := f() else (e) 1;\n");
t.expects(made.notes.length == 1);
t.expects(noted(&made, 1, 23, ec::token));
}
@test def a_comparison_after_a_cast_needs_parentheses(t: &mut tester): void {
val made := parse("val ok := n as u64 < limit;\n");
t.expects(made.notes.length == 1);
t.expects(noted(&made, 1, 27, ec::token));
t.expects(made.notes.at(0).detail.starts_with("Expected `>` to close the type arguments. A `<` after the type of `as` or `is`"));
# Anywhere else the plain message is given.
val plain := parse("val v: list<i64;\n");
t.expects(plain.notes.at(0).detail == "Expected `>` to close the type arguments.");
}
@test def too_deep_gives_up_on_only_its_declaration(t: &mut tester): void {
var text := string::from("val x := ", nothing {});
for _ in 0..150 { text.append("("); }
text.append("1");
for _ in 0..150 { text.append(")"); }
text.append(";\nval y := (;\nval z := 1;\n");
val made := parse(text.view());
t.expects(made.notes.length == 2);
t.expects(noted(&made, 1, 110, ec::syntax));
t.expects(noted(&made, 2, 11, ec::expr));
# The declarations after it are parsed as though nothing went wrong.
val decls := made.syntax.node_lefts.at(made.root);
t.expects(made.syntax.run_length(decls) == 3);
t.expects(made.syntax.print(made.syntax.run_at(decls, 2), &made.source, &made.names).view() == "(variable:z [] _ _ number:1)");
}
@test def notes_are_bounded(t: &mut tester): void {
var text := string::new(nothing {});
for _ in 0..150 { text.append("val v := ;\n"); }
t.expects(parse(text.view()).notes.length == parser::max_notes as u64);
}
@test def the_walker_follows_the_shapes(t: &mut tester): void {
val made := parse("def f(a: i64): i64 { return a + 1; }");
val function := made.syntax.run_at(made.syntax.node_lefts.at(made.root), 0);
var kids := vector::<u32>::new();
made.syntax.children(function, &mut kids);
# The record's runs and nodes in order: the parameter, the result, the body.
t.expects(kids.length == 3);
t.expects(made.syntax.node_kinds.at(kids.at(0)) == nk::param);
t.expects(made.syntax.node_kinds.at(kids.at(1)) == nk::type_name);
t.expects(made.syntax.node_kinds.at(kids.at(2)) == nk::block);
# Every node is reached once from the document.
var todo := vector::<u32>::new();
todo.append(made.root);
var walked := 0u;
while walked < todo.length {
made.syntax.children(todo.at(walked), &mut todo);
walked++;
}
t.expects(todo.length == made.syntax.node_count - 1);
}
+128
View File
@@ -0,0 +1,128 @@
#! @file reparse.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the tests of parsing a file again after an edit, which must give the
#! tree and notes a whole parse of the edited text gives.
import std::testing;
module sakura::analyzer;
@test def an_edit_within_a_declaration(t: &mut tester): void {
t.expects(reparses_as_whole(
"val a := 1;\ndef f(): void { g(1); }\nval b := 2;",
"val a := 1;\ndef f(): void { g(1, 2 + 3); h(); }\nval b := 2;"));
t.expects(reparses_as_whole(
"def f(): void {}\nval b := 2;",
"def f(): i64 { return 1; }\nval b := 2;"));
}
@test def an_edit_of_only_spacing_and_comments(t: &mut tester): void {
t.expects(reparses_as_whole(
"val a := 1;\nval b := 2;",
"val a := 1;\n\n# a comment\n#! documentation\nval b := 2;"));
}
@test def declarations_added_and_taken_away(t: &mut tester): void {
t.expects(reparses_as_whole("val a := 1;\nval c := 3;", "val a := 1;\nval b := 2;\nval c := 3;"));
t.expects(reparses_as_whole("val a := 1;\nval b := 2;\nval c := 3;", "val a := 1;\nval c := 3;"));
t.expects(reparses_as_whole("val a := 1;", "val a := 1;\nstruct s { var x: i64; }"));
t.expects(reparses_as_whole("val a := 1;\nval b := 2;", "val b := 2;"));
t.expects(reparses_as_whole("val a := 1;", ""));
}
@test def edits_that_make_and_mend_errors(t: &mut tester): void {
t.expects(reparses_as_whole("val a := 1;\nval b := 2;\nval c := 3;", "val a := 1;\nval b := ;\nval c := 3;"));
t.expects(reparses_as_whole("val a := 1;\nval b := ;\nval c := 3;", "val a := 1;\nval b := 2;\nval c := 3;"));
t.expects(reparses_as_whole("val a := 0x;\nval b := 2;", "val a := 0x1;\nval b := 2;"));
}
@test def an_edit_that_opens_what_runs_on(t: &mut tester): void {
# Taking away a `}` makes the function take in what follows it, which only
# parsing the whole file again finds.
t.expects(reparses_as_whole(
"def f(): void { g(); }\nval b := 2;\nval c := 3;",
"def f(): void { g();\nval b := 2;\nval c := 3;"));
}
@test def what_the_edit_did_not_touch_is_kept(t: &mut tester): void {
var made := parse("val a := 1;\nval b := 2;\nval c := 3;");
val decls := made.syntax.node_lefts.at(made.root);
val first := made.syntax.run_at(decls, 0);
val last := made.syntax.run_at(decls, 2);
var fresh := lex("val a := 1;\nval b := 20 + 2;\nval c := 3;");
made.root = made.syntax.reparse(&mut fresh.syntax, &fresh.names, made.root, &mut made.notes, &mut fresh.notes, 0);
val after := made.syntax.node_lefts.at(made.root);
t.expects(made.syntax.run_at(after, 0) == first);
t.expects(made.syntax.run_at(after, 2) == last);
# What moved along with the edit says where it is now.
t.expects(made.syntax.token(made.syntax.node_tokens.at(last), &fresh.names).offset == 33);
}
@test def what_follows_an_edit_is_kept_as_the_tree_grows(t: &mut tester): void {
# A longer comment above the first declaration moves every token, so all up
# to the edit is parsed again, and the nodes that adds move the tables the
# declarations after it are kept from, which are still read once it is done.
for count in 1..60 {
var before := string::from("# A file.\nimport std;\nmodule m;\n", nothing {});
var after := string::from("# A file, said at more length.\nimport std;\nmodule m;\n", nothing {});
for i in 0..count {
var line := $"def f{i}(x: u32): u32 ";
before.append(line.view());
before.append("{ return x + 1; }\n");
after.append(line.view());
after.append(i == count / 2 ? "{ return x * 2; }\n" : "{ return x + 1; }\n");
}
t.expects(reparses_as_whole(before.view(), after.view()));
}
}
@test def type_arguments_closed_by_one_token_are_kept(t: &mut tester): void {
# A `>>` closing type arguments is the same tokens after the edit as before,
# so the declaration it is in is kept.
var made := parse("val a: x<y<i64>> = 1;\nval b := 2;\nval c := 3;");
val first := made.syntax.run_at(made.syntax.node_lefts.at(made.root), 0);
var fresh := lex("val a: x<y<i64>> = 1;\nval b := 2;\nval c := 30;");
made.root = made.syntax.reparse(&mut fresh.syntax, &fresh.names, made.root, &mut made.notes, &mut fresh.notes, 0);
t.expects(made.syntax.run_at(made.syntax.node_lefts.at(made.root), 0) == first);
t.expects(reparses_as_whole(
"val a: x<y<i64>> = 1;\nval b := 2;\nval c := 3;",
"val a: x<y<i64>> = 1;\nval b := 2;\nval c := 30;"));
}
@test def notes_keep_the_order_a_whole_parse_gives(t: &mut tester): void {
# Parser notes before, within and after what is parsed again, and a lexer note.
t.expects(reparses_as_whole(
"val a := ;\nval b := 2;\nval c := ;",
"val a := ;\nval b := 2 +;\nval c := 0x;"));
t.expects(reparses_as_whole(
"val a := ;\nval b := 2 +;\nval c := ;",
"val a := ;\nval b := 2;\nval c := ;"));
}
@test def notes_past_the_cap_parse_whole(t: &mut tester): void {
var before := string::new(nothing {});
var after := string::new(nothing {});
for i in 0..(parser::max_notes + 20) {
before.append(i == 50 ? "val b := 2;\n" : "val a := ;\n");
after.append(i == 50 ? "val b := ;\n" : "val a := ;\n");
}
t.expects(reparses_as_whole(before.view(), after.view()));
}
@test def edits_over_time_do_not_keep_growing(t: &mut tester): void {
var made := parse("val a := 1;\nval b := 2;\nval c := 3;");
val whole := made.syntax.node_count;
for i in 0..50 {
var fresh := lex(i % 2 == 0 ? "val a := 1;\nval b := 2 + 3 * 4;\nval c := 3;" : "val a := 1;\nval b := 2;\nval c := 3;");
made.root = made.syntax.reparse(&mut fresh.syntax, &fresh.names, made.root, &mut made.notes, &mut fresh.notes, 0);
}
t.expects(made.syntax.node_count <= made.syntax.whole_nodes * 2);
t.expects(made.syntax.whole_nodes <= whole * 2);
}
+611
View File
@@ -0,0 +1,611 @@
#! @file support.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains what the tests share: lexing, parsing, and checking text, printing
#! trees, and asking what notes were made.
module sakura::analyzer;
#! Text that was lexed, with what the lexer reported.
struct lexed {
var source: source;
var names: names;
var syntax: syntax;
var notes: vector<note>;
}
#! Text that was lexed and parsed, with what both reported.
struct parsed {
var source: source;
var names: names;
var syntax: syntax;
var notes: vector<note>;
var root: u32;
}
#! Lexes the text through its `eof`.
#! @param text The text.
#! @returns Its source, names, tokens, and notes.
def lex(text: strview): lexed {
var made := lexed {
source = source::from("test.sakura", text),
names = names::new(),
syntax = syntax::new(),
notes = vector::<note>::new()
};
var lexing := lexer::new(&mut made.source, &mut made.names, &mut made.notes, 0);
lexing.tokenize_all(&mut made.syntax);
return made;
}
#! Lexes and parses the text as a file.
#! @param text The text.
#! @returns Its source, names, syntax, notes, and `document` node.
def parse(text: strview): parsed {
var made := parsed {
source = source::from("test.sakura", text),
names = names::new(),
syntax = syntax::new(),
notes = vector::<note>::new()
};
var lexing := lexer::new(&mut made.source, &mut made.names, &mut made.notes, 0);
lexing.tokenize_all(&mut made.syntax);
var parsing := parser::new(&mut made.syntax, &made.names, &mut made.notes, 0);
made.root = parsing.parse();
return made;
}
#! The kinds of the tokens lexed, without the `eof` ending them.
#! @param text The text.
#! @returns The kinds.
def kinds_of(text: strview): vector<tk> {
val lexing := lex(text);
var kinds := vector::<tk>::new();
for &each in lexing.syntax.token_kinds {
if each != tk::eof {
kinds.append(each);
}
}
return kinds;
}
#! Whether the tokens lexed are exactly those kinds.
#! @param text The text.
#! @param kinds The kinds expected, without the `eof`.
#! @returns Whether they are.
def lexes_as(text: strview, kinds: tk...): bool {
val got := kinds_of(text);
return false if got.length != kinds.length;
for i in 0..got.length {
return false if got.at(i) != kinds.at(i);
}
return true;
}
#! The tree of a whole file, printed.
#! @param text The text.
#! @returns The tree, as `printer` writes it.
def tree(text: strview): string {
val made := parse(text);
return made.syntax.print(made.root, &made.source, &made.names);
}
#! The statements of a function's body, each printed, separated by spaces.
#! @param text A file holding the function first.
#! @returns The statements.
def statements(text: strview): string {
var wrapped := string::from("def test(): void {\n", nothing {});
wrapped.append(text);
wrapped.append("\n}\n");
val made := parse(wrapped.view());
val function := made.syntax.run_at(made.syntax.node_lefts.at(made.root), 0);
val record := made.syntax.node_lefts.at(function);
val body := made.syntax.extras.at(record as u64 + 5);
val run := made.syntax.node_lefts.at(body);
var out := string::new(nothing {});
for i in 0..made.syntax.run_length(run) {
if i != 0 {
out.append(" ");
}
out.append(made.syntax.print(made.syntax.run_at(run, i as u32), &made.source, &made.names).view());
}
return out;
}
#! An expression statement's expression, printed.
#! @param text A file holding a function whose body is the expression
#! statement.
#! @returns The expression.
def expression(text: strview): string {
var wrapped := string::from(text, nothing {});
wrapped.append(";");
val printed := statements(wrapped.view());
val inner := printed.view();
# `(expr_stmt:x EXPR)` without its own head and closing parenthesis.
var at := 0u;
var spaces := 0u;
while at < inner.length && spaces == 0 {
if inner.at(at) == ' ' { spaces++; }
at++;
}
return string::from(inner.substr(at, inner.length - at - 1), nothing {});
}
#! Whether a note of the code was made at the line and column.
#! @param made What was parsed.
#! @param line The note's line, counted from 1.
#! @param column Its column, counted from 1.
#! @param code What kind of note it is.
#! @returns Whether it was.
def noted(made: &parsed, line: u32, column: u32, code: ec): bool {
for &each in made.notes {
val at := made.source.lines.place_of(each.offset);
return true if at.line == line && at.column == column && each.code == code;
}
return false;
}
#! Whether a note of the code was made at the line and column, lexing only.
#! @param made What was lexed.
#! @param line The note's line, counted from 1.
#! @param column Its column, counted from 1.
#! @param code What kind of note it is.
#! @returns Whether it was.
def lex_noted(made: &lexed, line: u32, column: u32, code: ec): bool {
for &each in made.notes {
val at := made.source.lines.place_of(each.offset);
return true if at.line == line && at.column == column && each.code == code;
}
return false;
}
#! Parses `before`, then reparses it as edited into `after`, and says whether
#! the tree and notes are those a whole parse of `after` makes.
#! @param before The text first parsed.
#! @param after The text it is edited into.
#! @returns Whether they are.
def reparses_as_whole(before: strview, after: strview): bool {
var made := parse(before);
var fresh := lex(after);
made.root = made.syntax.reparse(&mut fresh.syntax, &fresh.names, made.root, &mut made.notes, &mut fresh.notes, 0);
val whole := parse(after);
return false if made.syntax.print(made.root, &fresh.source, &fresh.names).view() != whole.syntax.print(whole.root, &whole.source, &whole.names).view();
return false if made.notes.length != whole.notes.length;
for i in 0..whole.notes.length {
val each := &whole.notes.at(i);
val other := &made.notes.at(i);
return false if other.offset != each.offset || other.code != each.code || other.lexed != each.lexed;
}
return true;
}
#! A note the checker made, where it is, and what it says.
struct seen {
var line: u32;
var column: u32;
var code: ec;
var detail: string;
var instance: string; #! The instance of a generic it was found in, or empty.
var related: u32; #! The line of the place it relates to, or 0.
}
#! What checking a program found: its notes, and the type of each local named
#! in `asked`, as notes spell it.
struct checking {
var notes: vector<seen>;
var asked: string;
var skipped: u32;
}
#! Checks the first text, then each after it in turn as an edit of the one
#! before, checking again only what each edit affects, and whether hovering
#! each name of the last text shows what it does once that text is checked
#! whole.
#! @param texts The text before every edit, then the text after each.
#! @returns The names whose hovers differ, each with both, or empty text.
def hovers_after_edits(texts: strview...): string {
return hovers_after_edits_with(span::<strview>::empty(), ...texts);
}
#! Checks the files, the edited one last, then each text after the first in turn
#! as an edit of the edited file, as `hovers_after_edits` does.
#! @param others The files checked with it, which are not edited.
#! @param texts The text before every edit, then the text after each.
#! @returns The names whose hovers differ, each with both, or empty text.
def hovers_after_edits_with(others: span<strview>, texts: strview...): string {
var names := names::new();
var notes := vector::<note>::new();
var parse_notes := vector::<vector<note>>::new();
var sources := vector::<source>::new();
var syntaxes := vector::<syntax>::new();
var roots := vector::<u32>::new();
val edited := others.length;
sources.reserve(others.length + texts.length);
syntaxes.reserve(others.length + 1);
parse_notes.reserve(others.length + 1);
for i in 0..(others.length + 1) {
sources.append(source::from(i == edited ? "test.sakura" : "other.sakura", i == edited ? texts[0] : others[i]));
syntaxes.append(syntax::new());
parse_notes.append(vector::<note>::new());
}
for i in 0..(others.length + 1) {
var lexing := lexer::new(&mut sources[i], &mut names, &mut parse_notes[i], i as u32);
lexing.tokenize_all(&mut syntaxes[i]);
var parsing := parser::new(&mut syntaxes[i], &names, &mut parse_notes[i], i as u32);
roots.append(parsing.parse());
}
var checker := checker::new(&mut names, &mut notes);
for i in 0..(others.length + 1) {
checker.add(&sources[i], &syntaxes[i], roots[i]);
}
checker.check();
for i in 1..texts.length {
sources.append(source::from("test.sakura", texts[i]));
val at := sources.length - 1;
var fresh := syntax::new();
var fresh_notes := vector::<note>::new();
var again := lexer::new(&mut sources[at], &mut names, &mut fresh_notes, edited as u32);
again.tokenize_all(&mut fresh);
roots[edited] = syntaxes[edited].reparse(&mut fresh, &names, roots[edited], &mut parse_notes[edited], &mut fresh_notes, edited as u32);
checker.update(edited as u32, &sources[at], roots[edited]);
}
val last := texts[texts.length - 1];
var files := vector::<strview>::new();
for &each in others {
files.append(each);
}
files.append(last);
return asked(def(whole: &mut checker): string {
var made := string::new(nothing {});
var at: u64 = 0;
while at < last.length {
if !is_word_byte(last[at]) || (at > 0 && is_word_byte(last[at - 1])) {
at++;
continue;
}
var one := checker.hover(edited as u32, at as u32);
var two := whole.hover(edited as u32, at as u32);
var a := string::new(nothing {});
var b := string::new(nothing {});
if one is some(&found) {
a = string::copy_of(&found.signature);
}
if two is some(&found) {
b = string::copy_of(&found.signature);
}
if a.view() != b.view() {
val line := $"{at}: {a} | {b}\n";
made.append(line.view());
}
at++;
}
return made;
}, ...files.view());
}
#! The top-level nodes of a file once parsed, each with the first node of what
#! it declares.
#! @param text The file's text.
#! @returns The pairs, as `top << 32 | first`.
def top_nodes(text: strview): vector<u64> {
val made := parse(text);
var found := vector::<u64>::new();
val decls := made.syntax.node_lefts[made.root];
for i in 0..made.syntax.run_length(decls) {
val top := made.syntax.run_at(decls, i as u32);
var lowest := top;
var todo := vector::<u32>::new();
todo.append(top);
while todo.length != 0 {
val at: u32 = todo[todo.length - 1];
todo.remove_at(todo.length - 1);
lowest = at < lowest ? at : lowest;
made.syntax.children(at, &mut todo);
}
found.append((top as u64 << 32) | lowest as u64);
}
return found;
}
#! Lexes, parses, and checks the files as one program, the first named
#! `test.sakura`, and the type of the local named `asked` in the first file.
#! @param asked The name of a local whose type is asked for, or empty text.
#! @param texts The files' texts.
#! @returns The notes made, the local's type as notes spell it, and how much was
#! let through unchecked.
def check_program(asked: strview, texts: strview...): checking {
var names := names::new();
var notes := vector::<note>::new();
var sources := vector::<source>::new();
var syntaxes := vector::<syntax>::new();
var roots := vector::<u32>::new();
# Each file's source and syntax stay where they are once the checker refers
# to them, so there is room for all of them before any is made.
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 names, &mut notes, i as u32);
lexing.tokenize_all(syntaxes.at(i));
var parsing := parser::new(syntaxes.at(i), &names, &mut notes, i as u32);
roots.append(parsing.parse());
}
var checker := checker::new(&mut names, &mut notes);
for i in 0..texts.length {
checker.add(sources.at(i), syntaxes.at(i), roots.at(i));
}
checker.check();
var made := checking {
notes = vector::<seen>::new(),
asked = string::new(nothing {}),
skipped = checker.skipped
};
for &each in notes {
val at := sources.at(each.file).lines.place_of(each.offset);
val related := each.related.length == 0 ? 0 : sources.at(each.related_file).lines.place_of(each.related_offset).line;
made.notes.append(seen {
line = at.line,
column = at.column,
code = each.code,
detail = string::from(each.detail, nothing {}),
instance = string::from(each.instance, nothing {}),
related = related
});
}
if asked.length != 0 {
checker.use_table(checker.units.at(0).table);
val syntax := &syntaxes.at(0);
for at in 1..syntax.node_count {
val node := at as u32;
continue if syntax.node_kinds.at(node) != nk::variable;
continue if names.text(syntax.token_names.at(syntax.node_tokens.at(node))) != asked;
var described := checker.describe(checker.type_at(node));
made.asked = move(&mut described);
}
}
return made;
}
#! Whether the program checks without a note.
#! @param texts The files' texts.
#! @returns Whether it does.
def checks(texts: strview...): bool {
val made := check_program("", ...texts);
return made.notes.length == 0;
}
#! Whether checking the program makes a note of the code at the line and
#! column, among any others.
#! @param line The note's line, counted from 1.
#! @param column Its column, counted from 1.
#! @param code What kind of note it is.
#! @param texts The files' texts.
#! @returns Whether it does.
def check_noted(line: u32, column: u32, code: ec, texts: strview...): bool {
val made := check_program("", ...texts);
for &each in made.notes {
return true if each.line == line && each.column == column && each.code == code;
}
return false;
}
#! How many notes checking the program makes.
#! @param texts The files' texts.
#! @returns How many.
def note_count(texts: strview...): u64 {
val made := check_program("", ...texts);
return made.notes.length;
}
#! The type of the local of the name in the program, as notes spell it.
#! @param name The local's name.
#! @param text The program's text.
#! @returns Its type.
def local_type(name: strview, text: strview): string {
var made := check_program(name, text);
return move(&mut made.asked);
}
#! A small standard library for checking programs that use what the checker
#! knows of std, as the real one declares it.
const mini_std: strview = """
module std; module core;
pub struct nothing {}
pub trait equatable { def equals(&this, other: &self): bool; }
pub trait ordered : equatable { def compare(&this, other: &self): i64; }
pub trait addable { def add(&this, other: &self): self; }
pub trait subtractable { def sub(&this, other: &self): self; }
pub trait multipliable { def mul(&this, other: &self): self; }
pub trait divisible { def div(&this, other: &self): self; }
pub trait modular { def rem(&this, other: &self): self; }
pub trait negatable { def negate(&this): self; }
pub trait additive : equatable, addable, subtractable, negatable {}
pub trait multiplicative : equatable, multipliable {}
pub trait numeric : additive, multiplicative, divisible, modular {}
pub trait integer {}
pub trait ordinal {}
pub trait zeroable {}
pub trait lockfree {}
pub trait owning { def close(&mut this): void; }
pub union maybe<T> { pub var none: nothing; pub var some: T; }
pub union result<T, E> { pub var value: T; pub var error: E; }
pub trait iterator<T> { def next(&mut this): maybe<T>; }
pub trait iterable<T> {
type cursor: iterator<&T>;
def iter(&this): cursor;
}
pub struct span<T> { pub var data: *T; pub var count: u64; }
pub val span<T>::length: u64 { get => this.count; }
pub def span<T>::at(&this, index: u64): &T { return &this.data[index]; }
pub struct span<T>::cursor : iterator<&T> { var at: *T; var left: u64; }
pub def span<T>::cursor::next(&mut this): maybe<&T> {
if this.left == 0 { return nothing {}; }
this.left--;
return &this.at[0];
}
pub def span<T>::iter(&this): span<T>::cursor { return span::<T>::cursor { at = this.data, left = this.count }; }
""";
#! What `mini_std` lacks for checking anonymous functions given for bounds and
#! ranges as values: `invokable`, `range`, which `a..b` makes, and `strview`.
const ranges_std: strview = """
module std; module core;
pub type strview = span<u8>;
pub trait invokable<def(Ts...): R> { def invoke(&mut this, args: Ts...): R; }
pub struct range<T> : iterator<T> where T: ordinal { pub var start: T; pub var end: T; var _last: bool; }
pub def range<T>::next(&mut this): maybe<T> { return nothing {}; }
""";
#! What checking a file again after an edit found, against checking it whole.
struct rechecked {
var same: bool; #! Whether its notes are those checking the edited text whole makes.
var checked: u32; #! How many top-level declarations were checked again.
var notes: u64; #! How many notes it made.
}
#! Checks `before`, with `others` after it, then edits it into `after`, parses
#! it again, and checks it again, and says whether its notes are those of
#! checking the edited program whole, and how much was checked again.
#! @param before The text of the file first checked.
#! @param after The text it is edited into.
#! @param others The texts of the program's other files.
#! @returns Whether its notes are the same, and how much was checked again.
def check_edit(before: strview, after: strview, others: strview...): rechecked {
var names := names::new();
var notes := vector::<note>::new();
var sources := vector::<source>::new();
var syntaxes := vector::<syntax>::new();
var roots := vector::<u32>::new();
sources.reserve(others.length + 2);
syntaxes.reserve(others.length + 1);
sources.append(source::from("test.sakura", before));
syntaxes.append(syntax::new());
for &each in others {
sources.append(source::from("other.sakura", each));
syntaxes.append(syntax::new());
}
for i in 0..syntaxes.length {
var lexing := lexer::new(sources.at(i), &mut names, &mut notes, i as u32);
lexing.tokenize_all(syntaxes.at(i));
var parsing := parser::new(syntaxes.at(i), &names, &mut notes, i as u32);
roots.append(parsing.parse());
}
var checker := checker::new(&mut names, &mut notes);
for i in 0..syntaxes.length {
checker.add(sources.at(i), syntaxes.at(i), roots.at(i));
}
checker.check();
# The edit: the text lexed whole, then parsed again where it changed.
sources.append(source::from("test.sakura", after));
val edited := sources.length - 1;
var fresh := syntax::new();
var fresh_notes := vector::<note>::new();
var lexing := lexer::new(sources.at(edited), &mut names, &mut fresh_notes, 0);
lexing.tokenize_all(&mut fresh);
val root := syntaxes.at(0).reparse(&mut fresh, &names, roots.at(0), &mut notes, &mut fresh_notes, 0);
val count := checker.update(0, sources.at(edited), root);
var texts := vector::<strview>::new();
texts.append(after);
for &each in others {
texts.append(each);
}
val whole := check_program("", ...texts.view());
var same := whole.notes.length == notes.length;
for &want in whole.notes {
var found := false;
for &each in notes {
val at := sources.at(each.file == 0 ? edited : each.file as u64).lines.place_of(each.offset);
found = found || (at.line == want.line && at.column == want.column && each.code == want.code);
}
same = same && found;
}
return rechecked { same = same, checked = count, notes = notes.length };
}
#! Lexes, parses, and checks the files as one program, the first named
#! `test.sakura` and the rest `other.sakura`, then asks it a question.
#! @param question What is asked of the checked program.
#! @param texts The files' texts.
#! @returns What the question gives.
def asked(question: def(&mut checker): string, texts: strview...): string {
var names := 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[i]));
syntaxes.append(syntax::new());
}
for i in 0..texts.length {
var lexing := lexer::new(sources[i], &mut names, &mut notes, i as u32);
lexing.tokenize_all(syntaxes[i]);
var parsing := parser::new(syntaxes[i], &names, &mut notes, i as u32);
roots.append(parsing.parse());
}
var checker := checker::new(&mut names, &mut notes);
for i in 0..texts.length {
checker.add(sources[i], syntaxes[i], roots[i]);
}
checker.check();
return question(&mut checker);
}
#! Where text first holds `needle`, and `skip` bytes into it.
#! @param text The text.
#! @param needle What to find.
#! @param skip How far into it the place is.
#! @returns The offset, or the text's length where it does not hold it.
def place_in(text: strview, needle: strview, skip: u32 = 0): u32 {
var at := 0u;
while at + needle.length <= text.length && text.substr(at, needle.length) != needle {
at++;
}
return at as u32 + skip;
}
#! What hovering the first place the text holds `needle` shows, once checked:
#! the signature, and after a blank line the documentation, where there is
#! some.
#! @param text The program's text.
#! @param needle The text to hover.
#! @param skip How far into the needle the place hovered is.
#! @returns What hovering shows, or empty text.
def hover_of(text: strview, needle: strview, skip: u32 = 0): string {
return asked(def(c: &mut checker): string {
var shown := c.hover(0, place_in(text, needle, skip)) else { return string::new(nothing {}); };
var made := move(&mut shown.signature);
if shown.documentation.length != 0 {
made.append("\n\n");
made.append(shown.documentation.view());
}
return made;
}, text);
}
+92
View File
@@ -0,0 +1,92 @@
#! @file syntax.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the tests of how a syntax holds its nodes: names and paths of one
#! segment, records of nothing, and the last token of each node.
import std::testing;
module sakura::analyzer;
@test def plain_type_names_and_paths_are_one_node(t: &mut tester): void {
val made := parse("import std;\nval x: u8 = 1;");
val decls := made.syntax.node_lefts.at(made.root);
val path := made.syntax.node_lefts.at(made.syntax.run_at(decls, 0));
t.expects(made.syntax.node_kinds.at(path) == nk::path && made.syntax.node_lefts.at(path) == 0);
# The document, the import, its path, the variable, its type, and its value,
# with node 0.
t.expects(made.syntax.node_count == 7);
}
@test def records_of_nothing_take_no_room(t: &mut tester): void {
# A parameter with no default value and no flags shares the zeros `extras`
# begins with, so the function's record and the run of its parameters are all
# it writes.
val made := parse("def f(a: i64, b: i64): void;");
val param := made.syntax.run_at(made.syntax.extras.at(made.syntax.node_lefts.at(made.syntax.run_at(made.syntax.node_lefts.at(made.root), 0)) as u64 + 3), 0);
t.expects(made.syntax.node_kinds.at(param) == nk::param && made.syntax.node_rights.at(param) == 0);
t.expects(made.syntax.extras.length == syntax::zeros as u64 + 2 + 7 + 3);
}
@test def nodes_know_their_last_token(t: &mut tester): void {
val made := parse("def f(): void { g(1, 2); }\nval x := a + b;");
val decls := made.syntax.node_lefts.at(made.root);
val func := made.syntax.run_at(decls, 0);
val local := made.syntax.run_at(decls, 1);
# `}` ends the function, and `;` the variable.
t.expects(made.syntax.token(made.syntax.node_end(func), &made.names).kind == tk::rbrace);
t.expects(made.syntax.token(made.syntax.node_end(local), &made.names).kind == tk::semicolon);
t.expects(made.syntax.node_end(made.root) == made.syntax.token_count as u32 - 1);
# A declaration begins at its keyword, its own token being its name.
t.expects(made.syntax.start_of(local) == made.syntax.node_end(func) + 1);
}
@test def documentation_belongs_to_what_it_is_written_before(t: &mut tester): void {
val made := parse("#! The answer.\n#! Twice.\n@a pub val x := 42;\n# Not documentation.\nval y := 1;\nstruct s {\n #! A field.\n var f: i64;\n}");
val decls := made.syntax.node_lefts.at(made.root);
t.expects(made.syntax.docs.length == 3);
val first := made.syntax.docs_of(made.syntax.run_at(decls, 0));
t.expects(first.first == 0 && first.count == 2);
t.expects(made.source.make_lexeme(made.syntax.docs.at(1).offset, made.syntax.docs.at(1).length) == "#! Twice.");
t.expects(made.syntax.docs_of(made.syntax.run_at(decls, 1)).count == 0);
val structure := made.syntax.run_at(decls, 2);
val field := made.syntax.run_at(made.syntax.node_rights.at(structure), 0);
val of_field := made.syntax.docs_of(field);
t.expects(of_field.first == 2 && of_field.count == 1);
}
@test def notes_say_what_they_found(t: &mut tester): void {
val made := parse("val x := 1\nval y := ;");
t.expects(made.notes.at(0).message(&made.source).view() == "Expected `;` after the declaration. Found `val`.");
t.expects(made.notes.at(1).message(&made.source).view() == "Expected an expression. Found `;`.");
val ended := parse("val x := 1");
t.expects(ended.notes.at(0).message(&ended.source).view() == "Expected `;` after the declaration. Found the end of the file.");
# A note saying what is wrong, rather than what was expected, says no more.
val twice := parse("pub pub val x := 1;");
t.expects(twice.notes.at(0).message(&twice.source).view() == "A declaration is `pub` once.");
}
@test def notes_say_which_stage_made_them(t: &mut tester): void {
val made := parse("val x := 0x;\nval y := ;");
t.expects(made.notes.length == 2);
t.expects(made.notes.at(0).lexed);
t.expects(!made.notes.at(1).lexed);
}
@test def token_tables_answer_for_each_kind(t: &mut tester): void {
t.expects(tk::pluseq.has(tt::assigns) && !tk::plus.has(tt::assigns));
t.expects(tk::kw_struct.has(tt::declares) && !tk::kw_if.has(tt::declares));
t.expects(tk::kw_if.has(tt::states) && tk::lbrace.has(tt::opens) && tk::istring_end.has(tt::closes));
t.expects(tk::name.has(tt::text) && !tk::lparen.has(tt::text));
t.expects(token_powers[tk::star as u64] == parser::bp::product && token_powers[tk::comma as u64] == parser::bp::none);
}
@@ -0,0 +1,4 @@
--- exit 1
sakura: runtime error: Index or slice is out of bounds.
at main (tests/checked/an_index_outside_a_view_is_a_fault_1.sakura:5:15)
@@ -0,0 +1,6 @@
import std::io;
def main(): void {
var a: i64[2] = [1, 2];
val s := span::<i64>::over(&a as *i64, 2);
println($"{s[5]}");
}
@@ -0,0 +1,5 @@
before
--- exit 1
sakura: runtime error: Value is not a member of its enum.
at main (tests/checked/enums_and_match_values_3.sakura:6:14)
@@ -0,0 +1,8 @@
import std::io;
enum color: u8 { red, green = 4, blue }
def main(): void {
val n := 260;
println("before");
val c := n as color;
println($"{c}");
}
@@ -0,0 +1,6 @@
lowest low middle high higher
--- exit 1
sakura: runtime error: Value is not a member of its enum.
at convert (tests/checked/enums_declared_out_of_order_check_their_members_1.sakura:7:39)
at main (tests/checked/enums_declared_out_of_order_check_their_members_1.sakura:15:21)
@@ -0,0 +1,16 @@
import std::io;
# Members declared out of the order of their values, which the check of a
# conversion sorts into runs.
enum level: u32 { high = 9, low = 1, middle = 5, lowest = 0, higher = 10 }
def convert(n: u32): level { return n as level; }
def main(): void {
val members: u32[5] = [0, 1, 5, 9, 10];
for n in members {
print($"{convert(n)} ");
}
println("");
println($"{convert(4)}");
}
+5
View File
@@ -0,0 +1,5 @@
99
--- exit 1
sakura: runtime error: Index or slice is out of bounds.
at main (tests/checked/faults_1.sakura:5:18)
+6
View File
@@ -0,0 +1,6 @@
import std::io;
def main(): void {
val text: span<u8> = "abc";
println($"{text[2]}");
println($"{text[3]}");
}
@@ -0,0 +1,4 @@
--- exit 1
sakura: runtime error: Index or slice is out of bounds.
at main (tests/checked/fixed_arrays_are_bounded_1.sakura:5:4)
@@ -0,0 +1,6 @@
import std::io;
def main(): void {
var a: int[3] = [1, 2, 3];
var i: uint = 3;
a[i] = 0;
}
+6
View File
@@ -0,0 +1,6 @@
4
--- exit 1
sakura: runtime error: Index or slice is out of bounds.
at <lambda> (tests/checked/functions_as_values_2.sakura:5:67)
at main (tests/checked/functions_as_values_2.sakura:7:18)
@@ -0,0 +1,8 @@
import std::io;
def main(): void {
var held: int[4] = [1, 2, 3, 4];
val view := ((&mut held) as *mut int)[0:4];
val pick := def(values: span<int>, at: u64): int { return values[at]; };
println($"{pick(view, 3)}");
println($"{pick(view, 9)}");
}
@@ -0,0 +1,5 @@
--- exit 1
sakura: runtime error: Value is not a member of its enum.
at back<color> (tests/checked/ordinal_parameters_convert_to_and_from_integers_2.sakura:3:52)
at main (tests/checked/ordinal_parameters_convert_to_and_from_integers_2.sakura:4:42)
@@ -0,0 +1,4 @@
import std::io;
enum color: u8 { red, green = 4 }
def back<T>(n: u64): T where T: ordinal { return n as T; }
def main(): void { val c := back::<color>(3); }
@@ -0,0 +1,4 @@
--- exit 1
sakura: runtime error: Union does not hold the field that was read.
at main (tests/checked/refined_functions_as_values_2.sakura:6:8)
@@ -0,0 +1,7 @@
import std::io;
struct failure { val message: span<u8>; }
union callable { var failure: failure; var call: def(): void; }
def main(): void {
val held := callable{ failure = failure{ message = "no" } };
held.call();
}
@@ -0,0 +1,5 @@
66
--- exit 1
sakura: runtime error: Index or slice is out of bounds.
at pick (tests/checked/text_constants_are_indexed_as_views_2.sakura:2:35)
at main (tests/checked/text_constants_are_indexed_as_views_2.sakura:3:57)
@@ -0,0 +1,3 @@
import std::io;
def pick(i: u64): u8 { return "AB"[i]; }
def main(): void { print($"{pick(1)} "); println($"{pick(5)}"); }
@@ -0,0 +1,6 @@
before
--- exit 1
sakura: runtime error: Index or slice is out of bounds.
at holder::at (tests/checked/types_implementing_indexable_are_indexed_3.sakura:4:71)
at main (tests/checked/types_implementing_indexable_are_indexed_3.sakura:8:15)
@@ -0,0 +1,9 @@
import std::io;
struct holder : indexable<u64, int> { var items: int[4]; }
def holder::at(&this, key: u64): &int { return &this.items[key]; }
def holder::at(&mut this, key: u64): &mut int { return &mut this.items[key]; }
def main(): void {
var d := holder { items = [1, 2, 3, 4] };
println("before");
println($"{d[9]}");
}
+5
View File
@@ -0,0 +1,5 @@
before
--- exit 1
sakura: runtime error: Union does not hold the field that was read.
at main (tests/checked/unions_2.sakura:6:14)
+7
View File
@@ -0,0 +1,7 @@
import std::io;
union number { var whole: int; var real: f64; }
def main(): void {
val n := number{ real = 1.5 };
println("before");
val i := n.whole;
}
@@ -0,0 +1,5 @@
before
--- exit 1
sakura: runtime error: Index or slice is out of bounds.
at main (tests/checked/views_of_fixed_arrays_write_where_the_array_can_2.sakura:6:13)
@@ -0,0 +1,8 @@
import std::io;
def main(): void {
var a: int[4] = [1, 2, 3, 4];
var n := 3;
println("before");
val s := a[n:2];
println($"{s}");
}
+510
View File
@@ -0,0 +1,510 @@
#! @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.view());
out.append("\n");
}
var wanted := string::from(names, nothing {});
for name in wanted.split(' ') {
for &function in lowering.program.functions {
if function.name.view() == name {
var text := function.body.print();
out.append(text.view());
}
}
}
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.view();
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)
"""));
}
+298
View File
@@ -0,0 +1,298 @@
#! @file intermediate.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the tests of the intermediate code: building it with variables,
#! which become the parameters of blocks where control flow joins, taking out
#! what stands for one value, verifying it, printing it, and walking it, and
#! the lists of indices its blocks and edges hold.
import std::io;
import std::testing;
module sakura::compiler;
#! Whether two texts are the same but for the line breaks ending them, which
#! printed code ends with and a block of text does not.
#! @param a One text.
#! @param b The other.
#! @returns Whether they are.
def same_text(a: strview, b: strview): bool {
var x := a.length;
var y := b.length;
while x > 0 && a.at(x - 1) == '\n' { x--; }
while y > 0 && b.at(y - 1) == '\n' { y--; }
val same := a.substr(0, x) == b.substr(0, y);
if !same {
println(a);
}
return same;
}
#! Builds the loop of `steps`, which counts the steps of the Collatz sequence:
#!
#! ```
#! 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;
#! }
#! ```
#! @returns Its code.
def build_steps(): code {
var params: vt[1] = [vt::word];
var made := builder::new(params[0:1]);
val n := made.variable(vt::word);
val count := made.variable(vt::word);
made.assign(n, made.param(0));
made.assign(count, made.word(0));
val head := made.new_block();
val body := made.new_block();
val exit := made.new_block();
made.jump(head);
made.switch_to(head);
val done := made.binary(op::ne, made.read(n), made.word(1));
made.branch(done, body, exit);
made.seal(body);
made.seal(exit);
made.switch_to(body);
val even := made.binary(op::eq, made.binary(op::remu, made.read(n), made.word(2)), made.word(0));
val half := made.new_block();
val odd := made.new_block();
val next := made.new_block();
made.branch(even, half, odd);
made.seal(half);
made.seal(odd);
made.switch_to(half);
made.assign(n, made.binary(op::divu, made.read(n), made.word(2)));
made.jump(next);
made.switch_to(odd);
made.assign(n, made.binary(op::add, made.binary(op::mul, made.word(3), made.read(n)), made.word(1)));
made.jump(next);
made.seal(next);
made.switch_to(next);
made.assign(count, made.binary(op::add, made.read(count), made.word(1)));
made.jump(head);
made.seal(head);
made.switch_to(exit);
var result: u32[1] = [made.read(count)];
made.ret(result[0:1]);
return made.finish();
}
@test def loops_take_their_variables_as_parameters(t: &mut tester): void {
var made := build_steps();
made.results.append(vt::word);
val verdict := made.verify();
t.expects(verdict.ok());
for &each in verdict.problems {
println(each);
}
val printed := made.print();
val want := """
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 b1(v16, v18)
""";
t.expects(same_text(printed.view(), want));
}
@test def parameters_standing_for_one_value_are_taken_out(t: &mut tester): void {
# `x` is given before the branch, and neither side changes it, so the join
# takes nothing.
var params: vt[1] = [vt::word];
var made := builder::new(params[0:1]);
val x := made.variable(vt::word);
made.assign(x, made.param(0));
val then := made.new_block();
val other := made.new_block();
val join := made.new_block();
made.branch(made.param(0), then, other);
made.seal(then);
made.seal(other);
made.switch_to(then);
made.jump(join);
made.switch_to(other);
made.jump(join);
made.seal(join);
made.switch_to(join);
var result: u32[1] = [made.read(x)];
made.ret(result[0:1]);
var code := made.finish();
code.results.append(vt::word);
t.expects(code.verify().ok());
t.expects(same_text(code.print().view(), """
b0(v0: i64):
branch v0, b2, b1
b1:
jump b3
b2:
jump b3
b3:
ret v0
"""));
}
@test def what_nothing_reaches_is_taken_out(t: &mut tester): void {
var made := builder::new(span::<vt>::empty());
var none: u32[1] = [0];
made.ret(none[0:0]);
# Code after a `return` goes in a block nothing reaches.
made.word(5);
made.ret(none[0:0]);
var code := made.finish();
t.expects(code.verify().ok());
t.expects(same_text(code.print().view(), "b0:\n ret"));
}
@test def the_verifier_finds_uses_not_dominated(t: &mut tester): void {
var params: vt[1] = [vt::word];
var made := builder::new(params[0:1]);
val then := made.new_block();
val other := made.new_block();
val join := made.new_block();
made.branch(made.param(0), then, other);
made.seal(then);
made.seal(other);
made.switch_to(then);
val only_here := made.word(1);
made.jump(join);
made.switch_to(other);
made.jump(join);
made.seal(join);
made.switch_to(join);
var result: u32[1] = [only_here];
made.ret(result[0:1]);
var code := made.finish();
code.results.append(vt::word);
val verdict := code.verify();
t.expects(!verdict.ok());
}
@test def lists_of_indices_hold_four_themselves_and_more_in_memory(t: &mut tester): void {
var list := ids {};
for i in 0..4u {
list.append(i as u32 * 3);
}
t.expects(list.length == 4 && list.at(3) == 9);
# Past four the indices move to memory of the list's own, and stay in order.
for i in 4..100u {
list.append(i as u32 * 3);
}
var total: u64 = 0;
for &each in list {
total += each as u64;
}
t.expects(list.length == 100 && list.at(0) == 0 && list.at(99) == 297 && total == 14850);
list.at(5) = 1;
var other := list.copied(nothing {});
t.expects(other.at(5) == 1 && other.length == 100);
var same := ids {};
for &each in other {
same.append(each);
}
t.expects(same.same(&list));
same.clear();
t.expects(same.length == 0 && !same.same(&list));
}
@test def walks_give_each_instruction_and_what_each_reads(t: &mut tester): void {
var made := build_steps();
# Every instruction of the blocks not removed, each once.
var count: u32 = 0;
var all := made.walk_all();
while all.more() {
all.next();
count++;
}
t.expects(count != 0 && count == made.size());
# The loop's head, block 1, compares and branches.
var found := vector::<u32>::new();
var head := made.walk(1);
while head.more() {
found.append(head.next());
}
t.expects(found.length == 3 && made.insts[found[0]].kind == op::iconst
&& made.insts[found[1]].kind == op::ne && made.insts[found[2]].kind == op::branch);
# The comparison reads its operands, in order.
var operands := made.reads_of(found[1]);
var places: u32 = 0;
while operands.more() {
operands.next();
t.expects(operands.operand() == places);
places++;
}
t.expects(places == 2);
# The branch leaves by two edges, one after another.
var outs := made.edges_of(found[2]);
t.expects(outs.more() && outs.next() == made.insts[found[2]].aux);
t.expects(outs.more() && outs.next() == made.insts[found[2]].aux + 1 && !outs.more());
# The jump back to the head reads only what its edge gives.
val jump: u32 = made.blocks[6].last;
val first: u32 = made.edges[made.insts[jump].aux].args[0];
var given := made.reads_of(jump);
var values := vector::<u32>::new();
while given.more() {
values.append(given.next());
t.expects(given.operand() == no_operand);
}
t.expects(values.length == 2 && values[0] == first);
# A walk reads where each instruction goes on to as it gives it, so taking
# the one given out of its block's order does not end the walk.
var cut: u32 = 0;
var again := made.walk(1);
while again.more() {
made.insts[again.next()].next = 0;
cut++;
}
t.expects(cut == 3);
}
+697
View File
@@ -0,0 +1,697 @@
#! @file optimizer.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the tests of the optimizer: small programs are checked, lowered,
#! and optimized at a level, the verifier running after every pass, and the
#! code of their functions printed and compared with what is expected. Each
#! test shows what one pass does, with the others cleaning up after it. The
#! containers the passes keep track of what they find with are tested too.
import std::io;
import std::testing;
import sakura::analyzer;
module sakura::compiler;
#! Checks the files as one program, lowers and optimizes every function of it
#! at a level, and gives the code of those named, printed one after another,
#! or what went wrong, the verifier's problems among it. At level 0, every named
#! local is kept in a cell of its own, as `-O0` keeps them.
#! @param level How much the code is optimized.
#! @param names The names of the functions, separated by spaces.
#! @param texts The files' texts.
#! @returns The code.
def optimized(level: u32, names: strview, texts: strview...): string {
return optimized_on(1, level, names, ...texts);
}
#! Checks the files as one program, lowers and optimizes every function of it
#! at a level on a number of threads, and gives the code of those named,
#! printed one after another, or what went wrong, as `optimized` does.
#! @param threads How many threads optimize the functions.
#! @param level How much the code is optimized.
#! @param names The names of the functions, separated by spaces.
#! @param texts The files' texts.
#! @returns The code.
def optimized_on(threads: u32, level: u32, 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, level = level, keep_locals = level == 0, threads = threads });
lowering.compile();
for &each in lowering.problems {
out.append(each.view());
out.append("\n");
}
var wanted := string::from(names, nothing {});
for name in wanted.split(' ') {
for &function in lowering.program.functions {
if function.name.view() == name {
var text := function.body.print();
out.append(text.view());
}
}
}
return out;
}
#! Checks the files as one program, lowers it checked and optimizes it with
#! inlining, and lists the checks left in its functions as
#! `check --checks-report` counts them: for each, the function, the line, the
#! kind, and how many, each followed by a space.
#! @param texts The files' texts.
#! @returns The list, or what went wrong.
def checks_left_in(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, level = 2 });
lowering.compile();
val kinds: strview[4] = ["index", "field", "member", "fault"];
for &each in lowering.checks_left() {
val line := sources.at(pair_high(each.at) as u64 - 1).lines.place_of(pair_low(each.at)).line;
out.append($"{lowering.program.functions[each.function].name}:{line}:{kinds[each.kind as u64]}:{each.count} ");
}
return out;
}
@test def the_checks_the_optimizer_leaves_are_listed_by_line(t: &mut tester): void {
# A check inlined is listed at the call, and one the code proved before, or
# a loop's own test answers, is not left.
val got := checks_left_in("""
union shape { var round: f64; var square: i64; }
enum color: u8 { red, green, blue }
def pick(xs: &i64[8], i: u64): i64 { return xs[i]; }
def side(s: shape): i64 { return s.square; }
def hue(n: u8): color { return n as color; }
def total(xs: &i64[8]): i64 { var t: i64 = 0; for i in 0..8u { t += xs[i]; } return t; }
def twice(xs: &i64[8], i: u64): i64 {
return pick(xs, i) + pick(xs, i);
}
""");
t.expects(got.view() == "pick:3:index:1 side:4:field:1 hue:5:member:1 twice:8:index:1 ");
}
@test def constants_fold_and_powers_of_two_shift(t: &mut tester): void {
# Operators of constants are worked out, and an unsigned division and
# remainder by a power of two become a shift and a mask.
val got := optimized(1, "fold", """
def fold(x: u64): u64 { return x / 8 + x % 16 + 2 * 3; }
""");
t.expects(lowers_as(&got, """
b0(v0: i64):
v1 = iconst 15
v2 = iconst 3
v3 = shru v0, v2
v4 = band v0, v1
v5 = add v3, v4
v6 = iconst 6
v7 = add v5, v6
ret v7
"""));
}
@test def values_nothing_needs_go_even_around_loops(t: &mut tester): void {
# `waste` is only ever added to, and read by nothing else, so the loop no
# longer carries it. The loop is rotated: whether to go round again is asked
# at its bottom, and once before it.
val got := optimized(1, "count", """
def count(n: u64): u64 {
var waste: u64 = 0;
var i: u64 = 0;
while i < n { waste += i; i += 1; }
return i;
}
""");
t.expects(lowers_as(&got, """
b0(v0: i64):
v1 = iconst 0
v2 = iconst 1
branch v0, b1(v1), b2(v1)
b1(v3: i64):
v4 = add v3, v2
v5 = ltu v4, v0
branch v5, b1(v4), b2(v4)
b2(v6: i64):
ret v6
"""));
}
@test def conditions_joined_as_constants_go_straight_where_they_lead(t: &mut tester): void {
# `a && !b` joins the constant it works out before branching on it; each
# edge giving a constant goes straight where the branch would send it.
val got := optimized(1, "both", """
def both(a: bool, b: bool): i64 {
if a && !b { return 1; }
return 2;
}
""");
t.expects(lowers_as(&got, """
b0(v0: i64, v1: i64):
branch v0, b1, b3
b1:
branch v1, b3, b2
b2:
v2 = iconst 1
ret v2
b3:
v3 = iconst 2
ret v3
"""));
}
@test def flags_worked_out_from_constants_go_straight_where_they_lead(t: &mut tester): void {
# The join works out `found == 1` from the constant each way gives it, so
# each goes straight where the test sends it, and the value it gave `at`
# reaches what reads it as a parameter of where it went.
val got := optimized(1, "first", """
def first(a: bool, x: i64): i64 {
var found: u64 = 0;
var at: i64 = 0;
if a { found = 1; at = x; }
if found == 1 { return at + 1; }
return 0;
}
""");
t.expects(lowers_as(&got, """
b0(v0: i64, v1: i64):
v2 = iconst 0
branch v0, b2, b1
b1:
ret v2
b2:
v3 = iconst 1
v4 = add v1, v3
ret v4
"""));
}
@test def branches_choosing_values_become_selects(t: &mut tester): void {
# The `if` only chooses the value `x` joins with, so it becomes a `select`.
val got := optimized(1, "pick", """
def pick(c: bool, a: i64, b: i64): i64 {
var x := b;
if c { x = a; }
return x;
}
""");
t.expects(lowers_as(&got, """
b0(v0: i64, v1: i64, v2: i64):
v3 = select v0, v1, v2
ret v3
"""));
# Where `n` is zero, `k` is 0 either way, which is `n`.
val zeros := optimized(1, "nonzero", """
def nonzero(n: u64): u64 {
var k: u64 = 0;
if n != 0 { k = n; }
return k;
}
""");
t.expects(lowers_as(&zeros, """
b0(v0: i64):
ret v0
"""));
# Within the `if`, `c` is known not to be zero, so the choice is known.
val known := optimized(1, "known", """
def known(c: bool, a: i64, b: i64): i64 {
if c { return c ? a : b; }
return 0;
}
""");
t.expects(lowers_as(&known, """
b0(v0: i64, v1: i64, v2: i64):
branch v0, b2, b1
b1:
v3 = iconst 0
ret v3
b2:
ret v1
"""));
}
@test def a_check_a_dominating_one_made_goes(t: &mut tester): void {
# The second `v[i]` compares what the first did, which was checked, and
# reads what it read.
val got := optimized(1, "twice", """
def twice(v: &i64[8], i: u64): i64 { return v[i] + v[i]; }
""");
t.expects(lowers_as(&got, """
b0(v0: i64, v1: i64):
v2 = iconst 3
v3 = iconst 8
v4 = ltu v1, v3
check v4, out_of_bounds
v5 = shl v1, v2
v6 = add v0, v5
v7 = load.i64 v6
v8 = add v7, v7
ret v8
"""));
}
@test def a_read_a_loop_writing_nothing_repeats_reads_what_was_read_before(t: &mut tester): void {
# Nothing in the loop writes, so `p.key` reads what it read before the loop
# each time round.
val got := optimized(1, "scan", """
struct pair { var key: i64; var other: i64; }
def scan(p: &pair, v: &i64[8]): u64 {
if p.key < 0 { return 8; }
var i: u64 = 0;
while i < 8 { if v[i] == p.key { return i; } i += 1; }
return i;
}
""");
t.expects(lowers_as(&got, """
b0(v0: i64, v1: i64):
v2 = iconst 1
v3 = iconst 8
v4 = iconst 3
v5 = load.i64 v0
v6 = iconst 0
v7 = lts v5, v6
branch v7, b6, b1
b1:
jump b2(v6)
b2(v8: i64):
v9 = shl v8, v4
v10 = add v1, v9
v11 = load.i64 v10
v12 = eq v11, v5
branch v12, b5, b3
b3:
v13 = add v8, v2
v14 = ltu v13, v3
branch v14, b2(v13), b4
b4:
ret v13
b5:
ret v8
b6:
ret v3
"""));
}
@test def a_choice_sunk_past_the_branch_deciding_it_is_what_it_chooses(t: &mut tester): void {
# `s` is only read where `c != 0`, so the `select` making it is sunk there,
# where the branch decides its condition, and becomes what it chooses.
val got := optimized(1, "pick", """
def pick(a: *u64): u64 {
val c := a[0];
val s := c != 0 ? c + 1 : 5;
if c != 0 { return s * 3; }
return 7;
}
""");
t.expects(lowers_as(&got, """
b0(v0: i64):
v1 = iconst 1
v2 = load.i64 v0
branch v2, b2, b1
b1:
v3 = iconst 7
ret v3
b2:
v4 = add v2, v1
v5 = iconst 3
v6 = mul v4, v5
ret v6
"""));
}
@test def loops_rotate_and_what_they_work_out_the_same_moves_out(t: &mut tester): void {
# The loop asks whether to go round again at its bottom, and once before it,
# where the size is read. Nothing in it writes, so the size is read there
# only, and where the pointer is read and checked is before the loop, as its
# first pass reads and checks it before anything else.
val got := optimized(1, "find", """
struct table { var data: *i64; var size: u64; }
def find(t: &table, key: i64): u64 {
var i: u64 = 0;
while i < t.size { if t.data[i] == key { return i; } i += 1; }
return t.size;
}
""");
t.expects(lowers_as(&got, """
b0(v0: i64, v1: i64):
v2 = iconst 0
v3 = iconst 1
v4 = iconst 3
v5 = load.i64 v0+8
branch v5, b1, b4
b1:
v6 = load.i64 v0
check v6, null_reference
jump b2(v2)
b2(v7: i64):
v8 = shl v7, v4
v9 = add v6, v8
v10 = load.i64 v9
v11 = eq v10, v1
branch v11, b5, b3
b3:
v12 = add v7, v3
v13 = ltu v12, v5
branch v13, b2(v12), b4
b4:
ret v5
b5:
ret v7
"""));
}
@test def writes_known_not_to_touch_a_read_leave_it_known(t: &mut tester): void {
# Writing `p.b` does not write `p.a`, so `p.a` is read once.
val fields := optimized(1, "bump", """
struct pair { var a: i64; var b: i64; }
def bump(p: &mut pair): i64 { val x := p.a; p.b = x; return p.a + 1; }
""");
t.expects(lowers_as(&fields, """
b0(v0: i64):
v1 = load.i64 v0
store.i64 v0+8, v1
v2 = iconst 1
v3 = add v1, v2
ret v3
"""));
# A call cannot write a cell whose address it is not given, so what was
# stored there is read again without the cell.
val called := optimized(1, "kept", """
def tick(): void {}
def kept(n: i64): i64 { var x := n * 3; tick(); return x + 1; }
""");
t.expects(lowers_as(&called, """
b0(v0: i64):
v1 = iconst 3
v2 = mul v0, v1
call f1()
v3 = iconst 1
v4 = add v2, v3
ret v4
"""));
# Writing the frame's array does not write what `p` points at, so the loop
# reads `p.a` once, before it.
val looped := optimized(2, "fill", """
struct pair { var a: i64; var b: i64; }
def fill(p: &pair): i64 {
var buf: i64[4] = [0, 0, 0, 0];
var i: u64 = 0;
while i < 4 { buf[i] = p.a; i += 1; }
return buf[0] + buf[3];
}
""");
t.expects(lowers_as(&looped, """
c0: 32, 8
b0(v0: i64):
v1 = iconst 1
v2 = iconst 4
v3 = iconst 3
v4 = cell c0
v5 = iconst 0
v6 = load.i64 v0
jump b1(v5)
b1(v7: i64):
v8 = shl v7, v3
v9 = add v4, v8
store.i64 v9, v6
v10 = add v7, v1
v11 = ltu v10, v2
branch v11, b1(v10), b2
b2:
v12 = load.i64 v4
v13 = load.i64 v4+24
v14 = add v12, v13
ret v14
"""));
}
@test def what_one_way_out_reads_moves_into_that_way(t: &mut tester): void {
# The limit and the step are read only where `go` holds, so they are read
# there, after the count that both ways read.
val got := optimized(1, "advance", """
struct counter { var count: u64; var limit: u64; var step: u64; }
def advance(c: &counter, go: bool): u64 {
val limit := c.limit;
val step := c.step;
val count := c.count;
if go { return limit + step + count; }
return count;
}
""");
t.expects(lowers_as(&got, """
b0(v0: i64, v1: i64):
v2 = load.i64 v0
branch v1, b2, b1
b1:
ret v2
b2:
v3 = load.i64 v0+8
v4 = load.i64 v0+16
v5 = add v3, v4
v6 = add v5, v2
ret v6
"""));
}
@test def small_functions_inline_and_their_cells_become_values(t: &mut tester): void {
# `sum` is inlined, and the point it was given the address of, and the copy
# of its literal, become the values they hold.
val got := optimized(2, "made", """
struct point { var x: i64; var y: i64; }
def point::sum(&this): i64 { return this.x + this.y; }
def made(a: i64, b: i64): i64 { val p := point { x = a, y = b }; return p.sum(); }
""");
t.expects(lowers_as(&got, """
b0(v0: i64, v1: i64):
v2 = add v0, v1
ret v2
"""));
# `% 2 == 0` becomes a mask, and `/ 2` a shift; both ways of the `if` are
# worked out and a `select` of the mask chooses between them, and the loop,
# rotated, goes round without making its constants again.
val looped := optimized(2, "steps", """
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;
}
""");
t.expects(lowers_as(&looped, """
b0(v0: i64):
v1 = iconst 3
v2 = iconst 1
v3 = iconst 0
v4 = ne v0, v2
branch v4, b1(v0, v3), b2(v3)
b1(v5: i64, v6: i64):
v7 = band v5, v2
v8 = mul v5, v1
v9 = add v8, v2
v10 = shru v5, v2
v11 = select v7, v9, v10
v12 = add v6, v2
v13 = ne v11, v2
branch v13, b1(v11, v12), b2(v12)
b2(v14: i64):
ret v14
"""));
}
@test def inline_functions_are_copied_at_every_level(t: &mut tester): void {
val text := """
struct inline {}
@inline def twice(x: i64): i64 { val y := x * 2; return y; }
def thrice(x: i64): i64 { return x * 3; }
@inline def count(n: i64): i64 { return n == 0 ? 0 : count(n - 1) + 1; }
def f(a: i64): i64 { return thrice(twice(a)) + count(a); }
""";
# At `-O0`, the calls of `twice` and `count` are copied, each parameter and
# local still in a cell of its own, and nothing else changes: `thrice` is
# called, and so is `count` within its copy, as that call closes a loop. The
# copies clear none of their cells, as each is written before it is read, so
# the functions' own frames would zero none of them.
val none := optimized(0, "f", text);
t.expects(lowers_as(&none, """
c0: 8, 8
c1: 8, 8
c2: 8, 8
c3: 8, 8
b0(v0: i64):
v1 = cell c0
store.i64 v1, v0
v2 = load.i64 v1
jump b1
b1:
v3 = cell c1
store.i64 v3, v2
v4 = cell c2
v5 = load.i64 v3
v6 = iconst 2
v7 = mul v5, v6
store.i64 v4, v7
v8 = load.i64 v4
jump b2
b2:
v9 = call f2(v8)
v10 = load.i64 v1
jump b3
b3:
v11 = cell c3
store.i64 v11, v10
v12 = load.i64 v11
v13 = iconst 0
v14 = eq v12, v13
branch v14, b5, b4
b4:
v15 = load.i64 v11
v16 = iconst 1
v17 = sub v15, v16
v18 = call f3(v17)
v19 = iconst 1
v20 = add v18, v19
jump b6(v20)
b5:
v21 = iconst 0
jump b6(v21)
b6(v22: i64):
jump b7
b7:
v23 = add v9, v22
ret v23
"""));
# At `-O1`, the copies are folded into what calls them as any code is.
val local := optimized(1, "f", text);
t.expects(lowers_as(&local, """
b0(v0: i64):
v1 = iconst 1
v2 = shl v0, v1
v3 = call f2(v2)
v4 = iconst 0
branch v0, b1, b2(v4)
b1:
v5 = sub v0, v1
v6 = call f3(v5)
v7 = add v6, v1
jump b2(v7)
b2(v8: i64):
v9 = add v3, v8
ret v9
"""));
# At `-O2`, one of any size is copied, past `--inline N`, though it is called
# more than once.
val large := optimized(2, "g", """
struct inline {}
@inline def mix(x: u64): u64 {
var h := x;
h = (h ^ (h >> 33)) * 0xFF51AFD7ED558CCD;
h = (h ^ (h >> 33)) * 0xC4CEB9FE1A85EC53;
h = (h ^ (h >> 29)) * 0xFF51AFD7ED558CCD;
h = (h ^ (h >> 31)) * 0xC4CEB9FE1A85EC53;
h = (h ^ (h >> 30)) * 0xFF51AFD7ED558CCD;
h = (h ^ (h >> 27)) * 0xC4CEB9FE1A85EC53;
return h ^ (h >> 31);
}
def g(a: u64, b: u64): u64 { return mix(a) + mix(b); }
""");
t.expects(large.view().find("mul") is some && large.view().find("call") is none);
}
@test def worklists_take_each_index_once_and_scopes_take_back_what_they_set(t: &mut tester): void {
var work := worklist::new(8, nothing {});
t.expects(work.push_new(3) && work.push_new(5) && !work.push_new(3));
t.expects(work.pop() == 5 && work.pop() == 3 && work.is_empty);
t.expects(work.has(3) && !work.has(4) && !work.push_new(5));
# A stamped set empties as each round begins.
var counted := stamped_set::new(8, nothing {});
t.expects(counted.insert(2) && !counted.insert(2) && counted.contains(2));
counted.next_round();
t.expects(!counted.contains(2) && counted.insert(2));
# Rewinding puts back what each key held at the mark, or takes it out.
val one: u32 = 1;
val two: u32 = 2;
var scoped := scoped_dict::<u32, u32>::new(nothing {});
scoped.set(1, 10);
val mark := scoped.mark();
scoped.set(1, 11);
scoped.set(2, 20);
t.expects(scoped.get_or(&one, 0) == 11 && scoped.contains(&two));
scoped.rewind(mark);
t.expects(scoped.get_or(&one, 0) == 10 && !scoped.contains(&two));
scoped.rewind(0);
t.expects(!scoped.contains(&one) && scoped.mark() == 0);
}
+137
View File
@@ -0,0 +1,137 @@
#! @file workers.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the tests of sharing the compiler's work out among threads: each
#! index done once, each after those it waits for, each thread with scratch
#! memory of its own, and functions optimized on threads made into what one
#! thread makes them.
import std::containers;
import std::testing;
import sakura::analyzer;
module sakura::compiler;
@test def work_shared_out_is_done_once_for_each_index(t: &mut tester): void {
val count: u64 = 2000;
for threads in 1..6u {
var done := vector::<atomic<u32>>::new();
for _ in 0..count {
done.append(atomic::<u32>::new(0));
}
share_out(count, threads as u32, def(index: u64): void { _ = done[index].fetch_add(1); });
var once := true;
for i in 0..count {
once = once && done[i].load() == 1;
}
t.expects(once);
}
}
@test def work_shared_out_in_order_waits_for_what_it_waits_for(t: &mut tester): void {
# Each index but the first waits for the one halfway to it, as in a heap,
# and is stamped as it is done, after the one it waits for.
val count: u64 = 1023;
var waiting := groups::<u32>::new(count);
for child in 1..count {
waiting.count((child - 1) / 2);
}
waiting.seal();
for child in 1..count {
waiting.put((child - 1) / 2, child as u32);
}
for threads in 1..6u {
var stamps := vector::<atomic<u64>>::new();
for _ in 0..count {
stamps.append(atomic::<u64>::new(0));
}
var clock := atomic::<u64>::new(0);
share_out_ordered(count, threads as u32, &waiting, def(index: u64): void {
stamps[index].store(clock.fetch_add(1) + 1);
});
var ordered := true;
for i in 1..count {
ordered = ordered && stamps[i].load() != 0 && stamps[(i - 1) / 2].load() < stamps[i].load();
}
t.expects(ordered && stamps[0].load() != 0);
}
}
@test def each_thread_takes_scratch_memory_of_its_own(t: &mut tester): void {
# Each index fills scratch memory it marked, then reads it back; another
# thread marking, taking, or rewinding the same memory meanwhile would change
# what it reads.
var wrong := atomic::<u32>::new(0);
share_out(256, 5, def(index: u64): void {
val point := mark_scratch();
var filled := vector::<u64>::new(scratch());
for k in 0..4000u {
filled.append(index * 4000 + k);
}
var also := vector::<u64>::new(scratch());
also.resize(512);
for k in 0..4000u {
if filled[k] != index * 4000 + k {
_ = wrong.fetch_add(1);
}
}
also.close();
filled.close();
release_scratch(point);
});
t.expects(wrong.load() == 0);
}
@test def functions_optimized_on_threads_are_made_what_one_thread_makes_them(t: &mut tester): void {
# Functions calling each other, in a cycle and through several levels, which
# inlining copies into one another, so one optimized before or after what it
# inlines would come out otherwise.
val text := """
def leaf(x: i64): i64 { return x * 2 + 1; }
def twice(x: i64): i64 { return leaf(x) + leaf(x + 1); }
def even(n: i64): bool { return n == 0 ? true : odd(n - 1); }
def odd(n: i64): bool { return n == 0 ? false : even(n - 1); }
def sum(n: i64): i64 {
var total: i64 = 0;
for i in 0..n { total += twice(i); }
return total;
}
def pick(n: i64): i64 { return even(n) ? sum(n) : twice(n); }
def main(): void { if pick(10) == 0 { return; } }
""";
val names := "leaf twice even odd sum pick main";
for level in 1..3u {
val one := optimized_on(1, level as u32, names, text);
t.expects(one.length > 200 && !one.view().starts_with("the program"));
for threads in 2..6u {
val many := optimized_on(threads as u32, level as u32, names, text);
t.expects(one.view() == many.view());
}
}
# The same, where some are `@inline`, and so copied at `-O0` too.
val marked := """
struct inline {}
@inline def leaf(x: i64): i64 { return x * 2 + 1; }
@inline def twice(x: i64): i64 { return leaf(x) + leaf(x + 1); }
@inline def even(n: i64): bool { return n == 0 ? true : odd(n - 1); }
def odd(n: i64): bool { return n == 0 ? false : even(n - 1); }
def sum(n: i64): i64 {
var total: i64 = 0;
for i in 0..n { total += twice(i); }
return total;
}
def pick(n: i64): i64 { return even(n) ? sum(n) : twice(n); }
def main(): void { if pick(10) == 0 { return; } }
""";
for level in 0..3u {
val one := optimized_on(1, level as u32, names, marked);
t.expects(one.length > 200 && !one.view().starts_with("the program"));
for threads in 2..6u {
val many := optimized_on(threads as u32, level as u32, names, marked);
t.expects(one.view() == many.view());
}
}
}
+16
View File
@@ -0,0 +1,16 @@
# Tests of the memory `core` gives: a block of the heap keeps what it holds
# through resizing. The allocators of std, an arena and a pool, are tested
# there.
import std::testing;
@test def uncleared_memory_keeps_what_it_holds_through_resizing(t: &mut tester): void {
val block := raw_allocate(64) as *mut u64;
for i in 0..8u { block[i] = i * 11; }
val grown := raw_resize(block as *mut u8, 8192) as *mut u64;
var same := true;
for i in 0..8u { same = same && grown[i] == i * 11; }
val shrunk := raw_resize(grown as *mut u8, 16) as *mut u64;
t.expects(same && shrunk[1] == 11);
raw_release(shrunk as *mut u8);
}
+195
View File
@@ -0,0 +1,195 @@
# Tests of atomics: each operation at each width, of integers, `bool`, enums,
# and pointers, the orders that make no sense stopping the program, and two
# processes adding to memory they share, which loses nothing only where every
# addition is one step.
import system;
import std::testing;
# Whether running the function stops the program. It runs in a copy of the
# program that writes nothing, so that this one goes on and the report of the
# stop is not mixed into the tests'.
def stops_atomically(run: def(): void): bool {
when os == windows {
val stopped := copied(run);
return !(stopped.exited && stopped.code == 0);
}
val child := fork();
if child == 0 {
val out: fd = fd::stdout;
val err: fd = fd::stderr;
out.close();
err.close();
run();
exit(0);
}
var status: process_status;
return wait(child, &mut status) >= 0 && !(status.exited && status.code == 0);
}
# Works every operation on an atomic of `T`, given a value below another, compared
# as `T` is, where of an unsigned type the higher has its top bit set, so that
# comparing it as signed would order them the other way, and the least and
# greatest of `T`.
def operations_of<T>(t: &mut tester, low: T, high: T, least: T, most: T): void where T: integer, lockfree {
var a := atomic::<T>::new(low);
t.expects(a.load() == low);
a.store(high);
t.expects(a.load() == high);
t.expects(a.exchange(low) == high && a.load() == low);
# Adding and subtracting wrap.
a.store(most);
t.expects(a.fetch_add(1) == most && a.load() == least);
t.expects(a.fetch_sub(1) == least && a.load() == most);
a.store(low);
t.expects(a.fetch_add(high) == low);
val sum := a.load();
t.expects(a.fetch_sub(high) == sum && a.load() == low);
# Bits, against the operators.
a.store(high);
t.expects(a.fetch_and(low) == high && a.load() == (high & low));
a.store(high);
t.expects(a.fetch_or(low) == high && a.load() == (high | low));
a.store(high);
t.expects(a.fetch_xor(low) == high && a.load() == (high ^ low));
# The least and greatest, compared as `T` is.
a.store(low);
t.expects(a.fetch_min(high) == low && a.load() == low);
t.expects(a.fetch_max(high) == low && a.load() == high);
t.expects(a.fetch_max(low) == high && a.load() == high);
t.expects(a.fetch_min(low) == high && a.load() == low);
# A compare-exchange writes where it finds what it expects, and otherwise gives
# what it found.
match a.compare_exchange(low, high) {
value(found) => t.expects(found == low && a.load() == high);
error(_) => t.expects(false);
}
match a.compare_exchange(low, most, order::acq_rel, order::acquire) {
value(_) => t.expects(false);
error(found) => t.expects(found == high && a.load() == high);
}
match a.compare_exchange_weak(high, least, order::release, order::relaxed) {
value(found) => t.expects(found == high && a.load() == least);
error(_) => t.expects(false);
}
}
@test def every_operation_works_at_every_width(t: &mut tester): void {
operations_of::<u8>(t, 100, 200, 0, 255);
operations_of::<i8>(t, -56, 100, -128, 127);
operations_of::<u16>(t, 0x1234, 0xF00D, 0, 0xFFFF);
operations_of::<i16>(t, -4000, 0x1234, -32768, 32767);
operations_of::<u32>(t, 7, 0x80000001, 0, 0xFFFFFFFF);
operations_of::<i32>(t, -2000000000, 2000000000, -2147483648, 2147483647);
operations_of::<u64>(t, 3, 0x8000000000000003, 0, 0xFFFFFFFFFFFFFFFF);
operations_of::<i64>(t, -0x7000000000000000, 0x7000000000000000, -0x7FFFFFFFFFFFFFFF - 1, 0x7FFFFFFFFFFFFFFF);
}
@test def every_order_is_taken_where_it_makes_sense(t: &mut tester): void {
var a := atomic::<u32>::new(1);
for how in [order::relaxed, order::acquire, order::seq_cst] {
t.expects(a.load(how) == 1);
}
for how in [order::relaxed, order::release, order::seq_cst] {
a.store(2, how);
t.expects(a.load() == 2);
}
for how in [order::relaxed, order::acquire, order::release, order::acq_rel, order::seq_cst] {
t.expects(a.fetch_add(1, how) == 2 && a.exchange(2, how) == 3);
fence(how);
}
t.expects(a.compare_exchange(2, 5, order::seq_cst, order::seq_cst) is value);
t.expects(a.compare_exchange(5, 6, order::acq_rel, order::acquire) is value);
t.expects(a.compare_exchange(6, 7, order::release, order::relaxed) is value);
t.expects(a.compare_exchange(0, 8, order::relaxed, order::relaxed) is error);
t.expects(a.load() == 7);
}
enum light { red, amber, green }
@test def bools_enums_and_pointers_are_atomic(t: &mut tester): void {
var flag := atomic::<bool>::new(false);
t.expects(!flag.exchange(true) && flag.load());
t.expects(flag.compare_exchange(true, false) is value && !flag.load());
t.expects(flag.compare_exchange(true, true) is error);
var lamp := atomic::<light>::new(light::red);
lamp.store(light::green);
t.expects(lamp.exchange(light::amber) == light::green);
match lamp.compare_exchange(light::red, light::green) {
value(_) => t.expects(false);
error(found) => t.expects(found == light::amber);
}
val block := raw_allocate(16);
var at := atomic::<*mut u8>::new(null);
t.expects(at.exchange(block) == null && at.load() == block);
t.expects(at.compare_exchange(block, block + 8) is value && at.load() == block + 8);
raw_release(block);
}
@test def orders_that_make_no_sense_stop_the_program(t: &mut tester): void {
t.expects(stops_atomically(def() { var a := atomic::<u64>::new(0); _ = a.load(order::release); }));
t.expects(stops_atomically(def() { var a := atomic::<u64>::new(0); _ = a.load(order::acq_rel); }));
t.expects(stops_atomically(def() { var a := atomic::<u64>::new(0); a.store(1, order::acquire); }));
t.expects(stops_atomically(def() { var a := atomic::<u64>::new(0); a.store(1, order::acq_rel); }));
t.expects(stops_atomically(def() { var a := atomic::<u64>::new(0); _ = a.compare_exchange(0, 1, order::seq_cst, order::release); }));
t.expects(stops_atomically(def() { var a := atomic::<u64>::new(0); _ = a.compare_exchange(0, 1, order::seq_cst, order::acq_rel); }));
# A failure no stronger than what the success reads.
t.expects(stops_atomically(def() { var a := atomic::<u64>::new(0); _ = a.compare_exchange(0, 1, order::relaxed, order::acquire); }));
t.expects(stops_atomically(def() { var a := atomic::<u64>::new(0); _ = a.compare_exchange(0, 1, order::release, order::acquire); }));
t.expects(stops_atomically(def() { var a := atomic::<u64>::new(0); _ = a.compare_exchange(0, 1, order::acq_rel, order::seq_cst); }));
t.expects(!stops_atomically(def() { var a := atomic::<u64>::new(0); _ = a.compare_exchange(0, 1, order::acq_rel, order::acquire); }));
t.expects(!stops_atomically(def() { var a := atomic::<u64>::new(0); _ = a.load(order::acquire); a.store(1, order::release); }));
}
# How many times each process adds.
const contended: u64 = 1000000;
# Sharing a page between processes takes `fork` and `mmap`, which Linux has.
when os == linux {
@test def two_processes_adding_to_memory_they_share_lose_nothing(t: &mut tester): void {
# A page both processes keep after `fork`, rather than a copy each.
val page := system::linux::syscall(9, 0, 4096, 3, 0x21, 0xFFFFFFFFFFFFFFFF, 0);
t.expects(page > 0);
return if page <= 0;
val sum := page as u64 as *mut atomic<u64>;
val tries := (page as u64 + 8) as *mut atomic<u32>;
val bits := (page as u64 + 16) as *mut atomic<u16>;
val most := (page as u64 + 24) as *mut atomic<i32>;
val child := fork();
val own: u64 = child == 0 ? 1 : 2;
for i in 0..contended {
_ = sum[0].fetch_add(1);
# A loop of compare-exchanges adds as well, trying again where the other
# process wrote first.
var seen := tries[0].load(order::relaxed);
while true {
match tries[0].compare_exchange_weak(seen, seen + 1, order::acq_rel, order::relaxed) {
value(_) => break;
error(found) => seen = found;
}
}
_ = most[0].fetch_max((i * 2 + own) as i32);
if i % 1000 == 0 {
_ = bits[0].fetch_or((1 << (own * 4 + i / 1000 % 4)) as u16);
}
}
if child == 0 {
exit(0);
}
var status: process_status;
t.expects(wait(child, &mut status) >= 0 && status.exited && status.code == 0);
t.expects(sum[0].load() == 2 * contended);
t.expects(tries[0].load() == 2 * contended as u32);
t.expects(bits[0].load() == 0xFF0);
t.expects(most[0].load() == ((contended - 1) * 2 + 2) as i32);
_ = system::linux::syscall(11, page as u64, 4096, 0, 0, 0, 0);
}
}
+111
View File
@@ -0,0 +1,111 @@
# Tests of the containers: what they check of what they are asked for, what they
# close of their elements, and what they do where an allocator gives no memory,
# with the helpers of std they lean on.
import system;
import std::testing;
import std::containers;
# How many counters have been closed, which only those holding a count are.
var closed: u64 = 0;
struct counter : owning, hashable, ordered {
var n: u64;
}
def counter::close(&mut this): void {
if this.n != 0 {
closed++;
this.n = 0;
}
}
def counter::hash(&this): u64 { return this.n; }
def counter::equals(&this, other: &counter): bool { return this.n == other.n; }
def counter::compare(&this, other: &counter): i64 { return this.n as i64 - other.n as i64; }
@test def vectors_grow_by_elements_left_undefined(t: &mut tester): void {
var v := vector::<u64>::new();
v.append(1);
v.extend_undefined(1000);
t.expects(v.length == 1001 && v[0] == 1);
for i in 1..v.length {
v[i] = i;
}
t.expects(v[1000] == 1000);
var zeroed := vector::<u64>::new();
zeroed.resize(5000);
var sum: u64 = 0;
for &each in zeroed {
sum += each;
}
t.expects(zeroed.length == 5000 && sum == 0);
}
# A set closes a value where it lets it go: one it is given and already holds, one
# removed, and one another set leaves or takes out, while what it copies in is its
# own, so the set copied from closes only its own.
# A vector reads its ends, removes its last, grows by copies, and sorts, closing
# only what it removes, and moving what it sorts without closing or copying it.
@test def vectors_read_their_ends_and_sort_what_they_hold(t: &mut tester): void {
closed = 0;
var v := vector::<counter>::new();
for n in 1..4 { v.append(counter { n = n as u64 }); }
t.expects(v.first().n == 1 && v.last().n == 3);
v.last().n = 9;
v.truncate();
t.expects(closed == 1 && v.length == 2 && v.last().n == 2);
# Many are sorted by merging runs, and those an order leaves equal keep theirs.
closed = 0;
var many := vector::<counter>::new();
for i in 0..40 { many.append(counter { n = ((i * 17) % 41 + 1) as u64 }); }
many.sort();
var sorted := true;
for i in 1..many.length { sorted = sorted && many[i - 1].n < many[i].n; }
t.expects(sorted && closed == 0);
many.sort_by(def(a: &counter, b: &counter): bool { return a.n % 2 < b.n % 2; });
t.expects(many[0].n == 2 && many[1].n == 4 && many[20].n == 1 && closed == 0);
many.clear();
t.expects(closed == 40);
var texts := vector::<string>::new();
val more: string[2] = [string::from("b", nothing {}), string::from("a", nothing {})];
texts.extend(more[:]);
texts.resize(4, string::from("z", nothing {}));
texts.sort();
t.expects(texts.length == 4 && texts[0].view() == "a" && texts[3].view() == "z" && more[0].view() == "b");
var numbers := vector::<u32>::new();
numbers.resize(3, 0xFFFFFFFF);
numbers.extend([4, 2]);
numbers.sort();
val view := numbers.view();
t.expects(numbers.first() == 2 && view.lower_bound(&4) == 1 && view.upper_bound(&4) == 2 && view.lower_bound(&5) == 2);
t.expects(view.partition_point(def(x: &u32): bool { return x < 0xFFFFFFFF; }) == 2);
var d := dict::<u32, string>::new();
d.set(1, string::from("one", nothing {}));
t.expects(d.get_or(&1, string::new(nothing {})).view() == "one" && d.get_or(&2, string::from("none", nothing {})).view() == "none");
}
@test def bytes_compare_flags_change_and_digits_read_in_any_base(t: &mut tester): void {
val a: strview = "abc";
val b: strview = "abd";
t.expects(memcmp(a.data, b.data, 3) < 0 && memcmp(b.data, a.data, 3) > 0 && memcmp(a.data, a.data, 3) == 0);
var f: flags32<target> = 0;
f.set(3, true);
t.expects(f.get(3 as u8) && !f.get(4 as u8));
f.set(3, false);
t.expects(!f.get(3 as u8) && f == 0);
t.expects(f.with(5, true).get(5 as u8) && !f.get(5 as u8));
f.set(target::fields);
t.expects(f.get(target::fields) && !f.with(4, false).get(target::fields));
t.expects(('2' as u8).is_base_digit(3) && !('3' as u8).is_base_digit(3) && !('9' as u8).is_base_digit(3));
t.expects(('z' as u8).is_base_digit(36) && ('F' as u8).is_base_digit(16) && !('g' as u8).is_base_digit(16));
}
+235
View File
@@ -0,0 +1,235 @@
# Tests of `function`, which holds one callable of a signature, whatever its type,
# and owns it: each kind of callable it holds, in its buffer or a box, signatures of
# every shape, closing what it holds exactly once, holding nothing, lending what it
# holds by its type, and being handed to another thread.
import std::testing;
import std::thread;
# How many callables the tests gave functions have been closed, from any thread.
var callables_closed: atomic<u64>;
# A functor of two words counting its calls, closed once where it holds a mark.
struct call_counter : invokable<def(i64): i64>, owning {
var mark: u64;
var calls: u64;
}
def call_counter::invoke(&mut this, x: i64): i64 {
this.calls++;
return x + this.calls as i64;
}
def call_counter::close(&mut this): void {
if this.mark != 0 {
_ = callables_closed.fetch_add(1);
this.mark = 0;
}
}
# Functors of 8, 24 and 25 bytes, the last too large for a function's buffer.
struct one_word : invokable<def(): u64> { var word: u64; }
def one_word::invoke(&mut this): u64 { return this.word; }
struct three_words : invokable<def(): u64> { var bytes: u8[24]; }
def three_words::invoke(&mut this): u64 { return this.bytes[0] as u64 + this.bytes[23] as u64; }
struct past_three_words : invokable<def(): u64> { var bytes: u8[25]; }
def past_three_words::invoke(&mut this): u64 { return this.bytes[0] as u64 + this.bytes[24] as u64; }
# A functor in a box, closed once where it holds a mark, as a large one held is.
struct large_counter : invokable<def(): u64>, owning {
var mark: u64;
var calls: u64;
var pad: u64[4];
}
def large_counter::invoke(&mut this): u64 {
this.calls++;
return this.calls;
}
def large_counter::close(&mut this): void {
if this.mark != 0 {
_ = callables_closed.fetch_add(1);
this.mark = 0;
}
}
struct held_point { var x: f64; var y: f64; }
def held_point::sum(&this): f64 { return this.x + this.y; }
def held_point::origin(): held_point { return held_point {}; }
def twice_given(x: i64): i64 { return x * 2; }
def added_up(xs: i64...): i64 { var total: i64 = 0; for x in xs { total += x; } return total; }
def nothing_given(): u64 { return 7; }
def four_given(a: u8, b: u16, c: u32, d: u64): u64 { return a as u64 + b as u64 + c as u64 + d; }
def larger_of(a: &i64, b: &i64): &i64 {
val x: i64 = a;
val y: i64 = b;
return x > y ? a : b;
}
# A lambda using no locals, which may outlive the function making it.
def lambda_using_none(): function<def(i64): i64> {
return function::new(def(x: i64): i64 => x - 1);
}
@test def functions_are_four_words_holding_any_callable(t: &mut tester): void {
t.expects(size_of::<function<def(i64): i64>>() == 32 && size_of::<function<def(): void>>() == 32);
val named: function<def(i64): i64> = function::new(twice_given);
t.expects(named(21) == 42);
# A method taken through its type takes its receiver first.
val method: function<def(&held_point): f64> = function::new(held_point::sum);
val p := held_point { x = 1.5, y = 2.0 };
t.expects(method(&p) == 3.5);
val made: function<def(): held_point> = function::new(held_point::origin);
t.expects(made().x == 0.0);
# A lambda refers to the locals it uses, which change under it.
var by := 10;
val lambda: function<def(i64): i64> = function::new(def(x: i64): i64 => x + by);
t.expects(lambda(1) == 11);
by = 20;
t.expects(lambda(1) == 21);
val kept := lambda_using_none();
t.expects(kept(5) == 4);
}
@test def functions_hold_small_functors_in_place_and_large_ones_in_a_box(t: &mut tester): void {
var bytes: u8[25];
bytes[0] = 1;
bytes[23] = 2;
bytes[24] = 3;
val one: function<def(): u64> = function::new(one_word { word = 9 });
var three: three_words;
three.bytes[0] = 1;
three.bytes[23] = 2;
val in_place: function<def(): u64> = function::new(three);
val boxed: function<def(): u64> = function::new(past_three_words { bytes = bytes });
t.expects(one() == 9 && in_place() == 3 && boxed() == 4);
# What a functor changes as it is called stays changed, in place or boxed.
val counting: function<def(i64): i64> = function::new(call_counter {});
t.expects(counting(10) == 11 && counting(10) == 12);
val large: function<def(): u64> = function::new(large_counter {});
t.expects(large() == 1 && large() == 2 && large() == 3);
}
@test def functions_call_a_functor_referred_to_where_it_is(t: &mut tester): void {
var counter := call_counter {};
{
val referring: function<def(i64): i64> = function::new(&mut counter);
t.expects(referring(0) == 1 && referring(0) == 2);
}
t.expects(counter.calls == 2);
}
@test def functions_take_signatures_of_every_shape(t: &mut tester): void {
val none: function<def(): u64> = function::new(nothing_given);
val four: function<def(u8, u16, u32, u64): u64> = function::new(four_given);
t.expects(none() == 7 && four(1, 2, 3, 4) == 10);
# References are given and given back.
val larger: function<def(&i64, &i64): &i64> = function::new(larger_of);
val a: i64 = 3;
val b: i64 = 8;
val got: i64 = larger(&a, &b);
t.expects(got == 8);
# What gives nothing, which a lambda appending to a vector does.
var seen := vector::<i64>::new();
val keep: function<def(i64): void> = function::new(def(x: i64) { seen.append(x); });
keep(4);
keep(5);
t.expects(seen.length == 2 && seen[1] == 5);
# A variadic signature takes any number of arguments, or a view of them.
val sum: function<def(i64...): i64> = function::new(added_up);
val more: i64[3] = [4, 5, 6];
t.expects(sum() == 0 && sum(1, 2, 3) == 6 && sum(...more) == 15);
}
@test def functions_close_what_they_hold_once(t: &mut tester): void {
val before := callables_closed.load();
{
val f: function<def(i64): i64> = function::new(call_counter { mark = 1 });
val g: function<def(): u64> = function::new(large_counter { mark = 1 });
}
t.expects(callables_closed.load() == before + 2);
# Written over, what it held closes; moved from, it holds nothing to close.
var f: function<def(i64): i64> = function::new(call_counter { mark = 1 });
f = function::new(call_counter { mark = 2 });
t.expects(callables_closed.load() == before + 3);
var moved := move(&mut f);
f.close();
t.expects(callables_closed.load() == before + 3);
moved.close();
moved.close();
t.expects(callables_closed.load() == before + 4);
# A vector of them grows by moving them, and closes each once.
{
var many := vector::<function<def(): u64>>::new();
for i in 0..40u {
many.append(function::new(large_counter { mark = i + 1 }));
}
t.expects(many[39]() == 1);
}
t.expects(callables_closed.load() == before + 44);
}
@test def empty_functions_hold_nothing_and_stop_where_called(t: &mut tester): void {
var empty: function<def(): void>;
t.expects(!empty.holds());
empty = function::new(def() {});
t.expects(empty.holds());
val moved := move(&mut empty);
t.expects(!empty.holds() && moved.holds());
t.expects(stops(def() { var none: function<def(i64): i64>; _ = none(1); }));
}
@test def functions_lend_what_they_hold_by_its_type(t: &mut tester): void {
val counting: function<def(i64): i64> = function::new(call_counter { calls = 5 });
_ = counting(0);
if counting.get::<call_counter>() is some(&held) {
t.expects(held.calls == 6);
} else {
t.expects(false);
}
t.expects(!(counting.get::<def(i64): i64>() is some));
val large: function<def(): u64> = function::new(large_counter {});
_ = large();
if large.get::<large_counter>() is some(&held) {
t.expects(held.calls == 1);
} else {
t.expects(false);
}
t.expects(!(large.get::<one_word>() is some));
var empty: function<def(): u64>;
t.expects(!(empty.get::<large_counter>() is some));
}
# Calls a function given to a thread, which then owns it.
def call_given(f: function<def(): u64>): void {
_ = f();
_ = f();
}
@test def functions_are_handed_to_other_threads(t: &mut tester): void {
val before := callables_closed.load();
var counting: function<def(): u64> = function::new(large_counter { mark = 1 });
var thread := thread::spawn_with(call_given, move(&mut counting)) else {
t.expects(false);
return;
};
thread.join();
t.expects(!counting.holds() && callables_closed.load() == before + 1);
}
+244
View File
@@ -0,0 +1,244 @@
# Tests of generics given constants, and of what calls infer. A constant parameter is
# given a value of its type, worked out while checking, and instances given equal values
# are one instance. Calls infer constants from the lengths of fixed arrays and the
# arguments of other instances, and infer type arguments from bounds, the type expected
# of their result, array literals, functions named as values, and the arguments around
# one that needs another's type first.
import std::testing;
import std::containers;
# A buffer of a number of elements its type gives.
struct buffer<T, const N: u64> where T: zeroable {
var items: T[N];
}
def buffer<T, N>::capacity(&this): u64 { return N; }
def buffer<T, const N: u64>::filled(value: T): buffer<T, N> {
var made: buffer<T, N>;
for i in 0..N { made.items[i] = value; }
return made;
}
const four_of: u64 = 4;
@test def constants_tell_instances_apart(t: &mut tester): void {
var b: buffer<i64, 4>;
val c: buffer<i64, four_of> = buffer::<i64, 2 + 2>::filled(7);
b = c;
t.expects(b.capacity() == 4 && b.items.length == 4 && b.items[3] == 7);
t.expects(name_of::<buffer<u8, 16>>() == "buffer<u8, 16>");
t.expects(name_of::<buffer<u16, four_of * 2>>() == "buffer<u16, 8>");
}
enum color { red, green, blue }
struct spot { var x: i64; var y: i64 = 7; }
union figure { var circle: f64; var square: f64; }
const origin: spot = spot { x = 1 };
const table: i64[3] = [10, 20, 30];
struct labelled<const NAME: strview> {}
def labelled<NAME>::name(&this): strview { return NAME; }
struct painted<const C: color> {}
def painted<C>::color(&this): color { return C; }
struct placed<const P: spot> {}
def placed<P>::sum(&this): i64 { return P.x + P.y; }
struct flagged<const B: bool> {}
def flagged<B>::on(&this): bool {
if const B {
return true;
}
return false;
}
struct scaled<const F: f64> {}
def scaled<F>::times(&this, x: f64): f64 { return x * F; }
struct drawn<const S: figure> {}
def drawn<S>::size(&this): f64 {
if S is circle(r) {
return r;
}
return 0.0;
}
def double(x: i64): i64 { return x * 2; }
def triple(x: i64): i64 { return x * 3; }
struct applied<const F: def(i64): i64> {}
def applied<F>::run(&this, x: i64): i64 { return F(x); }
struct indexed<const XS: i64[3]> {}
def indexed<XS>::second(&this): i64 { return XS[1]; }
struct aimed<const R: &i64[3]> {}
def aimed<R>::last(&this): i64 { return R[2]; }
struct keeper<T, const V: T> {}
def keeper<T, V>::get(&this): T { return V; }
@test def constants_are_values_of_every_kind(t: &mut tester): void {
t.expects(labelled::<"hello"> {}.name() == "hello");
t.expects(painted::<color::green> {}.color() == color::green);
# A struct is the same constant as another holding the same fields, its defaults
# included, however each is written.
val here: placed<spot { x = 1, y = 7 }> = placed::<origin> {};
t.expects(here.sum() == 8);
t.expects(flagged::<true> {}.on() && !flagged::<(1 > 2)> {}.on());
t.expects(scaled::<1.5> {}.times(2.0) == 3.0);
t.expects(drawn::<figure { circle = 2.5 }> {}.size() == 2.5);
t.expects(applied::<double> {}.run(5) == 10 && applied::<triple> {}.run(5) == 15);
t.expects(indexed::<table> {}.second() == 20 && indexed::<[4, 5, 6]> {}.second() == 5);
t.expects(aimed::<&table> {}.last() == 30);
t.expects(keeper::<u8, 200> {}.get() == 200 && keeper::<strview, "x"> {}.get() == "x");
}
def summed<const N: u64>(xs: &i64[N]): i64 {
var sum: i64 = 0;
for x in xs { sum += x; }
return sum;
}
def grown<T, const N: u64>(xs: &T[N], last: T): T[N + 1] where T: zeroable {
var out: T[N + 1];
for i, x in xs { out[i] = x; }
out[N] = last;
return out;
}
def capacity_of<T, const N: u64>(b: &buffer<T, N>): u64 where T: zeroable { return N; }
def widened<T, const N: u64>(b: &buffer<T, N>): buffer<T, N * 2> where T: zeroable {
var out: buffer<T, N * 2>;
for i, x in b.items {
out.items[i] = x;
out.items[i + N] = x;
}
return out;
}
type grid_of<const N: u64> = i64[N][N];
@test def constants_are_inferred_from_what_is_given(t: &mut tester): void {
val xs: i64[3] = [1, 2, 3];
t.expects(summed(&xs) == 6 && summed::<2>(&[5, 6]) == 11);
val ys := grown(&xs, 4);
t.expects(ys.length == 4 && ys[3] == 4);
val b := buffer::<i64, 3>::filled(9);
val w := widened(&b);
t.expects(capacity_of(&b) == 3 && capacity_of(&w) == 6 && w.items[5] == 9);
val sq: grid_of<2> = [[1, 2], [3, 4]];
t.expects(sq[1][0] == 3);
}
def doubled<const N: u64>(): u64 { return N * 2; }
const twelve: u64 = doubled::<6>();
def described<const N: u64>(): strview {
if const N > 2 {
return "many";
}
return "few";
}
@test def constants_are_known_while_compiling(t: &mut tester): void {
t.expects(twelve == 12);
t.expects(described::<1>() == "few" && described::<5>() == "many");
}
# What a container's elements are, as a bound gives it.
def leading<C, T>(c: &C): maybe<T> where C: iterable<T> {
for x in c {
return x;
}
return nothing {};
}
struct wrapped<T> { var value: T; }
def wrapped<T>::new(value: T): wrapped<T> { return wrapped::<T> { value = value }; }
def itself<T>(x: T): T { return x; }
def apply<T, U>(f: def(T): U, x: T): U { return f(x); }
def sum_of<T>(xs: span<T>): T where T: numeric, zeroable {
var all: T;
for x in xs { all += x; }
return all;
}
def made_empty<T>(): vector<T> { return vector::<T>::new(); }
def pick<T>(a: T, b: T): T { return b; }
def latter<T, U>(a: T, b: U): U { return b; }
@test def calls_infer_what_their_arguments_do_not_give(t: &mut tester): void {
var xs := vector::<i64>::new();
xs.append(4);
t.expects(leading(&xs) is some(got) && got == 4);
# A generic type's own static method infers the type's arguments too.
val b := wrapped::new(5);
val c: wrapped<u8> = wrapped::new(5);
var v: vector<i64> = vector::new();
v.append(1);
t.expects(b.value == 5 && c.value == 5 && v.length == 1);
# A generic function labelled as a value is the instance the type expected gives.
val f: def(i64): i64 = itself;
t.expects(f(4) == 4 && apply(itself, 3) == 3 && apply(double, 3) == 6);
t.expects(sum_of([1, 2, 3]) == 6 && sum_of([1.5, 2.5]) == 4.0);
# An argument needing another's type is checked once the other gives it.
var given := vector::<u8>::new();
given.append(1);
val picked := pick(made_empty(), move(given));
t.expects(picked.length == 1);
# Type arguments written are the first ones, and the call infers the rest.
t.expects(latter::<i64>(1, true));
}
# Says only whether a number is even, failing with the number otherwise.
def even_only(n: u64): result<void, u64> {
if n % 2 != 0 { return n; }
return;
}
@test def void_is_given_to_std_generics_as_any_type(t: &mut tester): void {
# Owners, containers, and results hold `void`, its one value taking no bytes.
val held := box::<void>::new(void {});
t.expects(held.holds());
var shared := rc::<void>::new(void {});
val also := copy(&shared);
t.expects(shared.count() == 2);
var marks := vector::<void>::new();
for _ in 0..5u { marks.append(void {}); }
t.expects(marks.length == 5 && size_of::<void>() == 0);
# A `maybe<void>` tells a value missing from the value of `void`.
var seen: maybe<void> = nothing {};
t.expects(!(seen is some));
seen = void {};
t.expects(seen is some);
# A result of `void` says only whether something failed.
t.expects(even_only(4) is value && even_only(3) is error);
var failed: u64 = 0;
even_only(7) else (n) { failed = n; };
t.expects(failed == 7);
# A function giving nothing is held, and called, as one giving any type.
var count := 0;
val f: function<def(): void> = function::new(def() { count++; });
f();
f();
t.expects(count == 2);
}
+440
View File
@@ -0,0 +1,440 @@
# Tests of iterating what an iterator gives by value: each element is the loop's own,
# closed where each pass of the body ends, however the pass ends.
import std::containers;
import std::testing;
# How many lines holding a number have been closed.
var lines_closed: u64 = 0;
struct line : owning {
var n: u64;
}
def line::close(&mut this): void {
if this.n != 0 {
lines_closed++;
this.n = 0;
}
}
# Gives lines numbered from how many are left down to 1, each a new value.
struct lines : iterator<line> {
var left: u64;
}
def lines::next(&mut this): maybe<line> {
if this.left == 0 {
return nothing {};
}
this.left--;
return line { n = this.left + 1 };
}
# Gives words numbered down to 0, each a new string, as a reader gives its lines.
struct words : iterator<string> {
var left: u64;
}
def words::next(&mut this): maybe<string> {
if this.left == 0 {
return nothing {};
}
this.left--;
return $"word {this.left}";
}
# The first line numbered no more than the limit, the rest skipped by `continue`.
def first_within(limit: u64): u64 {
for each in (lines { left = 5 }) {
if each.n > limit {
continue;
}
return each.n;
}
return 0;
}
@test def iterators_give_elements_the_loop_owns(t: &mut tester): void {
lines_closed = 0;
var total: u64 = 0;
for each in (lines { left = 4 }) {
total += each.n;
}
t.expects(total == 10 && lines_closed == 4);
# 5, then 4 by `continue`, then 3, then 2 by `break`, and 1 never given.
lines_closed = 0;
for each in (lines { left = 5 }) {
if each.n == 4 {
continue;
}
if each.n == 2 {
break;
}
}
t.expects(lines_closed == 4);
# 5 and 4 by `continue`, and 3 by `return`.
lines_closed = 0;
t.expects(first_within(3) == 3 && lines_closed == 3);
lines_closed = 0;
for _ in (lines { left = 3 }) {}
t.expects(lines_closed == 3);
# An iterator variable is advanced where it is, so a second loop goes on from there.
lines_closed = 0;
var walk := lines { left = 4 };
for each in walk {
if each.n == 3 {
break;
}
}
var rest: u64 = 0;
for each in walk {
rest += each.n;
}
t.expects(rest == 3 && lines_closed == 4);
}
@test def iterators_give_strings_the_loop_owns(t: &mut tester): void {
var joined := string::new(nothing {});
for word in (words { left = 3 }) {
joined.append(word.view());
joined.append(";");
}
t.expects(joined.view() == "word 2;word 1;word 0;");
var counted := 0u;
for word in (words { left = 100 }) {
counted += word.length;
}
t.expects(counted == 690);
}
@test def loops_refer_to_what_they_walk(t: &mut tester): void {
# Elements an array holds, or an iterator gives by reference, are referred to by
# `for x`, neither copied nor closed by the loop.
lines_closed = 0;
var kept: line[2];
kept[0] = line { n = 1 };
kept[1] = line { n = 2 };
var sum: u64 = 0;
for &each in kept {
sum += each.n;
}
t.expects(sum == 3 && lines_closed == 0);
var texts := vector::<string>::new();
texts.append(string::from("ab", nothing {}));
texts.append(string::from("cde", nothing {}));
var length: u64 = 0;
for &text in texts.view() {
length += text.length;
}
t.expects(length == 5 && texts.length == 2);
}
# The numbers 1 to 6, which the tests of adapters and consumers walk.
def six(): vector<u64> {
var made := vector::<u64>::new();
for i in 1..=6u {
made.append(i);
}
return made;
}
# The text of what an iterator gives, separated by spaces.
def spaced<T, I>(it: I): string where I: iterator<T> {
return it.to_string(" ");
}
@test def adapters_make_iterators_of_iterators(t: &mut tester): void {
val v := six();
t.expects(spaced(v.iter().map(def(x): u64 => x * 10)).view() == "10 20 30 40 50 60");
t.expects(spaced(v.iter().filter(def(x) => x % 2 == 0)).view() == "2 4 6");
t.expects(spaced(v.iter().filter_map(def(x): maybe<u64> => x % 3 == 0 ? something::<u64>(x / 3) : nothing {})).view() == "1 2");
t.expects(spaced(v.iter().enumerate().map(def(p): u64 => p.first * 10 + p.second)).view() == "1 12 23 34 45 56");
t.expects(spaced(v.iter().zip(v.iter().skip(1)).map(def(p): u64 => p.first * p.second)).view() == "2 6 12 20 30");
t.expects(spaced(v.iter().take(2).chain(v.iter().skip(4))).view() == "1 2 5 6");
t.expects(spaced(v.iter().take_while(def(x) => x < 4)).view() == "1 2 3");
t.expects(spaced(v.iter().skip_while(def(x) => x < 4)).view() == "4 5 6");
t.expects(spaced(v.iter().step(2)).view() == "1 3 5");
t.expects(spaced(v.iter().rev()).view() == "6 5 4 3 2 1");
t.expects(spaced(v.iter().take(3).flat_map(def(x) => 0..x)).view() == "0 0 1 0 1 2");
t.expects(spaced(v.iter().copied().map(def(x: u64): u64 => x + 1)).view() == "2 3 4 5 6 7");
var seen: u64 = 0;
t.expects(v.iter().inspect(def(x) { seen += x; }).count() == 6 && seen == 21);
var looked := v.iter().peekable();
t.expects(looked.peek() is some(first) && first == 1);
t.expects(spaced(looked).view() == "1 2 3 4 5 6");
}
@test def adapters_take_the_edges(t: &mut tester): void {
val v := six();
val none := vector::<u64>::new();
t.expects(none.iter().map(def(x): u64 => x).count() == 0 && none.iter().rev().count() == 0);
t.expects(v.iter().take(0).count() == 0 && v.iter().skip(9).count() == 0);
t.expects(spaced(v.iter().step(1)).view() == "1 2 3 4 5 6");
t.expects(v.iter().zip(v.iter().take(2)).count() == 2 && v.iter().take(1).zip(v.iter()).count() == 1);
# Walking from both ends gives each element once, until the ends meet.
var both := v.iter();
var taken := string::new(nothing {});
while true {
val front := both.next();
if front is some(a) {
taken.append($"{a}<");
}
val back := both.next_back();
if back is some(b) {
taken.append($">{b}");
}
break if both.remaining() == 0;
}
t.expects(taken.view() == "1<>62<>53<>4");
t.expects(both.next() is not some(_) && both.next_back() is not some(_));
}
@test def consumers_walk_to_the_end(t: &mut tester): void {
val v := six();
t.expects(v.iter().count() == 6 && v.iter().copied().sum() == 21 && v.iter().copied().product() == 720);
t.expects(v.iter().fold(100u, def(a: u64, x: &u64): u64 => a - x) == 79);
t.expects((v.iter().copied().reduce(def(a: u64, b: u64): u64 => a * b) else 0) == 720);
t.expects(v.iter().any(def(x) => x > 5) && !v.iter().any(def(x) => x > 6));
t.expects(v.iter().all(def(x) => x > 0) && !v.iter().all(def(x) => x > 1));
t.expects((v.iter().copied().find(def(x) => x > 3) else 0) == 4);
t.expects((v.iter().position(def(x) => x > 3) else 99) == 3 && v.iter().position(def(x) => x > 9) is not some(_));
t.expects((v.iter().copied().min() else 0) == 1 && (v.iter().copied().max() else 0) == 6);
t.expects((v.iter().copied().min_by(def(a, b) => a > b) else 0) == 6);
t.expects((v.iter().copied().max_by_key(def(x): u64 => (x * 7) % 5) else 0) == 2);
t.expects((v.iter().copied().min_by_key(def(x): u64 => (x * 7) % 5) else 0) == 5);
t.expects((v.iter().copied().last() else 0) == 6 && (v.iter().copied().nth(2) else 0) == 3);
t.expects(v.iter().nth(6) is not some(_));
val none := vector::<u64>::new();
t.expects(none.iter().copied().sum() == 0 && none.iter().copied().min() is not some(_));
t.expects(none.iter().copied().reduce(def(a: u64, b: u64): u64 => a + b) is not some(_));
val doubled := v.iter().map(def(x): u64 => x * 2).to_vector();
t.expects(doubled.length == 6 && doubled[5] == 12);
var into := vector::<u64>::new();
into.append(0);
v.iter().copied().into(&mut into);
t.expects(into.length == 7 && into[6] == 6);
var walked: u64 = 0;
v.iter().for_each(def(x) { walked += x; });
t.expects(walked == 21);
}
# How many `ticket`s holding a number have been closed.
var tickets_closed: u64 = 0;
struct ticket : owning {
var n: u64;
}
def ticket::close(&mut this): void {
if this.n != 0 {
tickets_closed++;
this.n = 0;
}
}
# Gives tickets numbered from how many are left down to 1, each a new value, and
# counts how many times it is closed itself, which one moved from is not.
var ticket_sources_closed: u64 = 0;
struct tickets : owning, iterator<ticket> {
var left: u64;
var live: bool;
}
def tickets::next(&mut this): maybe<ticket> {
return nothing {} if this.left == 0;
this.left--;
return ticket { n = this.left + 1 };
}
def tickets::close(&mut this): void {
if this.live {
ticket_sources_closed++;
this.live = false;
}
}
@test def adapters_close_what_they_own_once(t: &mut tester): void {
tickets_closed = 0;
ticket_sources_closed = 0;
val total := (tickets { left = 4, live = true }).map(def(x: ticket): u64 => x.n).sum();
t.expects(total == 10 && tickets_closed == 4 && ticket_sources_closed == 1);
tickets_closed = 0;
ticket_sources_closed = 0;
val kept := (tickets { left = 5, live = true }).filter(def(x) => x.n % 2 == 1).take(2).to_vector();
t.expects(kept.length == 2 && kept[0].n == 5 && kept[1].n == 3);
t.expects(tickets_closed == 1 && ticket_sources_closed == 1);
tickets_closed = 0;
ticket_sources_closed = 0;
var found := (tickets { left = 3, live = true }).enumerate().find(def(p) => p.second.n == 2);
t.expects(found is some(&p) && p.first == 1);
t.expects(tickets_closed == 1 && ticket_sources_closed == 1);
}
type view_cursor = span<u64>::cursor;
type view_filter = filtered<&u64, span<u64>::cursor, def(& &u64): bool>;
type list_map = mapped<&u64, u64, list<u64>::cursor, def(&u64): u64>;
# Whether a view's cursor knows how many it has left, which it does.
def view_is_sized(): bool { if const view_cursor is sized_iterator<&u64> { return true; } return false; }
# Whether filtering it knows, which it does not.
def filter_is_sized(): bool { if const view_filter is sized_iterator<&u64> { return true; } return false; }
# Whether mapping a list's cursor walks backward, which it does not.
def list_map_is_backward(): bool { if const list_map is backward_iterator<u64> { return true; } return false; }
@test def adapters_stay_sized_and_backward_as_what_they_adapt(t: &mut tester): void {
var v := six();
val view := v.view();
t.expects(view.iter().map(def(x): u64 => x).remaining() == 6);
t.expects(view.iter().zip(view.iter().skip(2)).remaining() == 4);
t.expects(view.iter().enumerate().rev().next() is some(p) && p.first == 5 && p.second == 6);
t.expects(view.iter().step(4).remaining() == 2 && view.iter().take(10).remaining() == 6);
t.expects(view.iter().chain(view.iter()).remaining() == 12);
t.expects(view.iter().filter(def(x) => x > 2).rev().next() is some(last) && last == 6);
t.expects(view_is_sized() && !filter_is_sized() && !list_map_is_backward());
}
# An enum with values no member has between its members', and one value two
# members share.
enum shade: i8 { deep = -3, dim, bright = 2, glare, plain = -2 }
@test def ranges_are_values(t: &mut tester): void {
t.expects(spaced(0..5).view() == "0 1 2 3 4" && spaced(0..=5).view() == "0 1 2 3 4 5");
t.expects(spaced((0..=5).rev()).view() == "5 4 3 2 1 0" && spaced((0..20).step(5)).view() == "0 5 10 15");
t.expects((1..=100).sum() == 5050 && (3..10).length == 7 && (3..=10).length == 8);
t.expects((5..2).count() == 0 && (5..=5).count() == 1 && (5..=4).count() == 0);
val r: range<u8> = 250..=255;
t.expects(r.length == 6 && r.contains(255) && !r.contains(249));
val first: u8 = 250;
val last: u8 = 255;
var top := first..=last;
var counted: u64 = 0;
while top.next() is some(x) {
counted++;
}
t.expects(counted == 6);
val low: i8 = -128;
val high: i8 = 127;
t.expects((low..=high).count() == 256 && (-3..3).sum() == -3);
t.expects((0xFFFFFFFFFFFFFFFDu..=0xFFFFFFFFFFFFFFFFu).count() == 3);
var walk := 0..10u;
t.expects(walk.nth(3) is some(x) && x == 3 && walk.next() is some(y) && y == 4);
t.expects(walk.nth(9) is not some(_) && walk.is_empty());
var sum: u64 = 0;
for i in 0..=4u {
sum += i;
}
for i in last..=last {
sum += i as u64;
}
t.expects(sum == 265);
}
@test def ranges_count_through_the_members_of_enums(t: &mut tester): void {
# Each value once, in order, passing over those no member has.
t.expects(spaced(shade::deep..=shade::glare).view() == "deep dim bright glare");
t.expects(spaced((shade::deep..shade::glare).rev()).view() == "bright dim deep");
t.expects(spaced((shade::deep..=shade::glare).step(2)).view() == "deep bright");
val shades := shade::dim..=shade::glare;
t.expects(shades.length == 3 && shades.contains(shade::bright) && !shades.contains(shade::deep));
t.expects((shade::glare..shade::deep).count() == 0 && (shade::plain..=shade::dim).count() == 1);
var along := shade::deep..=shade::glare;
t.expects(along.nth(2) is some(s) && s == shade::bright && along.remaining() == 1);
t.expects(along.next_back() is some(last) && last == shade::glare && along.is_empty());
var walked := 0;
for s in shade::deep..shade::glare {
walked = walked * 10 + (s as i64 + 4);
}
t.expects(walked == 126);
}
@test def text_is_walked_lazily(t: &mut tester): void {
val text: strview = "a,,b,c";
t.expects(text.split(',').to_string("|").view() == "a||b|c" && text.split(',').rev().to_string("|").view() == "c|b||a");
t.expects("".split(',').count() == 1 && ",".split(',').count() == 2);
val parts := text.split(',').to_vector();
t.expects(parts.length == 4 && parts[3] == "c");
val doc: strview = "one\r\ntwo\n\nthree\n";
t.expects(doc.lines().to_string("|").view() == "one|two||three");
t.expects("".lines().count() == 0 && "x".lines().count() == 1 && "\n".lines().count() == 1);
t.expects(" hello wide\tworld \n".words().to_string("|").view() == "hello|wide|world" && " \t".words().count() == 0);
val utf: strview = "aé€😀";
t.expects(utf.chars().map(def(c): u64 => c as u64).to_string(" ").view() == "97 233 8364 128512");
var bad: u8[6] = [0x61, 0xC3, 0x28, 0xFF, 0xE2, 0x82];
val broken: strview = strview::over(&bad[0] as *u8, 6);
t.expects(broken.chars().map(def(c): u64 => c as u64).to_string(" ").view() == "97 65533 40 65533 65533 65533");
var overlong: u8[2] = [0xC0, 0x80];
val long: strview = strview::over(&overlong[0] as *u8, 2);
t.expects(long.chars().count() == 2);
}
@test def containers_are_made_of_iterators(t: &mut tester): void {
var d := dict::<u64, u64>::new();
d.set(1, 10);
d.set(2, 20);
d.set(3, 30);
t.expects(d.keys().copied().sum() == 6 && d.values().copied().sum() == 60 && d.keys().remaining() == 3);
val squares := dict::from((0..4u).map(def(i: u64): pair<u64, u64> => pair::<u64, u64> { first = i, second = i * i }));
t.expects(squares.length == 4 && squares[3] == 9);
(5..7u).map(def(i: u64): pair<u64, u64> => pair::<u64, u64> { first = i, second = i }).into(&mut d);
t.expects(d.length == 5 && d[6] == 6);
var v := vector::from((0..10u).filter(def(x) => x % 3 != 0));
t.expects(v.iter().to_string(" ").view() == "1 2 4 5 7 8");
val taken := v.drain(2..5).to_vector();
t.expects(taken.iter().to_string(" ").view() == "4 5 7" && v.iter().to_string(" ").view() == "1 2 8");
tickets_closed = 0;
var held := vector::<ticket>::new();
for i in 1..=5u {
held.append(ticket { n = i });
}
{
var some_of := held.drain(1..=3);
t.expects(some_of.remaining() == 3);
t.expects(some_of.next_back() is some(x) && x.n == 4);
}
t.expects(tickets_closed == 3 && held.length == 2 && held[1].n == 5);
var joined := string::new(nothing {});
"a b c".split(' ').into(&mut joined);
t.expects(joined.view() == "abc");
var c := chain::<u64>::new();
c.push_back(1);
c.push_back(2);
c.push_back(3);
val read := &c;
t.expects(read.iter().rev().copied().to_string(" ").view() == "3 2 1" && read.iter().remaining() == 3);
var l := list::<u64>::new();
l.push_front(5);
l.push_front(6);
val lread := &l;
t.expects(lread.iter().copied().sum() == 11 && lread.iter().remaining() == 2);
}
+111
View File
@@ -0,0 +1,111 @@
# Runs the tests of `core` and `system`, from the root of the repository, where
# the tests that read files find them, with the standard library's repository
# beside this one. `blossom test` runs them as `sakurac.core`, or:
#
# sakurac run --lib std=../std tests/core/*.sakura
#
# Add `-- --only TEXT` to run those whose name holds the text, and `-- --here` to
# run them in one program, as a debugger wants. Built with `sakura build`, they run
# as an executable the same way.
import std::io;
import std::process;
import system;
import std::testing;
def main(args: span<strview>): void {
exit(tester::run(args));
}
# Whether running the function stops the program. It runs in a copy of the program
# that writes nothing, so that this one goes on and the report of the stop is not
# mixed into the tests'.
def stops(run: def(): void): bool {
when os == windows {
val stopped := copied(run);
return !(stopped.exited && stopped.code == 0);
}
val child := fork();
if child == 0 {
val out: fd = fd::stdout;
val err: fd = fd::stderr;
out.close();
err.close();
run();
exit(0);
}
var status: process_status;
return wait(child, &mut status) >= 0 && !(status.exited && status.code == 0);
}
# Windows cannot copy a program as it runs, as `system::fork` does, so what the tests
# run in a copy of their own runs there in a copy started again, as `std::testing`
# starts the copy each test runs in.
when os == windows {
# The variable a copy is given, listing how the copies before it stopped.
val copy_variable: strview = "SAKURA_TEST_COPY";
# How many functions `copied` has been asked to run, in this program or a copy,
# and how the copies running each stopped, as `exited,code,signal;` each.
var copies_asked: u64 = 0;
var copies_seen: string = string::new(nothing{});
# Runs a function in a copy of the program, giving how the copy stopped. The
# copy runs the test that asked again, writing nothing, and is told how each
# copy before it stopped, which it gives where it is asked for them, so it goes
# the way the test went here, though a check that fails asks again. It runs the
# function asked for after them, then exits with zero.
def copied(run: def(): void): system::process_status {
copies_asked++;
if process::variable(copy_variable) is some(given) {
if replayed(given, copies_asked) is some(status) {
return status;
}
run();
system::exit(0);
}
var device := path::parse(system::null_device) else (_) { return system::process_status {}; };
var quiet := io::file::open(&device, open_flags::write) else (_) { return system::process_status {}; };
val copy := system::respawn($"{copy_variable}={copies_seen.view()}".view(), system::fd::stdin, quiet.handle, quiet.handle);
var status := system::process_status { exited = true, code = -1 };
if copy > 0 {
_ = system::wait(copy, &mut status);
}
copies_seen.append($"{status.exited ? 1 : 0},{status.code},{status.signal};".view());
return status;
}
# How the copy running the function asked for at a count stopped, as a copy's
# variable lists it, or nothing for the one after those it lists.
def replayed(given: strview, count: u64): maybe<system::process_status> {
var seen := 0u;
for entry in given.split(';') {
if entry.length == 0 {
continue;
}
seen++;
if seen == count {
val parts := entry.split(',').to_vector();
return system::process_status {
exited = parts[0] == "1",
code = number_in(parts[1]) as i32,
signal = number_in(parts[2]) as i32
};
}
}
return nothing{};
}
# The integer text says, or zero where it says none.
def number_in(text: strview): i64 {
if integer::parse::<i64>(text) is value(number) {
return number;
}
return 0;
}
# A directory files may be made in for a while, as the system's `TEMP` names it.
def temporary(): strview {
return process::variable("TEMP") else { return process::variable("TMP") else { return "."; }; };
}
}
+91
View File
@@ -0,0 +1,91 @@
# Tests of std's memory routines against the same work done a byte at a time:
# every length up to past where they work 16 bytes at a time, buffers that
# overlap either way, and bytes differing at every place.
import std::testing;
# Fills a buffer with bytes that differ from place to place.
def scramble(at: *mut u8, count: u64, seed: u64): void {
var state := seed * 0x9E3779B97F4A7C15 + 1;
for i in 0..count {
state = state ^ (state << 13);
state = state ^ (state >> 7);
state = state ^ (state << 17);
at[i] = (state & 0xFF) as u8;
}
}
# Whether two buffers hold the same bytes.
def same_bytes(a: *u8, b: *u8, count: u64): bool {
for i in 0..count {
return false if a[i] != b[i];
}
return true;
}
@test def copies_agree_with_bytes_where_buffers_overlap_or_not(t: &mut tester): void {
val room: u64 = 256;
val made := raw_allocate(room);
val want := raw_allocate(room);
for length in 0..101u {
for from in 0..40u {
for to in 0..40u {
scramble(made, room, length * 131 + from * 7 + to);
scramble(want, room, length * 131 + from * 7 + to);
# The bytes copied, as `memmove` gives them: read whole before any is written.
var held: u8[128];
for i in 0..length {
held[i] = want[64 + from + i];
}
for i in 0..length {
want[64 + to + i] = held[i];
}
memcpy(made + 64 + to, made + 64 + from, length);
t.expects(same_bytes(made, want, room));
}
}
}
raw_release(made);
raw_release(want);
}
@test def setting_agrees_with_bytes(t: &mut tester): void {
val room: u64 = 160;
val made := raw_allocate(room);
val want := raw_allocate(room);
for length in 0..101u {
for at in 0..20u {
scramble(made, room, length + at);
scramble(want, room, length + at);
for i in 0..length {
want[at + i] = 0xA5;
}
memset(made + at, 0xA5, length);
t.expects(same_bytes(made, want, room));
}
}
raw_release(made);
raw_release(want);
}
@test def comparing_agrees_with_bytes(t: &mut tester): void {
val a := raw_allocate(128);
val b := raw_allocate(128);
for length in 0..101u {
scramble(a, 128, length);
for i in 0..128u {
b[i] = a[i];
}
t.expects(memcmp(a, b, length) == 0);
for place in 0..length {
for other in [0 as u8, 0x7F, 0x80, 0xFF] {
b[place] = other;
val want: i64 = a[place] == other ? 0 : (a[place] < other ? -1 : 1);
t.expects(memcmp(a, b, length) == want);
}
b[place] = a[place];
}
}
raw_release(a);
raw_release(b);
}
+188
View File
@@ -0,0 +1,188 @@
# Tests of operators as calls of the methods that give them: each alone, between
# operands of different types, through compound assignment, and in generic code by
# the traits of std and those a program composes of them.
import std::testing;
# A length of time, which adds to another, scales by a number, and divides into a ratio.
struct stretch : additive, ordered {
var ns: i64;
}
def stretch::equals(&this, other: &stretch): bool { return this.ns == other.ns; }
def stretch::compare(&this, other: &stretch): i64 { return this.ns - other.ns; }
def stretch::add(&this, other: &stretch): stretch { return stretch { ns = this.ns + other.ns }; }
def stretch::sub(&this, other: &stretch): stretch { return stretch { ns = this.ns - other.ns }; }
def stretch::negate(&this): stretch { return stretch { ns = -this.ns }; }
def stretch::mul(&this, by: &i64): stretch { return stretch { ns = this.ns * by }; }
def stretch::mul(&this, by: &f64): stretch { return stretch { ns = (this.ns as f64 * by) as i64 }; }
def stretch::div(&this, by: &i64): stretch { return stretch { ns = this.ns / by }; }
def stretch::div(&this, by: &stretch): f64 { return this.ns as f64 / by.ns as f64; }
# A moment, which moves by a length of time, and is a length of time from another.
struct moment : ordered {
var ns: i64;
}
def moment::equals(&this, other: &moment): bool { return this.ns == other.ns; }
def moment::compare(&this, other: &moment): i64 { return this.ns - other.ns; }
def moment::add(&this, by: &stretch): moment { return moment { ns = this.ns + by.ns }; }
def moment::sub(&this, by: &stretch): moment { return moment { ns = this.ns - by.ns }; }
def moment::sub(&this, since: &moment): stretch { return stretch { ns = this.ns - since.ns }; }
# A vector, which a number scales from either side.
struct arrow : additive {
var x: f64;
var y: f64;
}
def arrow::equals(&this, other: &arrow): bool { return this.x == other.x && this.y == other.y; }
def arrow::add(&this, other: &arrow): arrow { return arrow { x = this.x + other.x, y = this.y + other.y }; }
def arrow::sub(&this, other: &arrow): arrow { return arrow { x = this.x - other.x, y = this.y - other.y }; }
def arrow::negate(&this): arrow { return arrow { x = -this.x, y = -this.y }; }
def arrow::mul(&this, by: &f64): arrow { return arrow { x = this.x * by, y = this.y * by }; }
def arrow::mul(&this, with: &arrow): f64 { return this.x * with.x + this.y * with.y; }
def f64::mul(&this, of: &arrow): arrow { return of * this; }
# How often a ledger was added to, which only adds.
var ledgers_added: u64 = 0;
struct ledger {
var sum: i64;
}
def ledger::add(&this, other: &ledger): ledger {
ledgers_added++;
return ledger { sum = this.sum + other.sum };
}
# What holds a ledger behind a property.
struct purse {
var kept: ledger;
}
var purse::all: ledger {
get => this.kept;
set => this.kept = value;
}
# What scales by an `S`, beside adding: a trait of a program's own, composing std's.
trait stretches<S> : additive {
def mul(&this, by: &S): self;
}
def blend<V, S>(a: V, b: V, t: S): V where V: stretches<S> {
return a + (b - a) * t;
}
def gathered<T>(items: span<T>, from: T): T where T: addable {
var all := from;
for &each in items { all += each; }
return all;
}
def mirrored<T>(a: T, b: T): T where T: additive {
return a == b ? a : -(a - b);
}
def product_of<T>(a: T, b: T): T where T: multiplicative {
return a * b;
}
def shared_out<T>(whole: T, by: T): T where T: divisible, modular, addable {
return whole / by + whole % by;
}
def second(count: i64): stretch { return stretch { ns = count * 1000000000 }; }
const long_pause: stretch = second(1) + second(2) * 3 - -second(1);
@test def an_operator_is_a_call_of_its_method(t: &mut tester): void {
val a := stretch { ns = 250 };
val b := stretch { ns = 100 };
t.expects((a + b).ns == 350 && (a - b).ns == 150 && (-a).ns == -250);
t.expects(a + b == b + a && a - b > b - a && a + b - b == a);
# One with only `add` has `+`, and nothing else.
ledgers_added = 0;
val one := ledger { sum = 1 };
t.expects((one + one + one).sum == 3 && ledgers_added == 2);
}
@test def operands_and_results_are_what_the_method_declares(t: &mut tester): void {
val began := moment { ns = 100 };
val now := moment { ns = 350 };
val waited: stretch = now - began;
val due: moment = began + waited * 2;
t.expects(waited.ns == 250 && due.ns == 600 && (due - waited).ns == 350);
# A constant takes the type of the parameter it is given to, and of two
# overloads the one it is alone.
t.expects((waited * 2).ns == 500 && (waited * 0.5).ns == 125 && (waited / 5).ns == 50);
val count: u8 = 3;
t.expects((waited * count as i64).ns == 750);
# A result of a third type.
val ratio: f64 = (waited * 3) / waited;
t.expects(ratio == 3.0 && arrow { x = 1.0, y = 2.0 } * arrow { x = 3.0, y = 4.0 } == 11.0);
# References are read through, on either side.
val later: &moment = &due;
val by: &stretch = &waited;
t.expects((later - by).ns == 350 && (later - began).ns == 500 && (by + by).ns == 500);
}
@test def a_number_on_the_left_asks_its_own_type(t: &mut tester): void {
val v := arrow { x = 1.5, y = 2.0 };
val a := v * 2.0;
val b := 2.0 * v;
val scale := 4.0;
t.expects(a == b && a.x == 3.0 && (scale * v).y == 8.0 && (0.5 * v * 2.0) == v);
# The number is still the number it was: its own methods are beside the program's.
t.expects(2.5.mul(&2.0) == 5.0 && 2.5 * 2.0 == 5.0 && scale.mul(&scale) == 16.0);
t.expects(2.5 is numeric && 2.5 is multiplicative && product_of(1.5, 4.0) == 6.0);
}
@test def compound_assignment_writes_what_the_method_gives(t: &mut tester): void {
var due := moment { ns = 100 };
due += stretch { ns = 50 };
due -= stretch { ns = 20 };
t.expects(due.ns == 130);
var waited := stretch { ns = 10 };
waited += waited;
waited *= 3;
waited /= 4;
t.expects(waited.ns == 15);
# Through a property, an element, and a reference.
ledgers_added = 0;
var held := purse { kept = ledger { sum = 2 } };
held.all += ledger { sum = 5 };
var many := [ledger { sum = 1 }, ledger { sum = 10 }];
many[1] += many[0];
val through: &mut ledger = &mut many[0];
through += held.kept;
t.expects(held.kept.sum == 7 && many[1].sum == 11 && many[0].sum == 8 && ledgers_added == 3);
}
@test def generic_code_has_operators_through_its_bounds(t: &mut tester): void {
val low := arrow { x = 0.0, y = 0.0 };
val high := arrow { x = 2.0, y = 4.0 };
t.expects(blend(1.0, 3.0, 0.5) == 2.0 && blend(low, high, 0.5) == arrow { x = 1.0, y = 2.0 });
t.expects(gathered([1, 2, 3][0:3], 0) == 6 && gathered([1.5, 2.5][0:2], 0.0) == 4.0);
t.expects(gathered([second(1), second(2)][0:2], second(0)) == second(3));
t.expects(mirrored(7, 3) == -4 && mirrored(second(5), second(2)) == second(-3) && mirrored(high, high) == high);
t.expects(product_of(3, 4) == 12 && shared_out(17, 5) == 5 && shared_out(7.5, 2.0) == 5.25);
# What satisfies which: numbers all of them, and a type what it declares.
t.expects(1 is additive && 1 is multiplicative && 1 is numeric && 1.5 is divisible && 1 is modular);
t.expects(second(1) is additive && second(1) is addable && !(second(1) is numeric));
t.expects(high is additive && !(high is multiplicative) && !(true is addable) && !(moment { ns = 0 } is addable));
}
@test def operators_of_methods_make_constants(t: &mut tester): void {
t.expects(long_pause == second(8));
}
+74
View File
@@ -0,0 +1,74 @@
# Tests of `core`'s owner of heap memory, `box`, owned alone, which closes what
# it holds exactly once. `rc` and `arc`, owned by every copy, are std's, and
# tested there.
import std::testing;
# How many values the tests gave boxes have been closed.
var owned_closed: atomic<u64>;
struct owned : owning {
var mark: u64;
}
def owned::close(&mut this): void {
if this.mark != 0 {
_ = owned_closed.fetch_add(1);
this.mark = 0;
}
}
struct linked {
var value: u64;
var next: maybe<box<linked>>;
}
@test def boxes_and_maybe_boxes_are_one_word(t: &mut tester): void {
t.expects(size_of::<box<owned>>() == 8 && size_of::<maybe<box<owned>>>() == 8);
val none_held: maybe<box<owned>> = nothing {};
t.expects(!(none_held is some));
}
@test def a_box_closes_its_value_once(t: &mut tester): void {
val before := owned_closed.load();
{
var a := box::<owned>::new(owned { mark = 1 });
a.get().mark = 2;
t.expects(a.holds() && a.get().mark == 2);
# Moving leaves the box moved from empty, so it closes nothing.
var b := move(&mut a);
t.expects(!a.holds() && b.holds() && b.get().mark == 2);
a.close();
t.expects(owned_closed.load() == before);
# Taking the value leaves the box empty and the value its taker's.
val taken := b.take();
t.expects(!b.holds() && taken.mark == 2 && owned_closed.load() == before);
}
t.expects(owned_closed.load() == before + 1);
{
val c := box::<owned>::new(owned { mark = 3 });
}
t.expects(owned_closed.load() == before + 2);
}
@test def boxes_link_a_list_closed_with_its_front(t: &mut tester): void {
var front: maybe<box<linked>> = nothing {};
for i in 0..100u {
front = box::<linked>::new(linked { value = i, next = move(&mut front) });
}
var total: u64 = 0;
var count: u64 = 0;
var at: maybe<&linked> = nothing {};
if front is some(&first) { at = first.get(); }
while at is some(&each) {
total += each.value;
count++;
at = nothing {};
if each.next is some(&next) { at = next.get(); }
}
t.expects(total == 4950 && count == 100);
}
+209
View File
@@ -0,0 +1,209 @@
# Tests of what is closed where its scope ends: a type naming `owning`, and what holds
# one, which is `closeable`. A `close` alone is only a method, and a reference or a
# pointer owns nothing.
import std::testing;
# How many values holding a number have been closed.
var shut: u64 = 0;
struct named : owning {
var n: u64;
}
def named::close(&mut this): void {
if this.n != 0 {
shut++;
this.n = 0;
}
}
struct shaped {
var n: u64;
}
def shaped::close(&mut this): void {
if this.n != 0 {
shut++;
this.n = 0;
}
}
struct wraps {
var inner: named;
}
def kind<T>(): span<u8> {
if const T is owning { return "owning"; }
if const T is closeable { return "closeable"; }
return "plain";
}
@test def only_what_names_owning_is_closed(t: &mut tester): void {
t.expects(kind::<named>() == "owning" && kind::<wraps>() == "closeable" && kind::<named[2]>() == "closeable");
t.expects(kind::<shaped>() == "plain" && kind::<&mut named>() == "plain" && kind::<*mut named>() == "plain");
shut = 0;
{
val a := named { n = 1 };
val b := shaped { n = 1 };
val c := wraps { inner = named { n = 1 } };
}
t.expects(shut == 2);
# A `close` is still called by hand, through a reference too.
var d := shaped { n = 1 };
val through: &mut shaped = &mut d;
through.close();
t.expects(shut == 3 && d.n == 0);
}
# Gives values counting down to one, then nothing.
struct countdown {
var left: u64;
}
def countdown::next(&mut this): maybe<named> {
if this.left == 0 {
return nothing {};
}
this.left--;
return named { n = this.left + 1 };
}
def first_of(from: &mut countdown): named {
if from.next() is some(got) {
return got;
}
return named {};
}
@test def union_fields_are_taken_from_what_a_call_made(t: &mut tester): void {
# Named by value, each is taken out of what the call gave, and closed once, where the
# turn ends, a `continue` goes on, or a `break` leaves.
shut = 0;
var from := countdown { left = 5 };
var seen: u64 = 0;
while from.next() is some(got) {
if got.n == 4 {
continue;
}
seen += got.n;
if got.n == 2 {
break;
}
}
t.expects(seen == 10 && shut == 4);
from.left = 1;
if from.next() is some(got) {
seen += got.n;
}
from.left = 1;
match from.next() {
some(got) => seen += got.n;
else => {}
}
t.expects(seen == 12 && shut == 6);
# Given away, by `return` or as an arm's value, it is closed by what took it.
from.left = 2;
{
val kept := first_of(&mut from);
val also: named = match from.next() {
some(got) => got,
else => named {},
};
t.expects(kept.n == 2 && also.n == 1 && shut == 6);
}
t.expects(shut == 8);
# `is not` gives it to the rest of the block.
from.left = 1;
{
if from.next() is not some(got) {
return;
}
t.expects(got.n == 1 && shut == 8);
}
t.expects(shut == 9);
}
@test def a_while_closes_what_its_condition_made_each_turn(t: &mut tester): void {
# Named in place, each value is still the one the call gave, closed before the
# condition makes the next.
shut = 0;
var from := countdown { left = 4 };
var seen: u64 = 0;
while from.next() is some(&got) {
if got.n == 3 {
continue;
}
seen += got.n;
}
t.expects(seen == 7 && shut == 4);
}
@test def names_are_given_where_their_test_holds(t: &mut tester): void {
# What the left of `&&` names is the right's to use, and of the branch, and each value
# a test takes is closed once, whichever tests a short circuit leaves unrun.
shut = 0;
var from := countdown { left = 3 };
var seen: u64 = 0;
if from.next() is some(a) && from.next() is some(b) && a.n > b.n {
seen = a.n * 10 + b.n;
}
t.expects(seen == 32 && shut == 2);
if from.next() is some(a) && from.next() is some(b) {
seen = 0;
}
t.expects(seen == 32 && shut == 3);
# `||` gives its right what an `is not` test names, and `!` turns a test around.
from.left = 2;
val small := from.next() is not some(c) || c.n < 3;
t.expects(small && shut == 4);
from.left = 1;
{
if !(from.next() is some(d)) {
seen = 0;
} else {
seen = d.n;
}
}
t.expects(seen == 1 && shut == 5);
# A guard gives the rest of the block what it names.
from.left = 2;
{
if from.next() is not some(e) || from.next() is not some(f) {
return;
}
seen = e.n * 10 + f.n;
}
t.expects(seen == 21 && shut == 7);
}
@test def bindings_holding_values_are_moved_from(t: &mut tester): void {
# A value a binding took is its own, so it is moved on, and the binding then closes
# nothing, as a `var` moved from does.
shut = 0;
var from := countdown { left = 2 };
{
var kept := vector::<named>::new();
while from.next() is some(got) {
kept.append(move(got));
}
from.left = 1;
match from.next() {
some(got) => kept.append(move(got));
else => {}
}
from.left = 2;
for each in from {
kept.append(move(each));
}
t.expects(kept.length == 5 && shut == 0);
}
t.expects(shut == 5);
}
+372
View File
@@ -0,0 +1,372 @@
# Tests of what references and pointers satisfy. A reference satisfies the traits of
# what it refers to, called through it, so a generic given one borrows what it would
# otherwise own, and it is compared and hashed as what it refers to. A pointer is an
# address: it is compared and hashed as one, and what it points at is reached by
# dereferencing it.
import std::containers;
import std::testing;
# Something written to, a number at a time.
trait sink {
def put(&mut this, n: u64): void;
def put_twice(&mut this, n: u64): void { this.put(n); this.put(n); }
}
# Something whose size is read.
trait sized {
def size(&this): u64;
}
# How many tallies holding a count have been closed.
var tallies_closed: u64 = 0;
struct tally : sink, sized, owning {
var n: u64;
}
def tally::put(&mut this, n: u64): void { this.n += n; }
def tally::size(&this): u64 { return this.n; }
def tally::close(&mut this): void {
if this.n != 0 {
tallies_closed++;
this.n = 0;
}
}
# A sink that passes each number on to what it holds, owned or borrowed, and closes
# it where it owns what closes.
struct relay<S> : sink where S: sink {
var to: S;
}
def relay<S>::put(&mut this, n: u64): void {
this.to.put(n);
}
# Puts a number through a reference to the trait, made from the field.
def relay<S>::put_through_trait(&mut this, n: u64): void {
val to: &mut sink = &mut this.to;
to.put(n);
}
def relay_to<S>(to: S): relay<S> where S: sink {
return relay::<S> { to = move(to) };
}
def size_of_it<T>(it: T): u64 where T: sized {
return it.size();
}
# How many times a mark has been hashed by its own `hash`.
var marks_hashed: u64 = 0;
struct mark : ordered, hashable {
var n: u64;
}
def mark::equals(&this, other: &mark): bool { return this.n == other.n; }
def mark::compare(&this, other: &mark): i64 { return this.n as i64 - other.n as i64; }
def mark::hash(&this): u64 {
marks_hashed++;
return this.n;
}
# Something holding a field named as one of a pointer's own methods.
struct slot {
var hash: u64;
}
def larger<T>(a: T, b: T): T where T: ordered {
if a < b { return b; }
return a;
}
def same<T>(a: T, b: T): bool where T: equatable {
return a == b && a.equals(&b);
}
def total<C>(items: C): u64 where C: iterable<u64> {
var sum: u64 = 0;
for &each in items {
sum += each;
}
return sum;
}
def first_and_last<C>(items: C, count: u64): u64 where C: indexable<u64, u64> {
return items[0] * 10 + items.at(count - 1);
}
# How many elements lie between two pointers, by moving one along, as pointers do.
def elements_between<P>(first: P, last: P): i64 where P: pointer {
var at := first;
at += 1;
return last - at + 1;
}
def no_pointer<P>(): P where P: pointer {
var made: P;
return made;
}
def addressed<T>(): span<u8> {
if const T is pointer { return "pointer"; }
return "not";
}
# Puts a value in a slot, whatever it is: given a reference, the slot refers anew.
def put_in<T>(slot: &mut T, value: T): void {
slot = value;
}
def what<S>(): span<u8> {
if const S is owning { return "owning"; }
if const S is closeable { return "closeable"; }
if const S is sink { return "sink"; }
return "neither";
}
@test def references_satisfy_what_they_refer_to(t: &mut tester): void {
var kept := tally { n = 1 };
var by_reference := relay_to(&mut kept);
by_reference.put(2);
by_reference.put_through_trait(3);
t.expects(kept.n == 6);
# A pointer satisfies nothing of what it points at, but a reference through it does.
var by_pointer := relay_to(&mut through((&mut kept) as *mut tally));
by_pointer.put(4);
by_pointer.put_through_trait(5);
t.expects(kept.n == 15);
val as_trait: &mut sink = &mut kept;
var by_trait := relay_to(as_trait);
by_trait.put(6);
by_trait.put_through_trait(7);
t.expects(kept.n == 28);
# Relays nest, each borrowing the one inside it.
var inner := relay_to(&mut kept);
var outer := relay_to(&mut inner);
outer.put(2);
outer.put_through_trait(1);
t.expects(kept.n == 31);
# Read through a reference that only reads, since `size` takes `&this`.
t.expects(size_of_it(&kept) == 31 && size_of_it(&through((&kept) as *tally)) == 31);
}
@test def references_take_the_types_their_referents_give(t: &mut tester): void {
# A trait asking for types is satisfied through a reference with the referent's, as
# `iterable` asks for a `cursor`, and an `@optional` method writing is not asked of
# a reference that only reads.
var numbers := vector::<u64>::new();
numbers.append(4);
numbers.append(5);
numbers.append(6);
val viewed: &vector<u64> = &numbers;
t.expects(total(&viewed) == 15 && total(&mut numbers) == 15 && total(numbers.view()) == 15);
t.expects(first_and_last(&viewed, 3) == 46 && first_and_last(&numbers, 2) == 45);
}
@test def references_close_nothing_they_refer_to(t: &mut tester): void {
t.expects(what::<tally>() == "owning");
t.expects(what::<relay<tally>>() == "closeable");
t.expects(what::<&mut tally>() == "sink" && what::<*mut tally>() == "neither");
t.expects(what::<relay<&mut tally>>() == "sink");
tallies_closed = 0;
var lent := tally { n = 1 };
{
var borrowed := relay_to(&mut lent);
borrowed.put(1);
}
t.expects(tallies_closed == 0 && lent.n == 2);
{
var owned := relay_to(tally { n = 1 });
owned.put(1);
}
t.expects(tallies_closed == 1);
# Never closed itself, a reference still has `close` called through it on what it
# refers to, as a reference to the trait does, and what a pointer points at.
tallies_closed = 0;
var shut := tally { n = 1 };
val by_reference: &mut tally = &mut shut;
by_reference.close();
var pointed := tally { n = 1 };
(*((&mut pointed) as *mut tally)).close();
var traited := tally { n = 1 };
val by_trait: &mut owning = &mut traited;
by_trait.close();
t.expects(tallies_closed == 3 && shut.n == 0 && pointed.n == 0 && traited.n == 0);
}
# A condition is the `bool` a reference refers to, and a ternary's branches are the
# values theirs refer to where only one of them is a reference.
def read_through(flag: &mut bool, by: &u64): u64 {
var total: u64 = 0;
if flag {
total += 1;
}
while flag {
flag = false;
total += 10;
}
total += flag ? 0 : 100;
return total + (flag ? 0 : by);
}
@test def conditions_read_through_references(t: &mut tester): void {
var flag := true;
val by: u64 = 1000;
t.expects(read_through(&mut flag, &by) == 1111 && !flag);
# `_` names nothing, so a test naming it stands anywhere a `bool` does.
val held: maybe<u64> = 4;
val empty: maybe<u64> = nothing {};
t.expects(held is some(_) && !(empty is some(_)) && (empty is some(_) || held.some == 4));
}
@test def references_compare_what_they_refer_to(t: &mut tester): void {
var one := mark { n = 1 };
var two := mark { n = 2 };
var also := mark { n = 2 };
t.expects(larger(&one, &two).n == 2 && larger(&two, &one).n == 2);
t.expects(same(&two, &also) && !same(&one, &two));
var x: i32 = 4;
val by_reference: &i32 = &x;
t.expects(larger(by_reference, &x) == 4 && hash(&by_reference) == hash(&x));
# Keys and elements that are references are found by what they refer to.
marks_hashed = 0;
var counts := dict::<&mark, u64>::new();
counts.set(&two, 5);
t.expects(counts[&also] == 5 && counts.length == 1 && marks_hashed > 0);
var refs := vector::<&mark>::new();
refs.append(&one);
refs.append(&two);
val wanted: &mark = &also;
t.expects(refs.view().contains(&wanted));
}
@test def references_to_what_a_call_gives_are_what_it_gives(t: &mut tester): void {
# `&` of a call giving a reference is that reference, not one to a copy of it,
# so it is the element's address and writes reach the element.
var marks := vector::<mark>::new();
marks.append(mark { n = 1 });
val read := &marks.at(0);
t.expects((read as *mark) == (&marks.at(0)) as *mark && read.n == 1);
val written := &mut marks.at(0);
written.n = 7;
t.expects(marks.at(0).n == 7 && (written as *mark) == marks.view().data);
}
@test def pointers_compare_their_addresses(t: &mut tester): void {
var two := mark { n = 2 };
var also := mark { n = 2 };
val p := (&two) as *mark;
val q := (&also) as *mark;
t.expects(p != q && same(p, p) && !same(p, q));
t.expects(p.equals(&p) && !p.equals(&q) && p.compare(&p) == 0);
# Hashed as addresses, two pointers at equal marks are two keys, and no mark is hashed.
marks_hashed = 0;
var seen := dict::<*mark, u64>::new();
seen.set(p, 1);
seen.set(q, 2);
t.expects(seen.length == 2 && seen[p] == 1 && seen[q] == 2);
t.expects(p.hash() == hash(&p) && marks_hashed == 0);
# What they point at is still compared through them.
t.expects(p[0] == q[0] && (*p).n == (*q).n);
val held: &*mark = &p;
t.expects(held.equals(&p) && held.hash() == p.hash() && (*held).n == 2 && marks_hashed == 0);
# A type parameter bounded by `pointer` moves, subtracts, and starts at `null` as
# pointers do, however deep.
var xs := [1u, 2u, 3u, 4u];
val first := (&mut xs) as *mut u64;
t.expects(elements_between(first, first + 3) == 3 && no_pointer::<*mark>() == null);
t.expects(addressed::<**mark>() == "pointer" && addressed::<&mark>() == "not" && addressed::<u64>() == "not");
# What a pointer points at is reached by dereferencing it, even a field named as one
# of the pointer's own methods.
var s := slot { hash = 9 };
val at := (&mut s) as *mut slot;
t.expects((*at).hash == 9 && through(at).hash == 9 && at.hash() == hash(&at));
}
@test def containers_hold_references_and_pointers(t: &mut tester): void {
# A container moves what it is given, which for a reference is the reference
# itself, and closes none of what its references reach.
tallies_closed = 0;
var a := tally { n = 1 };
var b := tally { n = 2 };
{
var refs := vector::<&mut tally>::new();
refs.append(&mut a);
refs.append(&mut b);
refs[1].put(18);
refs.remove_at(0);
t.expects(refs.length == 1 && refs[0].n == 20);
var pointers := stack::<*mut tally>::new();
pointers.push((&mut a) as *mut tally);
(*pointers.peek()).put(9);
var named := dict::<u64, &tally>::new();
named.set(1, &b);
t.expects(named[1].size() == 20);
}
t.expects(a.n == 10);
t.expects(b.n == 20);
t.expects(tallies_closed == 0);
}
@test def what_a_pointer_points_at_is_reached_by_dereferencing_it(t: &mut tester): void {
var a := tally { n = 1 };
var p := (&mut a) as *mut tally;
(*p).put_twice(1);
through(p).put(1);
# A reference to a pointer reads through to the pointer, which is dereferenced.
val r: &mut *mut tally = &mut p;
(*r).put(5);
through(r).put_twice(1);
p[0].put(1);
t.expects(a.n == 12 && (*r).size() == 12 && r == (&mut a) as *mut tally);
}
@test def generics_assign_references_as_their_templates_say(t: &mut tester): void {
var a: u64 = 1;
var b: u64 = 2;
var r: &mut u64 = &mut a;
# References never stack, so `&mut r` is `r`, and the slot is `a`.
put_in(&mut r, 5);
t.expects(a == 5 && b == 2);
var n: u64 = 0;
put_in(&mut n, 4);
t.expects(n == 4);
# Where `T` is a reference, the template's assignment gives the slot the
# reference, as it gives any other value.
var slots := vector::<&mut u64>::new();
slots.append(&mut a);
put_in(&mut slots[0], &mut b);
b = 9;
t.expects(slots[0] == 9 && a == 5);
# A reference written as one points a variable elsewhere, and a value given to
# a reference is written to what it refers to.
r = &mut b;
r = 7;
t.expects(a == 5 && b == 7);
}
+168
View File
@@ -0,0 +1,168 @@
# Tests of the properties and methods of `maybe` and `result`: reading what they
# hold, by a copy where they are only read and by a move where they can be
# written, making others of them, and comparing, hashing, and copying them. A
# value that closes is closed once, whichever way it leaves.
import std::testing;
# How many tokens holding a mark have been closed.
var tokens_closed: u64 = 0;
struct token : owning, copyable {
var mark: u64;
}
def token::close(&mut this): void {
if this.mark != 0 {
tokens_closed++;
this.mark = 0;
}
}
def token::copy_of(other: &token): token {
return token { mark = other.mark };
}
# Half a number, where it is even.
def halved(n: i64): maybe<i64> {
return n % 2 == 0 ? something(n / 2) : nothing {};
}
# How long text is, or that it is empty.
def measured(text: strview): result<u64, strview> {
return text.length == 0 ? result::<u64, strview>::err("empty") : result::<u64, strview>::ok(text.length);
}
@test def a_maybe_reads_what_it_holds(t: &mut tester): void {
val held: maybe<i64> = 8;
val empty: maybe<i64> = nothing {};
t.expects(held.is_some && !held.is_none && empty.is_none && !empty.is_some);
t.expects(held.unwrap() == 8 && held.expect("held") == 8 && empty.unwrap_or(3) == 3 && held.unwrap_or(3) == 8);
t.expects(held.is_some_and(def(x: &i64) => x > 5) && !empty.is_some_and(def(x: &i64) => true));
# Plain data is copied out of what can be written, as `move` copies it.
var kept: maybe<i64> = 6;
t.expects(kept.unwrap() == 6 && kept.is_some && kept.unwrap_or(1) == 6);
var unset: maybe<i64> = nothing {};
t.expects(unset.unwrap_or_else(def(): i64 => 11) == 11);
}
@test def a_maybe_makes_others(t: &mut tester): void {
var six: maybe<i64> = 6;
t.expects(six.map(def(x: i64) => x * 10) == 60 && six.and_then(halved) == 3);
t.expects(six.and_then(halved).and_then(halved).is_none);
t.expects(six.filter(def(x: &i64) => x > 10).is_none && six.filter(def(x: &i64) => x > 1) == 6);
var empty: maybe<i64> = nothing {};
t.expects(empty.or(5) == 5 && six.or(5) == 6 && empty.or_else(def(): maybe<i64> => 7) == 7);
t.expects(six.ok_or::<strview>("none").unwrap() == 6 && empty.ok_or::<strview>("none").unwrap_err() == "none");
t.expects(six.as_ref().map(def(x: &i64) => x + 1) == 7 && empty.as_ref().is_none);
if six.as_mut() is some(&mut got) {
got += 1;
}
t.expects(six == 7);
# `take` and `replace` leave it holding nothing, or the new value.
t.expects(six.take() == 7 && six.is_none && six.replace(4).is_none && six == 4);
}
@test def a_maybe_compares_hashes_and_copies(t: &mut tester): void {
val a: maybe<i64> = 5;
val b: maybe<i64> = 5;
val c: maybe<i64> = 6;
val none: maybe<i64> = nothing {};
t.expects(a == b && a != c && a != none && none == maybe::<i64> { none = nothing {} } && a == 5);
t.expects(hash(&a) == hash(&b) && hash(&a) != hash(&none));
val text: maybe<string> = string::from("held", nothing {});
val copied := copy(&text);
t.expects(copied == text && copied.as_ref().map(def(s: &string) => s.length) == 4);
}
@test def a_maybe_moves_out_what_closes(t: &mut tester): void {
val before := tokens_closed;
{
# Moved out of what can be written, leaving it holding nothing.
var held: maybe<token> = token { mark = 1 };
var taken := held.unwrap();
t.expects(taken.mark == 1 && held.is_none && tokens_closed == before);
# Moved into what a function makes, which closes it there.
var given: maybe<token> = token { mark = 2 };
t.expects(given.map(def(x: token) => x.mark) == 2 && given.is_none && tokens_closed == before + 1);
# Left behind by `filter`, `or`, and `replace`, each closed once.
var failed: maybe<token> = token { mark = 3 };
t.expects(failed.filter(def(x: &token) => false).is_none && tokens_closed == before + 2);
var first: maybe<token> = token { mark = 4 };
var other := first.or(token { mark = 5 });
t.expects(other.as_ref().map(def(x: &token) => x.mark) == 4 && tokens_closed == before + 3);
var swapped: maybe<token> = token { mark = 6 };
var old := swapped.replace(token { mark = 7 });
t.expects(old.is_some && swapped.as_ref().is_some_and(def(x) => x.mark == 7));
# A box held by a `maybe` in one word is taken whole.
var boxed: maybe<box<token>> = box::<token>::new(token { mark = 8 });
var out := boxed.take();
t.expects(boxed.is_none && out.is_some && size_of::<maybe<box<token>>>() == 8);
}
# taken, other, old, swapped, and out's are closed at the end of the block.
t.expects(tokens_closed == before + 8);
}
@test def a_result_reads_what_it_holds(t: &mut tester): void {
val good := measured("four");
val bad := measured("");
t.expects(good.is_ok && !good.is_err && bad.is_err && !bad.is_ok);
t.expects(good.unwrap() == 4 && good.expect("good") == 4 && bad.unwrap_err() == "empty" && bad.expect_err("bad") == "empty");
t.expects(bad.unwrap_or(9) == 9 && good.unwrap_or(9) == 4);
t.expects(good.is_ok_and(def(x: &u64) => x == 4) && bad.is_err_and(def(e: &strview) => e.length == 5));
var failed := measured("");
t.expects(failed.unwrap_or_else(def(e: strview) => e.length) == 5);
}
@test def a_result_makes_others(t: &mut tester): void {
var two := measured("ab");
var none := measured("");
t.expects(two.map(def(x: u64) => x + 1).unwrap() == 3 && none.map(def(x: u64) => x + 1).unwrap_err() == "empty");
t.expects(none.map_err(def(e: strview) => e.length).unwrap_err() == 5 && two.map_err(def(e: strview) => e.length).unwrap() == 2);
t.expects(two.and_then(def(x: u64): result<u64, strview> => result::<u64, strview>::err("no")).unwrap_err() == "no");
t.expects(none.or_else(def(e: strview): result<u64, i64> => result::<u64, i64>::ok(7)).unwrap() == 7);
t.expects(two.to_maybe() == 2 && none.to_maybe().is_none && none.err_to_maybe() == "empty" && two.err_to_maybe().is_none);
t.expects(two.as_ref().is_ok_and(def(x) => x == 2) && none.as_ref().is_err);
# A value and an error of one type are told apart.
var same := result::<i64, i64>::err(5);
t.expects(same.is_err && same.map(def(x: i64) => x + 100).unwrap_err() == 5);
t.expects(result::<i64, i64>::ok(5) != result::<i64, i64>::err(5));
# A result of `void` says only whether it failed.
val done := result::<void, i64>::ok(void {});
done.unwrap();
t.expects(done.is_ok);
}
@test def a_result_compares_hashes_and_copies(t: &mut tester): void {
val a := measured("abc");
val b := measured("xyz");
val c := measured("");
t.expects(a == b && a != c && c == measured(""));
t.expects(hash(&a) == hash(&b) && hash(&a) != hash(&c));
val text := result::<string, u64>::ok(string::from("held", nothing {}));
val copied := copy(&text);
t.expects(copied == text && copied.as_ref().is_ok_and(def(s) => s.length == 4));
}
@test def a_result_moves_out_what_closes(t: &mut tester): void {
val before := tokens_closed;
{
var held := result::<token, u64>::ok(token { mark = 1 });
var taken := held.unwrap();
t.expects(taken.mark == 1 && tokens_closed == before);
var failed := result::<u64, token>::err(token { mark = 2 });
t.expects(failed.map_err(def(x: token) => x.mark).unwrap_err() == 2 && tokens_closed == before + 1);
var lost := result::<token, u64>::ok(token { mark = 3 });
t.expects(lost.err_to_maybe().is_none && tokens_closed == before + 2);
}
t.expects(tokens_closed == before + 3);
}
+76
View File
@@ -0,0 +1,76 @@
# Tests of std's scanning of text, which an executable does sixteen bytes at a
# time: what it looks for at every place, so on either side of where each
# sixteen ends, against the same work done a byte at a time.
import std::io;
import std::testing;
# The text of a length whose bytes at the places a pattern sets are a byte, and
# letters otherwise.
def text_with(length: u64, pattern: u64, byte: u8): string {
var made := string::new(nothing {});
for i in 0..length {
val set := ((pattern >> (i % 61)) & 1) != 0;
made.push(set ? byte : ('a' as u64 + i % 26) as u8);
}
return made;
}
@test def splitting_finds_every_delimiter_wherever_it_falls(t: &mut tester): void {
for length in 0..80u {
for pattern in [0 as u64, 1, 0x8000, 0x10001, 0x5555555555555555, 0xFFFFFFFFFFFFFFFF, 0x0123456789ABCDEF] {
val text := text_with(length, pattern, ',');
val parts := text.view().split(',').to_vector();
# Each part, joined by the delimiter, is the text again, and none holds it.
var joined := string::new(nothing {});
var clean := true;
for i in 0..parts.length {
if i != 0 {
joined.push(',');
}
joined.append(parts[i]);
for k in 0..parts[i].length {
clean = clean && parts[i][k] != ',';
}
}
t.expects(joined.view() == text.view() && clean);
}
}
}
@test def text_compares_as_its_bytes_do(t: &mut tester): void {
for length in 0..70u {
val a := text_with(length, 0x0F0F0F0F0F0F0F0F, 'x');
t.expects(a.view().compare(a.view()) == 0);
for place in 0..length {
for byte in [0 as u8, 'a', 'x', 0x80, 0xFF] {
var b := text_with(length, 0x0F0F0F0F0F0F0F0F, 'x');
b[place] = byte;
val was: u8 = a[place];
val want: i64 = was == byte ? 0 : (was < byte ? -1 : 1);
t.expects(a.view().compare(b.view()) == want);
}
# A prefix orders first.
t.expects(a.view().substr(0, place).compare(a.view()) == -1);
}
}
}
@test def lines_are_read_wherever_their_breaks_fall(t: &mut tester): void {
for length in 0..70u {
val text := text_with(length, 0x2104210421042104, '\n');
var input := io::reader_of(text.view());
var seen := string::new(nothing {});
for line in input.lines() {
seen.append(line.view());
seen.push('\n');
}
# The lines, each with its break, are the text, but for a last line without one.
var want := string::new(nothing {});
want.append(text.view());
if want.length != 0 && want[want.length - 1] != '\n' {
want.push('\n');
}
t.expects(seen.view() == want.view());
}
}
+541
View File
@@ -0,0 +1,541 @@
# Tests of signals: sending them, ignoring them, putting back what the system does
# with them, handling them, at the program's safe points and where a wait is
# interrupted, and watching for them. Each test runs in a copy of the program, so what one handles is its
# own. Windows sends a program no signal from another, so there a thread, or a
# copy of the program, sends what another program does on Linux.
import std::io;
import std::process;
import system;
import std::testing;
import std::thread;
# A function of the program's own, which begins with a safe point.
def safe_point(): void {}
when os == linux {
# Runs a copy of the program that puts back what the system does with a signal,
# then sends it to itself, giving the signal that stopped the copy, or zero where
# the copy went on and exited.
def raised_in_copy(sent: system::signal): i32 {
val copy := system::fork();
if copy == 0 {
_ = system::restore(sent);
_ = system::raise(sent);
safe_point();
system::exit(0);
}
var status: system::process_status;
_ = system::wait(copy, &mut status);
return status.exited ? 0 : status.signal;
}
# The signals the system says the program does something with, one bit each by
# number less one: those it handles, where `named` is `SigCgt`, or ignores, where
# it is `SigIgn`.
def dispositions(named: strview): u64 {
var at := path::parse("/proc/self/status") else (_) { return 0; };
val text := io::read_file(&at) else (_) { return 0; };
for line in text.view().split('\n') {
if !line.starts_with(named) || line.length < 16 {
continue;
}
val hex := line.substr(line.length - 16, 16);
var bits: u64 = 0;
for i in 0..hex.length {
val digit := hex[i] >= 'a' ? (hex[i] - 'a') as u64 + 10 : (hex[i] - '0') as u64;
bits = bits * 16 + digit;
}
return bits;
}
return 0;
}
# Waits until a process is in a state, as `/proc` gives it: `S` where it sleeps,
# as it does waiting in the system, so a signal sent to it then interrupts the
# wait, and `T` where it is paused. Gives whether it was.
def reaches(process: i64, state: u8): bool {
var at := path::parse($"/proc/{process}/stat") else (_) { return false; };
for tries in 0..1000000 {
val text := io::read_file(&at) else (_) { return false; };
val view := text.view();
var end := view.length;
while end > 0 && view[end - 1] != ')' {
end--;
}
if end + 1 < view.length && view[end + 1] == state {
return true;
}
}
return false;
}
# Starts a copy of the program that sends it a signal once it sleeps, then waits
# to be stopped, giving the copy's number.
def signalled_once_asleep(sent: system::signal): i64 {
val program := system::getpid();
val copy := system::fork();
if copy == 0 {
_ = system::restore(sent);
if reaches(program, 'S') {
_ = system::kill(program, sent);
}
system::pause();
system::exit(0);
}
return copy;
}
}
# Whether a read failed because a signal ended its wait.
def is_interrupted(error: maybe<io_error>): bool {
if error is some(why) {
return why == io_error::interrupted;
}
return false;
}
# A stream that gives its text in two parts, failing between them as a read does
# that a signal the program handles interrupts.
struct halting : readable {
var first: strview;
var rest: strview;
var halted: bool;
}
def halting::read(&mut this, into: slice<u8>): result<u64, io_error> {
if this.first.length > 0 {
return this.first.read(into);
}
if !this.halted {
this.halted = true;
return io_error::interrupted;
}
return this.rest.read(into);
}
when os == linux {
@test def signals_have_the_numbers_of_the_system(t: &mut tester): void {
# Those a program may handle are noted by the system under their numbers, and
# each handler is given the signal that came. Each is restored after, so that
# `child` interrupts no wait below.
val members: system::signal[12] = [
system::signal::hangup, system::signal::interrupt, system::signal::quit, system::signal::user1,
system::signal::user2, system::signal::pipe, system::signal::alarm, system::signal::terminate,
system::signal::child, system::signal::resume, system::signal::suspend, system::signal::resized
];
val numbers: u64[12] = [1, 2, 3, 10, 12, 13, 14, 15, 17, 18, 20, 28];
var came := system::signal::kill;
for i in 0..members.length {
t.expects(system::handle(members[i], def(s: system::signal) { came = s; }) == 0);
t.expects(((dispositions("SigCgt") >> (numbers[i] - 1)) & 1) == 1);
t.expects(system::raise(members[i]) == 0);
safe_point();
t.expects(came == members[i]);
t.expects(system::restore(members[i]) == 0);
t.expects(((dispositions("SigCgt") >> (numbers[i] - 1)) & 1) == 0);
}
# What stops a program by default stops a copy with its number.
t.expects(raised_in_copy(system::signal::hangup) == 1);
t.expects(raised_in_copy(system::signal::interrupt) == 2);
t.expects(raised_in_copy(system::signal::kill) == 9);
t.expects(raised_in_copy(system::signal::user1) == 10);
t.expects(raised_in_copy(system::signal::user2) == 12);
t.expects(raised_in_copy(system::signal::pipe) == 13);
t.expects(raised_in_copy(system::signal::alarm) == 14);
t.expects(raised_in_copy(system::signal::terminate) == 15);
# `stop` pauses a copy, and `resume` lets it go on.
val copy := system::fork();
if copy == 0 {
_ = system::raise(system::signal::stop);
system::exit(5);
}
t.expects(reaches(copy, 'T'));
_ = system::kill(copy, system::signal::resume);
var status: system::process_status;
_ = system::wait(copy, &mut status);
t.expects(status.exited && status.code == 5);
}
@test def ignored_signals_do_nothing_until_restored(t: &mut tester): void {
t.expects(system::ignore(system::signal::user1) == 0);
t.expects(((dispositions("SigIgn") >> 9) & 1) == 1);
t.expects(system::raise(system::signal::user1) == 0);
safe_point();
t.expects(system::restore(system::signal::user1) == 0);
t.expects(((dispositions("SigIgn") >> 9) & 1) == 0);
t.expects(raised_in_copy(system::signal::user1) == 10);
# Restoring a handled signal stops its handler running.
var count := 0;
t.expects(system::handle(system::signal::user2, def(s: system::signal) { count++; }) == 0);
t.expects(system::ignore(system::signal::user2) == 0);
t.expects(system::raise(system::signal::user2) == 0);
safe_point();
t.expects(count == 0 && ((dispositions("SigCgt") >> 11) & 1) == 0);
}
}
@test def kill_and_stop_cannot_be_handled_nor_child_ignored(t: &mut tester): void {
val nothing_done := def(s: system::signal) {};
t.expects(system::error_of(system::handle(system::signal::kill, nothing_done)) == io_error::invalid);
t.expects(system::error_of(system::handle(system::signal::stop, nothing_done)) == io_error::invalid);
t.expects(system::error_of(system::ignore(system::signal::kill)) == io_error::invalid);
t.expects(system::error_of(system::ignore(system::signal::stop)) == io_error::invalid);
t.expects(system::error_of(system::ignore(system::signal::child)) == io_error::invalid);
}
when os == linux {
@test def signals_watched_for_wait_to_be_asked_for(t: &mut tester): void {
t.expects(system::watch(system::signal::user1) == 0);
t.expects(((dispositions("SigCgt") >> 9) & 1) == 1);
t.expects(system::watched() == 0);
_ = system::raise(system::signal::user1);
safe_point();
t.expects(system::watched() == 1u << 10);
t.expects(system::watched() == 0);
# A handled signal is not given, and one watched for waits while the handlers
# run.
var count := 0;
t.expects(system::handle(system::signal::user2, def(s: system::signal) { count++; }) == 0);
_ = system::raise(system::signal::user1);
_ = system::raise(system::signal::user2);
safe_point();
t.expects(count == 1);
t.expects(system::watched() == 1u << 10);
# Handling a signal watched for stops it being watched for.
t.expects(system::handle(system::signal::user1, def(s: system::signal) { count++; }) == 0);
_ = system::raise(system::signal::user1);
safe_point();
t.expects(count == 2 && system::watched() == 0);
t.expects(system::error_of(system::watch(system::signal::kill)) == io_error::invalid);
t.expects(system::error_of(system::watch(system::signal::stop)) == io_error::invalid);
}
}
@test def handlers_run_at_the_next_safe_point(t: &mut tester): void {
var count := 0;
t.expects(system::handle(system::signal::user1, def(s: system::signal) { count++; }) == 0);
_ = system::raise(system::signal::user1);
t.expects(count == 0);
safe_point();
t.expects(count == 1);
# Signals that come together are handled once each.
_ = system::raise(system::signal::user1);
_ = system::raise(system::signal::user1);
safe_point();
t.expects(count == 2);
# A loop of the program's own runs the handler as it goes round.
var stopping := false;
t.expects(system::handle(system::signal::user2, def(s: system::signal) { stopping = true; }) == 0);
_ = system::raise(system::signal::user2);
var passes := 0;
while !stopping {
passes++;
}
t.expects(passes == 1);
}
when os == linux {
@test def a_loop_calling_nothing_is_ended_by_its_safe_points(t: &mut tester): void {
var flag := false;
t.expects(system::handle(system::signal::user1, def(s: system::signal) { flag = true; }) == 0);
val program := system::getpid();
val copy := system::fork();
if copy == 0 {
_ = system::kill(program, system::signal::user1);
system::exit(0);
}
while !flag {}
var status: system::process_status;
_ = system::wait(copy, &mut status);
t.expects(flag && status.exited);
}
}
@test def vectors_held_across_a_safe_point_keep_their_lanes(t: &mut tester): void {
# The handler works vectors of its own, in the registers the loop holds its
# sums in, which the safe point keeps whole for it: 16 bytes, and 32 where the
# loop's code has AVX.
var ran := 0;
t.expects(system::handle(system::signal::user1, def(s: system::signal) {
var noise := f32x8::splat(-1.0);
var bytes := u32x4::splat(7);
for _ in 0..4 {
noise = noise * noise + f32x8::splat(3.0);
bytes = bytes * bytes;
}
if noise.sum() > 0.0 && bytes.sum() != 0 {
ran++;
}
}) == 0);
# Raised before the loop, which calls nothing, so the handler runs at its
# first pass's safe point, the sums in registers.
_ = system::raise(system::signal::user1);
var narrow := u32x4::splat(0);
var wide := f32x8::splat(0.0);
for i in 0..100u {
narrow = narrow + u32x4::splat(i as u32);
wide = wide + f32x8::splat(1.0);
}
t.expects(ran == 1 && narrow.sum() == 4 * 4950 && wide.sum() == 800.0);
}
@test def handlers_do_not_nest(t: &mut tester): void {
var depth := 0;
var deepest := 0;
var runs := 0;
t.expects(system::handle(system::signal::user1, def(s: system::signal) {
depth++;
runs++;
deepest = depth > deepest ? depth : deepest;
if runs == 1 {
_ = system::raise(system::signal::user1);
safe_point();
}
depth--;
}) == 0);
_ = system::raise(system::signal::user1);
safe_point();
t.expects(runs == 2 && deepest == 1);
}
when os == linux {
@test def a_wait_a_handler_interrupts_fails_with_interrupted(t: &mut tester): void {
var count := 0;
t.expects(system::handle(system::signal::user1, def(s: system::signal) { count++; }) == 0);
val copy := signalled_once_asleep(system::signal::user1);
# The handler has run by the time the wait ends.
var status: system::process_status;
val waited := system::wait(copy, &mut status);
t.expects(system::error_of(waited) == io_error::interrupted && count == 1);
_ = system::kill(copy, system::signal::kill);
t.expects(system::wait(copy, &mut status) == copy && !status.exited && status.signal == 9);
}
@test def pause_returns_once_a_handler_has_run(t: &mut tester): void {
var count := 0;
t.expects(system::handle(system::signal::user1, def(s: system::signal) { count++; }) == 0);
# A signal sent just before is not missed.
_ = system::raise(system::signal::user1);
system::pause();
t.expects(count == 1);
# One sent while it waits ends the wait.
val copy := signalled_once_asleep(system::signal::user1);
system::pause();
t.expects(count == 2);
var status: system::process_status;
_ = system::kill(copy, system::signal::kill);
_ = system::wait(copy, &mut status);
}
@test def exit_in_a_handler_stops_the_program(t: &mut tester): void {
val copy := system::fork();
if copy == 0 {
_ = system::handle(system::signal::user1, def(s: system::signal) { system::exit(7); });
_ = system::raise(system::signal::user1);
safe_point();
system::exit(0);
}
var status: system::process_status;
_ = system::wait(copy, &mut status);
t.expects(status.exited && status.code == 7);
}
}
@test def a_reader_keeps_what_a_signal_cut_short(t: &mut tester): void {
# A line cut short is given whole by the next read.
var lines := io::reader_of(halting { first = "hel", rest = "lo\nworld" });
t.expects(lines.read_line() is none && is_interrupted(lines.error));
val line := lines.read_line() else { t.expects(false); return; };
t.expects(line.view() == "hello" && lines.error is none);
val last := lines.read_line() else { t.expects(false); return; };
t.expects(last.view() == "world");
# So are bytes asked for, and the rest of the input.
var bytes := io::reader_of(halting { first = "0123", rest = "456789" });
t.expects(bytes.read_exactly(6) is error);
val six := bytes.read_exactly(6) else (_) { t.expects(false); return; };
t.expects(six.view() == "012345");
var rest := io::reader_of(halting { first = "ab", rest = "cd" });
t.expects(rest.read_all() is error);
val all := rest.read_all() else (_) { t.expects(false); return; };
t.expects(all.view() == "abcd");
}
when os == windows {
# Runs a copy of the program that puts back what the system does with a signal,
# then sends it to itself, giving the signal that stopped the copy, or zero where
# the copy went on and exited. Windows stops a program by a signal's default with
# 128 more than its number, or by `interrupt` as the console's Ctrl-C does, which
# is the signal itself.
def raised_in_copy(sent: system::signal): i32 {
val status := copied(def() {
_ = system::restore(sent);
_ = system::raise(sent);
safe_point();
});
if !status.exited {
return status.signal;
}
return status.code > 128 && status.code < 192 ? status.code - 128 : 0;
}
# Starts a thread that sends the program a signal once a little time has passed.
# The thread is given the signal, which it owns, since it outlives this call.
def sent_soon(sent: system::signal): result<thread::handle<void>, io_error> {
return thread::spawn_with(def(which: system::signal) {
_ = system::sleep(50000000);
_ = system::raise(which);
}, sent);
}
@test def signals_have_the_numbers_of_the_system(t: &mut tester): void {
# Those a program may handle are noted under their numbers, and each handler
# is given the signal that came.
val members: system::signal[12] = [
system::signal::hangup, system::signal::interrupt, system::signal::quit, system::signal::user1,
system::signal::user2, system::signal::pipe, system::signal::alarm, system::signal::terminate,
system::signal::child, system::signal::resume, system::signal::suspend, system::signal::resized
];
val numbers: u64[12] = [1, 2, 3, 10, 12, 13, 14, 15, 17, 18, 20, 28];
var came := system::signal::kill;
for i in 0..members.length {
t.expects(system::handle(members[i], def(s: system::signal) { came = s; }) == 0);
t.expects(system::raise(members[i]) == 0);
safe_point();
t.expects(came == members[i]);
t.expects(system::watch(members[i]) == 0 && system::raise(members[i]) == 0);
t.expects(system::watched() == 1u << numbers[i]);
t.expects(system::restore(members[i]) == 0);
}
# What stops a program by default stops a copy with its number.
t.expects(raised_in_copy(system::signal::hangup) == 1);
t.expects(raised_in_copy(system::signal::interrupt) == 2);
t.expects(raised_in_copy(system::signal::kill) == 9);
t.expects(raised_in_copy(system::signal::user1) == 10);
t.expects(raised_in_copy(system::signal::user2) == 12);
t.expects(raised_in_copy(system::signal::pipe) == 13);
t.expects(raised_in_copy(system::signal::alarm) == 14);
t.expects(raised_in_copy(system::signal::terminate) == 15);
# Windows cannot pause a program.
t.expects(system::error_of(system::raise(system::signal::stop)) == io_error::unsupported);
}
@test def ignored_signals_do_nothing_until_restored(t: &mut tester): void {
t.expects(system::ignore(system::signal::user1) == 0);
t.expects(system::raise(system::signal::user1) == 0);
safe_point();
t.expects(system::restore(system::signal::user1) == 0);
t.expects(raised_in_copy(system::signal::user1) == 10);
# Restoring a handled signal stops its handler running.
var count := 0;
t.expects(system::handle(system::signal::user2, def(s: system::signal) { count++; }) == 0);
t.expects(system::ignore(system::signal::user2) == 0);
t.expects(system::raise(system::signal::user2) == 0);
safe_point();
t.expects(count == 0);
}
@test def signals_watched_for_wait_to_be_asked_for(t: &mut tester): void {
t.expects(system::watch(system::signal::user1) == 0);
t.expects(system::watched() == 0);
_ = system::raise(system::signal::user1);
safe_point();
t.expects(system::watched() == 1u << 10);
t.expects(system::watched() == 0);
# A handled signal is not given, and one watched for waits while the handlers
# run.
var count := 0;
t.expects(system::handle(system::signal::user2, def(s: system::signal) { count++; }) == 0);
_ = system::raise(system::signal::user1);
_ = system::raise(system::signal::user2);
safe_point();
t.expects(count == 1);
t.expects(system::watched() == 1u << 10);
# Handling a signal watched for stops it being watched for.
t.expects(system::handle(system::signal::user1, def(s: system::signal) { count++; }) == 0);
_ = system::raise(system::signal::user1);
safe_point();
t.expects(count == 2 && system::watched() == 0);
t.expects(system::error_of(system::watch(system::signal::kill)) == io_error::invalid);
t.expects(system::error_of(system::watch(system::signal::stop)) == io_error::invalid);
}
@test def a_loop_calling_nothing_is_ended_by_its_safe_points(t: &mut tester): void {
var flag := false;
t.expects(system::handle(system::signal::user1, def(s: system::signal) { flag = true; }) == 0);
var sender := sent_soon(system::signal::user1) else (_) { t.expects(false); return; };
while !flag {}
sender.close();
t.expects(flag);
}
@test def a_wait_a_handler_interrupts_fails_with_interrupted(t: &mut tester): void {
var count := 0;
t.expects(system::handle(system::signal::user1, def(s: system::signal) { count++; }) == 0);
var pinger := process::command::new("ping");
pinger.arguments(["-n", "30", "127.0.0.1"]);
pinger.output(process::stdio::none);
var running := pinger.spawn() else (_) { t.expects(false); return; };
var sender := sent_soon(system::signal::user1) else (_) { t.expects(false); return; };
# The handler has run by the time the wait ends.
var status: system::process_status;
val waited := system::wait(running.id as i64, &mut status);
t.expects(system::error_of(waited) == io_error::interrupted && count == 1);
sender.close();
t.expects(running.kill() is value);
val stopped := running.wait() else (_) { t.expects(false); return; };
t.expects(stopped == process::status { signaled = 9 });
}
@test def pause_returns_once_a_handler_has_run(t: &mut tester): void {
var count := 0;
t.expects(system::handle(system::signal::user1, def(s: system::signal) { count++; }) == 0);
# A signal sent just before is not missed.
_ = system::raise(system::signal::user1);
system::pause();
t.expects(count == 1);
# One sent while it waits ends the wait.
var sender := sent_soon(system::signal::user1) else (_) { t.expects(false); return; };
system::pause();
t.expects(count == 2);
sender.close();
}
@test def exit_in_a_handler_stops_the_program(t: &mut tester): void {
val status := copied(def() {
_ = system::handle(system::signal::user1, def(s: system::signal) { system::exit(7); });
_ = system::raise(system::signal::user1);
safe_point();
});
t.expects(status.exited && status.code == 7);
}
}
+431
View File
@@ -0,0 +1,431 @@
# Tests of std's vectors: each operation of each type of lane against what the
# number's own operator or `std::math` gives lane by lane, to the bit, masks and
# selecting, loading and storing at the ends of views, and what stops the
# program. Built natively, the vectors are worked with the processor's vector
# instructions where it has them, so the same tests check those against the
# lanes; `SAKURA_CPU=x86-64` runs them as on a processor with SSE2 alone. The
# corpus program `simd_lanes_agree_everywhere_1` compares their bits between the
# compilers, the machine, executables, and constants.
import system;
import std::math;
import std::testing;
# Whether running the function stops the program, in a copy of the program that
# writes nothing.
def simd_stops(run: def(): void): bool {
when os == windows {
val stopped := copied(run);
return !(stopped.exited && stopped.code == 0);
}
val child := fork();
if child == 0 {
val out: fd = fd::stdout;
val err: fd = fd::stderr;
out.close();
err.close();
run();
exit(0);
}
var status: process_status;
return wait(child, &mut status) >= 0 && !(status.exited && status.code == 0);
}
# Whether two values have the same bytes, as NaNs of the same bits do.
def same_lane_bits<T>(a: &T, b: &T): bool {
val x := a as *u8;
val y := b as *u8;
for k in 0..size_of::<T>() {
return false if x[k] != y[k];
}
return true;
}
var lane_seed: u64 = 0x2545F4914F6CDD1D;
def next_bits(): u64 {
lane_seed = lane_seed ^ (lane_seed << 13);
lane_seed = lane_seed ^ (lane_seed >> 7);
lane_seed = lane_seed ^ (lane_seed << 17);
return lane_seed;
}
# A lane worth testing: one of the edges of its type, or something between.
def random_lane<L>(): L where L: numeric, ordered, zeroable {
val pick := next_bits() % 12;
if const L is real {
val edges: f64[9] = [0.0, -0.0, 1.0, -1.5, 2.5, -2.5, 1e-310, 0.75, -3.0];
return edges[pick as u64] as L if pick < 9;
return math::infinity::<L>() if pick == 9;
return math::nan::<L>() if pick == 10;
return ((next_bits() % 200000) as f64 / 100.0 - 1000.0) as L;
}
if const L is integer {
return pick as L if pick < 2;
return ~(0 as L) if pick == 2;
return ~(0 as L) >> 1 if pick == 3;
var made: L;
val bits := next_bits();
val p := (&mut made) as *mut u8;
for k in 0..size_of::<L>() {
p[k] = ((bits >> (8 * k)) & 0xFF) as u8;
}
return made;
}
var none: L;
return none;
}
def random_vector<L, const N: u64>(): simd<L[N]> where L: numeric, ordered, zeroable {
var made: simd<L[N]>;
for i in 0..N {
made[i] = random_lane::<L>();
}
return made;
}
# Whether a vector's lanes are those the scalar operation gives each pair of lanes.
def lanes_agree<L, const N: u64>(made: &simd<L[N]>, a: &simd<L[N]>, b: &simd<L[N]>, op: def(L, L): L): bool
where L: numeric, ordered, zeroable {
for i in 0..N {
val want := op(a[i], b[i]);
val got: L = made[i];
return false if !same_lane_bits(&got, &want);
}
return true;
}
# Whether a vector's lanes are those the scalar operation gives each lane.
def lanes_agree1<L, const N: u64>(made: &simd<L[N]>, a: &simd<L[N]>, op: def(L): L): bool
where L: numeric, ordered, zeroable {
for i in 0..N {
val want := op(a[i]);
val got: L = made[i];
return false if !same_lane_bits(&got, &want);
}
return true;
}
# Whether a mask has the lanes set the scalar comparison holds for.
def mask_agrees<L, const N: u64>(made: &mask<L[N]>, a: &simd<L[N]>, b: &simd<L[N]>, op: def(L, L): bool): bool
where L: numeric, ordered, zeroable {
var bits: u32 = 0;
for i in 0..N {
val holds := op(a[i], b[i]);
return false if made.has(i) != holds;
if holds {
bits = bits | ((1 as u32) << i);
}
}
return made.bits() == bits && made.any() == (bits != 0) && made.count() == count_ones(bits);
}
# Each operation of a type of lane, against the scalar one, over many vectors.
def all_agree<L, const N: u64>(t: &mut tester): void where L: numeric, ordered, zeroable {
for _ in 0..40 {
val a := random_vector::<L, N>();
val b := random_vector::<L, N>();
val c := random_vector::<L, N>();
t.expects(lanes_agree(&(a + b), &a, &b, def(x: L, y: L): L { return x + y; }));
t.expects(lanes_agree(&(a - b), &a, &b, def(x: L, y: L): L { return x - y; }));
t.expects(lanes_agree(&(a * b), &a, &b, def(x: L, y: L): L { return x * y; }));
t.expects(lanes_agree(&a.min(&b), &a, &b, def(x: L, y: L): L { return math::min(x, y); }));
t.expects(lanes_agree(&a.max(&b), &a, &b, def(x: L, y: L): L { return math::max(x, y); }));
t.expects(lanes_agree1(&(-a), &a, def(x: L): L { return -x; }));
t.expects(mask_agrees(&a.equal(&b), &a, &b, def(x: L, y: L): bool { return x == y; }));
t.expects(mask_agrees(&a.equal(&a), &a, &a, def(x: L, y: L): bool { return x == y; }));
t.expects(mask_agrees(&a.not_equal(&b), &a, &b, def(x: L, y: L): bool { return x != y; }));
t.expects(mask_agrees(&a.less(&b), &a, &b, def(x: L, y: L): bool { return x < y; }));
t.expects(mask_agrees(&a.less_equal(&b), &a, &b, def(x: L, y: L): bool { return x <= y; }));
t.expects(mask_agrees(&a.greater(&b), &a, &b, def(x: L, y: L): bool { return x > y; }));
t.expects(mask_agrees(&a.greater_equal(&b), &a, &b, def(x: L, y: L): bool { return x >= y; }));
val m := a.less(&b);
val chosen := select(m, a, b);
for i in 0..N {
val want: L = m.has(i) ? a[i] : b[i];
val got: L = chosen[i];
t.expects(same_lane_bits(&got, &want));
}
val fused := a.fma(&b, &c);
for i in 0..N {
val x: L = a[i];
val y: L = b[i];
val z: L = c[i];
var want: L;
if const L is real {
want = math::fma(x, y, z);
} else {
want = x * y + z;
}
val got: L = fused[i];
t.expects(same_lane_bits(&got, &want));
}
if const L is real {
t.expects(lanes_agree(&(a / b), &a, &b, def(x: L, y: L): L { return x / y; }));
t.expects(lanes_agree1(&a.abs(), &a, def(x: L): L { return math::abs(x); }));
t.expects(lanes_agree1(&a.sqrt(), &a, def(x: L): L { return math::sqrt(x); }));
t.expects(lanes_agree1(&a.floor(), &a, def(x: L): L { return math::floor(x); }));
t.expects(lanes_agree1(&a.ceil(), &a, def(x: L): L { return math::ceil(x); }));
t.expects(lanes_agree1(&a.trunc(), &a, def(x: L): L { return math::trunc(x); }));
t.expects(lanes_agree1(&a.round(), &a, def(x: L): L { return math::round(x); }));
t.expects(lanes_agree1(&a.round_even(), &a, def(x: L): L { return math::round_even(x); }));
}
if const L is integer {
t.expects(lanes_agree(&(a & b), &a, &b, def(x: L, y: L): L { return x & y; }));
t.expects(lanes_agree(&(a | b), &a, &b, def(x: L, y: L): L { return x | y; }));
t.expects(lanes_agree(&(a ^ b), &a, &b, def(x: L, y: L): L { return x ^ y; }));
t.expects(lanes_agree1(&(~a), &a, def(x: L): L { return ~x; }));
val counts: u32[8] = [0, 1, 3, 7, 15, 31, 63, 64];
val count := counts[next_bits() % 8];
val left := a << count;
val right := a >> count;
for i in 0..N {
val want_left: L = a[i] << count;
val want_right: L = a[i] >> count;
val got_left: L = left[i];
val got_right: L = right[i];
t.expects(same_lane_bits(&got_left, &want_left));
t.expects(same_lane_bits(&got_right, &want_right));
}
}
}
}
@test def every_operation_agrees_with_its_lanes(t: &mut tester): void {
all_agree::<f32, 4>(t);
all_agree::<f32, 8>(t);
all_agree::<f64, 2>(t);
all_agree::<f64, 4>(t);
all_agree::<i8, 16>(t);
all_agree::<u8, 32>(t);
all_agree::<i16, 8>(t);
all_agree::<u16, 16>(t);
all_agree::<i32, 4>(t);
all_agree::<u32, 8>(t);
all_agree::<i64, 2>(t);
all_agree::<u64, 4>(t);
}
@test def lanes_wrap_and_round_as_their_numbers_do(t: &mut tester): void {
val bytes := u8x16::splat(250) + u8x16::splat(10);
t.expects(bytes[0] == 4 && bytes[15] == 4);
val most := i32x4::splat(0x7FFFFFFF) + i32x4::splat(1);
t.expects(most[2] == -2147483648);
val least := i8x16::splat(-128);
t.expects((-least)[3] == -128 && least.abs()[3] == -128);
t.expects(u16x8::splat(40000).abs()[0] == 40000);
val halves := f32x4::of([0.5, 1.5, 2.5, -2.5]);
val away: f32[4] = [1.0, 2.0, 3.0, -3.0];
val even: f32[4] = [0.0, 2.0, 2.0, -2.0];
t.expects(halves.round().lanes() == away);
t.expects(halves.round_even().lanes() == even);
val roots := f64x2::of([2.0, -0.0]).sqrt();
val root: f64 = roots[0];
val zero: f64 = roots[1];
t.expects(root == math::sqrt(2.0) && math::sign_bit(zero));
val floor: f32 = f32x8::splat(-0.75).floor()[7];
val ceil: f32 = f32x8::splat(-0.75).ceil()[7];
t.expects(floor == -1.0 && ceil == 0.0 && math::sign_bit(ceil));
}
@test def vector_fma_rounds_once(t: &mut tester): void {
# (1 + 2^-52)(1 - 2^-52) - 1 is -2^-104 exactly, which multiplying then adding
# rounds to 0.
val epsilon := math::epsilon::<f64>();
val fused := f64x2::splat(1.0 + epsilon).fma(&f64x2::splat(1.0 - epsilon), &f64x2::splat(-1.0));
t.expects(fused[0] == -(epsilon * epsilon) && fused[1] == fused[0]);
val plain := f64x2::splat(1.0 + epsilon) * f64x2::splat(1.0 - epsilon) - f64x2::splat(1.0);
t.expects(plain[0] == 0.0);
}
@test def least_and_greatest_of_reals_are_ieee_754s(t: &mut tester): void {
val a := f32x4::of([-0.0, 0.0, math::nan::<f32>(), 1.0]);
val b := f32x4::of([0.0, -0.0, 1.0, math::nan::<f32>()]);
val least := a.min(&b);
val most := a.max(&b);
val small := least.lanes();
val large := most.lanes();
t.expects(math::sign_bit(small[0]) && math::sign_bit(small[1]));
t.expects(!math::sign_bit(large[0]) && !math::sign_bit(large[1]));
t.expects(math::is_nan(small[2]) && math::is_nan(small[3]) && math::is_nan(large[2]) && math::is_nan(large[3]));
t.expects(a.equal(&a).bits() == 0b1011);
t.expects(a.not_equal(&a).bits() == 0b0100);
}
@test def masks_say_which_lanes_hold(t: &mut tester): void {
val v := i16x8::of([1, -2, 3, -4, 5, -6, 7, -8]);
val negative := v.less(&i16x8::splat(0));
t.expects(negative.bits() == 0b10101010 && negative.count() == 4 && negative.any() && !negative.all());
t.expects((negative.first() else 99) == 1);
t.expects((~negative).bits() == 0b01010101);
t.expects((negative | ~negative).all() && (negative & ~negative).none());
val absolute: i16[8] = [1, 2, 3, 4, 5, 6, 7, 8];
t.expects(select(negative, -v, v).lanes() == absolute);
val wide := u8x32::splat(9).equal(&u8x32::splat(9));
t.expects(wide.all() && wide.count() == 32 && wide.bits() == 0xFFFFFFFF);
t.expects((u8x32::splat(1).equal(&u8x32::splat(2)).first() else 99) == 99);
}
@test def vectors_load_and_store_within_views(t: &mut tester): void {
val text: strview = "a vector of sixteen bytes and more";
val first := u8x16::load(text.view(), 0);
t.expects(first[0] == 'a' as u8 && first[15] == 't' as u8);
val last := u8x16::load(text.view(), text.length - 16);
t.expects(last[15] == 'e' as u8);
if const checking() {
t.expects(simd_stops(def() { val past := u8x16::load("too short".view(), 0); }));
t.expects(simd_stops(def() { val at := u8x16::load("sixteen bytes, 1".view(), 1); }));
}
var room: f64[6] = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
f64x4::of([1.0, 2.0, 3.0, 4.0]).store(room[:], 2);
val stored: f64[6] = [0.0, 0.0, 1.0, 2.0, 3.0, 4.0];
t.expects(room == stored);
if const checking() {
t.expects(simd_stops(def() { var little: f64[3]; f64x2::splat(1.0).store(little[:], 2); }));
}
}
@test def lanes_are_reached_moved_and_converted(t: &mut tester): void {
var v := i32x4::of([10, 20, 30, 40]);
v[2] = 33;
val written: i32[4] = [10, 20, 33, 40];
val reversed: i32[4] = [40, 33, 20, 10];
val big: f32 = 3e9;
val converted: i32[4] = [1, -1, big as i32, 0];
t.expects(v[2] == 33 && v.lanes() == written);
t.expects(v.shuffle([3, 2, 1, 0]).lanes() == reversed);
t.expects(v.sum() == 103 && v.product() == 10 * 20 * 33 * 40 && v.smallest() == 10 && v.largest() == 40);
t.expects(f32x4::of([1.9, -1.9, 3e9, math::nan::<f32>()]).convert::<i32>().lanes() == converted);
val ones := f32x4::splat(1.0).bits::<u32, 4>();
t.expects(ones[0] == 0x3F800000);
t.expects(v == i32x4::of([10, 20, 33, 40]) && v != i32x4::splat(0));
if const checking() {
t.expects(simd_stops(def() { val w := i32x4::splat(1); val x := w[4]; }));
}
}
@test def integer_lanes_divided_by_zero_stop(t: &mut tester): void {
val threes: i32[4] = [3, 3, 3, 3];
val ones: i32[4] = [-1, -1, -1, -1];
t.expects((i32x4::splat(7) / i32x4::splat(2)).lanes() == threes);
t.expects((i32x4::splat(-7) % i32x4::splat(2)).lanes() == ones);
t.expects(simd_stops(def() { val q := i32x4::splat(7) / i32x4::of([1, 1, 0, 1]); }));
val infinite: f32 = (f32x4::splat(1.0) / f32x4::splat(0.0))[0];
t.expects(math::is_infinite(infinite));
}
# Whether converting each lane agrees with `as`, and with the lanes' own bits.
def converts_as_lanes<L, M, const N: u64>(a: &simd<L[N]>): bool
where L: numeric, ordered, zeroable where M: numeric, ordered, zeroable {
val made := a.convert::<M>();
for i in 0..N {
val want: M = a[i] as M;
val got: M = made[i];
return false if !same_lane_bits(&got, &want);
}
return true;
}
# Whether widening each half agrees with `as` of its lanes.
def widens_as_lanes<L, M, const N: u64>(a: &simd<L[N]>): bool
where L: numeric, ordered, zeroable where M: numeric, ordered, zeroable {
val low := a.widened::<M>();
val high := a.widened_high::<M>();
for i in 0..N / 2 {
val want_low: M = a[i] as M;
val want_high: M = a[N / 2 + i] as M;
val got_low: M = low[i];
val got_high: M = high[i];
return false if !same_lane_bits(&got_low, &want_low) || !same_lane_bits(&got_high, &want_high);
}
return true;
}
# Whether reductions agree with the lanes worked one at a time, lane 0 first.
def reduces_as_lanes<L, const N: u64>(a: &simd<L[N]>): bool where L: numeric, ordered, zeroable {
var sum: L = a[0];
var least: L = a[0];
var most: L = a[0];
for i in 1..N {
val lane: L = a[i];
sum = sum + lane;
least = least < lane ? least : lane;
most = most > lane ? most : lane;
}
val got_sum: L = a.sum();
if const L is integer {
val got_least: L = a.smallest();
val got_most: L = a.largest();
return same_lane_bits(&got_sum, &sum) && got_least == least && got_most == most;
}
return same_lane_bits(&got_sum, &sum);
}
@test def reshaping_agrees_with_its_lanes(t: &mut tester): void {
for _ in 0..8 {
t.expects(converts_as_lanes::<i32, f32, 4>(&random_vector::<i32, 4>()));
t.expects(converts_as_lanes::<u32, f32, 8>(&random_vector::<u32, 8>()));
t.expects(converts_as_lanes::<i16, f32, 8>(&random_vector::<i16, 8>()));
t.expects(converts_as_lanes::<i32, f64, 4>(&random_vector::<i32, 4>()));
t.expects(converts_as_lanes::<f32, i32, 8>(&random_vector::<f32, 8>()));
t.expects(converts_as_lanes::<f32, u32, 4>(&random_vector::<f32, 4>()));
t.expects(converts_as_lanes::<f64, i32, 4>(&random_vector::<f64, 4>()));
t.expects(converts_as_lanes::<f32, f64, 4>(&random_vector::<f32, 4>()));
t.expects(converts_as_lanes::<f64, f32, 4>(&random_vector::<f64, 4>()));
t.expects(converts_as_lanes::<u8, u16, 16>(&random_vector::<u8, 16>()));
t.expects(converts_as_lanes::<i8, i16, 16>(&random_vector::<i8, 16>()));
t.expects(converts_as_lanes::<u16, u8, 16>(&random_vector::<u16, 16>()));
t.expects(converts_as_lanes::<i64, i32, 4>(&random_vector::<i64, 4>()));
t.expects(widens_as_lanes::<i8, i16, 16>(&random_vector::<i8, 16>()));
t.expects(widens_as_lanes::<u16, u32, 16>(&random_vector::<u16, 16>()));
t.expects(widens_as_lanes::<i32, i64, 4>(&random_vector::<i32, 4>()));
t.expects(widens_as_lanes::<f32, f64, 8>(&random_vector::<f32, 8>()));
t.expects(reduces_as_lanes::<u8, 32>(&random_vector::<u8, 32>()));
t.expects(reduces_as_lanes::<i16, 8>(&random_vector::<i16, 8>()));
t.expects(reduces_as_lanes::<u32, 8>(&random_vector::<u32, 8>()));
t.expects(reduces_as_lanes::<i64, 2>(&random_vector::<i64, 2>()));
t.expects(reduces_as_lanes::<u64, 4>(&random_vector::<u64, 4>()));
t.expects(reduces_as_lanes::<f32, 8>(&random_vector::<f32, 8>()));
t.expects(reduces_as_lanes::<f64, 4>(&random_vector::<f64, 4>()));
}
# Narrowing saturates, as packing does.
val words := i16x8::of([-300, 300, 1, -1, 32767, -32768, 255, 0]);
val signed: i8[16] = [-128, 127, 1, -1, 127, -128, 127, 0, 5, 5, 5, 5, 5, 5, 5, 5];
val unsigned: u8[16] = [0, 255, 1, 0, 255, 0, 255, 0, 255, 255, 255, 255, 255, 255, 255, 255];
t.expects(words.narrowed::<i8>(&i16x8::splat(5)).lanes() == signed);
t.expects(words.narrowed::<u8>(&i16x8::splat(1000)).lanes() == unsigned);
val big: u16[4] = [65535, 7, 65535, 7];
t.expects(u32x4::of([70000, 7, 70000, 7]).narrowed::<u16>(&u32x4::of([70000, 7, 70000, 7])).lanes()[0:4] == big[0:4]);
# Halves taken apart and joined.
val eight := u32x8::of([1, 2, 3, 4, 5, 6, 7, 8]);
val first: u32[4] = [1, 2, 3, 4];
val second: u32[4] = [5, 6, 7, 8];
t.expects(eight.low().lanes() == first && eight.high().lanes() == second);
t.expects(simd::join(eight.low(), eight.high()) == eight);
# Rounding halves away from zero keeps the sign of what it does not move.
val halves := f64x4::of([-0.3, 0.49999999999999994, -2.5, 4503599627370495.5]).round();
t.expects(math::sign_bit(halves[0]) && halves[1] == 0.0 && halves[2] == -3.0 && halves[3] == 4503599627370496.0);
# Gathered and scattered by places, a later lane's write lasting.
val table: f64[6] = [0.5, 1.5, 2.5, 3.5, 4.5, 5.5];
val gathered := f64x4::gather(table[0:6], i32x4::of([5, 0, 5, 2]));
t.expects(gathered == f64x4::of([5.5, 0.5, 5.5, 2.5]));
var into: i32[8];
i32x8::of([1, 2, 3, 4, 5, 6, 7, 8]).scatter(into[0:8], i32x8::of([7, 6, 5, 4, 3, 2, 1, 7]));
t.expects(into[7] == 8 && into[1] == 7 && into[0] == 0);
# Shuffles of each size, against reading each lane.
val order: u8[8] = [7, 0, 6, 1, 5, 2, 4, 3];
val floats := random_vector::<f32, 8>();
val moved := floats.shuffle(order);
for i in 0..8u {
val want: f32 = floats[order[i] as u64];
val got: f32 = moved[i];
t.expects(same_lane_bits(&got, &want));
}
val bytes := random_vector::<u8, 16>();
t.expects(bytes.shuffle([15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0])[0] == bytes[15]);
if const checking() {
t.expects(simd_stops(def() { val wrong := i32x4::splat(1).shuffle([0, 1, 4, 2]); }));
t.expects(simd_stops(def() { val far := f64x4::gather(table[0:6], i32x4::of([0, 6, 1, 2])); }));
}
}
+315
View File
@@ -0,0 +1,315 @@
# Tests of words of bytes, `core::swar`: every test against the same choice made a
# byte at a time, for every value in every place, and the text functions that go
# by words against their loops a byte at a time, for every length to past a few
# words, wherever the bytes they look for fall.
import std::serial;
import core::swar;
import std::testing;
var swar_seed: u64 = 0x2545F4914F6CDD1D;
def swar_random(): u64 {
swar_seed = swar_seed ^ (swar_seed << 13);
swar_seed = swar_seed ^ (swar_seed >> 7);
swar_seed = swar_seed ^ (swar_seed << 17);
return swar_seed;
}
# What a search found, or a number where it found nothing.
def swar_or(found: maybe<u64>, none: u64): u64 {
if found is some(at) {
return at;
}
return none;
}
# The mask choosing the bytes of a word a test chooses, made a byte at a time.
def swar_choice(word: u64, test: u64, a: u8, b: u8): u64 {
var mask: u64 = 0;
for k in 0..8u {
val byte := ((word >> (k * 8)) & 0xFF) as u8;
val chosen := match test {
0 => byte == 0,
1 => byte == a,
2 => byte < a,
3 => byte > a,
4 => byte >= a && byte <= b,
else => byte < 0x80,
};
if chosen {
mask = mask | (0x80u << (k * 8));
}
}
return mask;
}
# The same choice by words.
def swar_chosen(word: swar::bytes8, test: u64, a: u8, b: u8): u64 {
return match test {
0 => word.zero(),
1 => word.equal(a),
2 => word.below(a),
3 => word.above(a),
4 => word.within(a, b),
else => word.ascii(),
};
}
@test def swar_tests_choose_exactly_the_bytes_they_say(t: &mut tester): void {
# Bounds at their edges, and bytes the tests are given.
val bounds: u8[12] = [0, 1, 9, 13, 32, 127, 128, 129, 200, 254, 255, '0'];
var wrong: u64 = 0;
for place in 0..8u {
for value in 0..256u {
# Each value in each place, with the other places random, and sometimes a
# copy of the value, so a borrow from one byte would reach the next.
var word := swar_random();
if (value & 3) == 0 {
word = word & 0x00FF00FF00FF00FF;
}
word = (word & ~(0xFFu << (place * 8))) | (value << (place * 8));
if swar_chosen(word, 0, 0, 0) != swar_choice(word, 0, 0, 0) { wrong++; }
if swar_chosen(word, 5, 0, 0) != swar_choice(word, 5, 0, 0) { wrong++; }
for i in 0..12u {
val a := bounds[i];
val b := bounds[(i + 3) % 12];
for test in 1..5u {
if swar_chosen(word, test, a, b) != swar_choice(word, test, a, b) { wrong++; }
}
# The byte itself is equal, and within itself.
if swar_chosen(word, 1, value as u8, 0) != swar_choice(word, 1, value as u8, 0) { wrong++; }
if swar_chosen(word, 4, value as u8, value as u8) != swar_choice(word, 4, value as u8, value as u8) { wrong++; }
}
}
}
t.expects(wrong == 0);
}
@test def swar_masks_say_where_and_how_many_they_choose(t: &mut tester): void {
var wrong: u64 = 0;
for bits in 0..256u {
var mask: u64 = 0;
var spread: u64 = 0;
var first: u64 = 8;
var last: u64 = 8;
var count: u64 = 0;
for k in 0..8u {
if ((bits >> k) & 1) != 0 {
mask = mask | (0x80u << (k * 8));
spread = spread | (0xFFu << (k * 8));
first = first == 8 ? k : first;
last = k;
count++;
}
}
val chosen: swar::mask8 = mask;
val rest: u64 = first == 8 ? 0 : mask & ~(0x80u << (first * 8));
if chosen.any() != (bits != 0) { wrong++; }
if chosen.first() != first || chosen.last() != last || chosen.count() != count { wrong++; }
if chosen.rest() != rest || chosen.spread() != spread { wrong++; }
}
t.expects(wrong == 0);
for count in 0..10u {
val want: u64 = count >= 8 ? 0x8080808080808080 : 0x8080808080808080 & ((1u << (count * 8)) - 1);
t.expects(swar::mask8::leading(count) == want);
}
}
@test def swar_words_change_case_and_read_digits(t: &mut tester): void {
var wrong: u64 = 0;
for place in 0..8u {
for value in 0..256u {
val word: swar::bytes8 = (swar_random() & ~(0xFFu << (place * 8))) | (value << (place * 8));
for k in 0..8u {
val byte := word.byte(k);
if word.upper().byte(k) != byte.to_upper || word.lower().byte(k) != byte.to_lower { wrong++; }
}
}
}
t.expects(wrong == 0);
t.expects(swar::repeat(0xAB) == 0xABABABABABABABAB && swar::repeat(0) == 0);
t.expects(swar::choose(0x0000800000000080, 0x1111111111111111, 0x2222222222222222) == 0x2222112222222211);
t.expects(swar_or(swar::load("20261016", 0).digits(), 1) == 20261016);
t.expects(swar_or(swar::load("00000000", 0).digits(), 1) == 0);
t.expects(swar_or(swar::load("99999999", 0).digits(), 1) == 99999999);
t.expects(swar_or(swar::load("01234567", 0).digits(), 1) == 1234567);
# Each place not a digit in turn, by a byte on either side of the digits.
for place in 0..8u {
for byte in ['/' as u8, ':', 'a', ' ', 0, 0xB0] {
var text := string::from("12345678", nothing {});
text[place] = byte;
t.expects(swar::load(text.view(), 0).digits() is none);
}
}
}
@test def swar_loads_read_only_the_bytes_of_the_view(t: &mut tester): void {
val buffer: strview = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for start in 0..8u {
for length in 1..12u {
# A view whose next byte is set, so a read past its end would show.
val view := buffer.substr(start, length);
for at in 0..length {
var want: u64 = 0;
val left := length - at;
for k in 0..(left < 8 ? left : 8) {
want = want | (('A' as u64 + start + at + k) << (k * 8));
}
t.expects(swar::load_last(view, at) == want);
if left >= 8 {
t.expects(swar::load(view, at) == want);
}
}
}
}
t.expects(swar::load_last("".data, 0) == 0);
}
# Text of a length over a few bytes, so each is found often, after `start` bytes
# of a buffer, which then views it.
def swar_text(buffer: &mut string, start: u64, length: u64, alphabet: strview): strview {
buffer.clear();
for _ in 0..start {
buffer.push('#');
}
for _ in 0..length {
buffer.push(alphabet[swar_random() % alphabet.length]);
}
buffer.push('#');
return buffer.view().substr(start, length);
}
@test def text_functions_find_what_a_byte_at_a_time_finds(t: &mut tester): void {
var buffer := string::new(nothing {});
var wrong: u64 = 0;
for length in 0..41u {
for start in 0..8u {
val text := swar_text(&mut buffer, start, length, length % 3 == 0 ? "abcdefgh" : "ab");
for byte in ['a' as u8, 'b', 'h', '#', 0] {
var first: u64 = length;
var last: u64 = length;
var count: u64 = 0;
for k in 0..length {
if text[k] == byte {
first = first == length ? k : first;
last = k;
count++;
}
}
val found := text.index_of(&byte);
val found_last := text.last_index_of(&byte);
if swar_or(found, length) != first { wrong++; }
if swar_or(found_last, length) != last { wrong++; }
if text.count_of(&byte) != count || text.contains(&byte) != (count != 0) { wrong++; }
}
# Runs of the text and others, and any of a few bytes.
for size in 0..6u {
var sought := string::new(nothing {});
val from := length > size ? swar_random() % (length - size + 1) : 0;
for k in 0..size {
sought.push(k + from < length && (swar_random() & 3) != 0 ? text[k + from] : 'a');
}
var want: u64 = length + 1;
if sought.length <= length {
for at in 0..(length - sought.length + 1) {
if text.substr(at, sought.length) == sought.view() {
want = at;
break;
}
}
}
val got := text.find(sought.view());
if swar_or(got, length + 1) != want { wrong++; }
var any: u64 = length;
for at in 0..length {
if sought.view().contains(&text[at]) {
any = at;
break;
}
}
val got_any := text.find_any(sought.view());
if swar_or(got_any, length) != any { wrong++; }
}
}
}
t.expects(wrong == 0);
# More than four bytes are looked for through a set.
val text: strview = "the quick brown fox jumps over the lazy dog";
t.expects(swar_or(text.find_any("xyzq!"), 99) == 4 && text.find_any("QWERTY") is none);
t.expects(swar_or(text.find("the"), 99) == 0 && swar_or(text.find("lazy"), 99) == 35);
t.expects(swar_or(text.find("dog"), 99) == 40 && text.find("dogs") is none);
t.expects(swar_or(text.find(""), 99) == 0 && swar_or("".find(""), 99) == 0 && "".find("a") is none);
}
@test def text_functions_change_and_check_as_a_byte_at_a_time_does(t: &mut tester): void {
var buffer := string::new(nothing {});
var wrong: u64 = 0;
for length in 0..41u {
for start in 0..8u {
val text := swar_text(&mut buffer, start, length, "aZz@[`{ \t\n\r\x0B\x0C9");
val upper := text.upper();
val lower := text.lower();
for k in 0..length {
if upper[k] != text[k].to_upper || lower[k] != text[k].to_lower { wrong++; }
}
if upper.length != length || lower.length != length { wrong++; }
# Trimming, where the text is mostly whitespace.
var left: u64 = 0;
while left < length && text[left].is_space { left++; }
var right := length;
while right > 0 && text[right - 1].is_space { right--; }
if text.ltrim() != text.substr(left, length - left) { wrong++; }
if text.rtrim() != text.substr(0, right) { wrong++; }
if text.trim() != (left < right ? text.substr(left, right - left) : text.substr(0, 0)) { wrong++; }
# ASCII, and a byte past it in each place.
if !text.is_ascii() || !serial::is_utf8(text) { wrong++; }
for place in 0..length {
var wide := string::from(text, nothing {});
wide[place] = 0x80 | (place as u8);
if wide.view().is_ascii() || serial::is_utf8(wide.view()) { wrong++; }
wide[place] = 0xC3;
if place + 1 < length {
wide[place + 1] = 0xA9;
if !serial::is_utf8(wide.view()) { wrong++; }
}
}
}
}
t.expects(wrong == 0);
# Whitespace of every length on either side.
for spaces in 0..20u {
var text := string::new(nothing {});
for k in 0..spaces { text.push(k % 3 == 0 ? '\t' : ' '); }
text.append("word");
for k in 0..spaces { text.push(k % 2 == 0 ? '\n' : ' '); }
t.expects(text.view().trim() == "word" && text.view().ltrim().length == 4 + spaces && text.view().rtrim().length == 4 + spaces);
}
}
# Where a run of text is found, while compiling and while running.
def swar_found(text: strview, sought: strview): u64 {
return swar_or(text.find(sought), text.length);
}
def swar_date(text: strview): u64 {
return swar_or(swar::load(text, 0).digits(), 0);
}
const swar_compiled_place: u64 = swar_found("a needle in a haystack of needles", "haystack");
const swar_compiled_date: u64 = swar_date("20261016");
const swar_compiled_count: u64 = "one\ntwo\nthree\nfour\n".count_of(&'\n');
@test def swar_words_work_alike_while_compiling(t: &mut tester): void {
t.expects(swar_compiled_place == 14 && swar_compiled_place == swar_found("a needle in a haystack of needles", "haystack"));
t.expects(swar_compiled_date == 20261016 && swar_compiled_date == swar_date("20261016"));
t.expects(swar_compiled_count == 4);
}
+35
View File
@@ -0,0 +1,35 @@
# Tests of text: what a literal is where nothing asks for a type, and what
# trimming gives of a view and of a string.
import std::testing;
# Whether the type is `strview`, which a literal is where nothing asks otherwise.
def is_view<T>(value: &T): bool {
return name_of::<T>() == "strview";
}
@test def text_literals_are_views(t: &mut tester): void {
val plain := "abc";
val built := $"abc{1}";
t.expects(is_view(&plain) && !is_view(&built));
t.expects(is_view(&"abc".trim()) && "abc".length == 3);
# Each trimmed literal views its own bytes, which last as long as the program.
val first := " x ".trim();
val second := " y ".trim();
t.expects(first == "x" && second == "y");
}
@test def text_trims_to_what_it_was_given(t: &mut tester): void {
val view: strview = " \t both \n";
t.expects(view.trim() == "both" && view.ltrim() == "both \n" && view.rtrim() == " \t both");
t.expects(is_view(&view.trim()));
# A string's trims are strings of their own, which leave it as it was.
val owned := string::from(" held ", nothing {});
var trimmed := owned.trim();
trimmed.append("!");
t.expects(trimmed.view() == "held!" && owned.view() == " held ");
t.expects(owned.ltrim().view() == "held " && owned.rtrim().view() == " held");
t.expects(!is_view(&owned.trim()));
}
+309
View File
@@ -0,0 +1,309 @@
# Tests of how a program's library files are found: `core` whole, and the
# modules of the others its files refer to, a round at a time, by their paths.
import std::io;
import std::process;
import std::testing;
import system;
module sakura::analyzer;
#! A resolver of the libraries a check reads: this repository's `core`, read
#! whole, and its `system` and runtime, from its root, where the tests run, and
#! the standard library.
#! @returns The resolver.
def test_finder(): resolver {
var made := resolver::new();
made.whole("core", "core");
made.add_library("system", "system");
made.add_library("runtime", "runtime");
made.add_library("std", std_folder());
return made;
}
#! The standard library's folder: its repository beside this one.
#! @returns The folder.
def std_folder(): strview {
return "../std";
}
#! Text that was lexed and parsed, with what both reported.
struct parsed {
var source: source;
var syntax: syntax;
var notes: vector<note>;
}
#! Lexes and parses the text as a file, as the analyzer's own tests do, with
#! the names of the program it is of, as the files a resolver is given are.
#! @param text The text.
#! @param names The program's names.
#! @returns Its source, syntax, and notes.
def parse(text: strview, names: &mut names): parsed {
var made := parsed {
source = source::from("test.sakura", text),
syntax = syntax::new(),
notes = vector::<note>::new()
};
var lexing := lexer::new(&mut made.source, names, &mut made.notes, 0);
lexing.tokenize_all(&mut made.syntax);
var parsing := parser::new(&mut made.syntax, names, &mut made.notes, 0);
_ = parsing.parse();
return made;
}
#! The library files a program of one file reads: what it refers to, then what
#! those refer to, until nothing new is, each as its path within its library,
#! as `std/io/file.sakura`.
#! @param finder The resolver.
#! @param text The program.
#! @returns The paths, in the order they were found.
def files_read(finder: &mut resolver, text: strview): vector<string> {
var found := vector::<string>::new();
var names := names::new();
val program := parse(text, &mut names);
finder.refer(&program.syntax, &names, &mut found);
var done: u64 = 0;
while done < found.length {
val to := found.length;
for i in done..to {
var at := path::parse(found[i].view()) else (_) { continue; };
val held := io::read_file(&at) else (_) { continue; };
val read := parse(held.view(), &mut names);
finder.refer(&read.syntax, &names, &mut found);
}
done = to;
}
return found;
}
#! Whether a path read ends as the text does.
#! @param paths The paths.
#! @param end The text.
#! @returns Whether one does.
def reads_any(paths: &vector<string>, end: strview): bool {
for &each in paths {
return true if each.view().ends_with(end);
}
return false;
}
@test def a_program_reads_core_and_the_modules_its_files_refer_to(t: &mut tester): void {
# With no import, nothing but `core`, which is read whole, apart from this.
var alone := test_finder();
val none := files_read(&mut alone, "def main(): void { var v := vector::<i64>::new(); v.append(0..4 is range<i64> ? 1 : 2); }");
t.expects(none.length == 0);
# `std::io`, the root holding it, and `system`, which its files name by path;
# not `std::serial`, `std::math`, or `std::testing`, which no file refers to.
var printing := test_finder();
val io := files_read(&mut printing, "import std::io;\ndef main(): void { io::println(\"hi\"); }");
t.expects(reads_any(&io, "std/io/console.sakura") && reads_any(&io, "std/io/path.sakura"));
t.expects(!reads_any(&io, "std/net/uri.sakura") && !reads_any(&io, "std/containers/deque.sakura"));
t.expects(reads_any(&io, "system/system.sakura") && reads_any(&io, "system/linux/linux.sakura"));
t.expects(!reads_any(&io, "std/serial/serial.sakura") && !reads_any(&io, "std/math/exp.sakura"));
t.expects(!reads_any(&io, "std/testing/testing.sakura"));
# A path reads the module it begins with, with no import; one beginning with
# no module's name, as an enum's, reads nothing.
var pathed := test_finder();
val exits := files_read(&mut pathed, "enum color { red }\ndef main(): void { val c := color::red; system::exit(0); }");
t.expects(reads_any(&exits, "system/system.sakura") && !reads_any(&exits, "std/net/uri.sakura"));
# A module's files reach a sibling they import, as `std::thread`'s do
# `std::time`'s, which is read too.
var threading := test_finder();
val threads := files_read(&mut threading, "import std::thread;\ndef main(): void {}");
t.expects(reads_any(&threads, "std/thread/thread.sakura") && reads_any(&threads, "std/time/duration.sakura"));
t.expects(!reads_any(&threads, "std/serial/serial.sakura"));
# An executable asks for the runtime, a library of its own beside `core`,
# which reads `system` and nothing of the standard library.
var building := test_finder();
var runtime := vector::<string>::new();
building.want("runtime", &mut runtime);
var names := names::new();
var done: u64 = 0;
while done < runtime.length {
val to := runtime.length;
for i in done..to {
var at := path::parse(runtime[i].view()) else (_) { continue; };
val held := io::read_file(&at) else (_) { continue; };
val read := parse(held.view(), &mut names);
building.refer(&read.syntax, &names, &mut runtime);
}
done = to;
}
t.expects(reads_any(&runtime, "runtime/start.sakura") && reads_any(&runtime, "runtime/memory.sakura"));
t.expects(reads_any(&runtime, "system/windows/windows.sakura"));
val library := std_folder();
for &each in runtime {
t.expects(!each.view().starts_with(library));
}
}
@test def a_module_no_file_refers_to_is_never_read(t: &mut tester): void {
# A library's module whose file does not parse is no matter where nothing
# refers to it, and is read where something does.
val folder := $"{scratch_folder("libraries")}/shelf";
write_text($"{folder}/shelf.sakura", "module shelf;\npub def one(): i64 { return 1; }\n");
write_text($"{folder}/broken/broken.sakura", "module shelf::broken;\npub def oops( {\n");
write_text($"{folder}/parts/a.sakura", "# A part of the root, in a folder of its own.\nmodule shelf;\npub def two(): i64 { return 2; }\n");
write_text($"{folder}/alone.sakura", "# A module of its own, in the root's folder.\nmodule shelf::alone;\npub def three(): i64 { return 3; }\n");
var finder := test_finder();
finder.add_library("shelf", folder.view());
val root := files_read(&mut finder, "import shelf;\ndef main(): void { _ = one() + two(); }");
t.expects(root.length == 2 && reads_any(&root, "shelf/shelf.sakura") && reads_any(&root, "shelf/parts/a.sakura"));
# A file of a module's folder of its own is no part of the module around it,
# and is read where it is referred to.
t.expects(!reads_any(&root, "shelf/alone.sakura"));
var alone := test_finder();
alone.add_library("shelf", folder.view());
val own := files_read(&mut alone, "import shelf::alone;\ndef main(): void { _ = three(); }");
t.expects(reads_any(&own, "shelf/alone.sakura"));
var again := test_finder();
again.add_library("shelf", folder.view());
val broken := files_read(&mut again, "import shelf::broken;\ndef main(): void {}");
t.expects(broken.length == 3 && reads_any(&broken, "shelf/broken/broken.sakura"));
# Completion finds the modules within one by their folders, without reading
# them.
var segments := vector::<string>::new();
segments.append(string::from("shelf", nothing {}));
var shelves := vector::<library>::new();
shelves.append(library { name = string::from("shelf", nothing {}), folder = string::copy_of(&folder) });
val within := modules_within(shelves.view(), segments.view());
t.expects(within.length == 2 && within.iter().any(def(x) => x.view() == "broken") && within.iter().any(def(x) => x.view() == "alone"));
# What the test wrote goes, deepest first.
for &each in ["shelf/broken/broken.sakura", "shelf/parts/a.sakura", "shelf/alone.sakura", "shelf/shelf.sakura", "shelf/broken", "shelf/parts", "shelf", ""] {
val at := each.length == 0 ? scratch_folder("libraries") : $"{scratch_folder("libraries")}/{each}";
var gone := path::parse(at.view()) else (_) { continue; };
_ = io::remove(&gone);
}
}
@test def a_library_may_be_a_module_within_another(t: &mut tester): void {
# A library named for a module within another, as `std::yaml` is, holds that
# module and what is within it, and the library around it the rest.
val root := scratch_folder("within");
write_text($"{root}/inner/inner.sakura", "module std::inner;\npub def one(): i64 { return 1; }\n");
write_text($"{root}/inner/deep/deep.sakura", "module std::inner::deep;\npub def two(): i64 { return 2; }\n");
write_text($"{root}/a/a.sakura", "module two::a;\npub def three(): i64 { return 3; }\n");
write_text($"{root}/b/b.sakura", "module two::b;\npub def four(): i64 { return 4; }\n");
val inner := $"{root}/inner";
val first := $"{root}/a";
val second := $"{root}/b";
var finder := test_finder();
finder.add_library("std::inner", inner.view());
val nested := files_read(&mut finder, "import std::inner::deep;\nimport std::io;\ndef main(): void {}");
t.expects(reads_any(&nested, "inner/inner.sakura") && reads_any(&nested, "inner/deep/deep.sakura"));
t.expects(reads_any(&nested, "std/io/path.sakura"));
# Two libraries within one module that is in none, as `sakura::analyzer` and
# `sakura::machine` are, are each found, and the module holding them has no
# files.
var siblings := test_finder();
siblings.add_library("two::a", first.view());
siblings.add_library("two::b", second.view());
val both := files_read(&mut siblings, "import two::a;\nimport two::b;\ndef main(): void { _ = two::a::three() + two::b::four(); }");
t.expects(both.length == 2 && reads_any(&both, "a/a.sakura") && reads_any(&both, "b/b.sakura"));
# Completion offers the libraries within a module beside its own modules.
var shelves := vector::<library>::new();
shelves.append(library { name = string::from("std", nothing {}), folder = string::from(std_folder(), nothing {}) });
shelves.append(library { name = string::from("std::inner", nothing {}), folder = string::copy_of(&inner) });
shelves.append(library { name = string::from("two::a", nothing {}), folder = string::copy_of(&first) });
shelves.append(library { name = string::from("two::b", nothing {}), folder = string::copy_of(&second) });
var std_path := vector::<string>::new();
std_path.append(string::from("std", nothing {}));
val in_std := modules_within(shelves.view(), std_path.view());
t.expects(in_std.iter().any(def(x) => x.view() == "inner") && in_std.iter().any(def(x) => x.view() == "io"));
var two_path := vector::<string>::new();
two_path.append(string::from("two", nothing {}));
val in_two := modules_within(shelves.view(), two_path.view());
t.expects(in_two.length == 2 && in_two[0].view() == "a" && in_two[1].view() == "b");
std_path.append(string::from("inner", nothing {}));
val in_inner := modules_within(shelves.view(), std_path.view());
t.expects(in_inner.length == 1 && in_inner[0].view() == "deep");
# What the test wrote goes, deepest first.
for &each in ["inner/deep/deep.sakura", "inner/inner.sakura", "a/a.sakura", "b/b.sakura", "inner/deep", "inner", "a", "b", ""] {
val at := each.length == 0 ? string::copy_of(&root) : $"{root}/{each}";
var gone := path::parse(at.view()) else (_) { continue; };
_ = io::remove(&gone);
}
}
@test def a_folder_is_of_each_module_a_file_within_it_is_of(t: &mut tester): void {
# A module's folder may hold the one file of a module within it, as
# `nest/deeper.sakura` of `lib::nest::deeper` beside `nest/nest.sakura` of
# `lib::nest`, whichever name comes first.
val root := scratch_folder("deeper");
write_text($"{root}/lib/lib.sakura", "module lib;\npub def zero(): i64 { return 0; }\n");
write_text($"{root}/lib/nest/nest.sakura", "module lib::nest;\npub def one(): i64 { return 1; }\n");
write_text($"{root}/lib/nest/deeper.sakura", "module lib::nest::deeper;\npub def two(): i64 { return 2; }\n");
val folder := $"{root}/lib";
var finder := test_finder();
finder.add_library("lib", folder.view());
val read := files_read(&mut finder, "import lib::nest;\nimport lib::nest::deeper;\ndef main(): void {}");
t.expects(reads_any(&read, "nest/nest.sakura") && reads_any(&read, "nest/deeper.sakura"));
# Completion offers each.
var shelves := vector::<library>::new();
shelves.append(library { name = string::from("lib", nothing {}), folder = string::copy_of(&folder) });
var lib_path := vector::<string>::new();
lib_path.append(string::from("lib", nothing {}));
val in_lib := modules_within(shelves.view(), lib_path.view());
t.expects(in_lib.length == 1 && in_lib[0].view() == "nest");
lib_path.append(string::from("nest", nothing {}));
val in_nest := modules_within(shelves.view(), lib_path.view());
t.expects(in_nest.length == 1 && in_nest[0].view() == "deeper");
# What the test wrote goes, deepest first.
for &each in ["lib/nest/deeper.sakura", "lib/nest/nest.sakura", "lib/lib.sakura", "lib/nest", "lib", ""] {
val at := each.length == 0 ? string::copy_of(&root) : $"{root}/{each}";
var gone := path::parse(at.view()) else (_) { continue; };
_ = io::remove(&gone);
}
}
@test def a_files_module_is_its_first_module_line(t: &mut tester): void {
t.expects(module_named("#! A file.\nimport std;\n\nmodule std::io;\n").view() == "std::io");
t.expects(module_named("extern import \"kernel32.dll\" when os == windows;\n\nextern module system::windows when os == windows;").view() == "system::windows");
t.expects(module_named("module system when os == linux && arch == x86_64;").view() == "system");
t.expects(module_named("import std;\ndef main(): void {}\nmodule late;").length == 0);
}
#! A folder of its own for a test, under the system's for such files.
#! @param name The test's name.
#! @returns The folder's path.
def scratch_folder(name: strview): string {
var base: strview = "/tmp";
if process::variable("TMPDIR") is some(found) {
base = found;
} else if process::variable("TEMP") is some(found) {
base = found;
}
return $"{base}/sakura-libraries-{system::getpid()}-{name}";
}
#! Writes a file, making the folders it is in.
#! @param at The file's path.
#! @param text What it holds.
def write_text(at: string, text: strview): void {
var end := at.length;
while end > 0 && at[end - 1] != '/' {
end--;
}
var folder := path::parse(at.view().substr(0, end - 1)) else (_) { return; };
_ = io::create_directories(&folder);
var file := path::parse(at.view()) else (_) { return; };
_ = io::write_file(&file, text);
}
+902
View File
@@ -0,0 +1,902 @@
#! @file machine.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the tests of the machine and of constant evaluation: small
#! programs, written over a standard library of their own, are checked, their
#! constants evaluated, and lowered, then run in the machine, which keeps what
#! they write rather than writing it, and what each wrote and how it stopped
#! is compared with what is expected. The collector runs at every allocation,
#! so what it loses is found. The corpus of `test/programs` runs whole programs
#! over the real standard library, by `tools/corpus.sakura`.
import std::io;
import std::testing;
import sakura::analyzer;
import sakura::compiler;
module sakura::machine;
#! A `core` and standard library small enough to check quickly: views, text, a
#! `string` owning its bytes, writing to the output, and exiting.
const prelude: strview = """
module core;
pub trait attribute {}
pub struct intrinsic : attribute {}
@intrinsic pub def raw_allocate(size: u64): *mut u8;
@intrinsic pub def raw_release(pointer: *mut u8): void;
@intrinsic pub def size_of<T>(): u64;
pub trait owning { def close(&mut this): void; }
pub struct span<T> { pub var _data: *T; pub var _length: u64; }
pub val span<T>::length: u64 { get => this._length; }
pub type strview = span<u8>;
pub struct string : owning { var _owner: u64; var _data: *mut u8; var _length: u64; var _capacity: u64; }
pub def string::close(&mut this): void { raw_release(this._data); }
pub def string::view(&this): strview { return span::<u8> { _data = this._data as *u8, _length = this._length }; }
module system;
@intrinsic def syscall(n: i64, a: u64, b: u64, c: u64, d: u64, e: u64, f: u64): i64;
@intrinsic pub def exit(code: i32): void;
@intrinsic pub def abort(): void;
pub def print(text: strview): void { syscall(1, 1, text._data as u64, text._length, 0, 0, 0); }
pub def println(text: strview): void { print(text); print("\\n"); }
@intrinsic pub def start(body: def(*mut u8): void, context: *mut u8): i64;
module std::math;
@intrinsic pub def square_root(x: f64): f64;
@intrinsic pub def ones_in(word: u64): u64;
@intrinsic pub def zeros_leading(word: u64): u64;
@intrinsic pub def zeros_trailing(word: u64): u64;
@intrinsic pub def bytes_reversed(word: u64): u64;
module core;
pub enum order : u8 { relaxed, acquire, release, acq_rel, seq_cst }
pub trait lockfree {}
@intrinsic pub def atomic_load<T>(at: *T, how: order): T where T: lockfree;
@intrinsic pub def atomic_store<T>(at: *mut T, value: T, how: order): void where T: lockfree;
@intrinsic pub def atomic_exchange<T>(at: *mut T, value: T, how: order): T where T: lockfree;
@intrinsic pub def atomic_compare_exchange<T>(at: *mut T, expected: T, desired: T, found: *mut T, success: order, failure: order): bool where T: lockfree;
@intrinsic pub def atomic_fetch<T, const OP: u32>(at: *mut T, operand: T, how: order): T where T: lockfree;
@intrinsic pub def atomic_fence(how: order): void;
pub struct allow : attribute {}
@intrinsic pub struct cfn<F> {}
@intrinsic pub def fault(why: strview): void;
module std;
""";
#! Checks a program written over the prelude, evaluates its constants, lowers
#! it, and runs it, giving what it wrote, then how it stopped where it did not
#! return from `main`: what it exited with, or the fault and its trace. Where
#! it does not check, or evaluating notes what goes wrong, the notes.
#! @param text The program.
#! @returns What it gave.
def ran(text: strview): string {
return ran_at(text, 0);
}
#! Checks a program written over the prelude, evaluates its constants, lowers
#! and optimizes it at a level, and runs it, giving what `ran` gives.
#! @param text The program.
#! @param level How much the code is optimized.
#! @returns What it gave.
def ran_at(text: strview, level: u32): string {
return ran_with(text, level, false);
}
#! Runs a program as `ran` does, with its memory checked, as `run --checks`
#! does, giving also the blocks it never released where it ends by returning
#! or exiting.
#! @param text The program.
#! @returns What it gave.
def ran_checked(text: strview): string {
return ran_with(text, 1, true);
}
#! Checks a program written over the prelude, evaluates its constants, lowers
#! and optimizes it at a level, and runs it, with its memory checked where it
#! is asked to be, giving what `ran` gives.
#! @param text The program.
#! @param level How much the code is optimized.
#! @param checks Whether its memory is checked.
#! @param other A file of the program beside it, `other.sakura`, or empty
#! for none.
#! @returns What it gave.
def ran_with(text: strview, level: u32, checks: bool, other: 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(3);
syntaxes.reserve(3);
sources.append(source::from("test.sakura", text));
if other.length != 0 {
sources.append(source::from("other.sakura", other));
}
sources.append(source::from("prelude.sakura", prelude));
val count := sources.length;
for i in 0..count {
syntaxes.append(syntax::new());
}
for i in 0..count {
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);
checker.target.os = checker.names.intern(&test_os);
for i in 0..count {
checker.add(sources.at(i), syntaxes.at(i), roots.at(i));
}
checker.check();
var out := string::new(nothing {});
var results := outcomes::new();
if notes.length == 0 {
results = evaluate(&mut checker);
}
if notes.length != 0 {
for &each in notes {
val at := sources.at(each.file).lines.place_of(each.offset);
var message := each.message(sources.at(each.file));
out.append($"{at.line}:{at.column}: {message}\n");
}
return out;
}
var lowered := lowerer::new(&mut checker, lowering { verify = true, level = level, checks = checks });
lowered.evaluated = move(&mut results);
lowered.compile();
for &each in lowered.problems {
out.append(each.view());
out.append("\n");
}
return out if lowered.problems.length != 0;
var running := interpreter::new(&mut lowered, interpreting { stack = 1048576, capture = true, checks = checks });
val why := running.run(span::<strview>::empty());
for &byte in running.output {
out.push(byte);
}
if why == halt::exited {
out.append($"--- exit {running.status}\n");
}
if checks && (why == halt::exited || why == halt::none) {
running.report_leaks(&mut out);
}
if why != halt::exited && why != halt::none {
var report := string::new(nothing {});
running.report(why, &mut report);
out.append(report.view());
}
return out;
}
# The system the programs are checked for, which is the one they run on, so
# what they declare for it, as C's functions, is there.
when os == linux {
val test_os: strview = "linux";
}
when os == windows {
val test_os: strview = "windows";
}
#! Whether what a program gave is what is expected, but for the line breaks
#! ending them, printing what it is where it is not.
#! @param got What it gave.
#! @param want What is expected.
#! @returns Whether it is.
def gives(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 numbers_loops_and_calls_run(t: &mut tester): void {
# Values move between the words of frames, loops take their variables as
# the parameters of their heads, and narrow numbers wrap as their types do.
val got := ran("""
import std;
import system;
def fib(n: u64): u64 { return n < 2 ? n : fib(n - 1) + fib(n - 2); }
def main(): void {
var total: u64 = 0;
for i in 0u..10u { total += i * i; }
var small: u8 = 250;
small += 10;
val third: f32 = 1f / 3f;
println($"{fib(20)} {total} {small} {-7 / 2} {-7 % 2} {third} {1.0 / 4.0} {1 << 63}");
}
""");
t.expects(gives(&got, "6765 285 4 -3 -1 0.33333334 0.25 9223372036854775808"));
}
@test def structs_closures_and_traits_run(t: &mut tester): void {
# A struct is returned through the memory its call gives, a closure refers to
# the locals it captures where they are, and a trait's method is called through
# the vtable of the reference.
val got := ran("""
import std;
import system;
struct pair { var a: i64; var b: i64; }
def swapped(p: pair): pair { return pair { a = p.b, b = p.a }; }
trait shape { def area(&this): i64; }
struct square : shape { var side: i64; }
def square::area(&this): i64 { return this.side * this.side; }
struct rect : shape { var w: i64; var h: i64; }
def rect::area(&this): i64 { return this.w * this.h; }
def area_of(s: &shape): i64 { return s.area(); }
def main(): void {
val p := swapped(pair { a = 1, b = 2 });
var n: i64 = 10;
var m: i64 = 20;
val f := def(): i64 { n += 1; return n; };
val g := def(): i64 { m += 1; return m; };
val s := square { side = 3 };
val r := rect { w = 2, h = 5 };
println($"{p} {f()} {g()} {f()} {area_of(&s)} {area_of(&r)}");
}
""");
t.expects(gives(&got, "pair{a = 2, b = 1} 11 21 12 9 10"));
}
@test def a_default_reads_the_locals_of_its_call_in_another_file(t: &mut tester): void {
# The files begin alike, so `f`'s `x` and `shown`'s `x` are nodes of the same
# index, each of its own file. The default making `got` names `shown`'s, and
# `values_of` evaluates what the call wrote for it, which names `f`'s.
t.expects(gives(&ran_with("""
import system;
def f(x: i64): void { shown(x * 3 == 9); }
def main(): void { f(3); }
""", 0, false, """
import system;
def shown(x: bool, got: string = values_of(x)): void { println(got.view()); }
module core;
@intrinsic pub def values_of<T>(value: T): string;
"""), "x * 3 = 9"));
}
@test def faults_report_where_each_function_was(t: &mut tester): void {
# A fault stops the program and names each function running, where it was,
# as the C machine does; an exit stops it with its status.
val got := ran("""
import std;
import system;
def divide(a: i64, b: i64): i64 { return a / b; }
def main(): void {
println("before");
println($"{divide(7, 0)}");
}
""");
t.expects(gives(&got, """
before
sakura: runtime error: Division by zero.
at divide (test.sakura:3:44)
at main (test.sakura:6:20)
"""));
val exited := ran("""
import std;
import system;
def main(): void {
println("going");
exit(3);
println("gone");
}
""");
t.expects(gives(&exited, "going\n--- exit 3"));
# `fault` stops it as a fault does, with the text it was given, and needs no
# import, being `core`'s.
val faulted := ran("""
def check(n: i64): i64 {
if n > 3 { fault("Past three."); }
return n;
}
def main(): void { _ = check(5); }
""");
t.expects(gives(&faulted, """
sakura: runtime error: Past three.
at check (test.sakura:2:19)
at main (test.sakura:5:29)
"""));
}
@test def contracts_stop_a_run_and_a_constant_they_fail(t: &mut tester): void {
# A contract that fails is a fault, saying which failed and what its operands
# held, made only there.
val failed := ran("""
def divide(a: i64, b: i64): i64 {
expects(b != 0);
return a / b;
}
def main(): void { _ = divide(7, 0); }
""");
t.expects(gives(&failed, """
sakura: runtime error: A pre-condition failed: b != 0, with b = 0.
at divide (test.sakura:2:3)
at main (test.sakura:5:30)
"""));
# One that holds runs while compiling, and one that fails stops the constant
# it is evaluated for, saying so there.
val held := ran("""
import system;
def half(n: i64): i64 {
asserts(n % 2 == 0);
return n / 2;
}
const four: i64 = half(8);
def main(): void { exit(four as i32); }
""");
t.expects(gives(&held, "--- exit 4"));
val stopped := ran("""
def half(n: i64): i64 {
asserts(n % 2 == 0);
return n / 2;
}
const odd: i64 = half(7);
def main(): void { _ = odd; }
""");
t.expects(gives(&stopped, """
5:7: Evaluating `odd` stopped: An assertion failed: n % 2 == 0, with n % 2 = 1.
at half (test.sakura:2:3)
at odd (test.sakura:5:22)
"""));
}
@test def checked_runs_stop_where_memory_is_not_held(t: &mut tester): void {
# A block read after its release, a block released twice, and a local read
# through a reference once its frame is gone each stop a checked run, where
# a run unchecked reads what is there.
val released := ran_checked("""
import std;
import system;
def main(): void {
val block := raw_allocate(16) as *mut i64;
block[0] = 3;
raw_release(block as *mut u8);
println("released");
block[1] = 4;
}
""");
t.expects(gives(&released, """
released
sakura: runtime error: Pointer reaches memory the program does not hold, as past the end of what it points into, or memory released.
at main (test.sakura:8:8)
"""));
val twice := ran_checked("""
import std;
def main(): void {
val block := raw_allocate(16);
raw_release(block);
raw_release(block);
}
""");
t.expects(gives(&twice, """
sakura: runtime error: Released memory that was not allocated, or was already released.
at main (test.sakura:5:14)
"""));
val dangling := ran_checked("""
import std;
struct point { var x: i64; }
@allow def made(): &mut point { var p := point { x = 7 }; return &mut p; }
def main(): void {
val p := &mut made();
p.x = 8;
}
""");
t.expects(gives(&dangling, """
sakura: runtime error: Pointer reaches memory the program does not hold, as past the end of what it points into, or memory released.
at main (test.sakura:6:5)
"""));
}
@test def checked_runs_report_the_blocks_nothing_reaches(t: &mut tester): void {
# What a global reaches, directly or through a block, and what the frames
# hold as the program exits, are kept; the rest is reported by where it was
# allocated, those of each place together, in order.
val got := ran_checked("""
import std;
import system;
struct node { var next: *mut node; }
var kept: *mut node;
def lose(): void { _ = raw_allocate(24); }
def finish(held: *mut u8): void {
held[0] = 1;
exit(2);
}
def main(): void {
kept = raw_allocate(8) as *mut node;
kept[0].next = raw_allocate(8) as *mut node;
lose();
lose();
val mine := raw_allocate(5);
finish(mine);
}
""");
t.expects(gives(&got, """
--- exit 2
sakura: 2 blocks the program allocated, 48 bytes, were never released, and nothing it keeps reaches them:
2 blocks, 48 bytes, allocated at lose (test.sakura:5:36)
"""));
}
@test def checked_runs_keep_the_frames_of_each_thread_as_the_program_exits(t: &mut tester): void {
# A thread still running as the program exits keeps what its frames hold, as
# `main` does, so the block it writes is not reported. Its frames are read
# whole for it, as `main`'s are, even the words nothing wrote.
val got := ran_checked("""
import std;
import system;
var started: u64;
def spin(held: *mut u8): void {
held[0] = 1;
atomic_store::<u64>((&mut started) as *mut u64, 1, order::release);
while true {
held[0] = held[0] + 1;
}
}
def work(context: *mut u8): void {
spin(raw_allocate(8));
}
def main(): void {
_ = system::start(work, null);
while atomic_load::<u64>((&started) as *u64, order::acquire) == 0 {}
exit(2);
}
""");
t.expects(gives(&got, """
--- exit 2
"""));
}
@test def a_fault_in_code_inlined_names_the_function_inlined(t: &mut tester): void {
# `divide` is inlined into `main`, and a fault within it still names it, where
# it was, then `main`, where it called it, as without inlining.
val got := ran_at("""
import std;
import system;
def divide(a: i64, b: i64): i64 { return a / b; }
def main(): void {
println("before");
println($"{divide(7, 0)}");
}
""", 2);
t.expects(gives(&got, """
before
sakura: runtime error: Division by zero.
at divide (test.sakura:3:44)
at main (test.sakura:6:20)
"""));
}
@test def atomics_work_while_compiling_as_they_do_running(t: &mut tester): void {
# Compiling runs one thread, where an atomic is what it reads and writes; the
# machine runs it as the program does, and each gives what it held.
val program: strview = """
import std;
import system;
def count(): u64 {
var held: u64 = 5;
val at := (&mut held) as *mut u64;
val was := atomic_fetch::<u64, 4>(at, 3, order::seq_cst);
atomic_store::<u64>(at, atomic_load::<u64>(at, order::acquire) * 2, order::release);
var found: u64 = 0;
val wrote := atomic_compare_exchange::<u64>(at, 16, 20, (&mut found) as *mut u64, order::seq_cst, order::seq_cst);
val refused := atomic_compare_exchange::<u64>(at, 16, 30, (&mut found) as *mut u64, order::seq_cst, order::relaxed);
val swapped := atomic_exchange::<u64>(at, 1, order::seq_cst);
atomic_fence(order::seq_cst);
var small: i8 = -5;
val least := atomic_fetch::<i8, 9>((&mut small) as *mut i8, -7, order::relaxed);
var top: u64 = 1;
val most := atomic_fetch::<u64, 10>((&mut top) as *mut u64, 0x8000000000000000u, order::relaxed);
val right := wrote && !refused && least == -5 && small == -7 && most == 1 && top == 0x8000000000000000u;
return was * 1000000 + found * 10000 + swapped * 100 + held + (right ? 50 : 0);
}
const counted: u64 = count();
def main(): void { println($"{counted} {count()}"); }
""";
t.expects(ran(program).view() == "5202051 5202051\n");
t.expects(ran_at(program, 2).view() == "5202051 5202051\n");
}
@test def math_operations_agree_to_the_bit(t: &mut tester): void {
# The operations of `std::math` the machine gives are the same bits run as
# written, folded by the optimizer where their operands are known, and in a
# constant: a correctly rounded square root, and counts of a word's bits, 64
# of zero, and its bytes reversed.
val program: strview = """
import std;
import system;
import std::math;
const root: f64 = square_root(2.0);
const ones: u64 = ones_in(0xF0F0u);
def bits(x: f64): u64 { var held := x; return ((&mut held) as *mut u64)[0]; }
def main(): void {
val zero: f64 = 0;
val reals: f64[9] = [2.0, 0.0, -0.0, -1.0, 1e-310, 1e300, 0.25, 3.0, 1.0 / zero];
for i in 0..9u { println($"{bits(square_root(reals[i]))}"); }
val words: u64[5] = [0u, 1u, 0x8000000000000000u, 0xFFFFFFFFFFFFFFFFu, 0x0102030405060708u];
for i in 0..5u {
val w: u64 = words[i];
println($"{ones_in(w)} {zeros_leading(w)} {zeros_trailing(w)} {bytes_reversed(w)}");
}
println($"{bits(root)} {ones} {bits(square_root(1e-310))} {zeros_leading(1u)} {bytes_reversed(0xFFu)}");
}
""";
val want: strview = """
4609047870845172685
0
9223372036854775808
18444492273895866368
2288155682980613038
6850974717710472879
4602678819172646912
4610479282544200874
9218868437227405312
0 64 64 0
1 63 0 72057594037927936
1 0 63 128
64 0 0 18446744073709551615
13 7 3 578437695752307201
4609047870845172685 8 2288155682980613038 63 18374686479671623680
""";
val plain := ran(program);
t.expects(gives(&plain, want));
val optimized := ran_at(program, 2);
t.expects(gives(&optimized, want));
}
@test def constants_are_evaluated_while_compiling(t: &mut tester): void {
# A constant the checker does not work out is evaluated in the machine, and
# held as data with the memory it points into; one reading another waits for
# it; a local constant is evaluated too, and so is a condition of `if const`.
val got := ran("""
import std;
import system;
struct entry { val name: strview; val value: i64; }
def made(n: i64): span<i64> {
val at := raw_allocate(3 * 8) as *mut i64;
for i in 0..3 { at[i] = n * (i as i64 + 1); }
return span::<i64> { _data = at as *i64, _length = 3 };
}
const table: span<i64> = made(base);
const base: i64 = twice(21);
const first: entry = entry { name = "first", value = table._data[2] };
def twice(x: i64): i64 { return x * 2; }
def wide<T>(): bool {
if const size_of::<T>() > 4 { return true; }
return false;
}
def main(): void {
const local: entry = entry { name = "local", value = twice(5) };
println($"{table._data[0]} {table._data[1]} {first.name} {first.value} {local.name} {local.value} {wide::<u64>()} {wide::<u8>()}");
}
""");
t.expects(gives(&got, "42 84 first 126 local 10 true false"));
}
@test def evaluating_notes_what_only_a_running_program_does(t: &mut tester): void {
# Evaluating stops where it reaches what only the program running has, as a
# system call, or an address taken as a number, as `print` gives the system
# its text's, and notes why at the constant, with the functions running.
val got := ran("""
import std;
import system;
def loud(): i64 { println("now"); return 1; }
const noisy: i64 = loud();
def main(): void { println($"{noisy}"); }
""");
t.expects(gives(&got, """
4:7: Evaluating `noisy` stopped: Function does not run while compiling.
at print (prelude.sakura:18:63)
at println (prelude.sakura:19:45)
at loud (test.sakura:3:26)
at noisy (test.sakura:4:24)
"""));
}
@test def values_share_the_words_of_frames(t: &mut tester): void {
# Values whose lives do not overlap share a word of the frame, so a long
# function with many short-lived values keeps a small frame.
var held := names::new();
var notes := vector::<note>::new();
var sources := vector::<source>::new();
var syntaxes := vector::<syntax>::new();
sources.reserve(1);
syntaxes.reserve(1);
sources.append(source::from("test.sakura", """
def many(x: u64): u64 {
var a := x;
a = a * 3 + 1; a = a * 3 + 1; a = a * 3 + 1; a = a * 3 + 1;
a = a * 3 + 1; a = a * 3 + 1; a = a * 3 + 1; a = a * 3 + 1;
return a;
}
def main(): void { many(1); }
"""));
syntaxes.append(syntax::new());
var lexing := lexer::new(sources.at(0), &mut held, &mut notes, 0);
lexing.tokenize_all(syntaxes.at(0));
var parsing := parser::new(syntaxes.at(0), &held, &mut notes, 0);
val root := parsing.parse();
var checker := checker::new(&mut held, &mut notes);
checker.add(sources.at(0), syntaxes.at(0), root);
checker.check();
var lowered := lowerer::new(&mut checker, lowering { verify = true });
lowered.compile();
lowered.assemble_all();
for &each in lowered.program.functions {
continue if each.name.view() != "many";
val values := each.body.origins.length;
t.expects(values > 30 && each.compiled.frame <= 8 * 8);
}
}
#! Checks a program written over the prelude, evaluates its constants, and
#! lowers every function of it, as a host embedding the machine does, then
#! gives a machine running it, not yet begun, to a function, which calls its
#! functions itself. Where it does not check, or does not lower, gives what was
#! noted, and otherwise nothing.
#! @param text The program.
#! @param options How it runs.
#! @param body What the host does with the machine.
#! @returns What was noted.
def hosted(text: strview, options: interpreting, body: def(&mut interpreter): void): 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(2);
syntaxes.reserve(2);
sources.append(source::from("test.sakura", text));
sources.append(source::from("prelude.sakura", prelude));
for i in 0u..2u {
syntaxes.append(syntax::new());
}
for i in 0u..2u {
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);
checker.target.os = checker.names.intern(&test_os);
for i in 0u..2u {
checker.add(sources.at(i), syntaxes.at(i), roots.at(i));
}
checker.check();
var out := string::new(nothing {});
var results := outcomes::new();
if notes.length == 0 {
results = evaluate(&mut checker);
}
for &each in notes {
val at := sources.at(each.file).lines.place_of(each.offset);
var message := each.message(sources.at(each.file));
out.append($"{at.line}:{at.column}: {message}\n");
}
return out if notes.length != 0;
var lowered := lowerer::new(&mut checker, lowering { verify = true, everything = true });
lowered.evaluated = move(&mut results);
lowered.compile();
for &each in lowered.problems {
out.append(each.view());
out.append("\n");
}
return out if lowered.problems.length != 0;
var running := interpreter::new(&mut lowered, options);
body(&mut running);
return out;
}
#! The function of a program of a name, as a trace writes it.
#! @param running The machine running the program.
#! @param name The name.
#! @returns The function, or `no_function`.
def function_named(running: &interpreter, name: strview): u32 {
for i in 0..running.c.program.functions.length {
return i as u32 if running.c.program.functions[i].name.view() == name;
}
return no_function;
}
#! The bits of an `f64`, as a word passes it.
def bits_of(x: f64): u64 {
var held := x;
return ((&mut held) as *mut u64)[0];
}
#! The `f64` of a word's bits.
def real_of(word: u64): f64 {
var held := word;
return ((&mut held) as *mut f64)[0];
}
@test def hosts_call_the_functions_of_a_program_they_began(t: &mut tester): void {
# A host begins a program, giving its globals their values, then calls its
# functions by their words: integers, floats as `f64`, a struct in memory
# both ways, and a function value the program gave, by its two words.
val noted := hosted("""
import std;
import system;
var counter: i64 = 10;
pub struct triple { pub var a: i64; pub var b: i64; pub var c: i64; }
def add(x: i64, y: i64): i64 { counter += 1; return x + y + counter; }
def scaled(v: f32, by: f64): f64 { return v as f64 * by; }
def made(x: i64): triple { return triple { a = x, b = x + 1, c = x + 2 }; }
def sum(p: triple): i64 { return p.a + p.b + p.c; }
def plus_four(x: i64): i64 { return x + 4; }
def adder(): def(i64): i64 { return plus_four; }
def loud(): void { println("hello from the program"); }
""", interpreting { stack = 1048576, capture = true }, def(running: &mut interpreter): void {
t.expects(running.begin() == halt::none);
var two: u64[2] = [2, 3];
t.expects(running.call(function_named(running, "add"), two[:]) == halt::none && running.result(0) == 16);
t.expects(running.call(function_named(running, "add"), two[:]) == halt::none && running.result(0) == 17);
var reals: u64[2] = [bits_of(1.5), bits_of(2.0)];
t.expects(running.call(function_named(running, "scaled"), reals[:]) == halt::none && real_of(running.result(0)) == 3.0);
var made: i64[3];
var five: u64[1] = [5];
t.expects(running.call(function_named(running, "made"), five[:], (&mut made) as *mut u8 as u64) == halt::none);
t.expects(made[0] == 5 && made[1] == 6 && made[2] == 7);
var address: u64[1] = [(&mut made) as *mut u8 as u64];
t.expects(running.call(function_named(running, "sum"), address[:]) == halt::none && running.result(0) == 18);
t.expects(running.call(function_named(running, "adder"), span::<u64>::empty()) == halt::none);
val function := running.result(0);
val environment := running.result(1);
var ten: u64[1] = [10];
t.expects(running.call_value(function, environment, ten[:]) == halt::none && running.result(0) == 14);
t.expects(running.call(function_named(running, "loud"), span::<u64>::empty()) == halt::none);
val said := running.take_output();
t.expects(said.view() == "hello from the program\n");
# Too few words is no call.
t.expects(running.call(function_named(running, "add"), five[:]) == halt::unsupported);
});
t.expects(gives(&noted, ""));
}
@test def a_call_stops_once_it_takes_more_steps_than_allowed(t: &mut tester): void {
# Each call the host makes may take as many steps as it allows, so one that
# never ends stops, and the next is allowed as many again.
val noted := hosted("""
import std;
import system;
def spin(): void { var x: u64 = 0; while true { x += 1; } }
def count(n: u64): u64 { var x: u64 = 0; for i in 0..n { x += i; } return x; }
""", interpreting { stack = 1048576, steps = 100000 }, def(running: &mut interpreter): void {
t.expects(running.begin() == halt::none);
val stopped := running.call(function_named(running, "spin"), span::<u64>::empty());
t.expects(stopped == halt::step_limit);
var report := string::new(nothing {});
running.report(stopped, &mut report);
t.expects(report.view().find("at spin (test.sakura:") is some(_));
var many: u64[1] = [1000];
t.expects(running.call(function_named(running, "count"), many[:]) == halt::none && running.result(0) == 499500);
});
t.expects(gives(&noted, ""));
}
when os == windows {
# The machine the functions the host provides call back into, and what they
# call there.
var hosting: *mut interpreter = null;
var tripled: u32 = 0;
var broken: u32 = 0;
# Functions of the host's, which the programs of the test call.
def host_twice(x: i64): i64 {
return x * 2;
}
def host_again(x: i64): i64 {
var args: u64[1] = [x as u64];
return -1 if through(hosting).call(tripled, args[:]) != halt::none;
return through(hosting).result(0) as i64;
}
def host_broken(x: i64): i64 {
var args: u64[1] = [x as u64];
val why := through(hosting).call(broken, args[:]);
return why == halt::out_of_bounds ? 100 : 0;
}
@test def programs_call_what_the_host_provides(t: &mut tester): void {
# A host gives a program functions of its own, which it declares as C's
# are, and those call back into the program; a fault there stops the
# program's call under way once the host returns to it, giving its trace.
val noted := hosted("""
import std;
import system;
import host;
def triple(x: i64): i64 { return x * 3; }
def through_host(x: i64): i64 { return twice(x) + again(x); }
def past_end(i: i64): i64 { var a: i64[2] = [1, 2]; return a[i as u64]; }
def breaks_through_host(x: i64): i64 { return fails(x) + 1; }
extern module host when os == windows;
pub def twice(x: i64): i64;
pub def again(x: i64): i64;
pub def fails(x: i64): i64;
""", interpreting { stack = 1048576 }, def(running: &mut interpreter): void {
val twice: cfn<def(i64): i64> = host_twice;
val again: cfn<def(i64): i64> = host_again;
val fails: cfn<def(i64): i64> = host_broken;
running.provide("twice", twice as u64);
running.provide("again", again as u64);
running.provide("fails", fails as u64);
hosting = running as *mut interpreter;
tripled = function_named(running, "triple");
broken = function_named(running, "past_end");
t.expects(running.begin() == halt::none);
var seven: u64[1] = [7];
t.expects(running.call(function_named(running, "through_host"), seven[:]) == halt::none && running.result(0) == 35);
val why := running.call(function_named(running, "breaks_through_host"), seven[:]);
t.expects(why == halt::out_of_bounds);
var report := string::new(nothing {});
running.report(why, &mut report);
t.expects(report.view().find("at past_end (test.sakura:") is some(_) && report.view().find("at breaks_through_host (test.sakura:") is some(_));
# The program goes on being called after.
t.expects(running.call(function_named(running, "through_host"), seven[:]) == halt::none && running.result(0) == 35);
hosting = null;
});
t.expects(gives(&noted, ""));
}
@test def c_calls_pass_values_as_c_does(t: &mut tester): void {
# On Windows a program reaches the system through C, so the machine calls C
# with Microsoft's ABI: integers and floats positional in registers and on
# the stack, an aggregate as large as an integer by value and a larger one
# by the address of a copy, a larger result through memory, and a function
# of the program C calls back. Every kind is passed to C's own library here.
val got := ran("""
import std;
import system;
import crt;
extern import "ucrtbase.dll" when os == windows;
def compare_ints(a: *u8, b: *u8): i32 { return (a as *i32)[0] - (b as *i32)[0]; }
def main(): void {
val root := sqrt(16.0);
val cube := cbrtf(27f);
val q := div(17, 5);
val w := lldiv(100, 7);
val c := conj(complex { re = 1.5, im = 2.5 });
var numbers: i32[5] = [5, 3, 1, 4, 2];
qsort((&mut numbers) as *mut u8, 5, 4, compare_ints);
println($"{root} {cube} {q.quot} {q.rem} {w.quot} {w.rem} {c.re} {c.im}");
println($"{numbers[0]} {numbers[1]} {numbers[2]} {numbers[3]} {numbers[4]}");
}
extern module crt when os == windows;
pub struct quotient { pub var quot: i32; pub var rem: i32; }
pub struct wide_quotient { pub var quot: i64; pub var rem: i64; }
pub struct complex { pub var re: f64; pub var im: f64; }
pub def sqrt(x: f64): f64;
pub def cbrtf(x: f32): f32;
pub def div(a: i32, b: i32): quotient;
pub def lldiv(a: i64, b: i64): wide_quotient;
pub def conj(z: complex): complex;
pub def qsort(base: *mut u8, count: u64, size: u64, compare: cfn<def(*u8, *u8): i32>): void;
""");
t.expects(gives(&got, "4 3 3 2 14 2 1.5 -2.5\n1 2 3 4 5"));
}
}
+32
View File
@@ -0,0 +1,32 @@
#! @file main.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the `main` that runs this repository's unit tests, each in a copy of
#! the program of its own: those of finding libraries, in `libraries.sakura`,
#! and those of each of the compiler's libraries, in the folder of its name, as
#! `tests/analyzer/`. Each set is a program of its own, read from the root of
#! the repository, where `core`, `system`, and `runtime` are, with the standard
#! library's repository beside it.
#!
#! `blossom test` runs them as `sakurac.tests` and `sakura.analyzer.tests` and
#! the rest, or, from the root of the repository:
#!
#! ```
#! sakurac run --lib std=../std --lib sakura::analyzer=analyzer
#! tests/main.sakura tests/libraries.sakura
#! sakurac run --lib sakura::analyzer=analyzer tests/main.sakura tests/analyzer/*.sakura
#! ```
#!
#! Each library's README gives the libraries its tests read.
#!
#! Add `-- --only TEXT` to run the tests whose name holds the text, and
#! `-- --here` to run them in one program, as a debugger wants.
import system;
import std::testing;
def main(args: span<strview>): void {
exit(tester::run(args));
}
@@ -0,0 +1,5 @@
released once
--- exit 1
sakura: runtime error: Released memory that was not allocated, or was already released.
at main (tests/memory/a_block_released_twice_stops_the_program_1.sakura:6:14)
@@ -0,0 +1,8 @@
import std::io;
def main(): void {
val block := raw_allocate(16);
raw_release(block);
println("released once");
raw_release(block);
println("released twice");
}
@@ -0,0 +1,5 @@
3
--- exit 1
sakura: runtime error: Pointer reaches memory the program does not hold, as past the end of what it points into, or memory released.
at main (tests/memory/a_block_used_after_its_release_stops_the_program_1.sakura:7:19)
@@ -0,0 +1,8 @@
import std::io;
def main(): void {
val block := raw_allocate(16) as *mut i64;
block[0] = 3;
println($"{block[0]}");
raw_release(block as *mut u8);
println($"{block[0]}");
}
@@ -0,0 +1,3 @@
held by main as it exits
--- exit 3
@@ -0,0 +1,12 @@
import std::io;
import system;
def finish(text: &string): void {
println(text.view());
system::exit(3);
}
def main(): void {
var text := string::from("held by main", nothing {});
text.append(" as it exits");
val block := raw_allocate(32);
finish(&text);
}
@@ -0,0 +1,5 @@
made
--- exit 1
sakura: runtime error: Pointer reaches memory the program does not hold, as past the end of what it points into, or memory released.
at main (tests/memory/a_reference_outliving_its_frame_stops_the_program_1.sakura:11:16)
@@ -0,0 +1,12 @@
import std::io;
struct point { var x: i64; var y: i64; }
# The warning that `p` ends with the function is quieted, so the program runs.
@allow def made(): &point {
var p := point { x = 7, y = 8 };
return &p;
}
def main(): void {
val p := &made();
println("made");
println($"{p.x}");
}
@@ -0,0 +1,9 @@
done
--- exit 0
sakura: 7 blocks the program allocated, 127 bytes, were never released, and nothing it keeps reaches them:
1 block, 16 bytes, allocated at chain (tests/memory/blocks_nothing_reaches_are_reported_where_they_were_allocated_1.sakura:10:28)
1 block, 16 bytes, allocated at chain (tests/memory/blocks_nothing_reaches_are_reported_where_they_were_allocated_1.sakura:11:31)
1 block, 40 bytes, allocated at hold (tests/memory/blocks_nothing_reaches_are_reported_where_they_were_allocated_1.sakura:17:36)
3 blocks, 48 bytes, allocated at lose (tests/memory/blocks_nothing_reaches_are_reported_where_they_were_allocated_1.sakura:5:26)
1 block, 7 bytes, allocated at named (tests/memory/blocks_nothing_reaches_are_reported_where_they_were_allocated_1.sakura:14:36)
@@ -0,0 +1,26 @@
import std::io;
struct node { var value: u64; var next: *mut node; }
def lose(count: u64): void {
for i in 0..count {
val n := raw_allocate(size_of::<node>()) as *mut node;
n[0].value = i;
}
}
def chain(): *mut node {
val first := raw_allocate(size_of::<node>()) as *mut node;
first[0].next = raw_allocate(size_of::<node>()) as *mut node;
return first;
}
def named(n: u64): string { return $"block {n}"; }
# What a lost block holds is lost with it, though the block holds its address.
def hold(n: u64): *mut string {
val holder := raw_allocate_zeroed(size_of::<string>()) as *mut string;
holder[0] = named(n);
return holder;
}
def main(): void {
lose(3);
_ = chain();
_ = hold(4);
println("done");
}
@@ -0,0 +1 @@
released
@@ -0,0 +1,10 @@
import std::io;
struct named : owning { var text: string; var more: string; }
def named::close(&mut this): void { this.text.close(); }
def main(): void {
{ var held := box::new(named{ text = $"one {1}", more = $"two {2}" }); }
var many := vector::<named>::new();
many.append(named{ text = $"three {3}", more = $"four {4}" });
many.close();
println("released");
}
@@ -0,0 +1 @@
5 6 4
@@ -0,0 +1,23 @@
import std::io;
# A functor too large for a function's buffer is held in a box, which the function
# gives back where it closes, written over, moved, or ended with its scope, so
# nothing is left for the report, the strings the functors hold included.
struct labeled : invokable<def(): u64> {
var label: string;
var spare: u64[3];
}
def labeled::invoke(&mut this): u64 { return this.label.length; }
def made(text: strview): function<def(): u64> {
return function::new(labeled { label = string::from(text, nothing {}) });
}
def main(): void {
var f := made("first");
val n := f();
f = made("second");
var g := move(&mut f);
val m := g();
var many := vector::<function<def(): u64>>::new();
for i in 0..20u { many.append(made("many")); }
g.close();
println($"{n} {m} {many[19]()}");
}
@@ -0,0 +1,6 @@
10
unmapped
--- exit 1
sakura: runtime error: Pointer reaches memory the program does not hold, as past the end of what it points into, or memory released.
at main (tests/memory/memory_mapped_from_the_system_is_held_until_unmapped_1.sakura:14:19)
@@ -0,0 +1,33 @@
import std::io;
import system;
def main(): void {
val page := map(8192);
val words := page as *mut u64;
# Two pages, the second word past the first's end on the second.
words[0] = 1;
words[511] = 2;
words[512] = 3;
words[1023] = 4;
println($"{words[0] + words[511] + words[512] + words[1023]}");
unmap(page, 8192);
println("unmapped");
println($"{words[0]}");
}
# Memory is mapped from the system and given back as each system has it: by
# `mmap` and `munmap` on Linux, and `VirtualAlloc` and `VirtualFree` on Windows.
when os == linux {
def map(bytes: u64): u64 {
return system::linux::syscall(9, 0, bytes, 3, 0x22, 0xFFFFFFFFFFFFFFFF, 0) as u64;
}
def unmap(at: u64, bytes: u64): void {
_ = system::linux::syscall(11, at, bytes, 0, 0, 0, 0);
}
}
else {
def map(bytes: u64): u64 {
return system::windows::VirtualAlloc(0, bytes, 0x3000, 0x04);
}
def unmap(at: u64, bytes: u64): void {
_ = system::windows::VirtualFree(at, 0, 0x8000);
}
}
@@ -0,0 +1,6 @@
36
--- exit 1
sakura: runtime error: Memory was read before anything wrote it, as memory `raw_allocate` gives or a variable `undefined`.
at total (tests/memory/reading_an_undefined_variable_before_writing_it_stops_the_program_1.sakura:11:17)
at main (tests/memory/reading_an_undefined_variable_before_writing_it_stops_the_program_1.sakura:18:19)
@@ -0,0 +1,19 @@
import std::io;
# A variable `undefined` holds what its memory happened to until written.
def total(count: u64): u64 {
var parts: u64[8] = undefined;
for i in 0..count {
parts[i] = i + 1;
}
var sum: u64 = 0;
for i in 0..8u {
sum += parts[i];
}
return sum;
}
def main(): void {
println($"{total(8)}");
println($"{total(5)}");
}
@@ -0,0 +1,5 @@
9
--- exit 1
sakura: runtime error: Pointer reaches memory the program does not hold, as past the end of what it points into, or memory released.
at main (tests/memory/reading_past_what_was_allocated_stops_the_program_1.sakura:7:19)
@@ -0,0 +1,8 @@
import std::io;
def main(): void {
# Ten bytes are asked for, though the block is rounded up to sixteen.
val bytes := raw_allocate(10);
bytes[9] = 9;
println($"{bytes[9]}");
println($"{bytes[12]}");
}
@@ -0,0 +1,5 @@
7 9
--- exit 1
sakura: runtime error: Memory was read before anything wrote it, as memory `raw_allocate` gives or a variable `undefined`.
at main (tests/memory/reading_what_raw_allocate_gave_before_writing_it_stops_the_program_1.sakura:11:19)
@@ -0,0 +1,12 @@
import std::io;
# A block `raw_allocate` gave holds what it may until written. Copying it, as
# growing it does, reads nothing, so only what the program reads stops it.
def main(): void {
val words := raw_allocate(16) as *mut u64;
words[0] = 7;
val grown := raw_resize(words as *mut u8, 32) as *mut u64;
grown[2] = 9;
println($"{grown[0]} {grown[2]}");
println($"{grown[1]}");
}
@@ -0,0 +1,23 @@
import std::io;
import std::thread;
import std::time;
# The thread's handle is kept where nothing closes it, so the program ends
# without waiting for the thread, which holds a block in its frame.
var worker: maybe<thread::handle<void>> = nothing {};
var ready := atomic::<u32>::new(0);
def work(): void {
val mine := raw_allocate(24);
mine[0] = 1;
ready.store(1, order::release);
while true {
thread::sleep(time::milliseconds(1));
mine[0] += 1;
}
}
def main(): void {
worker = thread::spawn(work) else (e) { return; };
while ready.load(order::acquire) == 0 {
thread::sleep(time::milliseconds(1));
}
println("main ends");
}
@@ -0,0 +1,3 @@
true false true true true
made
still 5
@@ -0,0 +1,30 @@
import std::io;
# `_` names nothing, so a test or an arm naming a field's value `_` takes nothing
# out of the union: a box stays with the holder a reference reaches, and one a
# call made is closed once, with the union.
struct holder { var b: maybe<box<u64>>; }
def holds(h: &holder): bool { return h.b is some(_); }
def lacks(h: &holder): bool { return h.b is not some(_); }
def arm(h: &holder): bool {
match h.b {
some(_) => { return true; }
none => { return false; }
}
return false;
}
def made(): maybe<box<u64>> { return box::<u64>::new(7); }
def main(): void {
var h := holder{ b = box::<u64>::new(5) };
val first := holds(&h);
val missing := lacks(&h);
val matched := arm(&h);
println($"{first} {missing} {matched} {holds(&h)} {made() is some(_)}");
match made() {
some(_) => { println("made"); }
none => {}
}
if h.b is some(&b) { println($"still {b.get()}"); }
}
@@ -0,0 +1 @@
1 5 6 2
@@ -0,0 +1,22 @@
import std::io;
import std::containers;
struct node { var value: u64; var next: *mut node; }
var kept: *mut node;
var names: vector<string>;
def main(): void {
# Blocks a global reaches, and those they reach in turn.
kept = raw_allocate(size_of::<node>()) as *mut node;
kept[0].next = raw_allocate(size_of::<node>()) as *mut node;
kept[0].next[0].next = raw_allocate(size_of::<node>()) as *mut node;
names = vector::<string>::new();
names.append(string::from("kept", nothing {}));
# Owners that close what they hold.
var v := vector::<u64>::new();
v.append(1);
val b := box::<u64>::new(5);
var r := rc::<u64>::new(6);
var also := copy(&r);
val text := $"{v[0]} {b.get()} {also.get()} {r.count()}";
println(text.view());
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1 @@
read past its mark
@@ -0,0 +1,2 @@
import std::io;
def main(): void { println("read past its mark"); }
@@ -0,0 +1 @@
1 2 9 4 5 8 6 true 6
@@ -0,0 +1,21 @@
import std::io;
struct holder : owning { var data: *mut u8; var tag: int; }
var closed: int = 0;
def holder::of(tag: int): holder { return holder { data = raw_allocate(8), tag = tag }; }
def holder::close(&mut this): void { if this.data != null { closed++; raw_release(this.data); this.data = null; } }
def holder::taken(src: &mut holder): holder { var made := holder { data = src.data, tag = src.tag }; src.data = null; return made; }
def reads(h: holder): int { return h.tag; }
def takes(h: holder): int { val held := holder::taken(&mut h); return held.tag; }
def swaps(h: holder): int { h = holder::of(9); return h.tag; }
def hands(h: holder): int { return reads(holder::taken(&mut h)); }
def gives(h: holder): holder { return h; }
def counts(n: int): int { n++; n = n * 2; return n; }
def main(): void {
print($"{reads(holder::of(1))} {takes(holder::of(2))} ");
print($"{swaps(holder::of(3))} {hands(holder::of(4))} ");
val kept := gives(holder::of(5));
print($"{kept.tag} {counts(3)} ");
var mine := holder::of(6);
print($"{takes(holder::taken(&mut mine))} {mine.data == null} ");
print($"{closed}\n");
}
@@ -0,0 +1,4 @@
number 7 | text hi
many 3 [1, 2, 3] | none
held{text = bad} held{none = empty{}}
10 z
@@ -0,0 +1,35 @@
import std::io;
struct empty {}
union held { var none: empty; var number: int; var text: span<u8>; var many: span<int>; }
def read(h: held): string {
if h is number(n) { return $"number {n}"; }
if h is text(t) { return $"text {t}"; }
if h is many(xs) { return $"many {xs.length} {xs}"; } else { return "none"; }
}
def fail_at(n: int): held { return held{ text = "bad" } if n < 0; return empty{}; }
def forward(n: int): held {
return why if fail_at(n) is text(why);
return empty{};
}
def total(xs: span<held>): string {
var sum := 0;
var seen := string::new(nothing {});
var i := 0 as u64;
while i < xs.length {
val each := xs[i];
i++;
if each is number(n) { sum += n; }
if each is text(t) { seen.append(t); }
}
return $"{sum} {seen}";
}
def main(): void {
val words := held{ text = "hi" };
val one := held{ text = "z" };
var ns: int[3] = [1, 2, 3];
println($"{read(held{ number = 7 })} | {read(words)}");
println($"{read(held{ many = span::<int>::over((&ns) as *int, 3) })} | {read(empty{})}");
println($"{forward(-2)} {forward(2)}");
var some: held[4] = [held{ number = 4 }, empty{}, one, held{ number = 6 }];
println(total(span::<held>::over((&some) as *held, 4)));
}
@@ -0,0 +1 @@
same same same
@@ -0,0 +1,16 @@
import std::io;
trait same<T> { def same(&this, other: &T): bool; }
struct pt { var x: i64; }
def pt::same(&this, other: &pt): bool { return this.x == other.x; }
type point = pt;
type spot = point;
def check<T>(a: &T, b: &T): string {
if const T is same<T> { return a.same(b) ? "same" : "differ"; }
return "unknown";
}
def main(): void {
val a: point = pt { 1 };
val b: point = pt { 1 };
val c: spot = pt { 2 };
println($"{check::<pt>(&a, &b)} {check::<point>(&a, &b)} {check::<spot>(&c, &c)}");
}
@@ -0,0 +1,2 @@
true true true true 7 3 true true true
released
@@ -0,0 +1,27 @@
import std::io;
def aligned(block: *mut u8): bool {
return block != null && (block as u64) % 16 == 0;
}
def main(): void {
var small := raw_allocate(10);
var class := raw_allocate(300);
var paged := raw_allocate(5000);
var odd := raw_allocate(1);
print($"{aligned(small)} {aligned(class)} {aligned(paged)} {aligned(odd)} ");
small[9] = 7;
# What a block grows by may hold anything, so it is written before it is read.
var grown := raw_resize(small, 40);
grown[39] = 3;
print($"{grown[9]} {grown[39]} {aligned(grown)} ");
var moved := raw_resize(paged, 9000);
print($"{aligned(moved)} ");
var fresh := raw_resize(null, 1);
println($"{aligned(fresh)}");
raw_release(grown);
raw_release(class);
raw_release(odd);
raw_release(moved);
raw_release(fresh);
raw_release(null);
println("released");
}
@@ -0,0 +1,5 @@
before
--- exit 1
sakura: runtime error: Program aborted.
at inner (tests/programs/an_abort_reports_where_it_was_1.sakura:3:44)
at main (tests/programs/an_abort_reports_where_it_was_1.sakura:4:25)
Loaded 100 of 706 files, more files were not shown because too many files have changed in this diff. Show more