🌸 Sakura
Sakura is a statically typed, compiled programming language. Values are immutable unless declared var, traits are satisfied by shape rather than by name, and errors are values. Programs run on a virtual machine, or as standalone x86-64 executables for Linux and Windows that behave identically. Source files use the .sakura extension.
This repository is sakurac, the compiler, written in Sakura, with the libraries every program reads.
import std::io;
# A union holds one of its fields at a time, and knows which.
union shape {
var circle: f64; # radius
var rect: f64[2]; # width and height
}
def shape::area(&this): f64 {
return match this {
circle(r) => 3.14159 * r * r,
rect(s) => s[0] * s[1],
};
}
# Traits are satisfied by shape: anything with an `area` method is `sized`.
trait sized {
def area(&this): f64;
}
# Generics are bounded by traits, and each use is compiled for its type.
def largest<T>(items: span<T>): f64 where T: sized {
var best := 0.0;
for item in items {
best = item.area() > best ? item.area() : best;
}
return best;
}
def main(args: span<strview>): void {
val shapes: shape[3] = [
shape{ circle = 1 },
shape{ rect = [2, 3] },
shape{ circle = 0.5 },
];
for i, s in shapes {
println($"shape {i}: area {s.area()}");
}
println($"largest: {largest(shapes[:])}");
}
shape 0: area 3.14159
shape 1: area 6
shape 2: area 0.7853975
largest: 6
Contents
- Getting started
- The language: modules, types, structs, unions, and enums, control flow, errors, faults, contracts, and checks, functions, methods, traits, generics, ownership, compile time, pointers, and C
- The standard library
- Executables, debugging, and editors
- This repository
- Grammar
- License
Getting started
Note: the language, toolchain, and standard library are still changing.
sakurac is built and tested with blossom, which clones the packages it reads (see This repository). Building it takes a sakurac already: the one blossom's config names, or else the first on PATH. The corpus, the tests of finding libraries, and the native backend's read the standard library's repository checked out beside this one, as ../std.
blossom build # writes .blossom/<key>/bin/sakurac
blossom test # builds it, then runs the tests, the corpus by the sakurac just built
blossom install --prefix ~/.local # sakurac in ~/.local/bin, with core, system, and runtime in ~/.local
The standard library is installed from its repository the same way, into ~/.local/share/sakura, where sakurac finds it.
sakurac run main.sakura util.sakura -- one two # check, then run `main` on the VM with the arguments after `--`
sakurac run --checks main.sakura # run with its memory checked too (see Pointers and memory)
sakurac run --fast main.sakura # run without checks, as a build is (see Checks)
sakurac check main.sakura # check only
sakurac check --checks-report main.sakura # list the checks left in the program's own code, by line
sakurac build -o hello main.sakura util.sakura # check, then write a standalone executable, hello.exe on Windows
sakurac build -O0 -g -o hello main.sakura # unoptimized, with debugging information in hello.petal, or hello.pdb and hello.exe
sakurac build --checks -o app main.sakura # an executable that checks indexes and the rest, as `run` does
sakurac build --contracts off -o app main.sakura # with every `expects`, `asserts`, and `ensures` left out
sakurac build --lib geometry=../geometry -o app app.sakura # with a library of its own name: `import geometry;` reads ../geometry
sakurac run --lib sakura::analyzer=analyzer app.sakura # one within another module: `import sakura::analyzer;`
sakurac run --lib std=../std app.sakura # the standard library in the folder named, rather than the one found
sakurac check --deps app.deps app.sakura # also writes the path of each file the program read
sakurac lsp # a language server, over standard input and output
sakurac --help, and --help after each command, list every option.
Libraries: every program reads core, the language's own: the types the syntax makes, the traits the compiler reads, and what those, system, and the runtime are built from, as vector and box. Every file sees its names with no import. A program reads the rest only where its files refer to it, by an import or a path, and what that refers to in turn: one printing a line reads core, std::io, and system, and none of JSON. See The standard library.
core/,system/, andruntime/are the compiler's own, found beside thesakuracexecutable or in the nearest folder above it that holds them. Nothing names them.runtime/holds the moduleruntime, which is read only for an executable, and needs nothing of std, so a program importing nothing of std builds without it.- The standard library, a repository of its own, is the folder
--lib std=DIRnames, or else astdfolder beside the executable or in the nearest folder above it, ascoreis found, or else its libraries in theshare/sakurafolder nearest above it, whereblossom installputs them, asshare/sakura/std.ioforstd::io. No other option or variable names it. blossom gives each of its modules a target lists with--lib, as--lib std::io=DIR. - Other libraries are named by
--lib NAME=DIR, once for each, and imported by their names.NAMEis the module the directory is, which may be within another, asstd::jsonorsakura::analyzer. A module is found in the library whose name is the most of its path, so--lib std::json=DIRholdsstd::jsonand the standard library the rest ofstd, and two libraries may be within one module that is in none, assakura::analyzerandsakura::machine.sakurac lsptakes them too. --deps FILEwrites the path of each file the program read, one to a line.
Statuses: check, run, and build end with 2 where the program has notes, or the command is wrong, and check with 0 otherwise. run ends with the program's own status, and build with 0 once the executable is written.
Programs and modules
A program is one or more files with one main, def main(): void or def main(args: span<strview>): void. Comments start with #, and documentation comments with #!. :: reaches into a module or type (std::io, color::red), and . into a value (p.x, p.length()).
import std::io; # imports come first,
import std::math;
module geometry; # then a module, which holds the rest of the file
pub struct rect {
pub var width := 0f; # a field other modules reach, as they do a `pub` method
pub var height := 0f;
}
pub def rect::area(&this): f32 { return this.width * this.height; }
- Modules have no braces, and may span several files.
geometry::shapesis a module withingeometry. Files without amoduledeclaration are the program itself, which nothing imports. - Visibility: a module sees what it declares, and what the modules holding it declare, with no import. Where no file of a module holding it is read, as a library's root left out, a name it would see is not declared, and the note says which module has no file. Everything else must be
pub. A field takes its ownpub, as does what is declared outside a type, aspub def rect::area, so a struct's fields are private to its module unless marked. A literal may leave a private field out, which then takes its default or zero value. Enum members are as visible as their enum, and a type parameter reaches what its bounds ask for,pubor not. - Imports bring a module's names into one file, without its submodules. The nearest name wins: a local's, then what the types around it give (see Methods and properties), then the current module's, then those of the modules holding it, then imports, then the built-in types and the names of
core's root, which every file sees. A name both a type around it and its module give, or two imports give, is told apart by path, astoken::kindorio::println. Anything a program declares or imports hides a name ofcore's, whichcore::vectorstill names. - Paths: a full path needs no import, as
system::exit(0), and reads the module it names. A path's first name is a module's, where a module of that name is seen, before a type's, so a module isn't named as a type it declares:std::netholdsuri, anduri::parsereaches the type. - Methods declared on another's type, as
std::mathdeclaressqrton asimd, or a module onu8, are seen within that module and where a file imports it, andcore's everywhere. Sostd::iodeclareswriteon astring, which iswritableonly where it's imported. What a file means doesn't hang on what another file of the program imports. - A member declared on
core's type with a namecoregives that type too, method or property, is chosen overcore's wherever it is seen, andcore's only where none of its overloads takes the call's arguments. Socoreadding a member never refuses a program or takes its calls, andcore's own code keeps calling its own. A type declared throughcore's, astype bool::storage = bit;for a trait asking for one, is kept apart the same way. - A library's modules are found by their paths: in the library
std,std::a::bis the foldera/b, or the one filea/b.sakura. A file or folder within a module's folder belongs to it where its firstmoduleline says so, and is otherwise a module of its own, asstd/testing.sakuraisstd::testing.
Variables and types
val x := 10; # immutable, type inferred
var y: f32 = 2.5; # mutable, type written
var count: u64; # starts at its zero value
var buffer: u8[4096] = undefined; # left as its memory happens to be
const page: u64 = 4096; # worked out while compiling
_ = io::write_file(at, "text"); # `_` lets go of what nothing reads
A block declares each name once: a second val x in the same block is refused, as is one after an is not test names x for the rest of the block. A parameter, a block within, a loop's body, or a function within may declare a name again, hiding the one around it.
The zero value of numbers is 0, of pointers null, of enums the member whose value is 0, and of unions their first field's. Arrays and structs are zeroed element by element and field by field, and struct fields take their defaults. References and functions have none, so they are always given a value.
= undefined leaves a var as its memory happens to be, for a buffer the program fills before it reads it, which then costs nothing to declare. Only a local var with its type written takes it, of a type that has a zero value and closes nothing. Reading one before writing it is the program's mistake, which run --checks stops at. Elsewhere undefined is a name.
void is a type of one value, void {}, which holds nothing and takes no bytes: what a function giving nothing gives. It is a type argument, a field, a local, or an element as any type is, so generic code serves it as any other, and result<void, E> says only whether something failed.
| Built-in type | |
|---|---|
i8 i16 i32 i64, u8 u16 u32 u64 |
Integers. int is i64, and uint is u64 |
f32 f64 |
Floats. float is f64 |
bool, void |
void's one value is void {} |
T[n] |
A fixed array of n elements |
&T, &mut T |
A reference that reads, or also writes |
*T, *mut T |
A raw pointer that reads, or also writes. It may be null |
def(T, U): R |
A function. def(T, U...): R takes any number of Us last |
cfn<def(T, U): R> |
The address of a C function. It may be null |
Text and dynamic arrays come from core, and the other containers from std::containers, imported:
| Type | |
|---|---|
span<T>, slice<T> |
A view of elements that reads, or also writes |
strview |
Read-only text, the alias of span<u8> with text's methods. Literals are strviews |
string |
Text it owns, and can grow |
vector<T> |
A dynamic array, core's |
dict<K, V>, hashset<T> |
Values by key, and values held once, found by their hashes |
list<T>, stack<T>, queue<T>, deque<T>, chain<T> |
Lists, stacks, queues, and the rest |
interner<T> |
Gives each distinct value an ID, counted from 0 in the order values are first given, and reads it back by ID |
heap<T> |
Keeps its least value first, for peek and pop |
runs<T>, groups<T> |
Many short lists in one block: named by an ID as each is added, or gathered by a key in two passes |
byte_writer |
std::io's: bytes laid out one after another, words least significant byte first, alignment, and lengths written once known |
maybe<T>, result<T, E> |
A value that may be missing, or have failed (see Errors) |
- Conversions: a number widens to a larger type of its kind, and an unsigned integer to a larger signed one. Anything else needs
as:3.9 as i32is3. A reference converts as the value it refers to, so(&x) as u64, which would bexrather than its address, is refused: the address is&x as *u8 as u64. A reference written as one,&xor&mut x, is a pointer where one at its type is expected (see Pointers and memory). - Mixed operands: integers of different signs compare exactly. An integer and a float operate as the float. Signed and unsigned arithmetic needs
as. %on floats takes the dividend's sign, as C'sfmoddoes.- Booleans are not numbers: write
if count != 0.flag as u8is0or1. - Aliases:
type meters = f32;converts to and fromf32implicitly, and takes methods of its own. Arithmetic, bitwise operators, and shifts keep an alias their operands are written with, the right operand's where it is the number they operate as:a | bof twomask8s is amask8, with its methods, whilemask | u64is au64.
| Literal | Type |
|---|---|
42, 0xFF, 0o17, 0b101 |
i64, or the integer type expected |
0u, 0xFFu |
uint, or the unsigned type expected. It cannot be negated |
3.14, 6.02e23, 2.5f |
f64, or f32 with f |
'a', '\n', 'é' |
Its code point, a u32 |
"text" |
strview, or string where one is expected |
$"x = {x}" |
An interpolated string |
[1, 2, 3] |
A T[3], or a span<T> of itself where one is expected |
null |
Any pointer |
Escapes are \n \t \r \0 \\ \' \", \{ and \} in interpolation, and \xHH. Text between """ lines spans lines, with the indentation of the closing """ removed from each.
Arrays, references, and views
var bytes: u8[64]; # 64 zeroed bytes, held inline
const table: i64[4] = [10, 20, 30, 40];
val middle := table[1:2]; # a span<i64> of 20 and 30
def grow(xs: &mut vector<i64>): void { xs.append(9); }
var numbers := vector::<i64>::new();
grow(numbers); # referred to as though `&mut` were written
- Fixed arrays have a length known while compiling, and are values: assigning one copies it. Indexing outside one stops a checked program, and one that isn't reads or writes past it, as C does (see Checks).
a[start:count]is a view, aslice<T>of avararray and aspan<T>of avalone, and either end may be left out, asa[:]. A view is narrowed the same way, astext[2:], into a view of the same kind, and a range past its end stops a checked program. - References are never
null, and are read through, however deep, to what they refer to. They never stack:&of a reference is that reference, wherever it is held, and&mutof one writes where it does, as&mut heldof aheldanis some(&mut held)names. Assigning to one writes what it refers to, a reference's too, while avargiven a reference written as one,r = &mut y, refers elsewhere. - Where a value goes says what happens to it: a reference type lends it, and any other type gives it. Only
&or&mutwritten, or a reference parameter at a call, makes a reference, so a binding, a pattern, andfortake the value a reference reaches, copied where it closes nothing, as are a variable's and a field's:val x := v[i]andfor x in vcopy, whileval x := &v[i],for &x in v, andis some(&x)refer. What closes is refused rather than copied (see Closing, copying, and moving). A reference to a trait is taken as it is, since no value is of a trait. - Validity: a reference or view into memory that moves or is released, as a vector's elements do when it grows, or into a local whose function has returned, no longer refers to anything, as in C++. The checker warns where it is sure, and
run --checksstops where one is used (see Pointers and memory). - Views come from slicing, from containers (
v.view(),s.view()), and fromspan::<T>::over(data, length). Aslice<T>converts to aspan<T>, and==compares their elements. get(i)gives amaybeof the element at an index, ornonepast the end, on every view and container that is indexed, for an index that may be past the end in a program that is right.
Text
val plain := "hello"; # a strview of the program's own bytes
val owned: string = "hello"; # a copy, which `owned` owns
val built := $"{plain}, world"; # interpolation makes a string
println(built); # a string lends a view wherever one is wanted
A literal's bytes last as long as the program, followed by a zero byte, so they can be given to C. == compares two strings or two views. Comparing a string with a view needs .view().
Equality and order
== works on numbers, bool, enums, pointers, and fixed arrays of them, and on any type implementing equatable, as views, strings, and containers do. Floats compare by value, so 0.0 == -0.0. A reference compares what it refers to, and a pointer its address. < works on numbers, enums, pointers, and what implements ordered (see Operators).
Structs, unions, and enums
struct vec2 {
var x := 0f; # a default, type inferred
var y := 0f;
}
val a := vec2{}; # defaults and zero values
val b := vec2{1, 2}; # positional
val c := vec2{y = 8, x = 5}; # named, in any order
val vec2::zero := vec2{}; # an associated variable, read as `vec2::zero`
A val field cannot change once made. A generic type has no associated variables, since each instance would need its own: an alias of one instance has them, as val vec3f::zero. var pos: ...point { x as left }; spreads the fields of point into the struct, here renaming x.
A union holds one of its fields at a time, and knows which:
union reply<T> {
var error: i32;
var data: T;
}
var r: reply<strview> = 5; # holds `error`, the only field 5 fits
r = "fine"; # now holds `data`
if r is data(text) { println(text); } # names the field's value where the test holds
val held := r.data; # stops the program if `r` holds another field
- Making one: a value becomes the field it fits. Where it fits several, name the field:
reply::<strview>{ error = 5 }. - Testing:
r is dataandr is not data.is data(x)names the value wherever the test holds, as in its branch, on the right of&&, and in the first branch of? :, asm is some(v) ? v : 0.is not data(x)names it wherever the test failed, such as after anifthat leaves, or in the second branch of? :.&xor&mut xrefers to the field in place, and_names nothing, sois data(_)and an arm'sdata(_)take nothing out, asis datadoesn't.iswith a type asks the value's own type, som is nothingof amaybe, never true, is refused: write the field,m is none. - Referring:
&r.datarefers to a field only where what it refers to closes nothing, and&mut r.data, or&mutof anything within a field, never, since the union could hold another field before the reference is used. A test names it where it is held, asif r is data(&mut x). - Changing: assigning a field switches to it. A field cannot be changed in place.
- Size: a union of an empty field and a reference, a reference to a trait, or a function value, as
maybe<&T>, is no larger than the reference: it holdsnullfor the empty field.
An enum is a set of named integers:
enum color: u8 { red, green = 4, blue } # 0, 4, 5
enum level { low = -1, mid, high } # held as an i32 where no type is given
An enum converts to its integer implicitly, and an integer to an enum with as, which stops the program unless the integer is some member's value. Enums print as their member's name, and their zero value is the member whose value is 0.
Structs, unions, and enums all take methods, associated variables, and nested types.
Control flow
if n < 0 { ... } else if n == 0 { ... } else { ... }
val sign := n < 0 ? -1 : 1;
while running { ... }
for name in names { } # a reference to each element
for i, name in names { } # with its index
for &mut n in counts { n += 1; } # changing each in place
for i in 0..10 { } # 0 up to 9
for i in 1..=10 { } # 1 up to 10
for i in (0..10).rev().step(3) { } # 9, 6, 3, 0
for c in color::red..=color::blue { } # each member of `color` from red to blue
return "negative" if n < 0; # guards keep early exits flat
continue if name.length == 0;
break if i > limit;
- Assignments are expressions.
x++andx--give the value from before. forwalks fixed arrays, views, and anythingiterable, ascore's containers are:iter()lends aniterator, whosenext()gives amaybeof each element. It also walks any iterator, from where it is, so a loop that stops early leaves the rest for the next.for xtakes a copy of each element,for &xrefers to it, andfor &mut xwrites it in place. What a loop's iterator gives by value, as eachstringoffor line in input.lines(), is the pass's own, closed where that pass ends.- Ranges are values:
a..banda..=barecore'srange<T>of the integers their ends are, or of the type expected, asval r: range<u8> = 0..9;or arange<u64>given for aniterator<u64>. A loop counts through one written in place without making it. Members of one enum make a range of its members, given in the order of their values, each value once and those no member has passed over, socolor::red..=color::bluegivesred,greenandblueofenum color: u8 { red, green = 4, blue }. Within a generic, the ends may be anyordinaltype parameter, which one bounded byintegeris.
Iterators take adapters, which make an iterator of another, and consumers, which walk one to its end. Each is compiled for the iterator it is called on, so a chain of them over a view runs as fast as the loop written out:
val total := v.iter().copied().filter(def(x) => x % 2 == 0).map(def(x) => x * x).sum();
val parts := line.split(',').to_vector(); # text is split as it is walked
for p in names.iter().zip(scores.iter()) { println($"{p.first}: {p.second}"); }
val longest := words.iter().max_by_key(def(w) => w.length) else { return; };
The adapters are map, filter, filter_map, enumerate, zip, chain, take, skip, take_while, skip_while, step, rev, peekable, flat_map, copied, and inspect; the consumers count, sum, product, fold, reduce, any, all, find, position, min, max, min_by, max_by, min_by_key, max_by_key, last, nth, for_each, to_vector, to_string(between), and into(&mut target), which appends to anything extendable. An adapter moves what it is called on into what it makes. rev is there for what walks from its far end, a backward_iterator, and sum for numbers.
match runs the first arm that fits. A union's arms name fields, an enum's name members, and anything else's list values. Matching a union or enum must cover every case, or end with else:
match held {
number(&mut n) => n += 1;
text(t) => println(t);
else => return;
}
val label := match c { red => "stop", green, blue => "go" };
Errors
A mistake in the program stops it, as indexing past the end does. What can go wrong in a correct program, such as a missing file, is a value: a result<T, E> holding its value or its error, or a maybe<T> holding some or none.
enum parse_error { empty, not_a_number }
def parse(text: strview): result<i64, parse_error> { ... }
val port := parse(arg) else 8080; # a value in its place
val n := parse(text) else (e) { return e; }; # a block that leaves, naming the error
if parse(text) is not value(v) { return; } # `v` is named from here on
val wide := big ? parse(text) else 0 : 1; # `else` within the branch `:` ends
val doubled := parse(text).map(def(n) => n * 2); # a result of what `map` makes of the value
result is @nodiscard, so dropping one is an error, and _ = parse(text); drops it on purpose. @nodiscard marks any function or type this way.
A result<void, E> says only whether something failed. return; gives its value, and a block after else may end rather than leave, since there's no value to stand in for: io::write_file(at, text) else (e) { warn(e); };.
A value that closes has one owner, so else takes over what a call made, but not what a variable holds, nor a union's field, whose union still closes it: name it in place with is value(&v), then copy or move it by name.
Both have methods for what else and is don't say as briefly:
- Asking:
is_someandis_noneof amaybe, andis_okandis_errof aresult, are properties.is_some_and(test),is_ok_and(test)andis_err_and(test)test what it holds too. - Reading:
unwrap(),expect(why)andunwrap_or(fallback)give the value, and aresult'sunwrap_err()andexpect_err(why)its error, stopping the program where it holds none. From what can be written they move it out, asmovedoes, so one holding what closes is left empty. From what is only read they copy it, which a value that closes refuses.unwrap_or_else(make)calls a function only where there's no value. - Making others: a
maybe'smap,and_then,filter,or,or_elseandok_or(error), and aresult'smap,map_err,and_then,or_else,to_maybeanderr_to_maybe, move what it holds into what they make, as an iterator's adapters do.as_ref()andas_mut()lend what it holds to them instead.take()empties amaybe, andreplace(value)puts another value in, each giving what it held. - Comparing: both compare with
==, hash, and copy where what they hold does. Aresultwhose value and error are of one type tells them apart.
Faults
A fault stops the program with a trace and exit status 1: every program's at null reached through and dividing by zero, and a checked program's at an index out of bounds and the like, as run's is (see Checks):
sakura: runtime error: Index or slice is out of bounds.
at pick (trap.sakura:5:12)
at main (trap.sakura:11:18)
A program stops itself the same way with fault(why), whose text the report gives, as the containers do where they're asked for what they don't hold: sakura: runtime error: The deque is empty.
Contracts
expects, asserts, and ensures are what a program promises itself: what a function needs of what it's given, what holds as the work goes on, and what holds where a block is left.
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;
}
- A contract that fails is a fault, with the trace and status
1:sakura: runtime error: A pre-condition failed: b != 0, with b = 0.A second argument, astrview, says what failed in place of the condition. Only a contract that fails makes its report, so one that holds costs its condition and a branch. ensuresis checked on every way out of its block once it's been reached: eachreturn, abreakorcontinueleaving the block, and the block's end, the last written first. In a function's own block,ensures(r: ...)names what the function returns, and within anyensures,old(e)is whatewas where it was reached, of a type that closes nothing.--contracts off, forrun,build, andcheck, leaves every contract out, conditions and all: the executable is byte for byte the one built from the source without them. So a condition changes nothing it names, by=,+=,++, or the like.contracts()is a constant, true where they're checked, soif const contracts()keeps work only they read.- In a constant, a contract that fails is reported where the constant is:
Evaluatinghstopped: An assertion failed: n % 2 == 0, with n % 2 = 1. - The words are names elsewhere:
t.expects(x)calls a method, and a field may be namedensures. Only at a statement's start, before(, is one a contract.
Contracts are apart from the checks a checked program makes: --contracts off leaves them out, and nothing else does.
Checks
A program is checked or it isn't, as a debug and a release build: run checks unless --fast, and build doesn't unless --checks.
- A checked program stops at an index or a range past the end, of a fixed array, a view, or a container; at a union's field read where it holds another; at an integer converted to an enum none of whose members has its value; and at a
matchfinding no arm. Each is a fault, saying what went wrong and where. std's containers check what they're asked for alike, as the front of one that's empty, or a key adictdoesn't hold. - One that isn't does none of that, and reads and writes where the program said, as C does. An index that may be past the end in a program that is right is asked of
get(i). - Every program stops at
nullreached through, at a division by zero, and as its stack runs out. The processor faults at the first two itself, and the runtime reports them as a check would, so they cost nothing where they hold. Only a checked program compares a pointer withnullwhere it reaches past the first page of memory. checking()is a constant, true where the program checks, soif const checking() { ... }checks only there, as std's containers do. In a constant, the checks are always made.sakurac check --checks-reportlowers the program checked and optimized, and lists the checks the optimizer couldn't leave out, in the program's own functions, a line of the source each, with how many of each kind: where an unchecked build trusts the program. A check inlined from std, as avector's index, is listed at the line calling it.
Functions
def add(a: f32, b: f32): f32 { return a + b; }
def greet(name: strview = "world", mark: strview = "!"): void { # defaults run at each call
println($"Hello, {name}{mark}");
}
def sum(xs: i64...): i64 { # variadic: `xs` is a span<i64> of the arguments
var total: i64 = 0;
for x in xs { total += x; }
return total;
}
sum(1, 2, 3); # 6
sum(...numbers); # a view or fixed array given as all of them
- Parameters belong to the function, which may change them. One that closes is closed where the function returns, unless it is returned.
- Overloads differ in their parameters. The best fit wins: an exact type, then a constant converting, then any other conversion, then becoming a union. A function that isn't generic wins a tie against one that is.
- No body: a function ending at its signature is given by the compiler,
@intrinsic, or by C, in anextern module(see Calling C). - Returning what gives nothing: a function giving nothing may
returna call that gives nothing, so generic code returns what a call gives,return f(x);, whatever that is.
Functions are values: named functions, static methods, and methods and properties taken through their type, as vec2::length, or rect::area, whose value is its get, a def(&rect): f32. A generic function, or a member of a generic type, named without its type arguments takes them from the function type expected, or from a parameter's invokable bound, as val empty: def(&vector<i64>): bool = vector::is_empty; takes vector<i64>'s. Where those don't give them all, they're written, as integer::parse::<u64>. A named function given where a function type it doesn't match is expected, as a type or a bound, is called as that type asks by a function made for it, which the optimizer inlines: each parameter is given to it as a call gives an argument, lent where it takes a reference and read through where it takes what one reaches, the parameters left over take their defaults, and among overloads the one such a call chooses is called. So words.iter().map(path::parse) gives each &strview to a parse(text: strview, alloc: maybe<&mut allocator> = nothing {}), and a method taking &mut this, given where each value is given away, as map gives them, is lent each one, which is closed after. Anonymous functions may leave out types where a function type is expected, or where they are given for a parameter bounded by invokable<def(A...): R>, as xs.iter().map(def(x) => x * 2), and => value returns the value. One whose parameters' types are all written has a type of its own, which gives the type parameters of what it's given for, where an overload is chosen among others too, as T of test: def(&T): bool. They refer to the locals they use where those are, so they see and change them, and must not outlive them:
var total := 0;
items.iter().for_each(def(x) { total += x; }); # changes `total` itself
val doubled := def(x: int) => x * 2;
A function value is the code and what it refers to, and owns nothing. One holding state past the function making it, as a counter returned, is a struct implementing invokable, as below. A function is never null. Functions can also be declared inside a block. A variadic function's value is of a type written with ..., as def(i64...): i64, and is called as the function is, f(1, 2, 3) or f(...xs).
Calling values: a value whose type is no function is called through its invoke, so f(1, 2) is f.invoke(1, 2), by the rules of a method's call: the overloads are chosen between, and one taking &mut this is called on what can be written. A function value and the address of a C function have an invoke the compiler gives them, so generic code bounded by invokable takes them and callable values alike:
struct counter : invokable<def(i64): i64> { var total: i64; }
def counter::invoke(&mut this, by: i64): i64 { this.total += by; return this.total; }
def twice<F>(f: &mut F, x: i64): i64 where F: invokable<def(i64): i64> { return f(f(x)); }
var c := counter{};
c(5); # counter::invoke(&mut c, 5)
twice(&mut c, 1);
var g := def(x: i64): i64 => x * 2;
twice(&mut g, 1); # 4
Holding any callable: function<def(T): R>, of core, holds one callable of a signature, whatever its type, and owns it: a functor, a named function, a lambda, or a method taken through its type. A list holds callables of different types so, and a functor is kept without naming its type:
struct tally : invokable<def(&event): void> { var seen: u64; }
def tally::invoke(&mut this, e: &event): void { this.seen++; }
var handlers := vector::<function<def(&event): void>>::new();
handlers.append(function::new(tally{}));
handlers.append(function::new(def(e: &event) { println(e.name); }));
for &h in handlers { h(&e); }
- A callable of up to 24 bytes is held in the
functionitself, and a larger one in abox. A call goes through one table of what the held type does. - It's moved, never copied. Its zero value holds nothing, which
holds()says, and calling it then stops the program.get::<F>()lends what it holds where that is anF. - Holding a lambda, it refers to what the lambda refers to, so it must not outlive those locals. What must outlive them is a functor.
- It is no constant: a constant would keep the words of what it holds, but not the function a function value among them is.
Methods and properties
Methods are declared outside their type, in any module, for any type, the built-in ones included. One taking &this or &mut this is called on a value, and any other is static:
def vec2::length(&this): f32 { ... }
def vec2::of(x: f32, y: f32): vec2 { ... } # called as vec2::of(1, 2)
def u8::is_upper(&this): bool { return this >= 'A' && this <= 'Z'; }
val rect::area: f32 { # a property, read like a field
get => this.width * this.height;
}
var rect::size: vec2 { # one written too
get => vec2{ this.width, this.height };
set { this.width = value.x; this.height = value.y; }
}
- Generic types name their parameters, as
def stack<T>::push. A method can't be declared for one instance, which is why text's methods are onstrview. &thisand&mut thismay overload each other. A writable receiver calls the second.- Bounds of their own: a method of a generic type may bound the type's parameters, as
def bag<T>::sum(&this): T where T: numeric, and belongs only to the instances meeting them, which then satisfy the traits asking for it. - Properties are
valwith aget, orvarwith asettoo, of any type butvoid. An accessor's parameters are implied: agethasthis, as&this, and asethasthis, as&mut this, andvalue, of the property's type. Its body is a block, or=> expression;, which agetreturns and asetdoes, asset => this.w = value;. A trait asks for a property with{ get; }or{ get; set; }.pub getorpub setgives one accessor visibility of its own.valueis a name only within aset. - Nested types are declared and named through another type, as
list<T>::cursor. A field may share its name with one, since the field is reached through a value and the type through its type:struct token { var kind: token::kind; }. - Names within a type: within a type, and what is declared through it, its nested types and associated variables, and an enum's members, are named without the type, as
cursorwithinlist<T>islist<T>::cursor, given the sameT. In a type, only its types are meant, so an enum's memberu8leavesu8the type. A type's functions are still named through it, since they are often named for the free functions they implement, asvector<T>::decodecallsdecode::<T>. - Indexing: a type implementing
indexable<K, V>, byat(&this, key): &Vand optionallyat(&mut this, key): &mut V, supportsx[key], which isx.at(key): the reference it gives, read, written, and bound as any reference is.
Traits
A trait lists methods, and any type with them satisfies it, whether or not it names the trait. A trait bounds a generic, which is compiled for each type, or is the type of a reference, which calls through a table at run time:
trait clickable {
def clicked(&mut this): void;
}
struct button : clickable { var label: strview; } # naming the trait is optional, but checked
def button::clicked(&mut this): void { println($"clicked {this.label}"); }
def press(target: &mut clickable): void { target.clicked(); }
- Default methods have a body, which types naming the trait take as their own.
@optionalmethods may be left out. In a trait that is only a bound, each default is compiled for each type implementing the trait, withselfthat type, so it calls the type's methods directly and may be generic, asdef map<U, F>(&mut this, f: F): mapped<T, U, self, F> where F: invokable<def(T): U>. In any other, a default is compiled once and calls through the table. - Bounds of a method: a method of a trait may bound the trait's parameters or
selfbeyond what the trait does, asdef sum(&mut this): T where T: numericordef rev(&mut this): reversed<T, self> where self: backward_iterator<T>. Only the types meeting them have it, and the bounds hold within its body. - Composition:
trait shape : named, sized { ... }asks for what both ask for. - Generic traits, as
trait into<T>, are a trait for each type argument. - Static methods and constants describe the type, and are reached through a bounded parameter, as
T::top(). - Functions of its own are declared through it, outside it, as
def real::parse<T>(text: strview): result<T, failure>, and named through it, asreal::parse::<f64>(text). The trait doesn't ask for them and what implements it doesn't take them, so they take nothisand may be generic. selfis the type implementing the trait, asdef copy_of(other: &self): self;.- Types a trait asks for, as
type cursor: iterator<&T>;, are given by each implementer and named through a bound, asC::cursor. A trait namingself, asking for types, or with generic methods or methods bounding its parameters orself, asiterator<T>, is only a bound. - References satisfy the traits of what they refer to, except
owning, and those whose methods make or take aselfby value:numericand the traits it composes,copyable,moveable,integer,real,ordinal, andzeroable. - Pointers satisfy
equatable,ordered, andhashableby address,zeroable, andpointer. - Built-in types are
equatableandhashable, numbers, enums, and pointersordered, and numbersnumeric, with every trait it composes. Function types andcfn<def(...): R>aresignature, andinvokableof their own type. - Receivers: a method taking
&thismeets one a trait asks for taking&mut this, since what can be written can be read. - Calling:
invokable<def(Ts...): R>asks forinvoke(&mut this, args: Ts...): R, which a call of the value calls (see Functions).signatureis every function type, namingF::resultand the pack of its parameter types,F::params.
Operators
A struct or union has each arithmetic and bitwise operator by the method that gives it, as it has == by equals:
| Operator | Method |
|---|---|
a + b, a - b, a * b, a / b, a % b |
add, sub, mul, div, rem |
-a |
negate |
a & b, a | b, a ^ b, ~a |
bit_and, bit_or, bit_xor, bit_not |
a << b, a >> b |
shift_left, shift_right |
a += b and the others |
add_assign and the others, changing a in place, where a's type has one taking b; otherwise the operator's method, whose result is written over a |
a == b, a != b |
equals, by implementing equatable |
a < b, a <= b, a > b, a >= b |
compare, giving a negative number, zero, or a positive one, by implementing ordered |
An arithmetic operator is a call of its method on the left operand, given the right one by reference, so the method says what the operands are and what the operator gives:
struct duration { var ns: i64; }
def duration::add(&this, other: &duration): duration { return duration { ns = this.ns + other.ns }; }
def duration::mul(&this, by: &i64): duration { return duration { ns = this.ns * by }; }
struct instant { var ns: i64; }
def instant::add(&this, by: &duration): instant { return instant { ns = this.ns + by.ns }; }
def instant::sub(&this, since: &instant): duration { return duration { ns = this.ns - since.ns }; }
val waited := now - started; # a duration
var due := started + waited * 2; # `2` is taken as the `i64` the method asks for
due += waited; # `add` gives an instant, written over `due`
- Each operator alone: a type with only
addhas+and nothing else. Keeping its operators consistent is the type's own job. - Overloads are chosen by the right operand, as a call chooses, so a type may add a
durationand subtract either adurationor aninstant. - The method's shape is
def T::add(&this, other: &B): R, anddef T::negate(&this): Randdef T::bit_not(&this): R, with no type parameters of its own. - A number on the left asks its own type, so
2.0 * vcalls a program'sdef f64::mul(&this, v: &vec2): vec2. A method a program declares on a number stands beside those the compiler gives it. - Compound assignment calls
add_assign,sub_assign, and the rest, asdef T::add_assign(&mut this, other: &B): void, where the type has one taking the value, so a type owning memory grows in place. Otherwise it isa = a + b, so what the method gives isa's own type. - Comparisons stay between two values of one type. Integers give
bit_andand the rest as methods too, a shift taking how far as a&u32, so a bound asking for them is met by integers as well as by a program's types. - Numbers operate as the language does, and never call a method.
core names the methods as traits, for generic code to ask for, each satisfied by any type with the method:
| Trait | Asks for | Gives a type parameter |
|---|---|---|
addable, subtractable, multipliable, divisible, modular, negatable |
add, sub, mul, div, rem, negate, each between values of one type |
+, -, *, /, %, -x |
additive |
addable, subtractable, negatable, and equatable |
+, -, -x, == |
multiplicative |
multipliable and equatable |
*, == |
numeric |
additive, multiplicative, divisible, and modular |
All of arithmetic, and constants |
A program composes its own, and any bound asking for an operator's method gives the operator:
trait scales<S> : additive { def mul(&this, by: &S): self; }
def lerp<V, S>(a: V, b: V, t: S): V where V: scales<S> { return a + (b - a) * t; }
lerp(1.0, 3.0, 0.5); # f64 scales by an f64
lerp(vec2 { x = 0, y = 0 }, vec2 { x = 2, y = 4 }, 0.5); # vec2::mul(&this, by: &f64)
Asking: x is shown and T is integer are decided while compiling, and a branch they guard gets the bounds they proved:
def tell<T>(x: &T): string {
return "?" if const x is not shown;
return x.show();
}
Generics
Functions, structs, unions, aliases, traits, and methods take type parameters. Each use compiles an instance for its types, which is only made where the program uses it:
struct stack<T> { var items: vector<T>; }
def stack<T>::push(&mut this, value: T): void { this.items.append(value); }
def largest<T>(a: T, b: T): T where T: ordered { return a > b ? a : b; }
var s := stack::<i64>{ items = vector::<i64>::new() };
val big := largest(3, 7); # T is inferred
- Type arguments are written
<>in types and::<>in expressions, so a lone<is a comparison. - Inference reads the arguments, the result type expected, struct literals' fields, bounds, and the lengths of fixed arrays, and for a function named as a value, the function type expected of it. A parameter of a type parameter's own type takes the value an argument is, so
largest(v[0], v[1])gives ani64rather than a reference intov, andmath::sqrt(xs[i])takes af64, whilef(&x)givesTthe reference. - Checking: a generic is checked against its bounds. Errors only an instance has, such as
x + 300whereTisu8, name the instance. - Bounds are written one
wherefor each parameter:where T: shown where U: shown, equatable.
| Bound | Allows |
|---|---|
| a trait | Its methods, and &T as a reference to it |
equatable, ordered |
Their operators |
numeric |
Arithmetic, with constants and as between numbers |
additive, multiplicative, addable and the rest |
The operators their methods give (see Operators) |
integer |
Bitwise operators, shifts, and indexing, with what numeric, ordered, ordinal, and zeroable allow |
real |
What numeric, ordered, and zeroable allow, with float constants. f32 and f64 are real, and the functions of std::math ask for it |
ordinal |
Comparing, as to and from integers, and ranges. Integers and enums are ordinal, as is a type parameter bounded by integer |
zeroable |
A zero value, as var made: T; |
pointer |
Moving and subtracting by elements |
closeable |
Nothing more. Generic code asks it, as if const T is closeable: whether values are closed |
signature |
F::result, the pack F::params, and calling a value of it, as f(...args) where args: F::params... |
The compiler decides integer, real, ordinal, zeroable, pointer, closeable, and signature, and no other type implements them.
Constant parameters stand for values each instance is given while compiling:
struct buffer<T, const N: u64> where T: zeroable { var items: T[N]; }
def buffer<T, N>::capacity(&this): u64 { return N; }
def grown<T, const N: u64>(xs: &T[N], last: T): T[N + 1] where T: zeroable {
var out: T[N + 1];
for i, x in xs { out[i] = x; }
out[N] = last;
return out;
}
val ys := grown(&xs, 4); # N is the length of xs
Their type is any that closes nothing. They are given literals, constants, enum members, functions, and literals and arithmetic of those, and equal values are one instance.
Packs take a type for each argument of a function's variadic parameter:
def show_all<Ts...>(args: Ts...): string where Ts...: shown {
var out: string = "";
for const x in args { out.append(x.show()); } # the body, once for each argument
return out;
}
A pack is used by for const, args.length, args[i] with i known while compiling, and f(...args), which moves the values that close to the function given them, leaving the pack empty, as move would. The pack of types has a length too, Ts.length. A function type takes one too, as def(Ts...): R. Structs, unions, and traits take a pack last, which the type arguments after those before it fill, and Ts... passes one on whole:
trait sink<Ts...> { def put(&mut this, args: Ts...): void; }
struct log<Ts...> : sink<Ts...> where Ts...: shown { var lines: vector<string>; }
var l := log::<i64, bool>{ lines = vector::<string>::new() };
l.put(1, true);
A pack is only the type of a variadic parameter, never of a field or variable, and a type alias takes none.
Pattern parameters take a function type or a fixed array and name its parts, on a struct, union, or trait. trait invokable<def(Ts...): R> is written invokable<def(i64, bool): u8>, which gives Ts the pack (i64, bool) and R the type u8:
struct functor<def(Ts...): R> : invokable<def(Ts...): R> where R: zeroable { var hits: i64; }
def functor<def(Ts...): R>::invoke(&mut this, args: Ts...): R {
this.hits++;
var out: R;
return out;
}
var f := functor::<def(i64, bool): u8>{};
_ = f(1, true);
- Names before a pack take a parameter type each, as
Aofdef(A, Rest...): R, and a pattern without a pack takes exactly as many. - A variadic function's pack ends in what its last parameter takes, so
invokable<def(i64...): i64>asks for a variadicinvoke, and within a function given one, the pack's last value is a view of the rest. - A type parameter bounded by
signatureis given whole, asinvokable<F>, namingF::paramsandF::result. Only a patterndef(Ts...): Rtakes it, since its parameters are not known. L[N]takes a fixed array, naming its element's typeLand its lengthN, a constantu64, asstruct simd<L[N]>is writtensimd<f32[4]>. A method names it in its receiver, asdef simd<L[N]>::sum(&this): L, and a function takes the parts, asdef first<L, const N: u64>(v: &simd<L[N]>): L, which inference gives them.
Closing, copying, and moving
A type naming owning is closed where its value's scope ends, so what it holds is released without a call written by hand:
pub struct buffer : owning {
var data: *mut u8;
var size: u64;
}
pub def buffer::close(&mut this): void {
raw_release(this.data);
this.data = null;
}
def work(): void {
var b := buffer::new(64);
fill(b);
} # b.close() runs here
- When: on every way out of the scope, in reverse order of declaration. A temporary closes where its statement ends, and a value written over closes after the new one is made. Fields close after their value's own
close. - Which: a type is
owningonly by naming it. A type whose values are closed, by beingowningor holding what is, iscloseable. - Returning hands a local to the caller instead of closing it.
- One owner: a value that closes is never copied implicitly. Wherever one goes that isn't a reference, as
val b := a;,take(a), a field,a = b,for x in v, oris some(x), a place holding it is refused, so it is referred to, returned, or copied or moved by name. A new value, as a call gives, is moved where it goes. - References and pointers own nothing, so they never close what they reach.
Copying and moving are explicit, through copyable and moveable:
var a := string::from("hello", nothing{});
var b := string::copy_of(&a); # a second string, with memory of its own
var c := string::move_of(&mut b); # b's memory, leaving b empty but valid
val d := copy(a); # the same, through `core`'s generic helpers, which a call lends `a`
val e := move(c);
copy copies anything that closes nothing byte for byte. close(x) closes a value where it stands, as its scope ending would: its own close, then its fields, and leaves it empty, so a box and a container close what they hold whole. A value moved from is left empty, and closed as usual where its scope ends.
Compile time
Constants
Any function can run while compiling where a constant calls it, unless it reads a global variable, calls C, or turns an address into a number:
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();
- Constants hold numbers,
bool, enums, functions, read-only pointers and references, and arrays, structs, and unions of those, so aspan<T>works and astringdoesn't. They may use each other in any order. - Memory built while compiling is kept where a constant still points into it, as read-only data. A constant may also point into another constant, as
const odd: span<u64> = primes[1:4];or&primes[4], which shares that constant's memory rather than copying it. - A fault while evaluating is reported at the constant, with a trace.
const defpromises a function can run while compiling.
Choosing code
if const keeps only the branch its condition chooses while compiling, and that branch gets the bounds the condition proved. Where the condition says a type parameter is a type, as T is strview, the branch takes the parameter as that type: each instance taking it checks it so, and what it says of T is noted there:
def describe<T>(x: T): string {
if const T is integer {
return $"{x + 1} is {size_of::<T>() * 8} bits";
}
if const T is strview {
val text: strview = x;
return $"{text.length} bytes of text";
}
return "something else";
}
T is X is exact: an alias is a type of its own, so strview isn't span<u8>.
for const i in 0..n counts through a range whose ends are known while checking, a copy of its body for each number, or each member of an enum, in which i is a constant, so if const decides by it and a fixed array may take its length from it. It unrolls at most 1024 numbers, and within a generic waits for each instance where an end depends on it:
def lanes<const N: u64>(): void {
for const i in 0..N {
if const i % 2 == 0 { even(i); } else { odd(i); }
}
}
if const and for const read constants, and if const also what functions give of them, as if const twice(count) == 6. A condition the checker can't work out itself, as one calling a function given text, as if const named(name_of::<T>()), is worked out by running it once checking is done, so both its branches are checked, and only the one it chooses is compiled, which reports any compile_error it holds.
when keeps declarations or statements only for some targets. Its keys are os (linux, macos, windows, freebsd), arch (x86_64, aarch64), and backend (vm, native), and an unknown key or value is an error. run and check target the system running sakurac, with the vm backend, and build and check --target an executable's, linux-x86_64 or windows-x86_64, with the native backend. module system when os == linux; limits a section of a file the same way:
when os == linux {
def config_dir(): strview { return ".config"; }
}
else when os == macos {
def config_dir(): strview { return "Library/Application Support"; }
}
Attributes
An attribute is a struct literal after @, worked out as a constant, of a struct implementing attribute. @usage says what it may be written on:
@usage{ on = target::functions | target::constants, many = false }
struct check : attribute { val skip: bool = false; }
@check def adds(): bool { return 1 + 1 == 2; }
@check{ skip = true } def later(): bool { return false; }
The compiler itself reads only @usage, @optional, @nodiscard, @allow, @intrinsic, and @inline.
@inline copies a function's body wherever it's called, at every level, -O0 too, whatever its size against --inline N: a small function a loop calls costs no call even in a build for debugging, where the copy's locals keep cells of their own and debuggers show it as a frame of its own. On a property, it marks both accessors. A call it can't copy stays a call: one through a trait reference, or through a function value the optimizer can't follow, and the call closing a loop of calls, as a function calling itself. A function C or the compiler gives has no body to copy, so it's never @inline, and neither is a trait's method, which each type gives its own of. run --checks copies nothing, so each function's locals end where its frame does. core's word tests, as bytes8::zero, and byte tests, as u8::is_space, are @inline:
@inline def is_blank(byte: u8): bool { return byte == ' ' || byte == '\t'; }
def indent(line: strview): u64 {
var at := 0u;
while at < line.length && is_blank(line[at]) { at++; } # no call, at -O0 too
return at;
}
call_site(), source_of(cond), and values_of(cond) describe the code calling them. As defaults, they describe the caller, which is how t.expects(b != 0) reports b != 0 and its values.
Reflection
A program reads its own declarations while compiling. for const checks its body once for each, and value_of(d) and x.(d) reach what d declares:
def run_checks(): void {
for const d in declarations() {
if const attached::<check>(d).length == 0 { continue; }
if attached::<check>(d)[0].skip { continue; }
println($"{d.name}: {value_of(d)()}");
}
}
def show<T>(x: &T): void {
print(name_of::<T>());
for const f in members_of(decl_of::<T>()) {
if const f.kind == target::fields { print($" {f.name}={x.(f)}"); }
}
println("");
}
The intrinsics are declarations(), decl_of::<T>(), members_of(d), owner_of(d), params_of(d), attributes_of(d), attached::<A>(d), name_of::<T>(), path_of::<T>(), value_of(d), type_of(d), and compile_error(text, at). name_of spells a type as notes do, as &mut position, and path_of with the module of each type it names, as &mut game::position, which no two types share. decl_of takes a type a declaration makes, so not a reference or a number. A module reaches what it could name, and declarations carrying its own attributes, so writing @check on a private function lets the module owning check call it. x.(f) reaches any field of the value it is given, pub or not, as reflection reaches what it was given. compile_error's text may be worked out while compiling, as $"{f.name} is not read", and at places the error, as f.at places it at the field.
Pointers and memory
Memory is owned as C++ owns it, by values the program can see: what a value holds is released where its owner closes it (see Closing, copying, and moving). References, views, pointers, and function values own nothing, and keep nothing alive. &x is x's address, wherever x is, and a local lives as long as its scope; a temporary referred to lives to the end of its statement, or as long as the name it is bound to, as val p := &point{ x = 1 };.
The heap's owners are box<T>, core's, rc<T> and arc<T>, std::containers', the containers and string, arenas and pools, and raw blocks:
struct node { var value: u64; var next: maybe<box<node>>; }
var front: maybe<box<node>> = nothing {};
for i in 0..3u { front = box::new(node { value = i, next = move(&mut front) }); }
var settings := rc::new(config{ depth = 2 });
var also := copy(&settings); # counted: the last copy to close closes it
val watching := settings.weak(); # lock() gives an owner while one is left
box<T>owns one value alone, as C++'sunique_ptrand Rust'sBox. It is one word that is never null, somaybe<box<T>>is one word too.getlends the value, andtakemoves it out.rc<T>owns one value with every copy of it, counting them plainly, for one thread;arc<T>counts them atomically, for values shared between threads.rc_weak<T>andarc_weak<T>refer to the value without keeping it.
Raw pointers are for memory a program manages itself, such as arenas and tables. They aren't checked, except that reaching through null stops the program:
struct node {
var name: strview;
var next: *node;
}
val nodes := raw_allocate_zeroed(16 * size_of::<node>()) as *mut node;
nodes[0].name = "first";
nodes[1] = node{ name = "second", next = nodes };
val second := nodes + 1; # moves by whole elements
println((*second).next[0].name); # first
raw_release(nodes as *mut u8);
p[i]is the elementialong,*pisp[0], andthrough(p)is a reference to it. A pointer is an address, so nothing is reached throughp.itself.p + nandp - nmove by elements, andp - qcounts them.p[start:count]is a view.- Taking an address is always written. A reference written as one is a pointer where one is expected,
&xa*Tand&mut xa*mut Tor a*T, asval p: *mut node = &mut n;orlook(&x)for a*Tparameter, andaddress(x)gives one,*mut Tfor what can be written and*Totherwise, asthrough(p)gives a reference. A pointer keeps nothing alive, so one at a value that ends with its statement, asval p: *i64 = &10;, is refused, though an argument lives as long as its call. A pointer becomes a reference only throughthrough. *mut Tconverts to*T, never the reverse.asconverts pointers to and from integers and other pointer types, and&x as *Ttakes an address as a pointer of any type.
| Function | Does |
|---|---|
raw_allocate(size) |
Memory that isn't zeroed, holding anything at first, as C's malloc |
raw_allocate_zeroed(size) |
Zeroed memory, as C's calloc: memory the system gives fresh is zero already, and isn't cleared again |
raw_resize(p, size), raw_release(p) |
Resizes or releases a block |
size_of<T>(), align_of<T>() |
The size and alignment of a type |
Allocators: each container takes an optional allocator, and uses the program's heap where it is given none. An arena, std::allocators', hands out memory from large chunks, and takes it back all at once, or back to a mark():
var scratch := arena::new();
val alloc: maybe<&mut allocator> = &mut scratch;
val point := scratch.mark();
var seen := vector::<u32>::new(alloc); # its memory is the arena's
seen.append(4);
seen.close();
scratch.rewind(point);
A pool, also std::allocators', hands out blocks of one size, taking each back to hand out again, for values made and released often: pool::of::<node>(), then make(value) gives a *mut node and unmake(p) closes it and takes it back. A list or other container given one holds a node in each block.
Lifetimes: a reference used after what it refers to ends is the program's mistake, as in C++. The checker warns where it is sure one outlives its referent: a function returning a reference to its own locals, or a function value, literal, or alias holding one; a reference to a local written into a global, through a parameter, or into a local of an outer scope; and a temporary kept past its statement. Warnings never stop a check, run, or build, and @allow on a function quiets them, where it is right for reasons the checker can't see.
Checked runs: sakurac run --checks checks every read and write through a reference or pointer, and stops where the program holds no memory there: a dangling reference, a block used after its release or past its end, or a block released twice. Released blocks are held back for a while, so a late use still finds them released. As the program ends, it lists the blocks it allocated that nothing it keeps reaches, by where each was allocated. Memory the program was given rather than allocated, as what it maps from the system, its arguments, and its variables, is held too, what it maps until it gives it back. Where code of its own calls C, memory the machine doesn't know is taken as C's from then on, but for what it mapped and gave back; system's own calls of C, which it's made of on Windows, don't count. Its code is optimized no more than -O1 would, since inlining may leave out the frames a dangling reference refers to.
It stops at a read of memory nothing wrote, too: of a block raw_allocate gave, the bytes raw_resize added, or a variable undefined, until each byte is written. Copying such bytes, as moving a block does, isn't reading them, and memory the system or C is given the address of counts as written. An executable can't check memory: build --checks makes the checks of Checks alone.
Calling C
C's functions, structs, and unions are declared in an extern module, a section of a module that says which systems it's for, and extern import names the library they're found in:
extern import "libc.so.6" when os == linux;
extern import "ucrtbase.dll" when os == windows;
extern module clib when os == linux || os == windows;
pub struct quotient { pub var quot: i32; pub var rem: i32; } # laid out as C's
pub def strlen(text: *u8): u64; # C's: it has no body
pub def div(a: i32, b: i32): quotient;
pub def qsort(base: *mut u8, count: u64, size: u64, compare: cfn<def(*u8, *u8): i32>): void;
pub def length_of(text: strview): u64 { return strlen(text.data); } # ordinary Sakura of `clib`
import clib;
def compare(a: *u8, b: *u8): i32 { return (a as *i32)[0] - (b as *i32)[0]; }
def main(): void {
var xs: i32[3] = [3, 1, 2];
qsort((&mut xs) as *mut u8, 3, 4, compare); # C calls `compare` back
val length := length_of("hello"); # 5: literals are followed by a zero byte
}
- A section's
whenis required, and namesos,arch, or both, since a library is one system's, and so is C's calling convention. A section forarchalone suits only libraries whose types are the same size on every system: C'slongis 64 bits on Linux and 32 on Windows. - In a section, a function with no body is C's, by its own name, and never generic, overloaded, or a method. A struct is laid out as C's, of fields that cross, and never generic. A union is C's: every field begins where it does, and nothing says which it holds, so
isandmatchcan't ask. Everything else, functions with a body included, is ordinary Sakura of the module. Outside a section, a function with no body is@intrinsic. - Libraries: a C function is found in the libraries its file's
extern imports name for the target, and anextern importmay have awhenof its own, so one file names a library as each system does. An executable for Linux needs every one. One for Windows lists each function under its library, so a file names one there. A file naming none finds its functions in the running process, which only the VM has: on Windows,sakurac.exeitself, then every DLL loaded into it butntdll.dll. - Calling back: a function of the program given where a
cfn<F>is expected is the address of an entry C calls it back through. It's never generic or a method, and a lambda can't be one, since C gives it no way to reach what the lambda refers to. The entry stops the program unless it's called while the program is in a call of C. - The VM calls C on Windows, which its
systemis made of there. On Linux it reaches the system through system calls, and calls no C, so a program calling C is built instead. - C functions can't run while compiling. Only types C lays out alike cross: numbers,
bool, enums, pointers,cfn<...>, and structs and C's unions of them, with&Tas a C function's parameter.
The standard library
The libraries are the best reference for idiomatic code. Three ship with the compiler, found beside it: core, system, and runtime, compiled into executables, which programs don't import. The standard library is a repository of its own, whose README says what each of its modules holds.
| Module | Holds |
|---|---|
core |
The language's own, which every file sees with no import: the types the syntax makes (string, strview, span, slice, range, maybe, result, nothing, whose declarations the compiler holds), the traits above, copy, move, close, and fault; vector, pair, box, and function; iterators and their adapters, sorting, the allocator trait and memory, counting bits, atomics, vectors of lanes, attributes, and reflection. It needs no system, and holds only what the compiler names, or what that, system, and the runtime are built from |
core::swar |
Words of bytes: eight bytes of text in a u64, tested at once |
core::intrinsics |
The square root and the operations on lanes the compiler gives, which std::math builds on |
system |
The layer beneath std::io that talks to the operating system, signals, clocks, and threads included, the same on every system, with what files are, who may use them, and io_error, why an operation failed. Beneath it, system::linux gives Linux's system calls, and system::windows the functions of kernel32.dll, each declared once |
std::containers, std::allocators |
The other containers, dict, hashset, deque, list, chain, heap, queue, stack, groups, runs, and interner, and the owners rc and arc; and the allocators arena and pool |
std::io, std::process, std::thread, std::time |
Files, streams and their traits, the console, and globs, in std::io::glob; running other programs; threads; and time |
std::math, std::serial, std::testing |
The functions of real numbers; typed values by their marks; and tests |
std::text, std::net, std::semver |
Regular expressions, URIs, and semantic versions |
std::json, std::yaml, std::args |
JSON and YAML, read and written, and a program's arguments, read into a struct |
Vectors: simd<L[N]> is 16 or 32 bytes of numbers that one instruction works on lane by lane, as SSE and AVX do, or 64 bytes of lanes of 16 bits or more, as AVX-512 does: L the type of each lane, and N how many. Aliases name each, as f32x4, f32x8, f64x2, f64x4, and i8x16 through u64x4 for each type of integer, and of 64 bytes f32x16, f64x8, and i16x32 through u64x8:
val a := f32x4::of([1.0, 2.0, 3.0, 4.0]);
val c := a * f32x4::splat(0.5) + f32x4::splat(1.0); # [1.5, 2, 2.5, 3]
val big := c.greater(&f32x4::splat(2.0)); # a mask of lanes 2 and 3
val d := select(big, c, f32x4::splat(0.0)); # [0, 0, 2.5, 3]
println($"{d.sum()} {big.count()}"); # 5.5 2
# Finds a byte sixteen at a time.
def index_of(text: strview, wanted: u8): maybe<u64> {
val needle := u8x16::splat(wanted);
var at := 0u;
while at + 16 <= text.length {
if u8x16::load(text.view(), at).equal(&needle).first() is some(lane) { return at + lane as u64; }
at += 16;
}
for i in at..text.length { return i if text[i] == wanted; }
return nothing {};
}
- Making and reading:
of(array),splat(value),load(view, at)andstore(slice, at), which stop the program past the view's end,lanes(),v[i]reading and writing a lane,shuffle(order),convert::<M>(), lane by lane asasconverts, andbits::<M, K>(), the same bytes as other lanes, which refusesKlanes ofMthat aren't as many bytes while compiling. - Halves and widths:
low()andhigh(), the halves of a vector as vectors of half as many lanes, andf32x4::join(low, high)the vector of both;widened::<M>()andwidened_high::<M>(), the first or second half of the lanes, each as a lane ofMtwice as wide; andnarrowed::<M>(&other), this vector's lanes then the other's, each as a lane ofMhalf as wide, held atM's limits. - Gathering:
f64x4::gather(from, at)reads the lanes of a view at the places asimd<i32[N]>names, andv.scatter(into, at)writes them there. A place below zero or past the view's end stops the program,gather's only where it's checked. - Operators:
+,-,*,/,%, and-x, lane by lane, and of integers&,|,^,~,<<, and>>, a shift by au32count. Integer lanes wrap, and dividing one by zero stops the program, as the numbers do.==is every lane equal. - Comparing:
equal,not_equal,less,less_equal,greater, andgreater_equalgive amask<L[N]>, whoseany,all,none,count,first,has(i), andbits()say which lanes hold, and whose&,|,^, and~combine them.select(mask, then, otherwise)takes each lane from one or the other. - Functions of lanes:
min,max, andabs, and across the lanessum,product,smallest, andlargest, lane 0 first.std::mathdeclares the functions of reals on vectors too, seen where it's imported:fma, and of real lanessqrt,floor,ceil,trunc,round, andround_even, each as it gives it of the lane. - The same bits everywhere: each operation is written in
corelane by lane, which the VM and constants run. An executable asks its processor which vector instructions it has as it starts, withcpuid, and works the lanes with them where it has those an operation needs: SSE2, which every x86-64 processor has, for most of 16 bytes, SSSE3, SSE4.1, and SSE4.2 for some, AVX and AVX2 for 32 bytes, AVX-512 for 64, and FMA3 forfma. Where it lacks them, a vector is worked a half or a quarter at a time, or the lanes ascorewrites them. Whichever runs, the bits are the same. Integer division and%,scatter, theproductof integers, and thesmallestandlargestof reals have no instructions, and are always worked a lane at a time. SAKURA_CPUnames the instruction sets an executable may use, joined by+:sse2,ssse3,sse4.1,sse4.2,avx,avx2,fma,popcnt,lzcnt,bmi1, andavx512, or a level of x86-64,x86-64,x86-64-v2,x86-64-v3, orx86-64-v4.SAKURA_CPU=x86-64 ./programruns a program as on a processor with SSE2 alone.- In registers: executables built with
-O2hold vectors of 16 and 32 bytes in vector registers between operations, as numbers are, and those of 64 in memory. A function using instructions some processors lack, as any workingf32x8does, or counting a word's bits, has a second version for processors with x86-64-v3's, which it goes to as it begins, and which still asks for AVX-512. lanes_held()says whether vectors are held in registers, as such an executable holds them, and is known while compiling. The virtual machine and constants work lanes one at a time, where code for one number is faster, so code with a way for each chooses by it.
Words: std searches text eight bytes at a time, as words, and sixteen at a time where vectors are held in registers. core::swar gives the words themselves, for reading text a program's own way:
import core::swar;
val lines := text.count_of(&'\n');
val day := swar::load("20261016", 0).digits() else { return; }; # 20261016
# Where a string's plain run ends: at a quote, a backslash, or a control byte.
def plain_end(text: strview, from: u64): u64 {
var at := from;
while at + 8 <= text.length {
val word := swar::load(text, at);
val stops := word.equal('"') | word.equal('\\') | word.below(0x20);
return at + stops.first() if stops.any();
at += 8;
}
for i in at..text.length { return i if text[i] == '"' || text[i] == '\\' || text[i] < 0x20; }
return text.length;
}
- Words: a
bytes8is eight bytes in au64, the first in its lowest byte.swar::load(text, at)reads one, stopping the program past the view's end, andload_lastreads the last one to seven bytes without passing it, with zeros after them.repeat(byte)is one byte eight times. - Tests:
equal,zero,below,above,within, andasciieach give amask8of the bytes they choose, exact in every byte. A mask'sany,first,last,count, andrestread it, and&,|,^, and~combine masks. - Changes:
upperandlowerchange ASCII letters,digitsreads eight ASCII digits as a number, ornothing, andchoose(mask, then, otherwise)takes each byte from one word or the other. - The same everywhere: words are
u64arithmetic, so they give the same results in the VM, in executables, and in constants.
Atomics: atomic<T> is a value that threads, or a program and its signal handlers, read and write without a lock, each operation in one step. T is an integer, bool, enum, or pointer, which every processor reads and writes whole:
var hits := atomic::<u64>::new(0);
_ = hits.fetch_add(1); # from wherever `&mut hits` is held
var ready := atomic::<bool>::new(false);
data = 42;
ready.store(true, order::release); # publishes `data`
if ready.load(order::acquire) { use(data); } # sees 42
match slot.compare_exchange(seen, seen + 1) {
value(_) => {} # it held `seen`, and now holds one more
error(found) => seen = found; # another wrote first, so try again with what it found
}
- Operations:
load,store,exchange,compare_exchange, andcompare_exchange_weak, and of integersfetch_add,fetch_sub,fetch_and,fetch_or,fetch_xor,fetch_min, andfetch_max, each giving what it held. Adding and subtracting wrap, and the least and greatest are compared asTis, signed or unsigned. AnotherTgiven to these stops the compile. - Orders are C11's, as C, C++, Rust, and Zig have them:
order::relaxed,acquire,release,acq_rel, andseq_cst, which is what each operation takes where none is written. Areleasestore that anacquireload reads makes everything written before the store seen after the load.fence(how)orders the reads and writes around it. An order that makes no sense, as areleaseload, stops the program with a fault saying so. - Never copied by accident: an atomic is
owning, closing nothing, soval b := a;is refused, as a copy would read it without a load. Threads share one through&mut atomic<T>. - The same everywhere: an executable works them with x86-64's locked instructions, and the VM with C's or
core's own atomics, so they're atomic between processes sharing memory there too. While compiling, one thread runs, and an atomic is what it reads and writes.
Signals: system::handle runs a function, a lambda, or a functor once a signal comes, at the program's next safe point rather than in the middle of what it was doing, so a handler may allocate, print, or set a flag. It keeps the handler in a function until another handles the signal, so a functor may hold what it needs:
var stopping := false;
_ = system::handle(system::signal::interrupt, def(s: system::signal) { stopping = true; });
while !stopping { work(); }
A program that never calls system::handle has no safe points, and pays nothing. One that would rather ask has the signal noted with system::watch(which), which runs no handler and so adds no safe points, and asks with system::watched(), which gives the signals that came since it last asked, one bit each by the system's number, and system::signal_of(number) names them. system::exit(code) stops with a status, and system::abort() with a fault report.
Windows has no signals of its own, so the console's events stand for them: Ctrl-C is interrupt, Ctrl-Break quit, closing the console hangup, and logging off or shutting down terminate. system::raise, system::handle, and system::watch work within the program as on Linux, but that raising stop or suspend gives unsupported. system::kill can only stop another process, with kill or terminate, which stop it at once with 128 more than the signal's number as its status.
Executables, debugging, and editors
sakurac build writes a standalone x86-64 executable, with no assembler, linker, or C library, for the system running sakurac unless --target names another: linux-x86_64 or windows-x86_64. One for Linux is static unless it calls C. One for Windows is a console program that calls the system through its DLLs, as kernel32.dll, and an output named without an extension gets .exe. A build replaces whatever file its output names, as a C compiler does, even one a program is running from: that one is moved aside to its name with .old added and removed from there, which Windows only allows once the program ends, so there it stays until a build next replaces it. The runtime is written in Sakura, in runtime, found beside the compiler as core is. It behaves as the VM does: the same output, the same fault reports, and the same exit status, but that an executable is unchecked unless built with --checks (see Checks).
| Level | Does |
|---|---|
-O0 |
Compiles the code as written, but for calls of @inline functions, which builds fastest and is what a debugger reads best |
-O1 |
Optimizes each function on its own: folds and combines what it computes, reuses what it already computed or loaded, threads jumps through what a branch already knows, makes small branches choose a value instead, and moves what a loop doesn't change out of it |
-O2 |
The default. Also inlines small functions, those called once, and the tests other functions return early on |
Compiling on threads: -j N, or --threads N, says how many threads check, run, and build compile on: one for each processor, up to eight, unless it says otherwise, and -j 1 starts none. What they make is the same, byte for byte, however many there are, and notes are printed in the order one thread would make them.
Debugging: -g also writes DWARF 5. For Linux, it goes to the executable's path with .petal added, which gdb and valgrind find through the executable. For Windows, it goes into sections of the .exe itself, named as gcc -g names them, which gdb and lldb read, and a PDB file is written beside the executable, its path with .pdb in place of .exe, which Visual Studio and WinDbg read. The executable names that file by its path and the GUID it is named by, which is made from what the file holds, so the same build writes the same file. It changes nothing in the executable's code. Fault traces and debuggers show inlined functions as frames of their own. Every executable for Windows, debugged or not, also says how each of its functions unwinds, in its .pdata and .xdata, as the system and its debuggers read to unwind a thread's stack.
Editors: sakurac lsp, the language server, checks the workspace as you type, unsaved text included. It gives hover documentation, completion, signature help, semantic highlighting, going to declarations, finding references, and renaming. Where several files declare main, each is a program of its own, together with the files that declare none. It checks for the system it runs on, or with --target for an executable's. Each job is worked out in a process of its own, so a fault while checking can't stop the server. Windows can't copy a process, so there those are this program started again, as sakurac lsp --base and sakurac lsp --worker.
This repository
sakurac is entry.sakura, the command line, over the compiler's own libraries, with the libraries every program reads beside it:
| Path | Holds |
|---|---|
entry.sakura |
The command line: check, run, build, and lsp |
analyzer/, compiler/, machine/, native/, server/ |
The compiler's parts, each a library of its own, with a README of its own |
core/, system/, runtime/ |
The language's own library, the layer over the operating system, and the runtime compiled into executables |
tests/ |
Each part's tests, in the folder of its name; the corpus, in programs/, checked/, and memory/, each program beside the .out file of what it writes; the tests of core and system, in core/; and the tests of finding libraries |
tools/corpus.sakura |
Runs each program of the corpus with a command given, and compares what it writes with its .out |
docs/ |
The roadmap, the plans not built yet, and what's left for later |
The compiler's parts are libraries the blossomfile declares and exports, so another project requiring this repository may read them:
sakura::analyzerlexes, parses, and checks, and answers the language server's queries.sakura::compilerlowers a checked program to intermediate code, optimizes it, and assembles the virtual machine's code.sakura::machineis the virtual machine, which also evaluates constants while compiling.sakura::nativeis the native backend, which chooses the instructions of an executable, places its values, and lays out its file and its debugging information.sakura::serveris the language serversakurac lspserves, which also findscore,system, and the runtime beside the compiler.
Packages it requires, each a repository at https://git.malunal.studio/sakura/NAME:
std, the standard library, of which the compiler readsstd::argsfor its command line andstd::jsonfor the language server, besides containers, files, and threads.binaryholds the back end's libraries,binary::amd64,binary::elf,binary::dwarf,binary::pe, andbinary::pdb: they encode instructions, write Linux's and Windows' executables, and write their debugging information.
Tests: blossom test builds sakurac, then runs:
sakurac.tests, of finding libraries, on the machine;sakura.analyzer.tests,sakura.compiler.tests,sakura.machine.tests,sakura.native.tests, andsakura.server.tests, each part's, on the machine;sakurac.core, the tests ofcoreandsystem, built and run as an executable;sakurac.corpus,sakurac.checked, andsakurac.memory, the corpus, each program run by thesakuracjust built over../std, the last withrun --checks.
Grammar
The syntax as the parser reads it, in EBNF: { x } is zero or more, [ x ] is optional, | separates choices, and quoted text is written as it is. What the parser accepts and the checker then refuses, such as break outside a loop, is left to the sections above.
Words and literals
ident = ( letter | "_" ) { letter | digit | "_" } ; (* not a keyword *)
keyword = "true" | "false" | "null" | "import" | "module" | "pub" | "var" | "val"
| "const" | "def" | "mut" | "type" | "struct" | "union" | "enum" | "trait"
| "where" | "return" | "if" | "else" | "for" | "in" | "while" | "break"
| "continue" | "match" | "when" | "as" | "is" | "not" | "extern" ;
int = ( digit { digit }
| "0x" hex { hex } | "0o" octal { octal } | "0b" bit { bit } ) [ "u" ] ;
float = digit { digit } [ "." digit { digit } ] exponent [ "f" ]
| digit { digit } "." digit { digit } [ "f" ]
| digit { digit } "f" ;
exponent = ( "e" | "E" ) [ "+" | "-" ] digit { digit } ;
char = "'" { char_item } "'" ;
string = '"' { char_item } '"'
| '"""' newline { any } '"""' ; (* spans lines *)
istring = "$" '"' { char_item | hole } '"'
| "$" '"""' newline { any | hole } '"""' ;
hole = "{" expression "}" ;
char_item = any character but the closing quote, a line break, "\" or, in an istring, "{"
| escape ;
escape = "\" ( "n" | "t" | "r" | "0" | "\" | "'" | '"' | "{" | "}" )
| "\x" hex hex ;
comment = "#" { any but a line break } ; (* "#!" is documentation *)
this, self, _, get, set, type_of, expects, asserts, ensures, old, undefined, and the when keys os, arch, and backend are identifiers the grammar gives a meaning in one place each.
Files and declarations
file = { declaration } ;
declaration = import | extern_import | module | extern_module | top_when
| { attribute } [ "pub" ] declared ;
attribute = "@" type_name [ field_list ] ;
declared = function | variable | property | struct | union | trait | enum | alias ;
import = "import" path ";" ;
module = "module" path [ "when" condition ] ";" ;
extern_import = "extern" "import" string [ "when" condition ] ";" ; (* C's library *)
extern_module = "extern" "module" path [ "when" condition ] ";" ; (* C's declarations; the checker asks for a `when` *)
path = ident { "::" ident } ;
top_when = "when" condition "{" { declaration } "}" (* no import or module *)
[ "else" ( top_when | "{" { declaration } "}" ) ] ;
condition = cond_and { "||" cond_and } ;
cond_and = cond_item { "&&" cond_item } ;
cond_item = "!" cond_item | "(" condition ")" | ident ( "==" | "!=" ) ident ;
decl_name = ident [ type_params ] { "::" ident [ type_params ] } ; (* receiver::name *)
type_params = "<" type_param { "," type_param } ">" ;
type_param = ident [ "..." ]
| "const" ident ":" type
| "def" "(" [ ident { "," ident } [ "..." ] ] ")" ":" ident (* a pattern *)
| ident "[" ident "]" ; (* an array's pattern *)
where = "where" bound_list { "where" bound_list } ;
bound_list = ident [ "..." ] ":" type_name { "," type_name } ; (* a trait's method may name its trait's parameters and `self` *)
function = [ "const" ] "def" decl_name params ":" type [ where ] ( block | ";" ) ;
params = "(" [ this_param [ "," ] ] [ param { "," param } [ "," ] ] ")" ;
this_param = "&" [ "mut" ] "this" ;
param = ident ":" type [ "..." ] [ "=" expression ] ;
variable = ( "val" | "var" | "const" ) decl_name ":" [ type ] [ "=" expression ] ";" ;
property = ( "val" | "var" ) decl_name ":" type "{" accessor [ accessor ] "}" ;
accessor = [ "pub" ] ( "get" | "set" ) ( block | "=>" expression ";" | ";" ) ;
struct = "struct" decl_name [ ":" type_name { "," type_name } ] [ where ]
"{" { { attribute } field } "}" ;
union = "union" decl_name [ ":" type_name { "," type_name } ] [ where ]
"{" { { attribute } field } "}" ;
field = [ "pub" ] ( "val" | "var" ) ident ":" ( type | spread ) [ "=" expression ] ";" ;
spread = "..." type_name [ "{" [ ident "as" ident { "," ident "as" ident } ] "}" ] ;
trait = "trait" decl_name [ ":" type_name { "," type_name } ] [ where ]
"{" { { attribute } trait_member } "}" ;
trait_member = function (* ";" leaves it to the implementer *)
| "const" ident ":" [ type ] [ "=" expression ] ";"
| property
| "type" ident [ "..." ] [ ":" type_name { "," type_name } ] [ "=" type ] ";" ;
enum = "enum" decl_name [ ":" type ]
"{" [ member { "," member } [ "," ] ] "}" ;
member = { attribute } ident [ "=" expression ] ;
alias = "type" decl_name "=" type [ where ] ";" ;
Types
type = "*" [ "mut" ] type (* pointer *)
| "&" [ "mut" ] type (* reference *)
| type_primary { "[" expression "]" } ; (* fixed array *)
type_primary = "def" "(" [ type { "," type } [ "..." ] ] ")" ":" type (* function *)
| "(" type ")"
| "type_of" "(" expression ")"
| type_name ;
type_name = segment { "::" segment } ;
segment = ident [ "<" type_arg { "," type_arg } ">" ] ;
type_arg = type [ "..." ] | expression ; (* "..." passes a pack on *)
Statements
block = "{" { statement } "}" ;
statement = local | local_def | if | when | while | for | match
| jump | contract | block | expression ";" ;
local = ( "val" | "var" | "const" ) ident ":" [ type ] [ "=" ( expression | "undefined" ) ] ";" ;
local_def = "def" ident params ":" type block ;
if = "if" [ "const" ] condition_expr block [ "else" ( if | block ) ] ;
when = "when" condition block [ "else" ( when | block ) ] ;
while = "while" condition_expr block ;
for = "for" [ "const" ] [ ident "," ] [ "&" [ "mut" ] ] ident "in"
condition_expr block ; (* a range here is counted in place *)
match = "match" condition_expr "{" { arm } "}" ;
arm = ( "else" | expression { "," expression } ) "=>" ( block | statement ) ;
jump = ( "return" [ expression ] | "break" | "continue" )
[ "if" [ "const" ] condition_expr ] ";" ;
contract = ( "expects" | "asserts" ) "(" expression [ "," expression ] ")" ";"
| "ensures" "(" [ ident ":" ] expression [ "," expression ] ")" ";" ;
condition_expr is an expression that cannot be a struct literal outside parentheses, so if x { opens the block.
Expressions
Lowest precedence first. Binary operators and ranges group to the left, and assignment, ?:, and else to the right.
expression = fallback [ assign_op expression ] ;
assign_op = "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "&=" | "|=" | "^=" | "<<=" | ">>=" ;
fallback = ternary [ "else" ( "(" ident ")" block | block | expression ) ] ;
ternary = range [ "?" fallback ":" ternary ] ;
range = binary { ( ".." | "..=" ) binary } ; (* core's range<T> *)
binary = cast { binary_op cast } ;
binary_op = "||" (* 1, lowest *)
| "&&" (* 2 *)
| "|" (* 3 *)
| "^" (* 4 *)
| "&" (* 5 *)
| "==" | "!=" (* 6 *)
| "<" | "<=" | ">" | ">=" (* 7 *)
| "<<" | ">>" (* 8 *)
| "+" | "-" (* 9 *)
| "*" | "/" | "%" ; (* 10, highest *)
cast = unary { "as" type_operand | "is" [ "not" ] is_target } ;
is_target = "(" expression ")" (* a field a declaration names *)
| type_operand [ "(" [ "&" [ "mut" ] ] ident ")" ] ;
type_operand = type ; (* where "<" always opens type arguments *)
unary = ( "-" | "!" | "~" | "++" | "--" | "*" | "&" [ "mut" ] ) unary
| postfix ;
postfix = primary { call | index | member | type_args | "++" | "--" } ;
call = "(" [ argument { "," argument } [ "," ] ] ")" ;
argument = [ "..." ] expression ;
index = "[" expression "]"
| "[" [ expression ] ":" [ expression ] "]" ; (* slice *)
member = "." ident [ "::<" type { "," type } ">" ]
| "." "(" expression ")" ; (* a member a declaration names *)
type_args = "::<" type { "," type } ">" ; (* after a call, as value_of(d)::<i64> *)
primary = literal | name [ field_list ] | "(" expression ")"
| lambda | array | "match" condition_expr "{" [ value_arm { "," value_arm } [ "," ] ] "}"
| "type_of" "(" expression ")" (* a type, tested with `is` *)
| "old" "(" expression ")" ; (* within an `ensures` *)
literal = int | float | char | string | istring | "true" | "false" | "null" ;
name = name_segment { "::" name_segment } ;
name_segment = ident [ "::<" type { "," type } ">" ] ;
field_list = "{" [ field_init { "," field_init } [ "," ] ] "}" ;
field_init = ident "=" expression | expression ;
array = "[" [ expression { "," expression } [ "," ] ] "]" ;
lambda = "def" "(" [ lambda_param { "," lambda_param } [ "," ] ] ")" [ ":" type ]
( "=>" expression | block ) ;
lambda_param = ident [ ":" type ] [ "=" expression ] ;
value_arm = ( "else" | expression { "," expression } ) "=>" expression ;
License
Sakura is released under the MIT License: see LICENSE. What changed in each version is in CHANGELOG.md.