#! @file machine.sakura #! @author John Christman (sorakatadzuma@gmail.com) #! @copyright Malunal Studios, LLC. #! @license MIT #! #! Contains the tests of the machine and of constant evaluation: small #! programs, written over a standard library of their own, are checked, their #! constants evaluated, and lowered, then run in the machine, which keeps what #! they write rather than writing it, and what each wrote and how it stopped #! is compared with what is expected. The collector runs at every allocation, #! so what it loses is found. The corpus of `test/programs` runs whole programs #! over the real standard library, by `tools/corpus.sakura`. import std::io; import std::testing; import sakura::analyzer; import sakura::compiler; module sakura::machine; #! A `core` and standard library small enough to check quickly: views, text, a #! `string` owning its bytes, writing to the output, and exiting. const prelude: strview = """ module core; pub trait attribute {} pub struct intrinsic : attribute {} @intrinsic pub def raw_allocate(size: u64): *mut u8; @intrinsic pub def raw_release(pointer: *mut u8): void; @intrinsic pub def size_of(): u64; pub trait owning { def close(&mut this): void; } pub struct span { pub var _data: *T; pub var _length: u64; } pub val span::length: u64 { get => this._length; } pub type strview = span; pub struct string : owning { var _owner: u64; var _data: *mut u8; var _length: u64; var _capacity: u64; } pub def string::close(&mut this): void { raw_release(this._data); } pub def string::view(&this): strview { return span:: { _data = this._data as *u8, _length = this._length }; } module system; @intrinsic def syscall(n: i64, a: u64, b: u64, c: u64, d: u64, e: u64, f: u64): i64; @intrinsic pub def exit(code: i32): void; @intrinsic pub def abort(): void; pub def print(text: strview): void { syscall(1, 1, text._data as u64, text._length, 0, 0, 0); } pub def println(text: strview): void { print(text); print("\\n"); } @intrinsic pub def start(body: def(*mut u8): void, context: *mut u8): i64; module std::math; @intrinsic pub def square_root(x: f64): f64; @intrinsic pub def ones_in(word: u64): u64; @intrinsic pub def zeros_leading(word: u64): u64; @intrinsic pub def zeros_trailing(word: u64): u64; @intrinsic pub def bytes_reversed(word: u64): u64; module core; pub enum order : u8 { relaxed, acquire, release, acq_rel, seq_cst } pub trait lockfree {} @intrinsic pub def atomic_load(at: *T, how: order): T where T: lockfree; @intrinsic pub def atomic_store(at: *mut T, value: T, how: order): void where T: lockfree; @intrinsic pub def atomic_exchange(at: *mut T, value: T, how: order): T where T: lockfree; @intrinsic pub def atomic_compare_exchange(at: *mut T, expected: T, desired: T, found: *mut T, success: order, failure: order): bool where T: lockfree; @intrinsic pub def atomic_fetch(at: *mut T, operand: T, how: order): T where T: lockfree; @intrinsic pub def atomic_fence(how: order): void; pub struct allow : attribute {} @intrinsic pub struct cfn {} @intrinsic pub def fault(why: strview): void; module std; """; #! Checks a program written over the prelude, evaluates its constants, lowers #! it, and runs it, giving what it wrote, then how it stopped where it did not #! return from `main`: what it exited with, or the fault and its trace. Where #! it does not check, or evaluating notes what goes wrong, the notes. #! @param text The program. #! @returns What it gave. def ran(text: strview): string { return ran_at(text, 0); } #! Checks a program written over the prelude, evaluates its constants, lowers #! and optimizes it at a level, and runs it, giving what `ran` gives. #! @param text The program. #! @param level How much the code is optimized. #! @returns What it gave. def ran_at(text: strview, level: u32): string { return ran_with(text, level, false); } #! Runs a program as `ran` does, with its memory checked, as `run --checks` #! does, giving also the blocks it never released where it ends by returning #! or exiting. #! @param text The program. #! @returns What it gave. def ran_checked(text: strview): string { return ran_with(text, 1, true); } #! Checks a program written over the prelude, evaluates its constants, lowers #! and optimizes it at a level, and runs it, with its memory checked where it #! is asked to be, giving what `ran` gives. #! @param text The program. #! @param level How much the code is optimized. #! @param checks Whether its memory is checked. #! @param other A file of the program beside it, `other.sakura`, or empty #! for none. #! @returns What it gave. def ran_with(text: strview, level: u32, checks: bool, other: strview = ""): string { var held := names::new(); var notes := vector::::new(); var sources := vector::::new(); var syntaxes := vector::::new(); var roots := vector::::new(); sources.reserve(3); syntaxes.reserve(3); sources.append(source::from("test.sakura", text)); if other.length != 0 { sources.append(source::from("other.sakura", other)); } sources.append(source::from("prelude.sakura", prelude)); val count := sources.length; for i in 0..count { syntaxes.append(syntax::new()); } for i in 0..count { var lexing := lexer::new(sources.at(i), &mut held, &mut notes, i as u32); lexing.tokenize_all(syntaxes.at(i)); var parsing := parser::new(syntaxes.at(i), &held, &mut notes, i as u32); roots.append(parsing.parse()); } var checker := checker::new(&mut held, &mut notes); checker.target.os = checker.names.intern(&test_os); for i in 0..count { checker.add(sources.at(i), syntaxes.at(i), roots.at(i)); } checker.check(); var out := string::new(nothing {}); var results := outcomes::new(); if notes.length == 0 { results = evaluate(&mut checker); } if notes.length != 0 { for &each in notes { val at := sources.at(each.file).lines.place_of(each.offset); var message := each.message(sources.at(each.file)); out.append($"{at.line}:{at.column}: {message}\n"); } return out; } var lowered := lowerer::new(&mut checker, lowering { verify = true, level = level, checks = checks }); lowered.evaluated = move(&mut results); lowered.compile(); for &each in lowered.problems { out.append(each.view()); out.append("\n"); } return out if lowered.problems.length != 0; var running := interpreter::new(&mut lowered, interpreting { stack = 1048576, capture = true, checks = checks }); val why := running.run(span::::empty()); for &byte in running.output { out.push(byte); } if why == halt::exited { out.append($"--- exit {running.status}\n"); } if checks && (why == halt::exited || why == halt::none) { running.report_leaks(&mut out); } if why != halt::exited && why != halt::none { var report := string::new(nothing {}); running.report(why, &mut report); out.append(report.view()); } return out; } # The system the programs are checked for, which is the one they run on, so # what they declare for it, as C's functions, is there. when os == linux { val test_os: strview = "linux"; } when os == windows { val test_os: strview = "windows"; } #! Whether what a program gave is what is expected, but for the line breaks #! ending them, printing what it is where it is not. #! @param got What it gave. #! @param want What is expected. #! @returns Whether it is. def gives(got: &string, want: strview): bool { var x := got.length; var y := want.length; while x > 0 && got.at(x - 1) == '\n' { x--; } while y > 0 && want.at(y - 1) == '\n' { y--; } val same := got.substr(0, x) == want.substr(0, y); if !same { println(got); } return same; } @test def numbers_loops_and_calls_run(t: &mut tester): void { # Values move between the words of frames, loops take their variables as # the parameters of their heads, and narrow numbers wrap as their types do. val got := ran(""" import std; import system; def fib(n: u64): u64 { return n < 2 ? n : fib(n - 1) + fib(n - 2); } def main(): void { var total: u64 = 0; for i in 0u..10u { total += i * i; } var small: u8 = 250; small += 10; val third: f32 = 1f / 3f; println($"{fib(20)} {total} {small} {-7 / 2} {-7 % 2} {third} {1.0 / 4.0} {1 << 63}"); } """); t.expects(gives(&got, "6765 285 4 -3 -1 0.33333334 0.25 9223372036854775808")); } @test def structs_closures_and_traits_run(t: &mut tester): void { # A struct is returned through the memory its call gives, a closure refers to # the locals it captures where they are, and a trait's method is called through # the vtable of the reference. val got := ran(""" import std; import system; struct pair { var a: i64; var b: i64; } def swapped(p: pair): pair { return pair { a = p.b, b = p.a }; } trait shape { def area(&this): i64; } struct square : shape { var side: i64; } def square::area(&this): i64 { return this.side * this.side; } struct rect : shape { var w: i64; var h: i64; } def rect::area(&this): i64 { return this.w * this.h; } def area_of(s: &shape): i64 { return s.area(); } def main(): void { val p := swapped(pair { a = 1, b = 2 }); var n: i64 = 10; var m: i64 = 20; val f := def(): i64 { n += 1; return n; }; val g := def(): i64 { m += 1; return m; }; val s := square { side = 3 }; val r := rect { w = 2, h = 5 }; println($"{p} {f()} {g()} {f()} {area_of(&s)} {area_of(&r)}"); } """); t.expects(gives(&got, "pair{a = 2, b = 1} 11 21 12 9 10")); } @test def a_default_reads_the_locals_of_its_call_in_another_file(t: &mut tester): void { # The files begin alike, so `f`'s `x` and `shown`'s `x` are nodes of the same # index, each of its own file. The default making `got` names `shown`'s, and # `values_of` evaluates what the call wrote for it, which names `f`'s. t.expects(gives(&ran_with(""" import system; def f(x: i64): void { shown(x * 3 == 9); } def main(): void { f(3); } """, 0, false, """ import system; def shown(x: bool, got: string = values_of(x)): void { println(got.view()); } module core; @intrinsic pub def values_of(value: T): string; """), "x * 3 = 9")); } @test def faults_report_where_each_function_was(t: &mut tester): void { # A fault stops the program and names each function running, where it was, # as the C machine does; an exit stops it with its status. val got := ran(""" import std; import system; def divide(a: i64, b: i64): i64 { return a / b; } def main(): void { println("before"); println($"{divide(7, 0)}"); } """); t.expects(gives(&got, """ before sakura: runtime error: Division by zero. at divide (test.sakura:3:44) at main (test.sakura:6:20) """)); val exited := ran(""" import std; import system; def main(): void { println("going"); exit(3); println("gone"); } """); t.expects(gives(&exited, "going\n--- exit 3")); # `fault` stops it as a fault does, with the text it was given, and needs no # import, being `core`'s. val faulted := ran(""" def check(n: i64): i64 { if n > 3 { fault("Past three."); } return n; } def main(): void { _ = check(5); } """); t.expects(gives(&faulted, """ sakura: runtime error: Past three. at check (test.sakura:2:19) at main (test.sakura:5:29) """)); } @test def contracts_stop_a_run_and_a_constant_they_fail(t: &mut tester): void { # A contract that fails is a fault, saying which failed and what its operands # held, made only there. val failed := ran(""" def divide(a: i64, b: i64): i64 { expects(b != 0); return a / b; } def main(): void { _ = divide(7, 0); } """); t.expects(gives(&failed, """ sakura: runtime error: A pre-condition failed: b != 0, with b = 0. at divide (test.sakura:2:3) at main (test.sakura:5:30) """)); # One that holds runs while compiling, and one that fails stops the constant # it is evaluated for, saying so there. val held := ran(""" import system; def half(n: i64): i64 { asserts(n % 2 == 0); return n / 2; } const four: i64 = half(8); def main(): void { exit(four as i32); } """); t.expects(gives(&held, "--- exit 4")); val stopped := ran(""" def half(n: i64): i64 { asserts(n % 2 == 0); return n / 2; } const odd: i64 = half(7); def main(): void { _ = odd; } """); t.expects(gives(&stopped, """ 5:7: Evaluating `odd` stopped: An assertion failed: n % 2 == 0, with n % 2 = 1. at half (test.sakura:2:3) at odd (test.sakura:5:22) """)); } @test def checked_runs_stop_where_memory_is_not_held(t: &mut tester): void { # A block read after its release, a block released twice, and a local read # through a reference once its frame is gone each stop a checked run, where # a run unchecked reads what is there. val released := ran_checked(""" import std; import system; def main(): void { val block := raw_allocate(16) as *mut i64; block[0] = 3; raw_release(block as *mut u8); println("released"); block[1] = 4; } """); t.expects(gives(&released, """ released sakura: runtime error: Pointer reaches memory the program does not hold, as past the end of what it points into, or memory released. at main (test.sakura:8:8) """)); val twice := ran_checked(""" import std; def main(): void { val block := raw_allocate(16); raw_release(block); raw_release(block); } """); t.expects(gives(&twice, """ sakura: runtime error: Released memory that was not allocated, or was already released. at main (test.sakura:5:14) """)); val dangling := ran_checked(""" import std; struct point { var x: i64; } @allow def made(): &mut point { var p := point { x = 7 }; return &mut p; } def main(): void { val p := &mut made(); p.x = 8; } """); t.expects(gives(&dangling, """ sakura: runtime error: Pointer reaches memory the program does not hold, as past the end of what it points into, or memory released. at main (test.sakura:6:5) """)); } @test def checked_runs_report_the_blocks_nothing_reaches(t: &mut tester): void { # What a global reaches, directly or through a block, and what the frames # hold as the program exits, are kept; the rest is reported by where it was # allocated, those of each place together, in order. val got := ran_checked(""" import std; import system; struct node { var next: *mut node; } var kept: *mut node; def lose(): void { _ = raw_allocate(24); } def finish(held: *mut u8): void { held[0] = 1; exit(2); } def main(): void { kept = raw_allocate(8) as *mut node; kept[0].next = raw_allocate(8) as *mut node; lose(); lose(); val mine := raw_allocate(5); finish(mine); } """); t.expects(gives(&got, """ --- exit 2 sakura: 2 blocks the program allocated, 48 bytes, were never released, and nothing it keeps reaches them: 2 blocks, 48 bytes, allocated at lose (test.sakura:5:36) """)); } @test def checked_runs_keep_the_frames_of_each_thread_as_the_program_exits(t: &mut tester): void { # A thread still running as the program exits keeps what its frames hold, as # `main` does, so the block it writes is not reported. Its frames are read # whole for it, as `main`'s are, even the words nothing wrote. val got := ran_checked(""" import std; import system; var started: u64; def spin(held: *mut u8): void { held[0] = 1; atomic_store::((&mut started) as *mut u64, 1, order::release); while true { held[0] = held[0] + 1; } } def work(context: *mut u8): void { spin(raw_allocate(8)); } def main(): void { _ = system::start(work, null); while atomic_load::((&started) as *u64, order::acquire) == 0 {} exit(2); } """); t.expects(gives(&got, """ --- exit 2 """)); } @test def a_fault_in_code_inlined_names_the_function_inlined(t: &mut tester): void { # `divide` is inlined into `main`, and a fault within it still names it, where # it was, then `main`, where it called it, as without inlining. val got := ran_at(""" import std; import system; def divide(a: i64, b: i64): i64 { return a / b; } def main(): void { println("before"); println($"{divide(7, 0)}"); } """, 2); t.expects(gives(&got, """ before sakura: runtime error: Division by zero. at divide (test.sakura:3:44) at main (test.sakura:6:20) """)); } @test def atomics_work_while_compiling_as_they_do_running(t: &mut tester): void { # Compiling runs one thread, where an atomic is what it reads and writes; the # machine runs it as the program does, and each gives what it held. val program: strview = """ import std; import system; def count(): u64 { var held: u64 = 5; val at := (&mut held) as *mut u64; val was := atomic_fetch::(at, 3, order::seq_cst); atomic_store::(at, atomic_load::(at, order::acquire) * 2, order::release); var found: u64 = 0; val wrote := atomic_compare_exchange::(at, 16, 20, (&mut found) as *mut u64, order::seq_cst, order::seq_cst); val refused := atomic_compare_exchange::(at, 16, 30, (&mut found) as *mut u64, order::seq_cst, order::relaxed); val swapped := atomic_exchange::(at, 1, order::seq_cst); atomic_fence(order::seq_cst); var small: i8 = -5; val least := atomic_fetch::((&mut small) as *mut i8, -7, order::relaxed); var top: u64 = 1; val most := atomic_fetch::((&mut top) as *mut u64, 0x8000000000000000u, order::relaxed); val right := wrote && !refused && least == -5 && small == -7 && most == 1 && top == 0x8000000000000000u; return was * 1000000 + found * 10000 + swapped * 100 + held + (right ? 50 : 0); } const counted: u64 = count(); def main(): void { println($"{counted} {count()}"); } """; t.expects(ran(program).view() == "5202051 5202051\n"); t.expects(ran_at(program, 2).view() == "5202051 5202051\n"); } @test def math_operations_agree_to_the_bit(t: &mut tester): void { # The operations of `std::math` the machine gives are the same bits run as # written, folded by the optimizer where their operands are known, and in a # constant: a correctly rounded square root, and counts of a word's bits, 64 # of zero, and its bytes reversed. val program: strview = """ import std; import system; import std::math; const root: f64 = square_root(2.0); const ones: u64 = ones_in(0xF0F0u); def bits(x: f64): u64 { var held := x; return ((&mut held) as *mut u64)[0]; } def main(): void { val zero: f64 = 0; val reals: f64[9] = [2.0, 0.0, -0.0, -1.0, 1e-310, 1e300, 0.25, 3.0, 1.0 / zero]; for i in 0..9u { println($"{bits(square_root(reals[i]))}"); } val words: u64[5] = [0u, 1u, 0x8000000000000000u, 0xFFFFFFFFFFFFFFFFu, 0x0102030405060708u]; for i in 0..5u { val w: u64 = words[i]; println($"{ones_in(w)} {zeros_leading(w)} {zeros_trailing(w)} {bytes_reversed(w)}"); } println($"{bits(root)} {ones} {bits(square_root(1e-310))} {zeros_leading(1u)} {bytes_reversed(0xFFu)}"); } """; val want: strview = """ 4609047870845172685 0 9223372036854775808 18444492273895866368 2288155682980613038 6850974717710472879 4602678819172646912 4610479282544200874 9218868437227405312 0 64 64 0 1 63 0 72057594037927936 1 0 63 128 64 0 0 18446744073709551615 13 7 3 578437695752307201 4609047870845172685 8 2288155682980613038 63 18374686479671623680 """; val plain := ran(program); t.expects(gives(&plain, want)); val optimized := ran_at(program, 2); t.expects(gives(&optimized, want)); } @test def constants_are_evaluated_while_compiling(t: &mut tester): void { # A constant the checker does not work out is evaluated in the machine, and # held as data with the memory it points into; one reading another waits for # it; a local constant is evaluated too, and so is a condition of `if const`. val got := ran(""" import std; import system; struct entry { val name: strview; val value: i64; } def made(n: i64): span { val at := raw_allocate(3 * 8) as *mut i64; for i in 0..3 { at[i] = n * (i as i64 + 1); } return span:: { _data = at as *i64, _length = 3 }; } const table: span = made(base); const base: i64 = twice(21); const first: entry = entry { name = "first", value = table._data[2] }; def twice(x: i64): i64 { return x * 2; } def wide(): bool { if const size_of::() > 4 { return true; } return false; } def main(): void { const local: entry = entry { name = "local", value = twice(5) }; println($"{table._data[0]} {table._data[1]} {first.name} {first.value} {local.name} {local.value} {wide::()} {wide::()}"); } """); t.expects(gives(&got, "42 84 first 126 local 10 true false")); } @test def evaluating_notes_what_only_a_running_program_does(t: &mut tester): void { # Evaluating stops where it reaches what only the program running has, as a # system call, or an address taken as a number, as `print` gives the system # its text's, and notes why at the constant, with the functions running. val got := ran(""" import std; import system; def loud(): i64 { println("now"); return 1; } const noisy: i64 = loud(); def main(): void { println($"{noisy}"); } """); t.expects(gives(&got, """ 4:7: Evaluating `noisy` stopped: Function does not run while compiling. at print (prelude.sakura:18:63) at println (prelude.sakura:19:45) at loud (test.sakura:3:26) at noisy (test.sakura:4:24) """)); } @test def values_share_the_words_of_frames(t: &mut tester): void { # Values whose lives do not overlap share a word of the frame, so a long # function with many short-lived values keeps a small frame. var held := names::new(); var notes := vector::::new(); var sources := vector::::new(); var syntaxes := vector::::new(); sources.reserve(1); syntaxes.reserve(1); sources.append(source::from("test.sakura", """ def many(x: u64): u64 { var a := x; a = a * 3 + 1; a = a * 3 + 1; a = a * 3 + 1; a = a * 3 + 1; a = a * 3 + 1; a = a * 3 + 1; a = a * 3 + 1; a = a * 3 + 1; return a; } def main(): void { many(1); } """)); syntaxes.append(syntax::new()); var lexing := lexer::new(sources.at(0), &mut held, &mut notes, 0); lexing.tokenize_all(syntaxes.at(0)); var parsing := parser::new(syntaxes.at(0), &held, &mut notes, 0); val root := parsing.parse(); var checker := checker::new(&mut held, &mut notes); checker.add(sources.at(0), syntaxes.at(0), root); checker.check(); var lowered := lowerer::new(&mut checker, lowering { verify = true }); lowered.compile(); lowered.assemble_all(); for &each in lowered.program.functions { continue if each.name.view() != "many"; val values := each.body.origins.length; t.expects(values > 30 && each.compiled.frame <= 8 * 8); } } #! Checks a program written over the prelude, evaluates its constants, and #! lowers every function of it, as a host embedding the machine does, then #! gives a machine running it, not yet begun, to a function, which calls its #! functions itself. Where it does not check, or does not lower, gives what was #! noted, and otherwise nothing. #! @param text The program. #! @param options How it runs. #! @param body What the host does with the machine. #! @returns What was noted. def hosted(text: strview, options: interpreting, body: def(&mut interpreter): void): string { var held := names::new(); var notes := vector::::new(); var sources := vector::::new(); var syntaxes := vector::::new(); var roots := vector::::new(); sources.reserve(2); syntaxes.reserve(2); sources.append(source::from("test.sakura", text)); sources.append(source::from("prelude.sakura", prelude)); for i in 0u..2u { syntaxes.append(syntax::new()); } for i in 0u..2u { var lexing := lexer::new(sources.at(i), &mut held, &mut notes, i as u32); lexing.tokenize_all(syntaxes.at(i)); var parsing := parser::new(syntaxes.at(i), &held, &mut notes, i as u32); roots.append(parsing.parse()); } var checker := checker::new(&mut held, &mut notes); checker.target.os = checker.names.intern(&test_os); for i in 0u..2u { checker.add(sources.at(i), syntaxes.at(i), roots.at(i)); } checker.check(); var out := string::new(nothing {}); var results := outcomes::new(); if notes.length == 0 { results = evaluate(&mut checker); } for &each in notes { val at := sources.at(each.file).lines.place_of(each.offset); var message := each.message(sources.at(each.file)); out.append($"{at.line}:{at.column}: {message}\n"); } return out if notes.length != 0; var lowered := lowerer::new(&mut checker, lowering { verify = true, everything = true }); lowered.evaluated = move(&mut results); lowered.compile(); for &each in lowered.problems { out.append(each.view()); out.append("\n"); } return out if lowered.problems.length != 0; var running := interpreter::new(&mut lowered, options); body(&mut running); return out; } #! The function of a program of a name, as a trace writes it. #! @param running The machine running the program. #! @param name The name. #! @returns The function, or `no_function`. def function_named(running: &interpreter, name: strview): u32 { for i in 0..running.c.program.functions.length { return i as u32 if running.c.program.functions[i].name.view() == name; } return no_function; } #! The bits of an `f64`, as a word passes it. def bits_of(x: f64): u64 { var held := x; return ((&mut held) as *mut u64)[0]; } #! The `f64` of a word's bits. def real_of(word: u64): f64 { var held := word; return ((&mut held) as *mut f64)[0]; } @test def hosts_call_the_functions_of_a_program_they_began(t: &mut tester): void { # A host begins a program, giving its globals their values, then calls its # functions by their words: integers, floats as `f64`, a struct in memory # both ways, and a function value the program gave, by its two words. val noted := hosted(""" import std; import system; var counter: i64 = 10; pub struct triple { pub var a: i64; pub var b: i64; pub var c: i64; } def add(x: i64, y: i64): i64 { counter += 1; return x + y + counter; } def scaled(v: f32, by: f64): f64 { return v as f64 * by; } def made(x: i64): triple { return triple { a = x, b = x + 1, c = x + 2 }; } def sum(p: triple): i64 { return p.a + p.b + p.c; } def plus_four(x: i64): i64 { return x + 4; } def adder(): def(i64): i64 { return plus_four; } def loud(): void { println("hello from the program"); } """, interpreting { stack = 1048576, capture = true }, def(running: &mut interpreter): void { t.expects(running.begin() == halt::none); var two: u64[2] = [2, 3]; t.expects(running.call(function_named(running, "add"), two[:]) == halt::none && running.result(0) == 16); t.expects(running.call(function_named(running, "add"), two[:]) == halt::none && running.result(0) == 17); var reals: u64[2] = [bits_of(1.5), bits_of(2.0)]; t.expects(running.call(function_named(running, "scaled"), reals[:]) == halt::none && real_of(running.result(0)) == 3.0); var made: i64[3]; var five: u64[1] = [5]; t.expects(running.call(function_named(running, "made"), five[:], (&mut made) as *mut u8 as u64) == halt::none); t.expects(made[0] == 5 && made[1] == 6 && made[2] == 7); var address: u64[1] = [(&mut made) as *mut u8 as u64]; t.expects(running.call(function_named(running, "sum"), address[:]) == halt::none && running.result(0) == 18); t.expects(running.call(function_named(running, "adder"), span::::empty()) == halt::none); val function := running.result(0); val environment := running.result(1); var ten: u64[1] = [10]; t.expects(running.call_value(function, environment, ten[:]) == halt::none && running.result(0) == 14); t.expects(running.call(function_named(running, "loud"), span::::empty()) == halt::none); val said := running.take_output(); t.expects(said.view() == "hello from the program\n"); # Too few words is no call. t.expects(running.call(function_named(running, "add"), five[:]) == halt::unsupported); }); t.expects(gives(¬ed, "")); } @test def a_call_stops_once_it_takes_more_steps_than_allowed(t: &mut tester): void { # Each call the host makes may take as many steps as it allows, so one that # never ends stops, and the next is allowed as many again. val noted := hosted(""" import std; import system; def spin(): void { var x: u64 = 0; while true { x += 1; } } def count(n: u64): u64 { var x: u64 = 0; for i in 0..n { x += i; } return x; } """, interpreting { stack = 1048576, steps = 100000 }, def(running: &mut interpreter): void { t.expects(running.begin() == halt::none); val stopped := running.call(function_named(running, "spin"), span::::empty()); t.expects(stopped == halt::step_limit); var report := string::new(nothing {}); running.report(stopped, &mut report); t.expects(report.view().find("at spin (test.sakura:") is some(_)); var many: u64[1] = [1000]; t.expects(running.call(function_named(running, "count"), many[:]) == halt::none && running.result(0) == 499500); }); t.expects(gives(¬ed, "")); } when os == windows { # The machine the functions the host provides call back into, and what they # call there. var hosting: *mut interpreter = null; var tripled: u32 = 0; var broken: u32 = 0; # Functions of the host's, which the programs of the test call. def host_twice(x: i64): i64 { return x * 2; } def host_again(x: i64): i64 { var args: u64[1] = [x as u64]; return -1 if through(hosting).call(tripled, args[:]) != halt::none; return through(hosting).result(0) as i64; } def host_broken(x: i64): i64 { var args: u64[1] = [x as u64]; val why := through(hosting).call(broken, args[:]); return why == halt::out_of_bounds ? 100 : 0; } @test def programs_call_what_the_host_provides(t: &mut tester): void { # A host gives a program functions of its own, which it declares as C's # are, and those call back into the program; a fault there stops the # program's call under way once the host returns to it, giving its trace. val noted := hosted(""" import std; import system; import host; def triple(x: i64): i64 { return x * 3; } def through_host(x: i64): i64 { return twice(x) + again(x); } def past_end(i: i64): i64 { var a: i64[2] = [1, 2]; return a[i as u64]; } def breaks_through_host(x: i64): i64 { return fails(x) + 1; } extern module host when os == windows; pub def twice(x: i64): i64; pub def again(x: i64): i64; pub def fails(x: i64): i64; """, interpreting { stack = 1048576 }, def(running: &mut interpreter): void { val twice: cfn = host_twice; val again: cfn = host_again; val fails: cfn = host_broken; running.provide("twice", twice as u64); running.provide("again", again as u64); running.provide("fails", fails as u64); hosting = running as *mut interpreter; tripled = function_named(running, "triple"); broken = function_named(running, "past_end"); t.expects(running.begin() == halt::none); var seven: u64[1] = [7]; t.expects(running.call(function_named(running, "through_host"), seven[:]) == halt::none && running.result(0) == 35); val why := running.call(function_named(running, "breaks_through_host"), seven[:]); t.expects(why == halt::out_of_bounds); var report := string::new(nothing {}); running.report(why, &mut report); t.expects(report.view().find("at past_end (test.sakura:") is some(_) && report.view().find("at breaks_through_host (test.sakura:") is some(_)); # The program goes on being called after. t.expects(running.call(function_named(running, "through_host"), seven[:]) == halt::none && running.result(0) == 35); hosting = null; }); t.expects(gives(¬ed, "")); } @test def c_calls_pass_values_as_c_does(t: &mut tester): void { # On Windows a program reaches the system through C, so the machine calls C # with Microsoft's ABI: integers and floats positional in registers and on # the stack, an aggregate as large as an integer by value and a larger one # by the address of a copy, a larger result through memory, and a function # of the program C calls back. Every kind is passed to C's own library here. val got := ran(""" import std; import system; import crt; extern import "ucrtbase.dll" when os == windows; def compare_ints(a: *u8, b: *u8): i32 { return (a as *i32)[0] - (b as *i32)[0]; } def main(): void { val root := sqrt(16.0); val cube := cbrtf(27f); val q := div(17, 5); val w := lldiv(100, 7); val c := conj(complex { re = 1.5, im = 2.5 }); var numbers: i32[5] = [5, 3, 1, 4, 2]; qsort((&mut numbers) as *mut u8, 5, 4, compare_ints); println($"{root} {cube} {q.quot} {q.rem} {w.quot} {w.rem} {c.re} {c.im}"); println($"{numbers[0]} {numbers[1]} {numbers[2]} {numbers[3]} {numbers[4]}"); } extern module crt when os == windows; pub struct quotient { pub var quot: i32; pub var rem: i32; } pub struct wide_quotient { pub var quot: i64; pub var rem: i64; } pub struct complex { pub var re: f64; pub var im: f64; } pub def sqrt(x: f64): f64; pub def cbrtf(x: f32): f32; pub def div(a: i32, b: i32): quotient; pub def lldiv(a: i64, b: i64): wide_quotient; pub def conj(z: complex): complex; pub def qsort(base: *mut u8, count: u64, size: u64, compare: cfn): void; """); t.expects(gives(&got, "4 3 3 2 14 2 1.5 -2.5\n1 2 3 4 5")); } }