Files
2026-11-19 04:54:17 -06:00

1300 lines
118 KiB
Markdown

# 🌸 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.
```sakura
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
1. [Getting started](#getting-started)
2. The language: [modules](#programs-and-modules), [types](#variables-and-types), [structs, unions, and enums](#structs-unions-and-enums), [control flow](#control-flow), [errors](#errors), [faults](#faults), [contracts](#contracts), and [checks](#checks), [functions](#functions), [methods](#methods-and-properties), [traits](#traits), [generics](#generics), [ownership](#closing-copying-and-moving), [compile time](#compile-time), [pointers](#pointers-and-memory), and [C](#calling-c)
3. [The standard library](#the-standard-library)
4. [Executables, debugging, and editors](#executables-debugging-and-editors)
5. [This repository](#this-repository)
6. [Grammar](#grammar)
7. [License](#license)
---
## Getting started
> **Note:** the language, toolchain, and standard library are still changing.
`sakurac` is built and tested with [blossom](https://git.malunal.studio/sakura/blossom), which clones the packages it reads (see [This repository](#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](https://git.malunal.studio/sakura/std) checked out beside this one, as `../std`.
```sh
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.
```sh
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, contracts, and the rest, as `run` does
sakurac build --contracts on -o app main.sakura # unchecked, but with every `expects`, `asserts`, and `ensures` checked
sakurac build --lib geometry=../geometry -o app app.sakura # with a library of its own name: `import geometry;` reads ../geometry
sakurac build --icon app.png --title App --semv 1.2.0 --windowed -o app app.sakura # a Windows program shown by its icon, title, and version, in windows of its own
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](#the-standard-library).
- **`core/`, `system/`, and `runtime/`** are the compiler's own, found beside the `sakurac` executable or in the nearest folder above it that holds them. Nothing names them. `runtime/` holds the module `runtime`, 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](https://git.malunal.studio/sakura/std), is the folder `--lib std=DIR` names, or else a `std` folder beside the executable or in the nearest folder above it, as `core` is found, or else its libraries in the `share/sakura` folder nearest above it, where `blossom install` puts them, as `share/sakura/std.io` for `std::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. `NAME` is the module the directory is, which may be within another, as `std::json` or `sakura::analyzer`. A module is found in the library whose name is the most of its path, so `--lib std::json=DIR` holds `std::json` and the standard library the rest of `std`, and two libraries may be within one module that is in none, as `sakura::analyzer` and `sakura::machine`. `sakurac lsp` takes them too.
- **`--deps FILE`** writes 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()`).
```sakura
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::shapes` is a module within `geometry`. Files without a `module` declaration 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 own `pub`, as does what is declared outside a type, as `pub 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, `pub` or 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](#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, as `token::kind` or `io::println`. Anything a program declares or imports hides a name of `core`'s, which `core::vector` still 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, unless the module declares nothing of the next name and a type of the first name is seen: where the module `geo::shape` declares the type `shape` and the function `helper`, `shape::make` and `shape::corner` reach the type's, and `shape::helper` the module's.
- **Methods declared on another's type**, as `std::math` declares `sqrt` on a `simd`, or a module on `u8`, are seen within that module and where a file imports it, and `core`'s everywhere. So `std::io` declares `write` on a `string`, which is `writable` only 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 name `core` gives that type too, method or property, is chosen over `core`'s wherever it is seen, and `core`'s only where none of its overloads takes the call's arguments. So `core` adding a member never refuses a program or takes its calls, and `core`'s own code keeps calling its own. A type declared through `core`'s, as `type 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::b` is the folder `a/b`, or the one file `a/b.sakura`. A file or folder within a module's folder belongs to it where its first `module` line says so, and is otherwise a module of its own, as `std/testing.sakura` is `std::testing`.
---
## Variables and types
```sakura
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 `U`s 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 `strview`s |
| `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](#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 i32` is `3`. A reference converts as the value it refers to, so `(&x) as u64`, which would be `x` rather than its address, is refused: the address is `&x as *u8 as u64`. A reference written as one, `&x` or `&mut x`, is a pointer where one at its type is expected, and a pointer converts to a reference with `as` (see [Pointers and memory](#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's `fmod` does.
- **Booleans** are not numbers: write `if count != 0`. `flag as u8` is `0` or `1`.
- **Aliases**: `type meters = f32;` converts to and from `f32` implicitly, 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 | b` of two `mask8`s is a `mask8`, with its methods, while `mask | u64` is a `u64`. An alias of a trait names the trait wherever one is named, among a type's traits, in a bound, and in `is`, as a trait renamed keeps its old name as one.
| 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
```sakura
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](#checks)). `a[start:count]` is a view, a `slice<T>` of a `var` array and a `span<T>` of a `val` one, and either end may be left out, as `a[:]`. A view is narrowed the same way, as `text[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 `&mut` of one writes where it does, as `&mut held` of a `held` an `is some(&mut held)` names. Assigning to one writes what it refers to, a reference's too, while a `var` given 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 `&mut` written, or a reference parameter at a call, makes a reference, so a binding, a pattern, and `for` take the value a reference reaches, copied where it closes nothing, as are a variable's and a field's: `val x := v[i]` and `for x in v` copy, while `val x := &v[i]`, `for &x in v`, and `is some(&x)` refer. What closes is refused rather than copied (see [Closing, copying, and moving](#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 --checks` stops where one is used (see [Pointers and memory](#pointers-and-memory)).
- **Views** come from slicing, from containers (`v.span`, `s.span`, and `v.slice` where `v` can be written), and from `span::<T>::over(data, length)`, or `span::<T>::blank()` for one over nothing. A container is sliced as a view is, `v[1:3]` or `s[6:]`, through its `span_of`, or its `slice_of` where it can be written (see [Methods and properties](#methods-and-properties)). A `slice<T>` converts to a `span<T>`, and `==` compares their elements.
- **`get(i)`** gives a `maybe` of the element at an index, or `none` past 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
```sakura
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 `.span`.
### 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](#operators)).
---
## Structs, unions, and enums
```sakura
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's associated variables and constants are one of each of its instances, read through one, as `counter::<u8>::count`, and by name alone within the type's own functions. A constant of one is known while compiling where its instance is, so `const isptr<T>::value := T is pointer;` makes `isptr::<*i32>::value` `true` and `isptr::<i32>::value` `false`, and the condition of `if const` and of a type can read it. `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:
```sakura
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 data` and `r 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 `? :`, as `m is some(v) ? v : 0`. `is not data(x)` names it wherever the test failed, such as after an `if` that leaves, or in the second branch of `? :`. `&x` or `&mut x` refers to the field in place, and `_` names nothing, so `is data(_)` and an arm's `data(_)` take nothing out, as `is data` doesn't. `is` with a type asks the value's own type, so `m is nothing` of a `maybe`, never true, is refused: write the field, `m is none`.
- **Referring**: `&r.data` refers to a field only where what it refers to closes nothing, and `&mut r.data`, or `&mut` of 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, as `if 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 holds `null` for the empty field.
An **enum** is a set of named integers:
```sakura
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
```sakura
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++` and `x--` give the value from before.
- `for` walks fixed arrays, views, and anything `iterable`, as `core`'s containers are: `iter()` lends an iterator, an `iter<T>`, whose `next()` gives a `maybe` of each element, the container's `iterator` that reads them or, from what can be written, its `mutator` that writes them, which it also lends as the properties of those names, as `v.iterator`. A container indexed by position need write neither, since `positions_iterator<C, T>` and `position_mutator<C, T>` walk anything `indexable` and `assignable` through its `at`, from either end. It also walks any iterator, from where it is, so a loop that stops early leaves the rest for the next. `for x` takes a copy of each element, `for &x` refers to it, and `for &mut x` writes it in place. What a loop's iterator gives by value, as each `string` of `for line in input.lines()`, is the pass's own, closed where that pass ends.
- **Ranges** are values: `a..b` and `a..=b` are `core`'s `range<T>` of the integers their ends are, or of the type expected, as `val r: range<u8> = 0..9;` or a `range<u64>` given for an `iter<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, so `color::red..=color::blue` gives `red`, `green` and `blue` of `enum color: u8 { red, green = 4, blue }`. Within a generic, the ends may be any `ordinal` type parameter, which one bounded by `integer` is.
**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:
```sakura
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`:
```sakura
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`.
```sakura
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_some` and `is_none` of a `maybe`, and `is_ok` and `is_err` of a `result`, are properties. `is_some_and(test)`, `is_ok_and(test)` and `is_err_and(test)` test what it holds too.
- **Reading**: `unwrap()`, `expect(why)` and `unwrap_or(fallback)` give the value, and a `result`'s `unwrap_err()` and `expect_err(why)` its error, stopping the program where it holds none. From what can be written they move it out, as `move` does, 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`'s `map`, `and_then`, `filter`, `or`, `or_else` and `ok_or(error)`, and a `result`'s `map`, `map_err`, `and_then`, `or_else`, `to_maybe` and `err_to_maybe`, move what it holds into what they make, as an iterator's adapters do. `as_ref()` and `as_mut()` lend what it holds to them instead. `take()` empties a `maybe`, and `replace(value)` puts another value in, each giving what it held.
- **Comparing**: both compare with `==`, hash, and copy where what they hold does. A `result` whose 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](#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, and with a contract that fails, as the containers do where they're asked for what they don't hold: `sakura: runtime error: A pre-condition failed: 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.
```sakura
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, a `strview`, 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.
- **`ensures` is checked on every way out of its block** once it's been reached: each `return`, a `break` or `continue` leaving 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 any `ensures`, `old(e)` is what `e` was where it was reached, of a type that closes nothing.
- **Contracts are checked where the program is** (see [Checks](#checks)): `run` checks them unless `--fast`, and `build` doesn't unless `--checks`. `--contracts on` or `--contracts off`, for `run`, `build`, and `check`, says otherwise whichever the program is. Left out, every contract goes, 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, so `if const contracts()` keeps work only they read.
- **The containers check with them**: `core`'s and std's ask for what they're given as contracts, as `expects(index < this._len)` and `expects(!this.empty, "The deque is empty.")`, so a checked program stops where one is asked for what it doesn't hold, and one that isn't trusts the program, as C does. A library's own checks are contracts the same way.
- **In a constant,** a contract that fails is reported where the constant is: `Evaluating `h` stopped: 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 named `ensures`. Only at a statement's start, before `(`, is one a contract.
### 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; at a `match` finding no arm; and at a contract that fails. Each is a fault, saying what went wrong and where. `core`'s and std's containers check what they're asked for with contracts, as the front of one that's empty, or a key a `dict` doesn'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)`.
- **`--checks`** checks the program's own integer arithmetic too, `run --checks` and `build --checks` alike: `+`, `-`, `*`, `/`, `+=` and the rest, `++`, `--`, and negating a signed number stop where they give what the type can't hold, as `u8` 200 + 56 or `i64`'s least divided by -1: "Integer arithmetic overflowed." Elsewhere integers wrap, as they always do in what libraries work, which wrap on purpose, as hashing does. A program's own code meaning to wrap calls `math::wrapping_add`, `wrapping_sub`, or `wrapping_mul`; negating an unsigned number wraps, as `x & -x` means it to.
- **Every program** stops at `null` reached 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 with `null` where it reaches past the first page of memory.
- **In a constant,** the checks are always made.
- **`sakurac check --checks-report`** lowers 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 a `vector`'s index, is listed at the line calling it, and a container's contract among the contracts.
---
## Functions
```sakura
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 an `extern module` (see [Calling C](#calling-c)).
- **Returning what gives nothing**: a function giving nothing may `return` a 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 none: def(&vector<i64>): bool = vector::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:
```sakura
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:
```sakura
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:
```sakura
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 `function` itself, and a larger one in a `box`. 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 an `F`.
- 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:
```sakura
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 on `strview`.
- **`&this` and `&mut this`** may 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 `val` with a `get`, or `var` with a `set` too, of any type but `void`. An accessor's parameters are implied: a `get` has `this`, as `&this`, and a `set` has `this`, as `&mut this`, and `value`, of the property's type. Its body is a block, or `=> expression;`, which a `get` returns and a `set` does, as `set => this.w = value;`. A trait asks for a property with `{ get; }` or `{ get; set; }`. `pub get` or `pub set` gives one accessor visibility of its own. `value` is a name only within a `set`.
- **`get mut`** reads a property where the value can be written, beside or instead of the `get`, as a method's `&mut this` overload is called there. Its `this` is `&mut this`, and where the property's type is a reference, it gives one that writes, which an assignment writes through: `val vector<T>::first: &T { get => ...; get mut => ...; }` makes `v.first = 4` and `v.first += 1` write where `v` can be written, while a `&vector` reads `first` as a `&T`. A property only a `get mut` reads, as `v.slice`, is read only of what can be written. A trait asks for neither.
- **Nested types** are declared and named through another type, as `list<T>::iterator`. A field or a property may share its name with one, since it is reached through a value and the type through its type: `struct token { var kind: token::kind; }`, or the property `v.iterator` giving a `vector<T>::iterator`.
- **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 `iterator` within `list<T>` is `list<T>::iterator`, given the same `T`, which is why the trait of iterators is `iter`, and named so there. In a type, only its types are meant, so an enum's member `u8` leaves `u8` the type. A type's functions are still named through it, since they are often named for the free functions they implement, as `vector<T>::decode` calls `decode::<T>`.
- **Indexing**: a type implementing `indexable<K, V>`, by `at(&this, key): &V`, supports `x[key]`, which is `x.at(key)`: the reference it gives, read and bound as any reference is. One implementing `assignable<K, V>` too, by `at(&mut this, key): &mut V`, is written that way, as `x[key] = v`, where it can be written, and so is a type parameter bounded by it.
- **Slicing**: a type implementing `spannable<T>`, by `span_of(other: &self, start: u64 = 0, count: u64 = ~0u): span<T>`, supports `x[start:count]`, which is `T::span_of(&x, start, count)`: `count` elements from `start`. One implementing `sliceable<T>` too, by `slice_of(other: &mut self, ...)`, giving a `slice<T>`, is sliced through that where it can be written, so `v[1:2][0] = 5` writes `v`. A bound left out is given as the defaults give it, the start as 0 and the count as `~0u`, which stands for every element after the start, so `v[2:]` is all but the first two. The function stops a checked program where the start or count reaches past the last element, as slicing the whole view, `whole[start:count]`, does for it.
---
## 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:
```sakura
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. `@optional` methods may be left out. In a trait that is only a bound, each default is compiled for each type implementing the trait, with `self` that type, so it calls the type's methods directly and may be generic, as `def 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 `self` beyond what the trait does, as `def sum(&mut this): T where T: numeric` or `def 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()`. A constant a trait asks for, as `T::bytes` of `trait sized { const bytes: u64; }`, given as `const i32::bytes: u64 = 4;`, is a constant wherever one may stand: a fixed array's length, in a signature or a field too, as `u8[T::bytes * 2]`, a constant type argument, as `buffer<u8, T::bytes>`, or a `const`, and each instance gives it the type's own. So are the constants of `pointer` and `array`, as `T::element[T::length]`. A constant the trait gives a value, as `const bytes: u64 = size_of::<self>();`, is a default: a type naming the trait and giving none of its own takes it, worked out for that type, as a default method is.
- **Functions of its own** are declared through it, outside it, as `def real::parse<T>(text: strview): result<T, failure>`, and named through it, as `real::parse::<f64>(text)`. The trait doesn't ask for them and what implements it doesn't take them, so they take no `this` and may be generic.
- **`self`** is the type implementing the trait, as `def copy_of(other: &self): self;`.
- **Sealed traits**, written `@sealed`, are ones nothing implements, which say something of the types they're given rather than asking anything of one. Their constants and types are their own, each given here, and read through the trait given its type arguments, anywhere a constant or type may stand, each instance of a generic reading its own:
```sakura
@sealed pub trait strip<T> {
type plain = T is reference ? T::target : T;
const bytes := size_of::<plain>(); # names the trait's types and constants by name
}
def deref<T>(x: T): strip<T>::plain { return x; }
def wide<T>(x: T): bool { return strip::<T>::bytes > 4; }
```
A constant whose value tests the trait's own parameters says, in a condition, what it tests of the types given for them, so within `if const owns::<T>::value`, of `const value := T is owning;`, `T` is owning, as within `if const T is owning`. Within one, `self` is the trait itself, given its arguments. No type or trait names it, it bounds nothing, no type `is` one, and nothing refers to it, and it holds no function or property, composes no trait, and gives its types no bounds: each is an error. A function of its own is declared through it, outside it, as any trait's is, and names its constants and types as they name each other.
- **Defaults of parameters** a trait gives, as `def span_of(other: &self, start: u64 = 0, count: u64 = ~0u): span<T>;`, are what a call through a bound leaving them out is given, as `C::span_of(c)`. A type's function meets the one asked for only where it gives a default for each parameter the trait does.
- **Types a trait asks for**, as `type iterator: iter<&T>;`, are given by each implementer and named through a bound, as `C::iterator`. A trait naming `self`, asking for types, or with generic methods or methods bounding its parameters or `self`, as `iter<T>`, is only a bound.
- **References** satisfy the traits of what they refer to, except `owning`, and those whose methods make or take a `self` by value: `numeric` and the traits it composes, `copyable`, `moveable`, `integer`, `real`, `ordinal`, and `zeroable`.
- **Pointers** satisfy `equatable`, `ordered`, and `hashable` by address, `zeroable`, and `pointer`.
- **Built-in types** are `equatable` and `hashable`, numbers, enums, and pointers `ordered`, and numbers `numeric`, with every trait it composes. Function types and `cfn<def(...): R>` are `signature`, and `invokable` of their own type. References are `reference`, fixed arrays `array`, and the instances of generic types `generic`.
- **Receivers**: a method taking `&this` meets one a trait asks for taking `&mut this`, since what can be written can be read.
- **Calling**: `invokable<def(Ts...): R>` asks for `invoke(&mut this, args: Ts...): R`, which a call of the value calls (see [Functions](#functions)). `signature` is every function type, naming `F::result` and 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:
```sakura
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 `add` has `+` 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 `duration` and subtract either a `duration` or an `instant`.
- **The method's shape** is `def T::add(&this, other: &B): R`, and `def T::negate(&this): R` and `def T::bit_not(&this): R`, with no type parameters of its own.
- **A number on the left** asks its own type, so `2.0 * v` calls a program's `def 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, as `def 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 is `a = a + b`, so what the method gives is `a`'s own type.
- **Comparisons** stay between two values of one type. Integers give `bit_and` and 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**:
```sakura
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:
```sakura
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:
```sakura
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 an `i64` rather than a reference into `v`, and `math::sqrt(xs[i])` takes a `f64`, while `f(&x)` gives `T` the reference. A parameter bounded by `reference`, which no value is, takes the reference an argument is, so `address(r)` of `address<T>(r: T): castptr<T> where T: reference` gives `T` the `&mut i32` that `r` is.
- **Checking**: a generic is checked against its bounds. Errors only an instance has, such as `x + 300` where `T` is `u8`, name the instance.
- **Bounds** are written one `where` for 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](#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, with `T::target`, what it points at, and `T::mutable`, whether it writes it, with `T` taken as a `*T::target`: `*x` reads it, and writes it within `if const T::mutable` |
| `reference` | `T::target`, what it refers to, and `T::mutable`, whether it writes it |
| `array` | `T::element`, the type of its elements, and `T::length`, how many it holds, with `T` taken as a `T::element[T::length]`: `x[i]`, `for e in x`, and `x.length` |
| `generic` | `T::args`, the pack of the type arguments it was given, as `(u8)` of `vector<u8>` |
| `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`, `reference`, `array`, `generic`, `closeable`, and `signature`, and no other type implements them. A reference satisfies `reference` by being one, never through what it refers to.
**Constant parameters** stand for values each instance is given while compiling:
```sakura
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:
```sakura
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`, `for const U in Ts` names each of its types in turn, as `U`, and `Ts...[i]` is its type at an index known while compiling, so `T::args...[0]` is the first type argument of a `generic` `T`. An index worked out from constant parameters, as `Ts...[I]` of `def pick<const I: u64, Ts...>(args: Ts...): Ts...[I]`, is worked out by each instance, in a signature as in a body. A constant among the types, as `4` of `buffer<i32, 4>`, is named as a constant parameter is. 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:
```sakura
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 struct's field** holds a pack too, written `items: Ts...` as a variadic parameter is: a value of each of its types, laid out in order as fields are, and used as a variadic parameter's pack is, as `t.items[0]`, `t.items.length`, `for const x in t.items`, and `f(...t.items)`. A literal gives it a pack of its types whole, as `bundle { items = args }`, and one leaving it out zeroes it. What closes is moved out of it by `...`, and by a literal given it, so it is then a place that can be written, and it closes the rest where the struct does, the last first. `core`'s `tuple<Ts...>` is a struct of one, made by `tuple::of(...)`, whose `t.at::<i>()` reads or writes the value at an index:
```sakura
var t := tuple::of(1, true, string::from("x", nothing {})); # a tuple<i64, bool, string>
t.at::<0>() += 1;
for const x in t.items { println($"{x}"); }
total(...tuple::of(1, 2, 3).items);
```
No local, union's field, or other value holds a pack, 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`:
```sakura
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 `A` of `def(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 variadic `invoke`, and within a function given one, the pack's last value is a view of the rest.
- A type parameter bounded by `signature` is given whole, as `invokable<F>`, naming `F::params` and `F::result`. Only a pattern `def(Ts...): R` takes it, since its parameters are not known.
- **`L[N]`** takes a fixed array, naming its element's type `L` and its length `N`, a constant `u64`, as `struct simd<L[N]>` is written `simd<f32[4]>`. A method names it in its receiver, as `def simd<L[N]>::sum(&this): L`, and a function takes the parts, as `def 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:
```sakura
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 `owning` only by naming it. A type whose values are closed, by being `owning` or holding what is, is `closeable`.
- **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`, or `is 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`:
```sakura
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:
```sakura
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 a `span<T>` works and a `string` doesn'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 def` promises a function can run while compiling.
- What a function gives is a constant type argument too, as `buffer<u8, small(2) ? 3 : 5>`. Within a generic, a constant only its type arguments decide, as `small(N)`, `size_of::<T>()`, or `M ? 4 : 8`, is worked out for each instance, in a type alias, a field's type, or a signature, so `type pick<const M: bool> = buffer<u8, M ? 4 : 8>;` makes `pick<true>` a `buffer<u8, 4>`.
### 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, and a value of `T` is one of that type there, so it is checked as each instance taking it is, though none does. Within a generic's own body, a branch is checked with what its condition says of `T`: a trait or generic type it fits gives its bound, a type names it, and one it doesn't fit, as in `T is not pointer` or the `else` of `T is pointer`, is ruled out, as it is for what follows a branch that leaves, and so is what implies it, as `integer` where `numeric` is ruled out. Where the condition holds in several cases, as `T is integer || T is real`, the branch is checked once for each, so `x + x` is checked as each, and a note only one case finds says which, as "(Where `T` is `real`.)". What follows a branch that leaves is checked once for each case the condition fails in, as after `if const A && B`, where `A` fails and where `B` does. A case that can't hold, as `T is i32 && T is u8`, isn't checked, and a condition holding, or failing, in more than 1024 cases is an error, and one what is proved there decides is decided, so after `if const M { return a; }`, `if const !M` holds, and `return a if const M; return b if const !M;` always returns. A constant parameter is said of too, as `if const MUTABLE` or `if const N == 4`:
```sakura
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>`. A generic type named without type arguments asks whether a type is one of its instances, looking through aliases, so `T is vector` holds of `vector<u8>` and `T is span` of `strview`, and its branch gets the bound `generic`, which names the arguments as `T::args`, and takes `T` as that generic given them, as `vector<T::args...[0]>`, so `x.append(e)` and `x[0]` are `vector`'s. A generic's pack parameter is given the types from its place on, as `T::args...[1:]`, and each of the shape's types is bounded as the generic bounds its parameter. Likewise `T: array` takes `T` as a `T::element[T::length]`, indexed, walked, and converted as one, with a zero value where `T` is `zeroable` too, and `T: pointer` as a `*T::target`, which `*x` reads, and as a `*mut T::target` within `if const T::mutable`, which it writes, and `T: reference` as a `&T::target`, or a `&mut T::target` there. A kind of type the compiler decides is none of the others, so `T: pointer` rules out `T is reference`, and a type's own shape decides which it is, whatever type parameters it holds, so `&mut T is pointer` is false within the generic's own body, and a `match const` choosing by `&mut T` among such kinds chooses there, as `castptr<&mut T>` chooses its `reference` arm.
**`match const`** chooses by a type, or a value's own type, as a chain of `if const` does: the first arm whose pattern the type fits is kept, and `else` fits every type. A pattern is a trait, a generic type without type arguments, or a type, fit as `is` fits it, and an arm may list several. Where its patterns are values written in place, as `4` or `true`, it chooses by a constant instead, as `match const N { 4 => u32, else => u64 }` or `match const T::mutable { true => &mut p[0], false => &p[0] }`, each arm checked within a generic's own body with what its pattern says of the constant parameter. As a statement, each arm ends with its block or statement, as a value, its arms are separated by commas, and as a type, each arm gives a type, so an alias can work one out:
```sakura
def describe<T>(x: T): string {
match const T {
integer => return $"{x + 1} is an integer";
strview => return $"{x.length} bytes of text";
pointer => return $"a pointer to {size_of::<T::target>()} bytes";
else => return "something else";
}
}
def bits<T>(): u64 { return match const T { integer, real => size_of::<T>() * 8, else => 0 }; }
type strip_pointer<T> = match const T {
pointer => strip_pointer<T::target>,
else => T,
};
```
Within a generic's own body, each arm is checked with its pattern fitting `T` and the patterns of the arms before it not, as an `if const` branch is, and once for each pattern an arm lists, so `pointer, reference => T::target` names what each points at or refers to. A type `match const` chooses by `T` is chosen there wherever what is proved of `T` decides it, as in an arm or branch, and is otherwise a type of its own until each instance chooses. A value given as one, or as a type holding one, as `&castref<T>` or `vector<castref<T>>`, returned, held, passed, or converted with `as`, is checked once in each way it can be chosen, with what that way says of `T`, as a branch is, so a function can give one. A value of one is used so too: what uses it, an operator, `*`, a member, an index, a method, an assignment, `is`, `match`, `for`, or a test naming what it holds, is checked in each way, and gives the type it gives in each, or one chosen as the value's is, as `w + w` of a `word<N>` is `N == 4 ? u32 : u64`:
```sakura
type widened<T> = match const T { integer => i64, real => f64, else => T };
def widen<T>(x: T): widened<T> {
return match const T { integer => x as i64, real => x as f64, else => x };
}
```
An instance no arm fits, where there is no `else`, is an error, and so is a type whose choosing never ends, as one naming itself in every arm, after 32 steps of aliases and choices. An alias of one stands for the type it chooses, unlike any other alias, so `strip_pointer<*i32>` is `i32`, to `is` and as a type argument: `vector<strip_pointer<*i32>>` is `vector<i32>`. Where none is expected, a `match const` value is of the type its arms share in the generic's own body, in each instance, so `integer => 1u, else => 0` is a `u64` in each.
**`C ? A : B`** as a type is `A` where the constant `bool` `C` holds and `B` where it doesn't. Each part of `C` chooses as `match const` does: a test of a type by what it tests, as `T is reference`, and any other part by the `bool` it is, as a constant, a constant parameter, `N == 4`, or what a function gives, as `small(N)`. So an alias of one stands for what it chooses, and within a generic's own body it is chosen where what is proved decides it, as within `if const C`. What follows each part is resolved with what the part says, so `T::target` names what `T` refers to where `T is reference`, and the right of `&&` is resolved where its left holds, as `T is pointer && T::target is integer`:
```sakura
type decay<T> = match const T { pointer, reference => decay<T::target>, else => T };
type makeref<T, const MUTABLE: bool> = MUTABLE ? &mut decay<T> : &decay<T>; # makeref<*i32, true> is &mut i32
type remref<T> = T is reference ? T::target : T; # remref<&u8> is u8
type word<const N: u64> = small(N) ? u32 : u64;
type pick<const M: bool> = M ? u64 : u8;
def picked<const M: bool>(): pick<M> {
if const M { return 1u; } # a u64 here
return 2 as u8; # and a u8 here
}
type castref<T> = match const T { reference => T, pointer => makeref<T::target, T::mutable>, else => &T };
def asref<T>(p: T): castref<T> where T: pointer {
return p as castref<T>; # a &mut T::target where T::mutable, and a &T::target where not
}
```
A ternary of values whose condition is known while compiling and names a type parameter chooses its branch the same way, 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, so `return T::mutable ? &mut p[0] : &p[0];` gives a `castref<T>`. Where nothing is expected of it, its type is the one its branches share, or else one chosen as its condition chooses. A ternary over a value the program gives while running, or over a constant naming no type parameter, checks both branches as it always has.
`C` is a name, `!` of one, a call, a name tested with `is` or compared with `==` or `!=`, or an expression in parentheses, and what `&&` and `||` join to one of those, as `small(N) && M`. A comparison by `<` or `>` is written in parentheses, as `(N > 4) ? u64 : u8`, since those are a type's arguments. Within an instance, only the type chosen is resolved, so `T::target` is never asked of a `u8`, as no arm of a `match const` type after the one chosen is. A condition of more than 1024 cases is an error, as an `if const` one is. After `as` or `is`, `?` goes on with the expression's ternary, so `x as bool ? a : b` is unchanged, and among type arguments `buffer<u8, M ? 4 : 8>` is still a constant.
`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:
```sakura
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:
```sakura
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:
```sakura
@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`, `@inline`, `@kept`, and `@sealed` (see [Traits](#traits)).
`@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`:
```sakura
@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:
```sakura
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](#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:
```sakura
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++'s `unique_ptr` and Rust's `Box`. It is one word that is never null, so `maybe<box<T>>` is one word too. `get` lends the value, and `take` moves 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>` and `arc_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:
```sakura
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 element `i` along, `*p` is `p[0]`, and `through(p)` is a reference to it. A pointer is an address, so nothing is reached through `p.` itself.
- `p + n` and `p - n` move by elements, and `p - q` counts 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, `&x` a `*T` and `&mut x` a `*mut T` or a `*T`, as `val p: *mut node = &mut n;` or `look(&x)` for a `*T` parameter, and `address(x)` gives one, `*mut T` for what can be written and `*T` otherwise, as `through(p)` gives a reference. A pointer keeps nothing alive, so one at a value that ends with its statement, as `val p: *i64 = &10;`, is refused, though an argument lives as long as its call. A pointer becomes a reference through `through`, or `as`, as `p as &mut node`, one that writes only from a `*mut T`, and never one to a trait, which holds its table beside the address. A type parameter bounded by `pointer` is a pointer there, so `through(p)` and `p as u64` take one.
- `*mut T` converts to `*T`, never the reverse. `as` converts pointers to and from integers and other pointer types, and `&x as *T` takes 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()`:
```sakura
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; a temporary kept past its statement; and what a loop walks changed whole by the loop's body, which may move what the loop reads next: a method taking `&mut this` of it, `&mut` of it, or assigning it, as `v.append(x)` within `for x in v`, `for x in v.span`, or `for x in v[1:]`. Changing what it holds in place, as `v[i] = x` or `v.first += 1`, moves nothing, and a fixed array holds its elements where it is, so neither is warned of. 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. What the machine reads for the program is checked as the program's own reads are: formatting a value, which reads what a reference refers to and each element of a view, and `==` of arrays, which compares their bytes. 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.
Once the program starts a thread, it stops where two threads reach the same memory, one writing it, with nothing ordering the two: "Threads raced", naming where the other access was. What orders threads is what C++'s memory model says: starting a thread orders what the starter did before what the thread does, an atomic stored with `release` (or `acq_rel`, or `seq_cst`) orders what its thread did before what follows a load of it with `acquire`, and joining a thread waits for it so, as std's mutexes, conditions, and channels do. A `relaxed` atomic orders nothing. It watches what threads reach of each other through references, a closure's locals among them, and memory allocated anew starts afresh. Of each word it keeps the last write and the last reads of two threads, so a race among three readers and a writer may go unseen.
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. A variable `undefined` stays in its memory at every level, where an unchecked run's optimizer would keep it in a register. Formatting a struct reads each field, and a union the field it holds, so the bytes between fields stop nothing. 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](#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:
```sakura
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`
```
```sakura
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 `when` is required**, and names `os`, `arch`, or both, since a library is one system's, and so is C's calling convention. A section for `arch` alone suits only libraries whose types are the same size on every system: C's `long` is 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 `is` and `match` can'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 import`s name for the target, and an `extern import` may have a `when` of 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.exe` itself, then every DLL loaded into it but `ntdll.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 `system` is 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 `&T` as 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](core), [system](system), and [runtime](runtime), compiled into executables, which programs don't import. The standard library is [a repository of its own](https://git.malunal.studio/sakura/std), 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`, `tuple`, `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`:
```sakura
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.span, 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)` and `store(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 as `as` converts, and `bits::<M, K>()`, the same bytes as other lanes, which refuses `K` lanes of `M` that aren't as many bytes while compiling.
- **Halves and widths**: `low()` and `high()`, the halves of a vector as vectors of half as many lanes, and `f32x4::join(low, high)` the vector of both; `widened::<M>()` and `widened_high::<M>()`, the first or second half of the lanes, each as a lane of `M` twice as wide; and `narrowed::<M>(&other)`, this vector's lanes then the other's, each as a lane of `M` half as wide, held at `M`'s limits.
- **Gathering**: `f64x4::gather(from, at)` reads the lanes of a view at the places a `simd<i32[N]>` names, and `v.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 a `u32` count. 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`, and `greater_equal` give a `mask<L[N]>`, whose `any`, `all`, `none`, `count`, `first`, `has(i)`, and `bits()` 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`, and `abs`, and across the lanes `sum`, `product`, `smallest`, and `largest`, lane 0 first. `std::math` declares the functions of reals on vectors too, seen where it's imported: `fma`, and of real lanes `sqrt`, `floor`, `ceil`, `trunc`, `round`, and `round_even`, each as it gives it of the lane.
- **The same bits everywhere**: each operation is written in `core` lane by lane, which the VM and constants run. An executable asks its processor which vector instructions it has as it starts, with `cpuid`, 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 for `fma`. Where it lacks them, a vector is worked a half or a quarter at a time, or the lanes as `core` writes them. Whichever runs, the bits are the same. Integer division and `%`, `scatter`, the `product` of integers, and the `smallest` and `largest` of reals have no instructions, and are always worked a lane at a time.
- **`SAKURA_CPU`** names the instruction sets an executable may use, joined by `+`: `sse2`, `ssse3`, `sse4.1`, `sse4.2`, `avx`, `avx2`, `fma`, `popcnt`, `lzcnt`, `bmi1`, and `avx512`, or a level of x86-64, `x86-64`, `x86-64-v2`, `x86-64-v3`, or `x86-64-v4`. `SAKURA_CPU=x86-64 ./program` runs a program as on a processor with SSE2 alone.
- **In registers**: executables built with `-O2` hold 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 working `f32x8` does, 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:
```sakura
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 `bytes8` is eight bytes in a `u64`, the first in its lowest byte. `swar::load(text, at)` reads one, stopping the program past the view's end, and `load_last` reads 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`, and `ascii` each give a `mask8` of the bytes they choose, exact in every byte. A mask's `any`, `first`, `last`, `count`, and `rest` read it, and `&`, `|`, `^`, and `~` combine masks.
- **Changes**: `upper` and `lower` change ASCII letters, `digits` reads eight ASCII digits as a number, or `nothing`, and `choose(mask, then, otherwise)` takes each byte from one word or the other.
- **The same everywhere**: words are `u64` arithmetic, 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:
```sakura
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`, and `compare_exchange_weak`, and of integers `fetch_add`, `fetch_sub`, `fetch_and`, `fetch_or`, `fetch_xor`, `fetch_min`, and `fetch_max`, each giving what it held. Adding and subtracting wrap, and the least and greatest are compared as `T` is, signed or unsigned. Another `T` given to these stops the compile.
- **Orders** are C11's, as C, C++, Rust, and Zig have them: `order::relaxed`, `acquire`, `release`, `acq_rel`, and `seq_cst`, which is what each operation takes where none is written. A `release` store that an `acquire` load 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 a `release` load, stops the program with a fault saying so.
- **Never copied by accident**: an atomic is `owning`, closing nothing, so `val 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:
```sakura
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, unless built `--windowed`, 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](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](#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 |
**Shown as a program of its own**: a Windows executable may hold what Explorer and the system show it by, in its resources. `--icon FILE` is its icon, a PNG or an icon file, `.ico`, given again for each size: Explorer, a shortcut to it, a pinned taskbar button, and its windows show it, as `LoadImageW(GetModuleHandleW(0), 1, ...)` finds it. A PNG is kept whole, as Windows has read an icon's PNGs since Vista, and one wider or taller than 256 pixels is left out, saying so, so a larger one meant for Linux builds too. `--title TEXT` and `--semv VERSION` are what its properties say of it: its description and product, which Task Manager names it by, its version, and its file's name. `--windowed` runs it in windows of its own, as a program of the GUI subsystem, so no console opens as it starts, and a console program it starts, as a shell or a compiler, is given a console no one sees rather than one Windows would open for it. The icon's files are among those `--deps` writes. A Linux executable holds none of these: Linux's desktops find a program's icon and title by a desktop entry installed beside it, which `blossom install` writes, so they're left out there, saying so.
**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` |
| `tools/winmd/`, `tools/winmd_dump.sakura` | [The reader of `.winmd` files](tools/winmd/README.md), which describe Windows' functions and types for bindings to be generated from, and a program showing what one holds |
| `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::analyzer`](analyzer/README.md) lexes, parses, and checks, and answers the language server's queries.
- [`sakura::compiler`](compiler/README.md) lowers a checked program to intermediate code, optimizes it, and assembles the virtual machine's code.
- [`sakura::machine`](machine/README.md) is the virtual machine, which also evaluates constants while compiling.
- [`sakura::native`](native/README.md) is the native backend, which chooses the instructions of an executable, places its values, and lays out its file and its debugging information.
- [`sakura::server`](server/README.md) is the language server `sakurac lsp` serves, which also finds `core`, `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 reads `std::args` for its command line and `std::json` for the language server, besides containers, files, and threads.
- `binary` holds the back end's libraries, `binary::amd64`, `binary::elf`, `binary::dwarf`, `binary::pe`, and `binary::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`, and `sakura.server.tests`, each part's, on the machine;
- `winmd.tests`, of the reader of `.winmd` files, on the machine;
- `sakurac.core`, the tests of `core` and `system`, built and run as an executable;
- `sakurac.corpus`, `sakurac.checked`, and `sakurac.memory`, the corpus, each program run by the `sakurac` just built over `../std`, the last with `run --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
```ebnf
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
```ebnf
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" [ "mut" ] | "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 ] ";" ; (* "..." holds a pack *)
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
```ebnf
type = "*" [ "mut" ] type (* pointer *)
| "&" [ "mut" ] type (* reference *)
| type_primary { "[" expression "]" (* fixed array *)
| "..." "[" expression "]" } ; (* a pack's type, as Ts...[0] *)
type_primary = "def" "(" [ type { "," type } [ "..." ] ] ")" ":" type (* function *)
| "(" type ")"
| "type_of" "(" expression ")"
| "match" "const" type "{" type_arm { "," type_arm } [ "," ] "}"
| type_cond "?" type ":" type (* chosen by a constant bool *)
| type_name ;
type_cond = "!" type_name
| ( type_name [ "is" [ "not" ] type | ( "==" | "!=" ) cast ]
| name call (* small(N) *)
| "(" expression ")" ) { ( "&&" | "||" ) cast } ;
type_arm = ( "else" | type { "," type } ) "=>" type ;
type_name = segment { "::" segment } ;
segment = ident [ "<" type_arg { "," type_arg } ">" ] ;
type_arg = type [ "..." ] | expression ; (* "..." passes a pack on *)
```
### Statements
```ebnf
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" [ "const" ] condition_expr "{" { arm } "}" ;
arm = ( "else" | pattern { "," pattern } ) "=>" ( block | statement ) ;
pattern = expression | type ; (* a type after `match const` *)
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.
```ebnf
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" [ "const" ] 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" | pattern { "," pattern } ) "=>" expression ;
```
---
## License
Sakura is released under the MIT License: see [LICENSE](LICENSE). What changed in each version is in [CHANGELOG.md](CHANGELOG.md).