Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-12-06 13:52:57 -06:00
commit 528ccf1523
782 files changed
+145156

No files matched your search

@@ -0,0 +1 @@
read past its mark
@@ -0,0 +1,2 @@
import std::io;
def main(): void { println("read past its mark"); }
@@ -0,0 +1 @@
1 2 9 4 5 8 6 true 6
@@ -0,0 +1,21 @@
import std::io;
struct holder : owning { var data: *mut u8; var tag: int; }
var closed: int = 0;
def holder::of(tag: int): holder { return holder { data = raw_allocate(8), tag = tag }; }
def holder::close(&mut this): void { if this.data != null { closed++; raw_release(this.data); this.data = null; } }
def holder::taken(src: &mut holder): holder { var made := holder { data = src.data, tag = src.tag }; src.data = null; return made; }
def reads(h: holder): int { return h.tag; }
def takes(h: holder): int { val held := holder::taken(&mut h); return held.tag; }
def swaps(h: holder): int { h = holder::of(9); return h.tag; }
def hands(h: holder): int { return reads(holder::taken(&mut h)); }
def gives(h: holder): holder { return h; }
def counts(n: int): int { n++; n = n * 2; return n; }
def main(): void {
print($"{reads(holder::of(1))} {takes(holder::of(2))} ");
print($"{swaps(holder::of(3))} {hands(holder::of(4))} ");
val kept := gives(holder::of(5));
print($"{kept.tag} {counts(3)} ");
var mine := holder::of(6);
print($"{takes(holder::taken(&mut mine))} {mine.data == null} ");
print($"{closed}\n");
}
@@ -0,0 +1,4 @@
number 7 | text hi
many 3 [1, 2, 3] | none
held{text = bad} held{none = empty{}}
10 z
@@ -0,0 +1,35 @@
import std::io;
struct empty {}
union held { var none: empty; var number: int; var text: span<u8>; var many: span<int>; }
def read(h: held): string {
if h is number(n) { return $"number {n}"; }
if h is text(t) { return $"text {t}"; }
if h is many(xs) { return $"many {xs.length} {xs}"; } else { return "none"; }
}
def fail_at(n: int): held { return held{ text = "bad" } if n < 0; return empty{}; }
def forward(n: int): held {
return why if fail_at(n) is text(why);
return empty{};
}
def total(xs: span<held>): string {
var sum := 0;
var seen := string::new(nothing {});
var i := 0 as u64;
while i < xs.length {
val each := xs[i];
i++;
if each is number(n) { sum += n; }
if each is text(t) { seen.append(t); }
}
return $"{sum} {seen}";
}
def main(): void {
val words := held{ text = "hi" };
val one := held{ text = "z" };
var ns: int[3] = [1, 2, 3];
println($"{read(held{ number = 7 })} | {read(words)}");
println($"{read(held{ many = span::<int>::over((&ns) as *int, 3) })} | {read(empty{})}");
println($"{forward(-2)} {forward(2)}");
var some: held[4] = [held{ number = 4 }, empty{}, one, held{ number = 6 }];
println(total(span::<held>::over((&some) as *held, 4)));
}
@@ -0,0 +1 @@
same same same
@@ -0,0 +1,16 @@
import std::io;
trait same<T> { def same(&this, other: &T): bool; }
struct pt { var x: i64; }
def pt::same(&this, other: &pt): bool { return this.x == other.x; }
type point = pt;
type spot = point;
def check<T>(a: &T, b: &T): string {
if const T is same<T> { return a.same(b) ? "same" : "differ"; }
return "unknown";
}
def main(): void {
val a: point = pt { 1 };
val b: point = pt { 1 };
val c: spot = pt { 2 };
println($"{check::<pt>(&a, &b)} {check::<point>(&a, &b)} {check::<spot>(&c, &c)}");
}
@@ -0,0 +1,2 @@
true true true true 7 3 true true true
released
@@ -0,0 +1,27 @@
import std::io;
def aligned(block: *mut u8): bool {
return block != null && (block as u64) % 16 == 0;
}
def main(): void {
var small := raw_allocate(10);
var class := raw_allocate(300);
var paged := raw_allocate(5000);
var odd := raw_allocate(1);
print($"{aligned(small)} {aligned(class)} {aligned(paged)} {aligned(odd)} ");
small[9] = 7;
# What a block grows by may hold anything, so it is written before it is read.
var grown := raw_resize(small, 40);
grown[39] = 3;
print($"{grown[9]} {grown[39]} {aligned(grown)} ");
var moved := raw_resize(paged, 9000);
print($"{aligned(moved)} ");
var fresh := raw_resize(null, 1);
println($"{aligned(fresh)}");
raw_release(grown);
raw_release(class);
raw_release(odd);
raw_release(moved);
raw_release(fresh);
raw_release(null);
println("released");
}
@@ -0,0 +1,5 @@
before
--- exit 1
sakura: runtime error: Program aborted.
at inner (tests/programs/an_abort_reports_where_it_was_1.sakura:3:44)
at main (tests/programs/an_abort_reports_where_it_was_1.sakura:4:25)
@@ -0,0 +1,4 @@
import std::io;
import system;
def inner(): void { print("before "); abort(); }
def main(): void { inner(); println("after"); }
@@ -0,0 +1,2 @@
[1, 9] [1, 2] 12 10 9 true
[[1, 0], [2, 9]]
@@ -0,0 +1,19 @@
import std::io;
struct point { var x: int; }
def point::move(&mut this, by: int): void { this.x += by; }
def grow(xs: &mut int[2]): void { xs[1] = 9; }
def bump(p: &mut point): void { p.x++; }
def total(xs: &int[2]): int { var t := 0; for x in xs { t += x; } return t; }
def same<T>(x: &T): T { return x; }
def main(): void {
var xs := [1, 2];
val alias := xs;
grow(&mut xs);
var p := point{ 1 };
bump(p);
p.move(same(10));
println($"{xs} {alias} {p.x} {total(&xs)} {total(&[4, 5])} {same(true)}");
var nested := [[1, 0], [2, 0]];
grow(&mut nested[1]);
println($"{nested}");
}
@@ -0,0 +1,2 @@
70 9 4 0 303
2 0 2 30 40 0
@@ -0,0 +1,26 @@
import std::io;
# Within a generic's own body, a type parameter bounded by `array` is a
# `T::element[T::length]`, indexed, walked, and converted as one, with a zero
# value where it is also `zeroable`; and one `T is vector` holds of is a
# `vector<T::args...[0]>`, with `vector`'s members.
def first<T>(x: &T): T::element where T: array { return x[0]; }
def copied<T>(x: T): T::element[T::length] where T: array { return x; }
def blank<T>(): T where T: array, zeroable { var made: T::element[T::length]; var e: T::element; made[0] = e; return made; }
def count<T>(x: &T): u64 where T: array { var n: u64 = 0; for e in x { n++; } return n * 100 + x.length; }
def set_first<T>(x: &mut T, v: T::element): void where T: array { x[0] = v; }
def length_of<T>(x: &T): u64 { if const T is vector { return x.length; } return 0; }
def grow<T>(x: &mut T): void { if const T is vector { val e := x[0]; x.append(e); } }
def arm_length<T>(x: &T): u64 { return match const T { vector => x.length, array => x.length * 10, else => 0u }; }
def main(): void {
var arr: i32[3] = [7, 8, 9];
set_first(&mut arr, 70);
val made: u8[4] = blank::<u8[4]>();
println($"{first(&arr)} {copied(arr)[2]} {made.length} {made[0]} {count(&arr)}");
var v := vector::<u8>::new();
v.append(3);
grow(&mut v);
val plain: i64 = 5;
println($"{length_of(&v)} {length_of(&arr)} {arm_length(&v)} {arm_length(&arr)} {arm_length(&made)} {arm_length(&plain)}");
}
@@ -0,0 +1,3 @@
else -2 -0.25 true 0
2 0 3 b
11 6 0
@@ -0,0 +1,16 @@
import std::io;
enum color { red, green, blue }
const words: span<span<u8>> = ["if", "else"];
const numbers: span<i32> = [1, -2, 3];
const reals: span<f32> = [1.5, -0.25, 2];
const colors: span<color> = [color::blue, color::red];
const nested: span<span<u8>> = [[1, 2], [], [3]];
const none: span<i64> = [];
def sum(xs: span<i64>): i64 { var t: i64 = 0; for x in xs { t += x; } return t; }
def main(): void {
val local: span<span<u8>> = ["a", "b"];
val n: i64 = 5;
println($"{words[1]} {numbers[1]} {reals[1]} {colors[0] == color::blue} {none.length}");
println($"{nested[0][1]} {nested[1].length} {nested[2][0]} {local[1]}");
println($"{sum([n, n + 1])} {sum([1, 2, 3])} {sum([])}");
}
@@ -0,0 +1,4 @@
2
close 2
close 1
done
@@ -0,0 +1,8 @@
import std::io;
struct noisy : owning { var n: i64; }
def noisy::close(&mut this): void { println($"close {this.n}"); }
def count(xs: span<noisy>): u64 { return xs.length; }
def main(): void {
println($"{count([noisy{ n = 1 }, noisy{ n = 2 }])}");
println("done");
}
+21
View File
@@ -0,0 +1,21 @@
u8: 100 44 200 200 236 36 36 200 100
wrote over 100, found 200
i8: -100 -10 90 90 -34 -124 -124 90 -100
wrote over -100, found 90
u16: 32767 32751 65520 65520 65535 15 15 65520 32767
wrote over 32767, found 65520
i16: -30000 0 30000 30000 -16 -30016 -30016 30000 -30000
wrote over -30000, found 30000
u32: 5 3 4294967294 4294967294 4294967295 1 1 4294967294 5
wrote over 5, found 4294967294
i32: -2147483647 0 2147483647 2147483647 -1 -2147483648 -2147483648 2147483647 -2147483647
wrote over -2147483647, found 2147483647
u64: 1 0 18446744073709551615 18446744073709551615 18446744073709551615 0 0 18446744073709551615 1
wrote over 1, found 18446744073709551615
i64: -9223372036854775807 0 9223372036854775807 9223372036854775807 -1 -9223372036854775808 -9223372036854775808 9223372036854775807 -9223372036854775807
wrote over -9223372036854775807, found 9223372036854775807
bool: false true true false
enum: true true
pointer: 30
struct: 45 255
shared: true 200000 600000
+171
View File
@@ -0,0 +1,171 @@
import std::io;
import std::process;
import system;
extern import "kernel32.dll" when os == windows;
# Atomics of every width and kind, their operations giving what they held, and
# two processes adding to a page they share, which loses nothing.
def show<T>(name: strview, a: &mut atomic<T>, low: T, high: T): void where T: integer, lockfree {
a.store(low);
val added := a.fetch_add(high);
val subtracted := a.fetch_sub(low, order::acq_rel);
val anded := a.fetch_and(high, order::relaxed);
val ored := a.fetch_or(low);
val xored := a.fetch_xor(high, order::release);
val least := a.fetch_min(low);
val most := a.fetch_max(high, order::acquire);
val swapped := a.exchange(low);
io::println($"{name}: {added} {subtracted} {anded} {ored} {xored} {least} {most} {swapped} {a.load()}");
match a.compare_exchange(low, high) {
value(found) => io::print($" wrote over {found}");
error(found) => io::print($" found {found}");
}
match a.compare_exchange(low, high, order::release, order::relaxed) {
value(found) => io::println($", wrote over {found}");
error(found) => io::println($", found {found}");
}
}
enum state { idle, busy, done }
struct counters {
var hits: atomic<u64>;
var flags: atomic<u8>;
}
def main(): void {
var a8 := atomic::<u8>::new(0);
var b8 := atomic::<i8>::new(0);
var a16 := atomic::<u16>::new(0);
var b16 := atomic::<i16>::new(0);
var a32 := atomic::<u32>::new(0);
var b32 := atomic::<i32>::new(0);
var a64 := atomic::<u64>::new(0);
var b64 := atomic::<i64>::new(0);
show::<u8>("u8", &mut a8, 100, 200);
show::<i8>("i8", &mut b8, -100, 90);
show::<u16>("u16", &mut a16, 0x7FFF, 0xFFF0);
show::<i16>("i16", &mut b16, -30000, 30000);
show::<u32>("u32", &mut a32, 5, 0xFFFFFFFE);
show::<i32>("i32", &mut b32, -2147483647, 2147483647);
show::<u64>("u64", &mut a64, 1, 0xFFFFFFFFFFFFFFFF);
show::<i64>("i64", &mut b64, -9223372036854775807, 9223372036854775807);
var flag := atomic::<bool>::new(false);
val was := flag.exchange(true);
io::println($"bool: {was} {flag.load()} {flag.compare_exchange(true, false) is value} {flag.load()}");
var now := atomic::<state>::new(state::idle);
now.store(state::busy, order::release);
val before := now.exchange(state::done);
io::println($"enum: {before == state::busy} {now.load(order::acquire) == state::done}");
var words: u64[4] = [10, 20, 30, 40];
var at := atomic::<*mut u64>::new(&mut words[0] as *mut u64);
match at.compare_exchange(&mut words[0] as *mut u64, &mut words[2] as *mut u64) {
value(_) => io::println($"pointer: {at.load()[0]}");
error(_) => io::println("pointer: refused");
}
var held := counters { hits = atomic::<u64>::new(0), flags = atomic::<u8>::new(0) };
for i in 0..10u {
_ = held.hits.fetch_add(i);
_ = held.flags.fetch_or((1 << (i % 8)) as u8);
}
fence(order::seq_cst);
io::println($"struct: {held.hits.load()} {held.flags.load()}");
# A page both processes keep, rather than a copy each.
val page := shared_page();
val sum := page as *mut atomic<u64>;
val tries := (page + 8) as *mut atomic<u32>;
val child := copy();
for _ in 0..100000 {
_ = sum[0].fetch_add(1);
var seen := tries[0].load(order::relaxed);
while true {
match tries[0].compare_exchange_weak(seen, seen + 3, order::acq_rel, order::relaxed) {
value(_) => break;
error(found) => seen = found;
}
}
}
if child == 0 {
exit(0);
}
var status: process_status;
_ = wait(child, &mut status);
io::println($"shared: {status.exited} {sum[0].load()} {tries[0].load()}");
}
# The page both processes add to, and the copy of the program adding with this
# one, whose number `copy` gives, or zero in the copy. Linux keeps a page mapped
# shared in the copy `fork` makes. Windows cannot fork, so there the copy is the
# program started again, writing nothing, which maps the page by the name it is
# started with.
when os == linux {
def shared_page(): u64 {
return system::linux::syscall(9, 0, 4096, 3, 0x21, 0xFFFFFFFFFFFFFFFF, 0) as u64;
}
def copy(): i64 {
return fork();
}
}
else {
# The variable the copy is started with, holding the name of the page.
val page_variable: strview = "SAKURA_ATOMICS_PAGE";
# The page, as this program mapped it.
var mapped: u64 = 0;
# The name of the page: the one the copy was given, or one of this program's
# own.
def page_name(): string {
if process::variable(page_variable) is some(given) {
return string::from(given, nothing {});
}
return $"sakura-atomics-{getpid()}";
}
def shared_page(): u64 {
val name := page_name();
var wide: u16[64];
for i in 0..name.length {
wide[i] = name[i] as u16;
}
val mapping := pages::CreateFileMappingW(0xFFFFFFFFFFFFFFFF, null, 0x04, 0, 4096, (&wide) as *u16);
mapped = pages::MapViewOfFile(mapping, 0x02, 0, 0, 4096);
return mapped;
}
# The copy is slow to start, so it says it has mapped the page, in the word
# after what the two add to, and the program waits for that, for ten seconds
# at most, so that the two add at once, as after `fork`.
def copy(): i64 {
val ready := (mapped + 12) as *mut atomic<u32>;
if process::variable(page_variable) is some(_) {
ready[0].store(1);
return 0;
}
var device := path::parse(null_device) else (_) { return -1; };
var quiet := io::file::open(&device, open_flags::write) else (_) { return -1; };
val started := respawn($"{page_variable}={page_name()}".span, fd::stdin, quiet.handle, fd::stderr);
val until := clock(clock_kind::steady) + 10000000000;
while started > 0 && ready[0].load() == 0 && clock(clock_kind::steady) < until {
_ = sleep(1000000);
}
return started;
}
}
# What Windows gives of memory that processes share: a mapping of the system's
# own file of pages, by a name, and a view of it.
extern module pages when os == windows;
pub def CreateFileMappingW(
file: u64, security: *mut u8, protection: u32, size_high: u32, size_low: u32, name: *u16
): u64;
pub def MapViewOfFile(mapping: u64, access: u32, offset_high: u32, offset_low: u32, size: u64): u64;
@@ -0,0 +1 @@
7 1
@@ -0,0 +1,11 @@
import std::io;
struct serial : attribute { val name: span<u8>; val aliases: span<u8>[2]; }
struct weight : attribute { val value: i64 = 1; }
const def double(x: i64): i64 { return x * 2; }
@serial{ name = "point", aliases = ["p", "pt"] }
struct point { @weight{ value = double(21) } var x: i64; @weight var y: i64; }
enum axis { @weight x, y }
@weight def sum(p: point): i64 { return p.x + p.y; }
def main(): void {
println($"{sum(point{ 3, 4 })} {axis::y as i64}");
}
@@ -0,0 +1,6 @@
61440 65520 4080 3855
986880 3855
30720
240
8 15 9 4294967283 48 3
8
@@ -0,0 +1,36 @@
import std::io;
# A struct has the bitwise operators and shifts by the methods that give them,
# `bit_and`, `bit_or`, `bit_xor`, `bit_not`, `shift_left`, and `shift_right`, as it
# has arithmetic, their compound assignments too, and a bound asking for them
# gives a type parameter the operators. Integers give the methods as well.
struct bits { var word: u64; }
def bits::bit_and(&this, other: &bits): bits { return bits { word = this.word & other.word }; }
def bits::bit_or(&this, other: &bits): bits { return bits { word = this.word | other.word }; }
def bits::bit_xor(&this, other: &bits): bits { return bits { word = this.word ^ other.word }; }
def bits::bit_not(&this): bits { return bits { word = ~this.word }; }
def bits::shift_left(&this, by: &u32): bits { return bits { word = this.word << by }; }
def bits::shift_right(&this, by: &u32): bits { return bits { word = this.word >> by }; }
trait masks { def bit_and(&this, other: &self): self; def bit_not(&this): self; }
def clear<T>(a: T, b: T): T where T: masks { return a & ~b; }
def main(): void {
val a := bits { word = 0xF0F0 };
val b := bits { word = 0xFF00 };
io::println($"{(a & b).word} {(a | b).word} {(a ^ b).word} {(~a).word & 0xFFFF}");
io::println($"{(a << 4).word} {(a >> 4).word}");
var c := a;
c &= b;
c |= bits { word = 1 };
c <<= 1;
c ^= bits { word = 3 };
c >>= 2;
io::println($"{c.word}");
io::println($"{clear(a, b).word}");
val x: u32 = 12;
io::println($"{x.bit_and(&10)} {x.bit_or(&3)} {x.bit_xor(&5)} {x.bit_not()} {x.shift_left(&2)} {x.shift_right(&2)}");
io::println($"{clear(x, 4 as u32)}");
}
@@ -0,0 +1 @@
true [true, false, false] true true 1 true false true true true false true false 200 2.3333333333333335 1.5 true 57 [10, 21, 32] 0:10 1:20 2:30
@@ -0,0 +1,26 @@
import std::io;
struct nothing {}
union value { var none: nothing; var flag: bool; var number: i64; var real: f64; }
def main(): void {
val yes: bool = 3 > 2;
val flags: bool[3] = [true, !yes, yes && false];
val held := value{ flag = true };
val three := value{ number = 3 };
print($"{yes} {flags} {held.flag} {three is number} {yes as u8} {7 as bool} {0 as bool} {flags == [true, false, false]} ");
val xs := [10, 20, 30];
var i: i64 = -1;
val n: u64 = 3;
val small: u8 = 200;
val wide: i16 = small;
var total: f64 = 7;
print($"{i < xs.length} {xs.length > i} {i == n} {n != i} {i >= n} {wide} {total / xs.length} {n * 0.5} {i < 0.5} ");
var sum := 0;
for k in 0..xs.length { sum += xs[k]; }
for k in -2..1 { sum += k; }
for k in 3..3 { sum += 1000; }
var ys := xs;
for at, &mut y in ys { y += at as i64; }
var shown := $"";
for at, x in xs { shown.append($"{at}:{x} "); }
println($"{sum} {ys} {shown}");
}
@@ -0,0 +1,2 @@
d1 d1 d1 d1d1 d1true
? ? ? .. ?
@@ -0,0 +1,35 @@
import std::io;
trait shows { def show(this: &shows): string; }
struct wrap<T> { var v: T; }
def wrap<T>::plain(this: &wrap<T>): string {
if const T is shows { return this.v.show(); }
return "?";
}
def wrap<T>::inverted(this: &wrap<T>): string {
if const T is not shows { return "?"; } else { return this.v.show(); }
}
def wrap<T>::guarded(this: &wrap<T>): string {
if const T is not shows { return "?"; }
return this.v.show();
}
def wrap<T>::looped(this: &wrap<T>, times: int): string {
var out := string::new(nothing {});
for i in 0..times {
if const T is not shows { out.append($"."); continue; }
out.append($"{this.v.show()}");
}
return out;
}
def wrap<T>::joined(this: &wrap<T>): string {
if const !(T is shows && T is equatable) { return "?"; }
return $"{this.v.show()}{this.v == this.v}";
}
struct dot: shows { var n: int; }
def dot::show(this: &dot): string { return $"d{this.n}"; }
def dot::equals(&this, other: &dot): bool { return this.n == other.n; }
def main(): void {
val d := wrap{ v = dot{ n = 1 } };
val i := wrap{ v = 7 };
println($"{d.plain()} {d.inverted()} {d.guarded()} {d.looped(2)} {d.joined()}");
println($"{i.plain()} {i.inverted()} {i.guarded()} {i.looped(2)} {i.joined()}");
}
@@ -0,0 +1,9 @@
node 1
leaf 2
leaf 1
node 3
leaf 4
leaf 3
hidden 6
hidden 5
done
@@ -0,0 +1,22 @@
import std::io;
import lib;
struct leaf : owning { var n: int; }
def leaf::close(&mut this): void { if this.n != 0 { println($"leaf {this.n}"); } }
struct node : owning { var a: leaf; var b: leaf; }
def node::close(&mut this): void { if this.a.n != 0 { println($"node {this.a.n}"); } }
def main(): void {
{ var held := box::new(node{ a = leaf{ n = 1 }, b = leaf{ n = 2 } }); }
{ var many := vector::<node>::new(); many.append(node{ a = leaf{ n = 3 }, b = leaf{ n = 4 } }); }
{ var kept := holder::make(); }
println("done");
}
module lib;
struct hidden : owning { var n: int; }
def hidden::close(&mut this): void { if this.n != 0 { println($"hidden {this.n}"); } }
pub struct holder : owning { var one: box<hidden>; var many: vector<hidden>; }
pub def holder::make(): holder {
var made := holder{ one = box::new(hidden{ n = 5 }), many = vector::<hidden>::new() };
made.many.append(hidden{ n = 6 });
return made;
}
pub def holder::close(&mut this): void {}
@@ -0,0 +1 @@
6 6 0 42 0
@@ -0,0 +1,20 @@
import std::io;
# A branch or arm naming a type parameter as a type, as `T is strview` does,
# is checked within the generic's own body, where a value of `T` is of that
# type, as it is in each instance taking it.
def described<T>(x: T): u64 {
if const T is strview { val s: strview = x; return x.length + s.length; }
match const T {
i32 => return (x + 1) as u64;
else => return 0;
}
}
def after<T>(x: T): u64 {
if const T is not u16 { return 0; }
return (x * 2) as u64;
}
def main(): void {
println($"{described("abc")} {described(5 as i32)} {described(true)} {after(21 as u16)} {after(true)}");
}
@@ -0,0 +1,5 @@
--- exit 2
tests/programs/branches_naming_a_type_report_what_is_wrong_1.sakura:4:59: member: `strview` has no field, property, or method `lenght`.
tests/programs/branches_naming_a_type_report_what_is_wrong_1.sakura:5:63: member: `i32` has no field, property, or method `nothing`.
tests/programs/branches_naming_a_type_report_what_is_wrong_1.sakura:6:59: assignable: A pointer of a type parameter writes what it points at only where `if const T::mutable` says it does.
@@ -0,0 +1,8 @@
# What is wrong within a branch or arm naming a type parameter as a type is
# reported within the generic's own body, though no instance takes it, and a
# pointer of a type parameter writes only where `if const T::mutable` says so.
def typo<T>(x: T): u64 { if const T is strview { return x.lenght; } return 0; }
def wrong_arm<T>(x: T): u64 { return match const T { i32 => x.nothing, else => 0u }; }
def blind<T>(x: T, v: T::target): void where T: pointer { *x = v; }
def main(): void {}
@@ -0,0 +1 @@
true 5 7 true true 1 true true false true true true true 5 1 7
@@ -0,0 +1,16 @@
import std::io;
enum color { red, green }
struct pt { var x: i64; }
def pt::equals(&this, other: &pt): bool { return this.x == other.x; }
def same<T>(a: &T, b: &T): bool where T: equatable { return a == b; }
def through(h: &hashable): u64 { return h.hash(); }
def main(): void {
val a: i64 = 5; val b: u8 = 7; val f: f64 = -0.0; val g: f64 = 0.0;
val c := color::green; val p := &a as *i64;
val arr: i64[3] = [1, 2, 3]; val other: i64[3] = [1, 2, 3];
val pts: pt[2] = [pt{1}, pt{2}]; val more: pt[2] = [pt{1}, pt{3}];
print($"{a.equals(&a)} {a.hash()} {b.hash()} {f.hash() == g.hash()} {f == g} {c.hash()} ");
print($"{arr.equals(&other)} {arr.hash() == other.hash()} {pts == more} {pts[0] == more[0]} ");
print($"{same::<*i64>(&p, &p)} {same::<color>(&c, &c)} {same::<pt[2]>(&pts, &pts)} ");
println($"{through(&a)} {through(&c)} {through(&b)}");
}
@@ -0,0 +1,7 @@
--- exit 2
tests/programs/cases_say_what_one_case_finds_1.sakura:4:74: operands: `T` and `T` are not both numbers, which the operator takes. (Where `T` is `pointer`.)
tests/programs/cases_say_what_one_case_finds_1.sakura:5:72: operands: `T` and `T` are not both numbers, which the operator takes. (Where `T` is `pointer`.)
tests/programs/cases_say_what_one_case_finds_1.sakura:6:71: undefined: `nothing_here` is not declared where it is used.
tests/programs/cases_say_what_one_case_finds_1.sakura:7:85: undefined: `T` has no type `target`. (Where `T` is `integer`.)
tests/programs/cases_say_what_one_case_finds_1.sakura:8:43: undefined: No type `nowhere` is declared where it is written.
@@ -0,0 +1,10 @@
# A branch or arm checked once for each case it holds in says each note once,
# with the case where only that case finds it, and an undeclared name an `if
# const` tests by is said once.
def added<T>(x: T): T { if const T is pointer || T is integer { return x + x; } return x; }
def squared<T>(x: T): T { return match const T { integer, pointer => x * x, else => x }; }
def missing<T>(x: T): T { if const T is integer || T is real { return nothing_here; } return x; }
def target_bits<T>(): u64 { return size_of::<match const T { pointer, integer => T::target, else => T }>(); }
def unknown<T>(x: T): u64 { if const T is nowhere { return 1; } return 0; }
def main(): void {}
@@ -0,0 +1,11 @@
peek seen
ends a
close a
short b
close b
close cc
2
close e
end
close d
close seen
@@ -0,0 +1,20 @@
import std::io;
struct noisy : owning { var name: span<u8>; }
def noisy::new(name: span<u8>): noisy { return noisy { name = name }; }
def noisy::close(&mut this): void { println($"close {this.name}"); }
def ends(n: noisy): void { println($"ends {n.name}"); }
def back(n: noisy): noisy { return n; }
def later(n: noisy, flag: bool = true): void { if flag { return; } }
def main(): void {
val short := def(n: noisy): void => println($"short {n.name}");
val length := def(n: noisy): u64 => n.name.length;
var seen := noisy::new("seen");
val peek := def(): void { println($"peek {seen.name}"); };
peek();
ends(noisy::new("a"));
short(noisy::new("b"));
println($"{length(noisy::new("cc"))}");
var kept := back(noisy::new("d"));
later(noisy::new("e"));
println("end");
}
@@ -0,0 +1,17 @@
close a
close b
close a
close x0
close x1
close inner
close gone
close first
end
close second
close m
close e1
close e0
owner body
close h
close p2
close p1
@@ -0,0 +1,40 @@
import std::io;
struct noisy : owning { var name: span<u8>; }
def noisy::new(name: span<u8>): noisy { return noisy { name = name }; }
def noisy::close(&mut this): void { println($"close {this.name}"); }
struct pair { var first: noisy; var second: noisy; }
struct owner : owning { var held: noisy; }
def owner::close(&mut this): void { println("owner body"); }
def early(flag: bool): void {
var a := noisy::new("a");
if flag { return; }
var b := noisy::new("b");
}
def looped(): void {
var i := 0;
while i < 3 {
var label := $"x{i}";
var x := noisy::new(label);
i++;
if i == 2 { break; }
continue;
}
}
def made(): noisy {
var m := noisy::new("m");
return m;
}
def main(): void {
early(true);
early(false);
looped();
{ var inner := noisy::new("inner"); }
var p := pair { first = noisy::new("p1"), second = noisy::new("p2") };
var o := owner { held = noisy::new("h") };
var many: noisy[2] = [noisy::new("e0"), noisy::new("e1")];
noisy::new("gone");
var got := made();
var over := noisy::new("first");
over = noisy::new("second");
println("end");
}
@@ -0,0 +1,4 @@
--- exit 2
tests/programs/compile_error_in_a_generic_property_1.sakura:9:39: invalid: A vector of two has no z. (In `z<f32, 2>`, made at tests/programs/compile_error_in_a_generic_property_1.sakura:21:18)
tests/programs/compile_error_in_a_generic_property_1.sakura:14:39: invalid: A vector of fewer than four has no w to write. (In `w<f32, 2>`, made at tests/programs/compile_error_in_a_generic_property_1.sakura:22:7)
@@ -0,0 +1,23 @@
import std::io;
# A `compile_error` in the accessor of a generic type's property is reported
# in the instance a value of the type given its arguments reads or writes, as
# one in a method called is.
struct vec<T, const N: u64> { var items: T[N]; }
pub val vec<T, const N: u64>::z: T {
get { if const N < 3 { compile_error("A vector of two has no z."); } return this.items[2]; }
}
pub var vec<T, const N: u64>::w: T {
get => this.items[0];
set { if const N < 4 { compile_error("A vector of fewer than four has no w to write."); } this.items[3] = value; }
}
def main(): void {
val three := vec::<f32, 3> { items = [1.0, 2.0, 3.0] };
println($"{three.z}");
var two := vec::<f32, 2> { items = [1.0, 2.0] };
println($"{two.z}");
two.w = 4.0;
}
@@ -0,0 +1,3 @@
--- exit 2
tests/programs/compile_error_says_text_worked_out_while_compiling_1.sakura:7:16: invalid: A constant says what is wrong.
@@ -0,0 +1,8 @@
import std::io;
# A `compile_error` given a constant holding text says that text.
const said: strview = "A constant says what is wrong.";
def main(): void {
compile_error(said);
}
@@ -0,0 +1,4 @@
--- exit 2
tests/programs/compile_error_says_text_worked_out_while_compiling_2.sakura:12:31: invalid: `b` is a field of `pair`
tests/programs/compile_error_says_text_worked_out_while_compiling_2.sakura:7:18: invalid: `u32` takes 4 bytes, and `u8` 1 (In `same_size<u32, u8>`, made at tests/programs/compile_error_says_text_worked_out_while_compiling_2.sakura:15:40)
@@ -0,0 +1,19 @@
import std::io;
# A `compile_error` given interpolated text says what evaluating works out it
# says, in a generic's instance, and at the declaration whose `at` it is given.
def same_size<A, B>(): u64 {
if const size_of::<A>() != size_of::<B>() {
compile_error($"`{name_of::<A>()}` takes {size_of::<A>()} bytes, and `{name_of::<B>()}` {size_of::<B>()}");
}
return size_of::<A>();
}
struct pair { var a: i64; var b: i64; }
def main(): void {
println($"{same_size::<u64, i64>()} {same_size::<u32, u8>()}");
for const f in members_of(decl_of::<pair>()) {
if const f.name == "b" { compile_error($"`{f.name}` is a field of `{name_of::<pair>()}`", f.at); }
}
}
@@ -0,0 +1,6 @@
--- exit 2
tests/programs/compile_error_waits_for_evaluating_to_choose_its_branch_1.sakura:25:59: invalid: broken
tests/programs/compile_error_waits_for_evaluating_to_choose_its_branch_1.sakura:36:43: invalid: no field is b
tests/programs/compile_error_waits_for_evaluating_to_choose_its_branch_1.sakura:42:66: invalid: no field is z
tests/programs/compile_error_waits_for_evaluating_to_choose_its_branch_1.sakura:17:23: invalid: not the same size (In `same_size<uint, u8>`, made at tests/programs/compile_error_waits_for_evaluating_to_choose_its_branch_1.sakura:52:40)
@@ -0,0 +1,53 @@
import std::io;
# A `compile_error` in a branch of `if const` that only evaluating decides is
# reported where evaluating chooses that branch, as one in a branch the checker
# decides is, and never where it chooses another: of a computed constant, of
# `size_of` in a generic's instance, and of what a pass of `for const` over a
# struct's fields describes. As with a branch the checker decides, what follows
# a branch taken that reports one is not checked, so each case is a function
# of its own.
struct outcome { val failed: bool; }
def build(n: i64): outcome { return outcome { failed = n > 5 }; }
const broken: outcome = build(7);
const fine: outcome = build(3);
def same_size<A, B>(): u64 {
if const size_of::<A>() == size_of::<B>() { return size_of::<A>(); }
else { compile_error("not the same size"); }
return 0;
}
@usage{ on = target::fields }
struct mark : attribute { val letter: u8 = 0; }
struct marked { @mark{ letter = 'q' } var a: i64; @mark{ letter = 'z' } var b: i64; }
def taken(): void { if const broken.failed { compile_error("broken"); } }
def not_taken(): void { if const fine.failed { compile_error("fine, so never reported"); } }
def nested(): void {
if const broken.failed && !fine.failed {
if const fine.failed { compile_error("a branch not taken within one taken"); }
} else {
compile_error("a branch not taken");
}
}
def names(): void {
for const f in members_of(decl_of::<marked>()) {
if const f.name == "b" { compile_error("no field is b"); }
if const f.name == "c" { compile_error("no field is c, so never reported"); }
}
}
def letters(): void {
for const f in members_of(decl_of::<marked>()) {
if const attached::<mark>(f)[0].letter == 'z' { compile_error("no field is z"); }
}
}
def main(): void {
taken();
not_taken();
nested();
names();
letters();
println($"{same_size::<u64, i64>()} {same_size::<u64, u8>()}");
}
@@ -0,0 +1,4 @@
fine
8 1
a
b
@@ -0,0 +1,27 @@
import std::io;
# Where evaluating chooses no branch of `if const` holding a `compile_error`,
# the program compiles, and runs the branches chosen.
struct outcome { val failed: bool; }
def build(n: i64): outcome { return outcome { failed = n > 5 }; }
const fine: outcome = build(3);
def same_size<A, B>(): u64 {
if const size_of::<A>() == size_of::<B>() { return size_of::<A>(); }
else { compile_error("not the same size"); }
return 0;
}
@usage{ on = target::fields }
struct mark : attribute { val letter: u8 = 0; }
struct marked { @mark{ letter = 'q' } var a: i64; @mark{ letter = 'r' } var b: i64; }
def main(): void {
if const fine.failed { compile_error("fine"); } else { println("fine"); }
println($"{same_size::<u64, i64>()} {same_size::<u8, bool>()}");
for const f in members_of(decl_of::<marked>()) {
if const f.name == "c" { compile_error("no field is c"); }
if const attached::<mark>(f)[0].letter == 'z' { compile_error("no field is z"); }
println(f.name);
}
}
@@ -0,0 +1,6 @@
52 made 1 grown 2
6 made 0 grown 1
8 made 0 grown 1
15
top
more
@@ -0,0 +1,47 @@
import std::io;
# A compound assignment calls the method changing its target in place where the
# target's type has one taking the value, as `+=` calls `add_assign`, which gives
# nothing, and otherwise writes what the operator's method gives over the target,
# as `x = x + y` would. So a type owning memory can grow in place.
struct tally { var total: i64; var made: i64; var grown: i64; }
def tally::add(&this, other: &tally): tally { return tally { total = this.total + other.total, made = this.made + 1, grown = this.grown }; }
def tally::add(&this, k: &i64): tally { return tally { total = this.total + k, made = this.made + 1, grown = this.grown }; }
def tally::add_assign(&mut this, other: &tally): void { this.total += other.total; this.grown++; }
def tally::shift_left_assign(&mut this, by: &u32): void { this.total <<= by; this.grown++; }
struct box { var held: tally; }
var box::inside: tally { get => this.held; set => this.held = value; }
# A type owning memory grows in place, through a property's `get` and `set` too.
struct lines { var text: string; }
def lines::add_assign(&mut this, more: &strview): void { this.text.append(more); this.text.append("\n"); }
struct page { var body: lines; }
var page::lines: lines {
get => lines { text = copy(&this.body.text) };
set => this.body = move(&mut value);
}
def main(): void {
var t := tally { total = 1 };
t += tally { total = 2 }; # add_assign
t += 10 as i64; # no `add_assign` takes an `i64`, so `add`
t <<= 2; # shift_left_assign
io::println($"{t.total} made {t.made} grown {t.grown}");
var b := box { held = tally { total = 5 } };
b.inside += tally { total = 1 };
io::println($"{b.held.total} made {b.held.made} grown {b.held.grown}");
var all := vector::<tally>::new();
all.append(tally { total = 7 });
all[0] += tally { total = 1 };
io::println($"{all[0].total} made {all[0].made} grown {all[0].grown}");
var written := lines { text = string::new(nothing {}) };
for i in 0..3 { written += "line"; }
var p := page { body = lines { text = string::from("top\n", nothing {}) } };
p.lines += "more";
io::print($"{written.text.length}\n{p.body.text}");
}
+5
View File
@@ -0,0 +1,5 @@
0 green shape{circle = 1.5}
-100 green shape{count = 1}
1996959894 256 755167117 44 0.1 -5
narrow 3 wide 4 8 is 8 bits ordered other
0 1
@@ -0,0 +1,53 @@
import std::io;
enum color: u8 { red, green = 4, blue }
union shape { var circle: f32; var count: i32; }
struct entry { var weight: i16; var hue: color; var form: shape; }
def make(): entry[2] {
var out: entry[2];
for i in 0..2 {
out[i] = entry{ weight = -(i as i16) * 100, hue = color::green,
form = i % 2 == 0 ? shape{ circle = 1.5 } : shape{ count = i as i32 } };
}
return out;
}
const entries: entry[2] = make();
def crc_table(): u32[256] {
var table: u32[256];
for i in 0..256 {
var c := i as u32;
for _ in 0..8 { c = (c & 1) != 0 ? 0xEDB88320 ^ (c >> 1) : c >> 1; }
table[i] = c;
}
return table;
}
const crc: u32[256] = crc_table();
def doubled(): int { return base * 2; }
const twice := doubled();
const base := 21;
struct counter { var n: int; }
def counter::bump(&mut this): void { this.n++; }
def bumped(): int { var c := counter{ 0 }; c.bump(); c.bump(); return c.n; }
trait sized { const bytes: u64; }
const i32::bytes: u64 = 4;
const i64::bytes: u64 = 8;
def show<T>(x: T): string where T: sized {
const bits := T::bytes * 8;
if const bits > 32 { return $"wide {x}"; } else { return $"narrow {x}"; }
}
def kind<T>(x: T): string {
if const T is integer { return $"{x + 1} is {size_of::<T>() * 8} bits"; }
else if const T is ordered { return "ordered"; }
else { return "other"; }
}
const small: f32 = 0.1;
const neg: i8 = -5;
val copied := crc;
def main(): void {
for e in entries { println($"{e.weight} {e.hue} {e.form}"); }
const local := bumped() + twice;
println($"{crc[1]} {crc.length} {copied[255]} {local} {small} {neg}");
println($"{show(3 as i32)} {show(4)} {kind(7 as u8)} {kind(2.5)} {kind(entries)}");
var mine := crc;
mine[0] = 1;
println($"{crc[0]} {mine[0]}");
}
+1
View File
@@ -0,0 +1 @@
[4, 3, 2, 1, 0] 13 7
+40
View File
@@ -0,0 +1,40 @@
import std::io;
struct node { var value: int; var next: *mut node; }
type block = *mut u8;
def countdown(): int[5] {
var head: *mut node = null;
var blocks: block[5];
for i in 0..5 {
val made := raw_allocate(size_of::<node>()) as *mut node;
(*made).value = i as int;
(*made).next = head;
head = made;
blocks[i] = made as *mut u8;
}
var out: int[5];
var at := head;
var k := 0;
while at != null { out[k] = (*at).value; k++; at = (*at).next; }
for i in 0..5 { raw_release(blocks[i]); }
return out;
}
def total(first: *int, count: u64): int {
var sum := 0;
for i in 0..count { sum += first[i]; }
val last := first + (count - 1);
return sum + (last - first) as int;
}
def summing(): int {
var xs: int[4] = [1, 2, 3, 4];
return total((&xs) as *int, 4);
}
def through_local(): int {
var x := 5;
val p := &mut x as *mut int;
p[0] = 7;
return x;
}
const down := countdown();
const summed := summing();
const written := through_local();
def main(): void { println($"{down} {summed} {written}"); }
@@ -0,0 +1 @@
7000000000 -6000000000 12000000000
@@ -0,0 +1,13 @@
import std::io;
# An operator calling a method still makes a constant while compiling.
struct length { val ns: i64; }
def length::add(&this, other: &length): length { return length { ns = this.ns + other.ns }; }
def length::mul(&this, by: &i64): length { return length { ns = this.ns * by }; }
def length::negate(&this): length { return length { ns = -this.ns }; }
def seconds(count: i64): length { return length { ns = count * 1000000000 }; }
const pause: length = seconds(1) + seconds(2) * 3;
const back: length = -pause + seconds(1);
const longest: length = seconds(2) * 3 + -seconds(1) + pause;
def main(): void {
println($"{pause.ns} {back.ns} {longest.ns}");
}
@@ -0,0 +1,9 @@
--- exit 2
tests/programs/constants_choosing_values_report_mistakes_1.sakura:13:90: mismatch: Expected `&T::target`, but the value is `integer constant`. (Where `T::mutable` is `false`.)
tests/programs/constants_choosing_values_report_mistakes_1.sakura:14:63: mismatch: Expected `uint`, but the value is `text`.
tests/programs/constants_choosing_values_report_mistakes_1.sakura:15:45: constant: A value is a pattern of `match const` choosing by a constant, as `match const N { 4 => ... }`; this chooses by a type.
tests/programs/constants_choosing_values_report_mistakes_1.sakura:16:46: constant: A `match const` of values chooses by a constant known while compiling: a constant, a constant parameter, or what a function gives of them.
tests/programs/constants_choosing_values_report_mistakes_1.sakura:17:69: mismatch: Expected `u8`, but the value is `M ? u8 : text`.
tests/programs/constants_choosing_values_report_mistakes_1.sakura:23:10: assignable: A `&` reference reads what it refers to; write through a `&mut` one.
tests/programs/constants_choosing_values_report_mistakes_1.sakura:18:45: arms: No arm of the `match const` fits `3`, and it has no `else`. (In `none<3>`, made at tests/programs/constants_choosing_values_report_mistakes_1.sakura:24:12)
@@ -0,0 +1,25 @@
# A ternary choosing while compiling checks each branch with what its
# condition says, and a note said in one case says which. A `match const` of
# values chooses by a constant, its patterns of the constant's type, and an
# instance none fits, without `else`, is an error. Each instance checks the
# branch it takes, so `&` of what a `*T` points at writes nothing.
type addref<T, const M: bool> = M ? &mut T : &T;
type castref<T> = match const T {
reference => T,
pointer => addref<T::target, T::mutable>,
else => addref<T, false>
};
pub def tern<T>(ptr: T): castref<T> where T: pointer { return T::mutable ? &mut ptr[0] : 5; }
def pats<const N: u64>(): u8 { return match const N { 4 => 1, "a" => 2, else => 3 }; }
def typed<T>(): u8 { return match const T { 4 => 1, else => 2 }; }
def runtime(x: u64): u8 { return match const x { 1 => 1, else => 2 }; }
def mixed<const M: bool>(): u8 { val v := M ? 1 as u8 : "a"; return v; }
def none<const N: u64>(): u8 { return match const N { 1 => 1, 2 => 2 }; }
def through<T>(ptr: T): castref<T> where T: pointer { return T::mutable ? &mut ptr[0] : &ptr[0]; }
def main(): void {
var x: i32 = 1;
through(&x as *i32) = 3;
val n := none::<3>();
}
@@ -0,0 +1 @@
add=9 mul=18 sub=3 42 20 9 def mul
@@ -0,0 +1,20 @@
import std::io;
type op = def(i64, i64): i64;
def add(a: i64, b: i64): i64 { return a + b; }
def mul(a: i64, b: i64): i64 { return a * b; }
def twice<T>(x: T): T where T: numeric { return x + x; }
struct entry { val name: span<u8>; val run: op; }
const ops: entry[3] = [entry{ name = "add", run = add }, entry{ name = "mul", run = mul },
entry{ name = "sub", run = def(a: i64, b: i64): i64 { return a - b; } }];
const dbl: def(i64): i64 = twice::<i64>;
def made(): span<op> {
val table := raw_allocate(2 * size_of::<op>()) as *mut op;
table[0] = mul;
table[1] = add;
return table[0:2];
}
const kept: span<op> = made();
def main(): void {
for &e in ops { print($"{e.name}={e.run(6, 3)} "); }
println($"{dbl(21)} {kept[0](4, 5)} {kept[1](4, 5)} {ops[1].run}");
}
@@ -0,0 +1 @@
hello 5 true
@@ -0,0 +1,4 @@
import std::io;
const greeting: span<u8> = "hello";
const empty: *i64 = null;
def main(): void { println($"{greeting} {greeting.length} {empty == null}"); }
@@ -0,0 +1,4 @@
2 3 3 4 4 5 5
5 5 1 2 7 3
4 8 2 10 20 30 0 1
1 2
@@ -0,0 +1,71 @@
import std::io;
# A ternary whose condition is known while compiling and names a type
# parameter, as `T::mutable ? &mut p[0] : &p[0]`, chooses its branch as `if
# const` does: each instance checks and compiles only the branch it takes, and
# the generic's own body checks each with what the condition says. `match
# const` chooses by a constant where its patterns are values, as `match const
# T::mutable { true => ..., false => ... }` or `match const N { 4 => u32 }`.
# What a branch proves decides a condition after it, so `return a if const M;
# return b if const !M;` always returns. A type parameter bounded by
# `reference` is a reference there, as one bounded by `pointer` is a pointer.
type addptr<T, const M: bool> = M ? *mut T : *T;
type addref<T, const M: bool> = M ? &mut T : &T;
type remptr<T> = T is pointer ? T::target : T;
type remref<T> = T is reference ? T::target : T;
type castref<T> = match const T {
reference => T,
pointer => addref<remptr<T>, T::mutable>,
else => addref<T, false>
};
type castptr<T> = match const T {
pointer => T,
reference => addptr<remref<T>, false>,
else => addptr<T, false>
};
type word<const N: u64> = match const N { 4 => u32, 8 => u64, else => u16 };
pub def asptr<T>(ref: T): castptr<T> where T: reference { return ref as castptr<T>; }
pub def asref<T>(ptr: T): castref<T> where T: pointer { return ptr as castref<T>; }
pub def tern<T>(ptr: T): castref<T> where T: pointer { return T::mutable ? &mut ptr[0] : &ptr[0]; }
pub def matched<T>(ptr: T): castref<T> where T: pointer {
return match const T::mutable { false => &ptr[0], true => &mut ptr[0] };
}
pub def guards<T>(ptr: T): castref<T> where T: pointer {
return &mut ptr[0] if const T::mutable;
return &ptr[0] if const !T::mutable;
}
def flag<T>(): u8 where T: pointer { val f := T::mutable ? 1 as u8 : 2 as u8; return f; }
def chosen<const M: bool>(): u64 { val v := M ? 7 as u64 : 3 as u8; return v as u64; }
def sized<const N: u64>(): u64 { return size_of::<word<N>>(); }
def named<const N: u64>(): u8 {
return match const N { 1 => 10, 2, 3 => 20, else => 30 };
}
def stmt<const N: u64>(): u8 {
match const N {
0 => return 0;
else => return 1;
}
}
struct holder<T> { var value: T; }
def holder<T>::kind(&this): u8 { return T is integer ? 1 as u8 : 2 as u8; }
def main(): void {
var x: i32 = 1;
val p := &mut x as *mut i32;
val q := &x as *i32;
asref(p) = 2;
print($"{x} ");
tern(p) = 3;
print($"{x} {tern(q)} ");
matched(p) = 4;
print($"{x} {matched(q)} ");
guards(p) = 5;
println($"{x} {guards(q)}");
val back := asptr(&x);
println($"{*back} {*asptr(&mut x)} {flag::<*mut u8>()} {flag::<*u8>()} {chosen::<true>()} {chosen::<false>()}");
println($"{sized::<4>()} {sized::<8>()} {sized::<2>()} {named::<1>()} {named::<3>()} {named::<9>()} {stmt::<0>()} {stmt::<5>()}");
val h := holder::<i32> { value = 1 };
val g := holder::<f32> { value = 1.0 };
println($"{h.kind()} {g.kind()}");
}
@@ -0,0 +1,4 @@
4 8 4 8
4 8 4 2 1 3
8 1 4 8
4 8 8
@@ -0,0 +1,33 @@
import std::io;
# A constant within a generic that only its type arguments decide, as what a
# function gives of them, `size_of::<T>()`, or `M ? 4 : 8`, is worked out for
# each instance: in a type alias, a struct's field, the condition of a type,
# which a call is without parentheses too, and a type argument, as `T is
# integer ? 4 : 8`. Outside a generic, a function's value is a type argument
# as it is an array's length.
const def small(n: u64): bool { return n < 4; }
def bytes_of<T>(): u64 { return size_of::<T>(); }
struct buffer<T, const N: u64> { var items: T[N]; }
struct table<const N: u64> { var cells: u8[small(N) ? 1 : 2]; }
type word<const N: u64> = small(N) ? u32 : u64;
type nonzero<const N: u64> = (small(N) && N != 0) ? u32 : u64;
type both<const N: u64, const M: bool> = small(N) && M ? u32 : u64;
type pick<const M: bool> = buffer<u8, M ? 4 : 8>;
type sized<T> = buffer<u8, size_of::<T>()>;
type wide<T> = (bytes_of::<T>() > 4) ? u64 : u8;
def tested<T>(): u64 { var b: buffer<u8, T is integer ? 4 : 8>; return b.items.length; }
def main(): void {
var p: pick<true>;
var q: pick<false>;
var s: sized<u32>;
var t: table<9>;
var u: table<1>;
var b: buffer<u8, small(2) ? 3 : 5>;
println($"{size_of::<word<2>>()} {size_of::<word<8>>()} {size_of::<nonzero<2>>()} {size_of::<nonzero<0>>()}");
println($"{p.items.length} {q.items.length} {s.items.length} {t.cells.length} {u.cells.length} {b.items.length}");
println($"{size_of::<wide<u64>>()} {size_of::<wide<u8>>()} {tested::<u8>()} {tested::<f32>()}");
println($"{size_of::<both<2, true>>()} {size_of::<both<2, false>>()} {size_of::<both<9, true>>()}");
}
@@ -0,0 +1,7 @@
5 28 3 7 5 2 0
two three 2
odd 4 26
2 5 23
true true true true
11 true true
8 true
@@ -0,0 +1,60 @@
import std::io;
# A constant holds views of another constant's array, which it shares rather
# than copies: a view of a view, views within a struct and within memory the
# constant allocated, an empty view at the array's end, and a reference to an
# element.
const primes: u64[5] = [2, 3, 5, 7, 11];
const all: span<u64> = primes[:];
const middle: span<u64> = primes[1:3];
const inner: span<u64> = rest(middle);
const none: span<u64> = primes[5:0];
const largest: &u64 = &primes[4];
const words: strview[3] = ["one", "two", "three"];
const later: span<strview> = words[1:];
struct table {
var name: strview;
var rows: span<u64>;
}
const odd: table = table{ name = "odd", rows = primes[1:] };
def rest(of: span<u64>): span<u64> {
return of.sub(1, of.length - 1) else { return of; };
}
def halves(): span<span<u64>> {
val made := raw_allocate(2 * size_of::<span<u64>>()) as *mut span<u64>;
made[0] = primes[0:2];
made[1] = primes[2:3];
return span::<span<u64>>::over(made as *span<u64>, 2);
}
const split: span<span<u64>> = halves();
def sum(of: span<u64>): u64 {
var total := 0u;
for each in of { total += each; }
return total;
}
def main(): void {
println($"{all.length} {sum(all)} {middle[0]} {middle[2]} {inner[0]} {inner.length} {none.length}");
println($"{later[0]} {later[1]} {later.length}");
println($"{odd.name} {odd.rows.length} {sum(odd.rows)}");
println($"{split.length} {sum(split[0])} {sum(split[1])}");
# The views are of the array itself, not of copies of it.
println($"{all.data == primes[:].data} {inner.data == primes[2:].data} {split[1].data == primes[2:].data} {none.data == primes[5:0].data}");
# A reference to an element, as a constant and as the program runs, is to
# the element where the array is.
val held: &u64 = &primes[4];
println($"{largest} {(largest as *u64) == all.data + 4} {(held as *u64) == all.data + 4}");
# A local constant views a global one.
const first: span<u64> = primes[1:2];
println($"{sum(first)} {first.data == all.data + 1}");
}
@@ -0,0 +1,7 @@
--- exit 2
tests/programs/constants_worked_out_for_instances_report_faults_1.sakura:10:34: constant: Evaluating `<value>` stopped: Division by zero.
at halves (tests/programs/constants_worked_out_for_instances_report_faults_1.sakura:5:43)
at <value> (tests/programs/constants_worked_out_for_instances_report_faults_1.sakura:10:34)
tests/programs/constants_worked_out_for_instances_report_faults_1.sakura:8:34: constant: Evaluating `<value>` stopped: Division by zero.
at <value> (tests/programs/constants_worked_out_for_instances_report_faults_1.sakura:8:34)
@@ -0,0 +1,17 @@
# A constant only an instance works out, as what a function gives of its
# constant parameter or a constant of a generic type, is reported where it is
# written when working it out faults, as dividing by zero does where `N` is 0,
# and is no type then.
const def halves(n: u64): bool { return 8 / n > 2; }
struct narrow<T> {}
const narrow<T>::bytes: u64 = 64 / (size_of::<T>() - 1);
type split<const N: u64> = halves(N) ? u8 : u64;
def main(): void {
val b: split<2> = 1;
val c: split<0> = 1;
val d := narrow::<u64>::bytes;
val e := narrow::<u8>::bytes;
}
@@ -0,0 +1,8 @@
front 1 2, middle 2 3 4, back 4 5, all 5
written 20 30, past the end 0
tail 59, whole 60
doubled 2 40 30 4 5
world
Jello world
stack 8 9
shelf 1 2 13 14, 2 13
@@ -0,0 +1,77 @@
import std::io;
import std::containers;
# `x[a:n]` of what is no view calls its type's `span_of`, or its `slice_of`
# where `x` can be written, as generic code bounded by the traits does.
def tail_total<C>(c: &C): u64 where C: spannable<u64> {
var sum: u64 = 0;
for x in c[1:] {
sum += x;
}
return sum;
}
def doubled_front<C>(c: &mut C): void where C: sliceable<u64> {
for &mut x in c[:2] {
x *= 2;
}
}
# A type of its own, sliced through what it gives, which takes the bounds as
# the traits do.
struct shelf {
var items: i64[4];
}
def shelf::span_of(other: &shelf, start: u64 = 0, count: u64 = ~0u): span<i64> {
return count == ~0u ? other.items[start:] : other.items[start:count];
}
def shelf::slice_of(other: &mut shelf, start: u64 = 0, count: u64 = ~0u): slice<i64> {
return count == ~0u ? other.items[start:] : other.items[start:count];
}
def main(): void {
val between := " ";
var v := vector::<u64>::new();
for i in 0..5u {
v.append(i + 1);
}
val front := v[:2];
val middle := v[1:3];
val back := v[3:];
println($"front {front.iter().to_string(between)}, middle {middle.iter().to_string(between)}, back {back.iter().to_string(between)}, all {v[:].length}");
# A vector that can be written is sliced to write it; one read through a `&`
# only to read it.
var written := v[1:2];
written[0] = 20;
written[1] = 30;
val read := &v;
val seen: span<u64> = read[1:2];
println($"written {seen.iter().to_string(between)}, past the end {v[5:].length}");
println($"tail {tail_total(&v)}, whole {tail_total(&v) + v[0]}");
doubled_front(&mut v);
println($"doubled {v.span.iter().to_string(between)}");
var s := string::from("hello world", nothing {});
println(s[6:]);
var first := s[:5];
first[0] = 'J';
println(s[:]);
var st := stack::<u64>::new();
st.push(7);
st.push(8);
st.push(9);
println($"stack {st[1:].iter().to_string(between)}");
var sh := shelf { items = [1, 2, 3, 4] };
for &mut x in sh[2:] {
x += 10;
}
val kept := &sh;
println($"shelf {kept[:].iter().to_string(between)}, {kept[1:2].iter().to_string(between)}");
}
@@ -0,0 +1,5 @@
vector 22 4 47, total 73, first 22, last 47
left 3, walked 22, empty false
string zbc, empty false, bytes 3
blank true false, view 22 47
shelf 115 3 115 2 3
@@ -0,0 +1,79 @@
import std::io;
# What reads through `spannable`, `sliceable`, and `iterable`, as generic code
# does, by the functions and types they ask for.
def total<C>(c: &C): u64 where C: spannable<u64> {
var sum: u64 = 0;
for x in C::span_of(c) {
sum += x;
}
return sum;
}
def doubled<C>(c: &mut C): void where C: sliceable<u64> {
for &mut x in C::slice_of(c) {
x *= 2;
}
}
def first_walked<C>(c: &C): u64 where C: iterable<u64> {
var walk: C::iterator = c.iter();
return walk.next() is some(x) ? x : 0;
}
# A container of its own, whose `first` writes where it can be written, and
# whose iterator type and property share a name.
struct shelf<T> {
var items: T[3];
}
type shelf<T>::iterator = span<T>::iterator;
val shelf<T>::span: span<T> { get => span::<T>::over(&this.items[0] as *T, 3); }
val shelf<T>::iterator: shelf<T>::iterator { get => this.span.iter(); }
val shelf<T>::first: &T {
get => &this.items[0];
get mut => &mut this.items[0];
}
def bump<T>(s: &mut shelf<T>, by: T): void where T: numeric {
s.first += by;
}
def main(): void {
val between := " ";
var v := vector::<u64>::new();
v.append(1);
v.append(2);
v.append(3);
v.first = 10;
v.last += 20;
v.first++;
doubled(&mut v);
var writes := v.mutator;
if writes.next_back() is some(&mut x) {
x += 1;
}
val read := &v;
println($"vector {read.span.iter().to_string(between)}, total {total(read)}, first {read.first}, last {read.last}");
println($"left {read.iterator.remaining()}, walked {first_walked(read)}, empty {read.empty}");
var s := string::from("abc", nothing {});
s.slice[0] = 'z';
println($"string {s.span}, empty {s.empty}, bytes {s.iterator.remaining()}");
val none := span::<u64>::blank();
val view := read.span;
val start := view.first is some(f) ? f : 0;
val end := view.last is some(l) ? l : 0;
println($"blank {none.empty} {none.first is some(_)}, view {start} {end}");
var sh := shelf::<u64> { items = [1, 2, 3] };
sh.first = 5;
sh.first *= 3;
bump(&mut sh, 100);
val kept := &sh;
println($"shelf {kept.first} {kept.iterator.remaining()} {kept.span.iter().to_string(between)}");
}
+6
View File
@@ -0,0 +1,6 @@
3
--- exit 1
sakura: runtime error: A pre-condition failed: b != 0, with b = 0.
at divide (tests/programs/contracts_1.sakura:6:3)
at main (tests/programs/contracts_1.sakura:13:24)
+14
View File
@@ -0,0 +1,14 @@
# A pre-condition that fails stops the program, saying what it checked and
# what its operands held.
import std::io;
def divide(a: i64, b: i64): i64 {
expects(b != 0);
ensures(q: q * b + a % b == a);
return a / b;
}
def main(): void {
io::println($"{divide(7, 2)}");
io::println($"{divide(7, 0)}");
}
+7
View File
@@ -0,0 +1,7 @@
(a) closes what it opens
((b) c) closes what it opens
--- exit 1
sakura: runtime error: An assertion failed: A parenthesis closes one never opened, with depth = -1.
at balanced (tests/programs/contracts_2.sakura:12:7)
at main (tests/programs/contracts_2.sakura:20:11)
+21
View File
@@ -0,0 +1,21 @@
# An assertion says what failed in words of its own, in place of the condition,
# and an `ensures` in a loop's block is checked at each pass's end.
import std::io;
def balanced(lines: span<strview>): void {
for line in lines {
var depth := 0;
ensures(depth == 0);
for c in line {
continue if c == ' ';
depth += c == '(' ? 1 : c == ')' ? -1 : 0;
asserts(depth >= 0, "A parenthesis closes one never opened.");
}
io::println($"{line} closes what it opens");
}
}
def main(): void {
balanced(["(a)", "((b) c)"]);
balanced(["(d))"]);
}
+6
View File
@@ -0,0 +1,6 @@
first second first pass0 pass1 pass2 turn1 turn2 block
--- exit 1
sakura: runtime error: A post-condition failed: found == -1 || found % 2 == 0.
at first_even (tests/programs/contracts_3.sakura:40:5)
at main (tests/programs/contracts_3.sakura:54:28)
+55
View File
@@ -0,0 +1,55 @@
# An `ensures` is checked on every way out of its block once it is reached: a
# `return`, a `break` or `continue` leaving the block, and the block's end. Of
# several, the last written is checked first.
import std::io;
var seen: string;
def saw(what: strview): bool {
seen.append(what);
seen.append(" ");
return true;
}
def returns(early: bool): i64 {
ensures(saw("first"));
return 1 if early;
ensures(saw("second"));
return 2;
}
def loops(): void {
for i in 0..4 {
ensures(saw($"pass{i}"));
continue if i == 1;
break if i == 2;
}
var k := 0;
while k < 2 {
k++;
ensures(saw($"turn{k}"));
}
{
ensures(saw("block"));
}
}
def first_even(xs: span<i64>): i64 {
var found: i64 = -1;
for x in xs {
ensures(found == -1 || found % 2 == 0);
if x % 2 == 1 {
found = x;
break;
}
}
return found;
}
def main(): void {
_ = returns(true);
_ = returns(false);
loops();
io::println(seen.span);
io::println($"{first_even([1, 2, 3][:])}");
}
+6
View File
@@ -0,0 +1,6 @@
7
--- exit 1
sakura: runtime error: A post-condition failed: left == old(from.balance) - amount, with left = 5, old(from.balance) - amount = 4.
at withdraw_wrongly (tests/programs/contracts_4.sakura:15:3)
at main (tests/programs/contracts_4.sakura:23:34)
+24
View File
@@ -0,0 +1,24 @@
# An `ensures` names what the function returns, and `old` within it is what an
# expression was where the `ensures` was reached.
import std::io;
struct wallet { var balance: u64; }
def withdraw(from: &mut wallet, amount: u64): u64 {
expects(amount <= from.balance, "A wallet gives no more than it holds.");
ensures(left: left == old(from.balance) - amount);
from.balance -= amount;
return from.balance;
}
def withdraw_wrongly(from: &mut wallet, amount: u64): u64 {
ensures(left: left == old(from.balance) - amount);
from.balance -= amount;
return from.balance + 1;
}
def main(): void {
var held := wallet { balance = 10 };
io::println($"{withdraw(&mut held, 3)}");
io::println($"{withdraw_wrongly(&mut held, 3)}");
}
+4
View File
@@ -0,0 +1,4 @@
abc
9 2.5 5
108 true true
contracts are checked
+43
View File
@@ -0,0 +1,43 @@
# Contracts that hold change nothing: a local given back by name reads as
# itself, generic code checks each instance, a lambda's `ensures` covers its own
# `return`, and `expects`, `asserts`, `ensures`, and `old` are names wherever no
# statement begins with one.
import std::io;
struct terms { var expects: bool; var ensures: i64; }
def asserts(n: i64): i64 { return n * 2; }
def old(n: i64): i64 { return n + 100; }
def named(): string {
var s := string::from("abc", nothing {});
ensures(r: r.length == 3 && s.length == 3);
return s;
}
def largest<T>(a: T, b: T): T where T: ordered {
ensures(r: r >= a && r >= b);
return a > b ? a : b;
}
def next_of(n: i64): i64 {
val step := def(k: i64): i64 {
ensures(r: r > k);
return k + 1;
};
return step(n);
}
def main(): void {
io::println(named().span);
io::println($"{largest(3, 9)} {largest::<f64>(2.5, 1.5)} {next_of(4)}");
val made := terms { expects = true, ensures = 3 };
var expects := asserts(made.ensures) + old(1);
ensures(old(expects) == 107 && expects == 108);
expects++;
io::println($"{expects} {made.expects} {contracts()}");
if const contracts() {
io::println("contracts are checked");
}
}
+6
View File
@@ -0,0 +1,6 @@
2 counted
--- exit 1
sakura: runtime error: A pre-condition failed: A count of 0 is above zero, with count = 0.
at counted (tests/programs/contracts_6.sakura:6:3)
at main (tests/programs/contracts_6.sakura:12:10)
+13
View File
@@ -0,0 +1,13 @@
# What a contract says failed may be any view of text, made only where it
# fails, and a full stop it ends with is the report's own.
import std::io;
def counted(why: strview, count: i64): void {
expects(count > 0, why);
io::println($"{count} counted");
}
def main(): void {
counted("A count is above zero.", 2);
counted($"A count of {0} is above zero.", 0);
}
+3
View File
@@ -0,0 +1,3 @@
negative zero small large
1 3 5 7 9 fib 75025
97120 98120
+30
View File
@@ -0,0 +1,30 @@
import std::io;
def view(text: span<u8>): span<u8> { return text; }
def classify(n: int): string {
if n < 0 { return "negative"; }
else if n == 0 { return "zero"; }
else if n < 10 { return "small"; }
return "large";
}
def fib(n: int): int { return n < 2 ? n : fib(n - 1) + fib(n - 2); }
def main(): void {
println($"{classify(-1)} {classify(0)} {classify(5)} {classify(50)}");
var i := 0;
while true {
i++;
if i % 2 == 0 { continue; }
if i > 9 { break; }
print($"{i} ");
}
println($"fib {fib(25)}");
val text: span<u8> = "a,b,,c";
for c in text {
if c == ',' { continue; }
if c == 'c' { break; }
for d in view("xy") {
if d == 'y' { break; }
print($"{c as u8}{d as u8} ");
}
}
println("");
}
+7
View File
@@ -0,0 +1,7 @@
vector 5 total 30 first 0 last 16
owner 7
function 42 pair
maybe 16 result 12
string core alone 10 CORE ALONE true
lanes 22 4 7 8
atomic 5 equal true
+62
View File
@@ -0,0 +1,62 @@
# A program with no imports, which reads `core` alone, and names its types and
# functions with nothing before them: `vector`, `box`, and `function`, the types
# the syntax makes, traits, lanes, and atomics. It writes through `system`, by its
# path, which reads that too.
struct tally : equatable {
var count: i64;
}
def tally::equals(&this, other: &tally): bool {
return this.count == other.count;
}
def say(text: strview): void {
system::fd::stdout.put(text);
system::fd::stdout.put("\n");
}
def total<T>(values: span<T>): T where T: integer {
var sum: T = 0;
for &each in values {
sum = sum + each;
}
return sum;
}
def main(): void {
var numbers := vector::<i64>::new();
for i in 0..5 {
numbers.append(i * i);
}
val view: span<i64> = numbers.span;
say($"vector {numbers.length} total {total(view)} first {view[0]} last {view[4]}");
val boxed := box::<i64>::new(7);
say($"owner {boxed.get()}");
val doubled := function::<def(i64): i64>::new(def(x: i64): i64 { return x * 2; });
val both := pair::<i64, strview> { first = doubled(21), second = "pair" };
say($"function {both.first} {both.second}");
var found: maybe<i64> = nothing {};
if view.last is some(&at) {
found = at;
}
val parsed: result<i64, strview> = 12;
if found is some(value) && parsed is value(twelve) {
say($"maybe {value} result {twelve}");
}
var text := string::from("core", nothing {});
text.append(" alone");
val words: strview = text.span;
say($"string {text} {words.length} {words.upper()} {text.span == words}");
var lanes := u32x4::splat(3) + u32x4::of([1, 2, 3, 4]);
say($"lanes {lanes.sum()} {lanes.smallest()} {lanes.largest()} {count_ones(255u)}");
var counter := atomic::<u64>::new(1);
_ = counter.fetch_add(4);
say($"atomic {counter.load()} equal {tally { count = 1 } == tally { count = 1 }}");
}
@@ -0,0 +1,6 @@
16 128 64
false true
128 128 0
false true false
5002 3016 7
3 1 1 0
@@ -0,0 +1,36 @@
import std::io;
# The traits the compiler decides name the parts of the types they hold of: a
# pointer's and a reference's target and whether it writes it, an array's
# element and length, and the type arguments a generic type was given.
struct point { var x: i64; var y: i64; }
struct trio<A, B, C> { var a: A; var b: B; var c: C; }
def target_bits<T>(): u64 where T: pointer { return size_of::<T::target>() * 8; }
def writes<T>(): bool where T: pointer { return T::mutable; }
def referred_bits<T>(x: T): u64 {
if const T is reference { return size_of::<T::target>() * 8; }
return 0;
}
def referred_writes<T>(x: T): bool {
if const T is reference { return T::mutable; }
return false;
}
def array_info<T>(): u64 where T: array { return T::length * 1000 + size_of::<T::element>(); }
def made_of<T>(): u64 where T: array {
return size_of::<T::element[T::length]>() / size_of::<T::element>();
}
def arg_count<T>(): u64 {
if const T is generic { return T::args.length; }
return 0;
}
def main(): void {
println($"{target_bits::<*u16>()} {target_bits::<*mut point>()} {target_bits::<**u8>()}");
println($"{writes::<*u16>()} {writes::<*mut point>()}");
var p := point { x = 1, y = 2 };
println($"{referred_bits(&p)} {referred_bits(&mut p)} {referred_bits(3)}");
println($"{referred_writes(&p)} {referred_writes(&mut p)} {referred_writes(3)}");
println($"{array_info::<u16[5]>()} {array_info::<point[3]>()} {made_of::<u8[7]>()}");
println($"{arg_count::<trio<u8, bool, point>>()} {arg_count::<vector<u8>>()} {arg_count::<strview>()} {arg_count::<i64>()}");
}
@@ -0,0 +1,3 @@
--- exit 2
tests/programs/decl_of_takes_a_type_a_declaration_makes_1.sakura:3:53: invalid: `decl_of` takes a type a declaration makes, as a struct, union, enum, or trait, and `&position` is none: `name_of` and `path_of` name any type. (In `path_of_decl<&position>`, made at tests/programs/decl_of_takes_a_type_a_declaration_makes_1.sakura:6:11)
@@ -0,0 +1,7 @@
import std::io;
struct position { var x: int; }
def path_of_decl<T>(): strview { return decl_of::<T>().path; }
def main(): void {
println(path_of_decl::<position>());
println(path_of_decl::<&position>());
}
Loaded 100 of 782 files, more files were not shown because too many files have changed in this diff. Show more