Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-11-19 04:54:17 -06:00
commit f086abcea6
789 files changed
+149185

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.span;
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")));
}
+305
View File
@@ -0,0 +1,305 @@
#! @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").span ==
"(assign:= name:a (assign:+= name:b name:c))");
t.expects(expression("c ? d : e ? f : g").span ==
"(ternary name:c name:d (ternary name:e name:f name:g))");
t.expects(expression("p else q else r").span ==
"(fallback name:p _ (fallback name:q _ name:r))");
t.expects(expression("x = p else q").span ==
"(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").span ==
"(ternary name:c (fallback name:p _ name:q) name:r)");
t.expects(expression("c ? p else q ? s : t : r").span ==
"(ternary name:c (fallback name:p _ (ternary name:q name:s name:t)) name:r)");
t.expects(expression("c ? p else (e) { return; } : r").span ==
"(ternary name:c (fallback name:p name:e (block [return_stmt])) name:r)");
t.expects(expression("c ? p : q else r").span ==
"(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").span ==
"(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").span ==
"(binary:+ (cast (unary:- name:m) type_name:u8) name:n)");
t.expects(expression("true != null").span ==
"(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)").span ==
"(is_test (unary:! name:k) type_name:value (reference:& name:v {mutable}) {negated})");
t.expects(expression("r is error(why)").span ==
"(is_test name:r type_name:error name:why)");
t.expects(expression("x is (d)").span ==
"(is_test name:x name:d _ {computed})");
t.expects(expression("T is copyable && T is not moveable").span ==
"(binary:&& (is_test name:T type_name:copyable _) (is_test name:T type_name:moveable _ {negated}))");
t.expects(expression("type_of(d) is numeric").span ==
"(is_test (type_of:type_of name:d) type_name:numeric _)");
t.expects(expression("box::<T> is Shown").span ==
"(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]++").span ==
"(postfix:++ (index (call (member:f name:w []) [number:1]) number:2))");
t.expects(expression("xs[a:] + xs[:n] + xs[a:n]").span ==
"(binary:+ (binary:+ (slice name:xs name:a _) (slice name:xs _ name:n)) (slice name:xs name:a name:n))");
t.expects(expression("x.(d)").span ==
"(member_of name:x name:d)");
t.expects(expression("value_of(d)::<i64>").span ==
"(type_args (call name:value_of [name:d]) [type_name:i64])");
t.expects(expression("max::<u8>(a, ...xs)").span ==
"(call (path:max [(segment:max [type_name:u8])]) [name:a (unary name:xs)])");
t.expects(expression("std::io::print").span ==
"(path:std [segment:std segment:io segment:print])");
t.expects(expression("*p = &mut x").span ==
"(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").span ==
"(fallback (call name:f [number:1]) _ number:0)");
t.expects(expression("f(1) else (e) { return; }").span ==
"(fallback (call name:f [number:1]) name:e (block [return_stmt]))");
t.expects(expression("f(1) else (e) + 1").span ==
"(fallback (call name:f [number:1]) _ (binary:+ name:e number:1))");
t.expects(expression("f(1) else { return; }").span ==
"(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 }").span ==
"(construct type_name:point [(field_init:x number:1 {named}) (field_init:2 number:2)])");
t.expects(expression("[1, 2, 3,]").span ==
"(array [number:1 number:2 number:3])");
t.expects(expression("def(a, b: i64) => a + b").span ==
"(lambda [param:a (param:b type_name:i64 _ [])] _ (binary:+ name:a name:b))");
t.expects(expression("def(): i64 { return 1; }").span ==
"(lambda [] type_name:i64 (block [(return_stmt number:1)]))");
t.expects(statements("val v := match k { 1, 2 => a, else => b };").span ==
"(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\"").span ==
"(istring:$\"a{ [string:$\"a{ name:b string:}c{ (binary:+ name:d number:1) string:}e\"])");
t.expects(expression("$\"plain\"").span ==
"(istring:$\"plain\" [string:$\"plain\"])");
}
@test def conditions_and_jumps(t: &mut tester): void {
t.expects(statements("if a {} else if b {} else {}").span ==
"(if_stmt name:a block (if_stmt name:b block block))");
t.expects(statements("if const T is integer {}").span ==
"(if_const (is_test name:T type_name:integer _) block _)");
t.expects(statements("if x == y { }").span ==
"(if_stmt (binary:== name:x name:y) block _)");
t.expects(statements("return x if a;").span ==
"(if_stmt name:a (block [(return_stmt name:x)]) _)");
t.expects(statements("break if const n > 1;").span ==
"(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 {}").span ==
"(for_stmt name:i name:x name:xs _ {mutable,reference} block)");
t.expects(statements("for const x in args {}").span ==
"(for_stmt _ name:x name:args _ {constant} block)");
t.expects(statements("for i in 0..n {}").span ==
"(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 {}").span ==
"(for_stmt _ name:i number:0 name:n {inclusive} block)");
t.expects(statements("for i in (0..n).rev() {}").span ==
"(for_stmt _ name:i (call (member:rev (range:.. number:0 name:n) []) []) _ block)");
t.expects(statements("while a { continue; }").span ==
"(while_stmt name:a (block [continue_stmt]))");
t.expects(statements("match k { 1 => a(); else => { b(); } }").span ==
"(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").span == "(range:.. (binary:+ name:a number:1) (binary:* name:b number:2))");
t.expects(expression("lo..=hi").span == "(range:..= name:lo name:hi)");
t.expects(expression("f(0..n, 1..=2)").span == "(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;").span ==
"(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; }").span ==
"(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 {}").span ==
"(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));").span ==
"(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;").span ==
"(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;").span ==
"(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;").span ==
"(document [(import_decl (path:std [segment:std segment:io]))])");
t.expects(tree("module a::b when os == linux && backend == vm;").span ==
"(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; }").span ==
"(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;").span ==
"(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;").span ==
"(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; }").span ==
"(document [(function:zero [] _ [] [] type_name:i64 (block [(return_stmt number:0)]) {constant})])");
}
@test def parameters_take_attributes_before_their_names(t: &mut tester): void {
t.expects(tree("def keep<F>(@kept f: F, @tag{ n = 1 } @kept g: F = 0): F;").span ==
"(document [(function:keep [] _ [type_param:F] [(param:f type_name:F _ [(attribute type_name:kept [])]) (param:g type_name:F number:0 [(attribute type_name:tag [(field_init:n number:1 {named})]) (attribute type_name:kept [])])] type_name:F _)])");
# An anonymous function's parameters are no declaration's, so they take none.
val stray := parse("val f := def(@kept x: i64) => x;");
t.expects(noted(&stray, 1, 20, ec::token));
}
@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 }; }").span ==
"(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; }").span ==
"(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; }").span ==
"(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; }").span ==
"(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; }").span ==
"(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 {} }").span ==
"(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; }").span ==
"(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));
# `get mut` is the `get` of a value that can be written, whose `this` is
# `&mut`; one of each is declared, and a trait asks for neither.
t.expects(tree("val r::f: i64 { get => this.p; get mut => this.p; }").span ==
"(document [(property:f [] (type_name:r [segment:r]) type_name:i64 [(accessor:get [(param:this _ _ {implied} [])] (block [(return_stmt (member:p name:this []))])) (accessor:get [(param:this _ _ {mutable,implied} [])] (block [(return_stmt (member:p name:this []))]))])])");
val twice := parse("val r::f: i64 { get mut => this.p; get mut => this.p; }");
t.expects(noted(&twice, 1, 36, ec::token));
val asked := parse("trait t { val f: i64 { get mut; } }");
t.expects(noted(&asked, 1, 24, ec::token));
t.expects(tree("enum color : u8 { red, @old green = 2, blue, }").span ==
"(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;").span ==
"(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();").span ==
"(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;").span ==
"(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;").span ==
"(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;").span ==
"(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...; }").span ==
"(document [(trait_decl:t [] _ [(type_pattern [type_param:A (type_param:Ts [] {packed})] type_param:R)] [] [(assoc_type:p [] [] {packed} _)])])");
# A field holding a pack is written as a variadic parameter is, and one
# spreading a struct's fields with `...` first.
t.expects(tree("struct s<Ts...> { var items: Ts...; var pos: ...point; }").span ==
"(document [(struct_decl:s [] _ [(type_param:Ts [] {packed})] [] [(field:items [] _ type_name:Ts _ {mutable,variadic}) (field:pos [] _ (spread type_name:point []) _ {mutable})])])");
}
# 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]; }").span ==
"(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; }").span ==
"(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").span ==
"(binary:>= (binary:>> name:a name:b) name:c)");
t.expects(expression("a >>= b").span ==
"(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").span ==
"(binary:> (cast name:x (type_name:box [(segment:box [type_name:u8])])) name:y)");
t.expects(expression("x as box<box<u8>>>= y").span ==
"(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;").span ==
"(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]; }").span ==
"(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;").span ==
"(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;").span ==
"(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)>()").span ==
"(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).span == "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").span == "pub var x: int\n\nAcross.");
t.expects(hover_of(text, "across(p").span == "pub def across(p: &point): int\n\nHow far across.\n@param p The point.");
t.expects(hover_of(text, "p: &point").span == "p: &point\n\nThe point.");
t.expects(hover_of(text, "moved(2)").span == "def point::moved(this: &point, by: int): point");
t.expects(hover_of(text, "color: u8").span == "enum color: u8 {\n red = 0,\n green = 4,\n}");
t.expects(hover_of(text, "green;").span == "color::green = 4");
t.expects(hover_of(text, "limit as").span == "const limit: u32");
t.expects(hover_of(text, "p := point").span == "var p: point");
t.expects(hover_of(text, "q := p").span == "val q: point");
t.expects(hover_of(text, "y = this", 0).span == "var y: int");
t.expects(hover_of(text, "i64; #!").span == "type int");
t.expects(hover_of(text, "return p.x").span == "");
}
@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.span);
made.append("|");
var box := c.hover(0, place_in(text, "box<u8>")) else { return made; };
made.append(box.signature.span);
made.append("|");
var item := c.hover(0, place_in(text, "item +")) else { return made; };
made.append(item.signature.span);
return made;
}, text, lib).span == "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.span.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.span);
}
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.span);
if named.refusal.length != 0 {
made.append("!");
}
made.append("|");
}
return made;
}, text, lib).span == "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.span);
made.append("|");
}
return made;
}, text, lib).span == "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).span == "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).span == "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;").span == "value: int");
t.expects(hover_of(text, "this.w;").span == "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).span == "`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).span == "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").span ==
"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).span == "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).span == "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.span);
}
return made;
}, text).span == "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.span != "else";
if made.length != 0 {
made.append(" ");
}
made.append(each.name.span);
if each.insert.length != 0 {
made.append("=");
made.append(each.insert.span);
}
}
return made;
}, ...texts.span);
}
@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).span == "x y norm");
t.expects(completed(text, "x = 1, ", 7).span.starts_with("y=y = p c point color f "));
t.expects(completed(text, "red => {} }", 10).span == "green=green => else=else => ");
val locals := completed(text, "return 0", 7);
t.expects(locals.span.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).span.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.span);
made.append("|");
}
val line := $"{help.parameter}";
made.append(line.span);
return made;
}, text).span == "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").span == "");
t.expects(hovers_after_edits(before, "def a(): i64 { return 1;\ndef e(): i64 { return 5; }\n", before).span == "");
}
@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.span) {
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.span);
t.expects(hovers_after_edits_with(others.span, before, after).span == "");
}
@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).span == "");
}
+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).span ==
"(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).span ==
"(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; }").span ==
"(document [(trait_decl:t [] _ [] [] [(error [(variable:x [] _ type_name:i64 _ {mutable})])])])");
t.expects(tree("struct s { @a }").span ==
"(document [(struct_decl:s [] _ [] [] [(error [(attribute type_name:a [])])])])");
t.expects(statements("@a val x := 1;").span ==
"(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 {}").span ==
"(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.span);
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).span == "(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.span).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.span);
before.append("{ return x + 1; }\n");
after.append(line.span);
after.append(i == count / 2 ? "{ return x * 2; }\n" : "{ return x + 1; }\n");
}
t.expects(reparses_as_whole(before.span, after.span));
}
}
@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.span, after.span));
}
@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);
}
+646
View File
@@ -0,0 +1,646 @@
#! @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. A program is checked with the
#! machine's evaluator, as one compiled is, so what only running gives is known.
import sakura::machine;
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.span);
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).span);
}
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.span);
val inner := printed.span;
# `(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).span != whole.syntax.print(whole.root, &whole.source, &whole.names).span;
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>::blank(), ...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.span != b.span {
val line := $"{at}: {a} | {b}\n";
made.append(line.span);
}
at++;
}
return made;
}, ...files.span);
}
#! 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));
}
_ = check_evaluating(&mut checker, notes.length == 0);
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 a program makes of its own file and a library's,
#! whose declarations are checked where the program reaches them, or whole.
#! @param whole Whether every declaration is checked.
#! @param own The program's own file's text.
#! @param library The library's file's text.
#! @returns How many.
def library_notes(whole: bool, own: strview, library: strview): u64 {
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(2);
syntaxes.reserve(2);
sources.append(source::from("test.sakura", own));
sources.append(source::from("library.sakura", library));
syntaxes.append(syntax::new());
syntaxes.append(syntax::new());
for i in 0..2u {
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);
checker.whole = whole;
checker.add(sources.at(0), syntaxes.at(0), roots.at(0));
checker.add(sources.at(1), syntaxes.at(1), roots.at(1), false);
checker.check();
return notes.length;
}
#! 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, in the first file.
#! @param texts The files' texts.
#! @returns Its type.
def local_type(name: strview, texts: strview...): string {
var made := check_program(name, ...texts);
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 iter<T> { def next(&mut this): maybe<T>; }
pub trait iterable<T> {
type iterator: iter<&T>;
def iter(&this): iterator;
}
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>::iterator : iter<&T> { var at: *T; var left: u64; }
pub def span<T>::iterator::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>::iterator { return span::<T>::iterator { 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> : iter<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.span);
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.span);
}
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).span == "Expected `;` after the declaration. Found `val`.");
t.expects(made.notes.at(1).message(&made.source).span == "Expected an expression. Found `;`.");
val ended := parse("val x := 1");
t.expects(ended.notes.at(0).message(&ended.source).span == "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).span == "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);
}