Rio
Rio is a small, statically typed scripting language for embedding, from desktop apps down to microcontrollers: one C99 library that runs in a single block of memory, with no allocation, no garbage collector and no recursion.
Point :: [2]Float
Ball :: struct
pos, vel: Point
end
b := Ball{pos = {1, 2}, vel = {3, 4}}
b.pos += b.vel * 0.5
log("at", b.pos.x, b.pos.y)
at 2.5 4.0
- The tutorial shows Rio by example.
- The spec says what Rio programs mean, mostly with examples, which the tests run.
- The guide covers the C library and the
riocommand: embedding, memory, images, C output and native code on ARM.
Source: github.com/contextfreeinfo/rio.
Getting started
This tutorial shows Rio by example, a page at a time. Each example is a whole program you can run. For the exact rules, see the spec.
Get Rio
Download a build from the nightly release, or build it, with a C compiler and CMake:
cmake -S . -B build
cmake --build build --config Release
Hello
Save this as hello.rio:
log("hello from rio")
and run it:
rio hello.rio
hello from rio
log prints its arguments on a line, with spaces between them. The program's top-level code runs
first; then, if there's a proc named main, rio calls it:
greeting := "hi"
main :: proc()
log(greeting, "from main")
end
hi from main
The REPL
rio on its own starts a REPL, where each input runs as you enter it, and a bare expression shows
its value. Names stay around from one input to the next:
> x := 6 * 7
> x
42
> sq :: proc(n: Int) -> Int
. return n * n
. end
> sq(x)
1764
An unfinished input, such as an open block, gets a . prompt for more. Ctrl-C stops a program that's
running.
Next: values and procs.
Values and procs
Variables
:= declares a variable, with its type from its value. : writes the type instead, and the
variable starts at zero unless you give it a value:
count := 0 # Int: 32 bits
speed := 2.5 # Float: 32 bits
name := "ann" # String
ready := false # Bool
hp: Int # 0
scale: Float = 2 # a number literal fits a Float
count += 3
log(count, speed, name, ready, hp, scale)
3 2.5 ann false 0 2.0
Each variable keeps its type. Rio doesn't mix Int and Float without being asked:
n := 3
x := 1.5
log(x * n.toFloat(), (x * 2.0).toInt())
4.5 3
:: declares a constant, a value known when compiling:
SIZE :: 8
HALF :: SIZE / 2
log(HALF)
4
Procs
A proc takes parameters, and maybe gives a result with -> Type:
area :: proc(w, h: Int) -> Int
return w * h
end
shout :: proc(text: String)
log(text, "!")
end
shout("hey")
log(area(3, 4))
hey !
12
Everything is declared before it's used, so a proc can only call procs above it. That rules out recursion, and Rio uses that: each proc gets one fixed piece of memory for its locals, with no stack to overflow.
Choices and loops
for n in 1..=15
if n % 15 == 0
log("fizzbuzz")
case n % 3 == 0
log("fizz")
case n % 5 == 0
log("buzz")
case n > 12
log(n)
end
end
fizz
buzz
fizz
fizz
buzz
fizz
13
14
fizzbuzz
Conditions are Bools, joined with and, or and not. for also loops while a condition holds,
or forever until break:
n := 1
for n < 100
n *= 3
end
steps := 0
for
steps += 1
if steps == 4
break
end
end
log(n, steps)
243 4
A block of one statement can go on its line, after do, with no end:
steps := 0
for
steps += 1
if steps == 4 do break
end
for i in 0..<3 do log(i * steps)
0
4
8
When things go wrong
Mistakes the compiler can see stop the program before it runs, with a line and column. Mistakes it can't see, such as an index out of range, stop the program where they happen, with a line:
xs: [3]Int
i := 5
log(xs[i]) # runtime error: index out of bounds
Integer math wraps around instead of failing, and dividing by zero is an error.
Next: data.
Data
Structs
A struct groups named fields. A literal names the fields it sets; the rest are zero:
Vec :: struct
x, y: Float
end
Ball :: struct
pos, vel: Vec
bounces: Int
end
b := Ball{pos = {x = 10}, vel = {x = 1, y = -2}}
b.pos.y += b.vel.y
log(b.pos.x, b.pos.y, b.bounces)
10.0 -2.0 0
The literal's type can be left off where it's known, as in pos = {x = 10} above. Structs are values:
c := b is a copy, and changing c leaves b alone.
For vectors, use an array of numbers: it does math an element at a time, and .x and .y name its
first two elements:
Point :: [2]Float
pos := Point{1, 1}
vel := Point{3, 4}
pos += vel * 0.5
log(pos.x, pos.y)
2.5 3.0
Arrays and slices
[N]T is N values in a row. A slice []T is a view of some of them, and it's what procs usually take:
total :: proc(xs: []Int) -> Int
sum := 0
for x in xs
sum += x
end
return sum
end
scores: [5]Int
for s, i in scores
s = i * 10 # s is the element itself
end
log(total(scores), total(scores[1..<3]), scores.len())
100 30 5
Every index is checked, so a bad one stops the program instead of reading the wrong memory.
An array literal gives the values in order, and the rest are zero. As with structs, the type can be left off where it's known:
primes := [6]Int{2, 3, 5, 7}
corners: [4][2]Int = {{0, 0}, {1, 0}, {1, 1}}
log(primes[3], primes[5], corners[2][1], corners[3][0])
7 0 1 0
Changing the caller's things
Parameters are copies. To let a proc change something of yours, give it a & parameter, and pass
& the thing:
Ship :: struct
hp: Int
end
hit :: proc(s: &Ship, damage: Int)
s.hp -= damage
end
fleet: [3]Ship
for s in fleet
s.hp = 10
end
hit(&fleet[1], 4)
log(fleet[0].hp, fleet[1].hp)
10 6
Strings and bytes
A String is read-only text, and a Blob is bytes you can change. Indexing either gives a byte as an
Int. b[] views a Blob[N] as a Blob, and b.asString() as a String:
s := "rio"
b: Blob[3]
for c, i in s
b[i] = c - 32 # to uppercase
end
log(s[0], b.asString(), s == "rio")
114 RIO true
Next: builders and text.
Builders and text
Rio never allocates memory while running, so builders have a fixed capacity, and a length that changes.
[..N]T holds up to N:
Enemy :: struct
x, hp: Int
end
enemies: [..64]Enemy
for i in 0..<3
_ = enemies.push({x = i * 10, hp = 3})
end
for e in enemies
e.hp -= 1
end
enemies.swapRemove(0) # quick: the last one takes its place
log(enemies.len(), enemies[0].x, enemies.cap())
2 20 64
push gives false when the builder is full, and changes nothing. A proc that adds to a builder
takes a builder view, [..]T, that pushes into the caller's builder:
spawn :: proc(out: [..]Int, n: Int)
for i in 0..<n
_ = out.push(i)
end
end
xs: [..8]Int
spawn(xs, 3)
spawn(xs, 2)
log(xs.len(), xs[4])
5 1
Building text
A builder of bytes, Blob[..N], builds text. print appends values as log would show them, but
without spaces:
line: Blob[..32]
hp := 7
_ = line.print("hp: ", hp, "/", 10)
_ = line.push('!')
log(line[])
hp: 7/10!
If it doesn't all fit, print changes nothing and gives false. format does the same, with
settings for widths, digits and bases first (see format):
row: Blob[..32]
_ = row.format({width = 3}, 7, 42, 100)
log(row[])
7 42100
Next: methods, enums, unions and maybes.
Methods, enums, unions and maybes
Methods
A method is a proc on a type. Inside, self is what it was called on, and for a struct, changes to
self change the real thing:
Ship :: struct
x, vx: Float
end
Ship.move :: proc(dt: Float)
self.x += self.vx * dt
end
s := Ship{vx = 4}
s.move(0.5)
log(s.x)
2.0
Enums
An enum is a set of named values:
Dir :: enum
north, east, south, west
end
turn :: proc(d: Dir) -> Dir
switch d
case .north
return .east
case .east
return .south
case .south
return .west
case .west
return .north
end
end
d := Dir.north
d = turn(turn(d))
log(d)
south
.south is enough where Rio knows the type. A switch on an enum has to handle every value (or have
an else), so adding a value later points you at every switch to update.
Unions
A union holds one of several types, and knows which:
Circle :: struct
r: Float
end
Box :: struct
w, h: Float
end
Shape :: union
Circle, Box
end
area :: proc(s: Shape) -> Float
switch s
case Circle
return 3.14 * s.r * s.r # here, s is the Circle
case Box
return s.w * s.h
end
end
shapes: [2]Shape
shapes[0] = Circle{r = 1}
shapes[1] = Box{w = 2, h = 3}
for s in shapes
log(area(s))
end
3.14
6.0
if s is Box works too, and inside that if, s is the Box.
Maybes
Some things may not be there: a search that finds nothing, an enemy with no target yet. ?T is either
nil or a T, and it starts as nil:
Item :: struct
name: String
price: Int
sale: ?Int # a sale price, if there is one
end
items: [3]Item
items[0] = Item{name = "lamp", price = 30}
items[1] = Item{name = "rug", price = 80, sale = 60}
items[2] = Item{name = "vase", price = 45}
cost :: proc(it: &Item) -> Int
sale := it.sale
if sale is Int
return sale # here, sale is the Int
end
return it.price
end
cheapest :: proc() -> ?Int # which item costs least under 50, if any does
best: ?Int
bestCost := 50
for i in 0..<3
if cost(&items[i]) < bestCost
best = i
bestCost = cost(&items[i])
end
end
return best
end
log(cost(&items[0]), cost(&items[1]))
pick := cheapest()
switch pick
case nil
log("nothing under 50")
case Int
log(items[pick].name)
end
log(items[1].sale, items[2].sale)
30 60
lamp
60 nil
Rio won't let a ?Int be used as an Int until it's checked, so a missing value can't slip through
as a 0 by mistake.
Proc values
A proc can be passed around and called later:
twice :: callback proc(n: Int) -> Int
return n * 2
end
each :: proc(xs: []Int, f: proc(Int) -> Int)
for x in xs
x = f(x)
end
end
nums: [3]Int
nums[2] = 5
each(nums, twice)
log(nums[2])
10
Next: modules.
Modules
Each file is a module. Names ending in * are exported; the rest stay private. Import a file next to
yours with a leading .:
Rect* :: struct
w, h: Int
end
Rect.area* :: proc() -> Int
return self.w * self.h
end
import .shapes
r := shapes.Rect{w = 3, h = 4}
log(r.area())
12
Without the ., an import names a package from your library directories: rio -L libs game.rio
finds import tween as libs/tween.rio or libs/tween/tween.rio. Bring in single names with
import tween.{lerp}, and rename with as.
include "part.rio" pulls another file into this module, private names and all, to split a big
module up.
Next: embedding Rio in C.
Embedding Rio in C
Rio is made to live inside another program, the host. The host gives it one block of memory, and Rio never allocates any more:
#include <stdio.h>
#include <string.h>
#include "rio.h"
static uint8_t mem[64 << 10]; // everything: the program's code and data
static rio_Vm vm;
static void print(void *ud, const char *s, int n) { fwrite(s, 1, n, stdout); putchar('\n'); }
static void beep(rio_Vm *vm, rio_Val *a) { printf("beep %d\n", a[0].i); } // a host proc
int main(void) {
const char *src = "pitch* := 440\nbeep(pitch)\nupdate* :: proc()\n pitch += 1\nend\n";
rio_init(&vm, mem, sizeof mem, NULL, 0);
rio_setLog(&vm, print, NULL);
rio_addFfi(&vm, "beep", "i", beep); // beep(Int): no result
if (rio_compile(&vm, src, strlen(src)) || rio_run(&vm)) return puts(rio_error(&vm)), 1;
int update = rio_findProc(&vm, "update"); // marked with * in the source
for (int i = 0; i < 3; i++) rio_call(&vm, update);
int *pitch = rio_findGlobal(&vm, "pitch");
printf("%d\n", *pitch); // 443
return 0;
}
rio_compilethenrio_runcompiles the program and runs its top-level code.- Host procs, registered with
rio_addFfi, are what a program can do beyond math and text: draw, play sound, read files. Their signature letters areiInt,fFloat,sString,bBlob, with>before the result:"ff>f"takes twoFloats and gives one. - Names ending in
*in the main file are what the host can find and call.
To publish a host's API in Rio, write the host procs out with host, and the compiler checks them
against the real ones:
beep* :: host proc(pitch: Int)
The C API guide has the rest: modules of host procs, errors, the REPL, memory limits, and saving compiled programs as images.
The Rio language
Rio is a small, statically typed language for embedding in other programs, down to microcontrollers.
This spec says what Rio programs mean, for people writing them and for people implementing Rio. It
leans on examples, and the examples are tests: tests/docs.py runs every one against the Rio in this
repository.
Design in brief
- Static types, mostly inferred:
x := 1is anInt. - No hidden allocation. A program's memory is known when it compiles: globals, one frame per proc, and fixed-size arrays and builders.
- No recursion. Everything is declared before it's used, so a proc can't call itself, directly or through others. That's what lets each proc have one fixed frame.
- Values are copied, views are explicit. Structs and arrays are values, copied when assigned.
Slices,
Strings,Blobs and builder views are views of memory, with types that say so.&lets a proc change the caller's things. - Safe at runtime. Indexes are checked, integers wrap, and errors stop the program with a line number, never with undefined behavior.
- The host provides the rest. There's no standard library beyond math and text. Anything else, such as drawing or files, comes from the program that embeds Rio as host procs.
Reading the examples
A rio block is a whole program. When it logs something, the block after it shows the output:
x := 6 * 7
log("x is", x)
x is 42
A comment # error: ... ends a line that must fail to compile with that message, and
# runtime error: ... a line that must stop the program when it runs:
x := 1
x = "one" # error: type mismatch
xs: [3]Int
i := 3
log(xs[i]) # runtime error: index out of bounds
The messages are the reference implementation's. Another implementation needs the same errors at the same places, not the same words.
Words used here
- Compile error: the program is rejected before any of it runs.
- Runtime error: the program stops, reporting the line. Nothing after it runs.
- Word: 4 bytes, the size of an
Int. - View: a value that refers to memory it doesn't own: a slice,
String,Blobor builder view.
Not yet in Rio
Generics, recursion (on purpose), closures, heap allocation (on purpose), and a standard library (the host's job). Where something is planned, the spec says so.
Source text
A source file is bytes, normally UTF-8. Names and keywords are ASCII; strings and comments can hold any bytes.
Lines and statements
A statement ends at the end of its line, or at ;. An expression goes on to the next line inside
brackets ((), [], {}), or after an operator that ends a line, but not before one that starts a
line:
a := 1; b := 2
total := a +
b
sum := (a
+ b)
log(total, sum)
3 3
a := 1
b := a
+ 1 # error: expected expression
Indentation means nothing to the compiler. Blocks end with end.
Comments
# starts a comment, to the end of the line (so #! works on the first line). There are no block
comments, and // is an error that says to use #:
x := 1 # one
y := "# is just a character here"
log(y)
# is just a character here
x := 1 // one # error: comments start with #
Names
A name is a letter or _, then letters, digits and _: x, hp2, _tmp, fromHex, up to 255
characters long. _ alone isn't a name: it means what's left out, in _ = f() (a value dropped),
for _ in xs (no variable) and [_]T{...} (a size from the values). Case matters. By convention, types are PascalCase and everything else, enum values included, is
camelCase; constants are often UPPER_CASE.
Keywords can't be names:
and break case continue do else end enum for if import in include is nil not or proc
return struct switch union
A few names mean something only in one place, and are ordinary names elsewhere: self in methods,
as in imports and destructuring, by in for loops, and host before proc or struct in a
declaration. The builtin names (Int,
true, sqrt, ...) are declared outside every module, so a declaration with the same name hides
them.
Numbers
Integer literals are decimal, hex (0x) or binary (0b), and _ can go between any two digits.
A decimal literal can be at most 2147483647 (and 2147483648 right after -). Hex and binary give
any 32 bits:
log(1_000_000, 0xFF, 0b1010, 0xFFFF_FFFF, -2147483648)
1000000 255 10 -1 -2147483648
x := 2147483648 # error: number too big for Int
A float literal has a decimal point with digits on both sides, or an exponent, or both: 1.5,
2e10, 1.5e-3. 1. and .5 aren't numbers. Floats are 32-bit, so a literal rounds to the
nearest Float:
log(1.5, 2e3, 1_000.25, 123456789.0)
1.5 2000.0 1000.25 123456792.0
Characters and strings
A character literal is one byte, as an Int: 'a' is 97. A string literal is "...". Both take
these escapes, and any other backslash is an error:
| escape | byte |
|---|---|
\n \t \r \0 | newline, tab, carriage return, zero |
\\ \" \' | the character itself |
\xHH | the byte of those two hex digits (\x1b is 27) |
\u{1F600} | a code point, by its 1 to 6 hex digits: in a string, its bytes in UTF-8; as a character, the code point itself ('\u{E9}' is 233) |
log('a', '\n', "say \"hi\"", '\xff', "\x48\x69".len())
log("caf\u{E9}", "caf\u{E9}".len(), "\u{1F600}".len(), '\u{E9}')
97 10 say "hi" 255 2
café 5 4 233
A code point past 10FFFF, or a surrogate (D800 to DFFF, which UTF-8 doesn't have), is an error:
log("\u{D800}") # error: \u{...} takes 1 to 6 hex digits, a code point up to 10FFFF and not a surrogate
log("\q") # error: unknown escape
log("\x4") # error: \x takes two hex digits
Strings over more lines
A line with no closing quote ends its string with a line break, and the string goes on if the next line starts with a quote. Each line's indent comes before its quote, so it isn't part of the string, and neither are the spaces and tabs at the end of an open line. Close the last line for no line break at the end:
keys :=
"Keys:
" arrows move
" Z jump"
log(keys)
Keys:
arrows move
Z jump
Left open, the last line keeps its line break too, and a line of just a quote is an empty one. A string ends with its line unless the next one starts with a quote, so a quote left open by mistake goes no further:
s :=
"one
"
"three
log(s.len(), s == "one\n\nthree\n")
11 true
Strings side by side
Strings side by side are one string: on one line, and over more lines inside brackets. That splits a long line without breaking it, and keeps spaces at the end of a line:
log("abc" "def")
long := (
"a long line, "
"split in two"
)
log(long)
log("two spaces: " "|")
abcdef
a long line, split in two
two spaces: |
Operators and punctuation
+ - * / % & | ^ ~ << >> arithmetic and bits
== != < <= > >= and or not is comparison and logic
= := : :: += -= *= /= %= &= |= ^= <<= >>=
( ) [ ] { } , . ; ..< ..= -> & *
&&, || and ! are errors that name the word to use instead (and, or, not).
Types
Every expression has a type, known when compiling. There are no implicit conversions, except that
a number literal (or a constant made of them) takes the type its place needs: an Int literal can
be a Float.
Basic types
| type | values | size |
|---|---|---|
Int | 32-bit signed integers; arithmetic wraps | 1 word |
Float | 32-bit IEEE floats | 1 word |
Bool | true and false | 1 word |
String | a read-only view of bytes | 2 words |
Blob | a writable view of bytes | 2 words |
A byte read from a String or Blob is an Int from 0 to 255. Storing an Int as a byte keeps its
low 8 bits:
b: Blob[2]
b[0] = 300
b[1] = -1
log(b[0], b[1], "hi"[1])
44 255 105
Arrays, slices, builders
| owns its memory | a view of it (what procs take) | |
|---|---|---|
| fixed length | [N]T | []T |
| grows up to a capacity | [..N]T (a builder) | [..]T (a builder view) |
| bytes | Blob[N], Blob[..N] | Blob, Blob[..] |
N is a positive Int constant: a number, a constant's name, or arithmetic on those ([W * H]T,
[geo.SIZE + 1]T), worked out while compiling. An array indexed by an enum, [E]T, has one element per value of
E (see enums). Arrays nest: [4][4]Float is 4 rows of 4.
- An array
[N]Tis N elements, one after another. It's a value: assigning it copies it. - A slice
[]Tviews some elements of an array (2 words: where they start, how many). - A builder
[..N]Tholds up to N elements, and knows how many it has (a length word, then N elements). New builders are empty, unless made from a literal. - A builder view
[..]Tviews a builder, or any array, as a builder (3 words: where the length lives, where the elements start, the capacity). Pushing through a builder view changes the length it views. Blob[N]is N bytes, padded to whole words;Blob[..N]is a builder of bytes, for text.
xs: [4]Int # 4 Ints, all 0
part := xs[1..<3] # a []Int of 2, viewing xs
part[0] = 7
names: [..8]String # up to 8; empty for now
_ = names.push("ann")
log(xs[1], part.len(), names.len(), names.cap())
7 2 1 8
Structs
A struct is fields, in the order declared, one after another:
Vec :: struct
x, y: Float
end
Ship :: struct
pos, vel: Vec
hp: Int
tag: Blob[4]
end
s: Ship
log(s.pos.x, s.hp, s.tag.len())
0.0 0 4
Bitfields
A struct's field can be Int(n), n bits of a word, for n from 1 to 31: unsigned, or signed with
Int(-n). It reads as an Int (a signed one's top bit spread over the rest, so Int(-1) holds 0 or
-1), and storing keeps the value's low n bits, as storing a byte does. Bitfields fill a word from its
low bits, in order; one that doesn't fit in what's left starts a new word (none crosses words), and any
other field after them starts a new word too:
Header :: struct
kind: Int(4) # bits 0-3
level: Int(-4) # bits 4-7
flags: Int(8) # bits 8-15
size: Int(16) # bits 16-31: the same word
count: Int # the next word
end
h := Header{kind = 3, size = 70000}
h.level -= 3
log(h, h.size + 1)
raw: Blob[8]
raw.pack(0, h)
log(raw[0], raw.getInt(2, 16))
Header{kind = 3, level = -3, flags = 0, size = 4464, count = 0} 4465
211 4464
Since a word is little-endian, Int(8), Int(8), Int(16) are its bytes 0, 1 and 2 to 3, so a struct
can lay out a binary format byte for byte, for pack and unpack
(packing).
A bitfield can also be a Bool(1), or an enum's E(n), n bits with room for every one of E's values,
so adding a value an enum's bits can't hold is a compile error, not a broken layout. Each reads,
stores and prints as its own type:
Shape :: enum
circle, box, tri
end
Tile :: struct
kind: Shape(2) # bits 0-1: room for 4 values, and Shape has 3
solid: Bool(1) # bit 2
height: Int(5) # bits 3-7
end
t := Tile{kind = .tri, solid = true, height = 9}
t.kind = .box
raw: Blob[4]
raw.pack(0, t)
log(t, t.kind == .box, raw[0])
Tile{kind = box, solid = true, height = 9} true 77
A bitfield has no address of its own: &h.kind is an error, as is a bitfield type (Int(n),
Bool(1), E(n)) anywhere but a struct's field.
Enums
An enum is a named set of values, its own type, stored as an Int. Its values are 0, 1, 2 and so on,
in the order listed, so new variables start as the first; listing nil first makes that zero mean
"nothing":
Dir :: enum
north, east, south, west
end
Tile :: enum
nil
wall
water # 2
end
d: Dir
t: Tile
log(d, t, Tile.water.toInt())
for dir, i in Dir
log(i, dir)
end
north nil 2
0 north
1 east
2 south
3 west
A value can't be given a number of its own: other numbers, such as a file format's codes, are
constants (WALL :: 3), or an array [E]Int of them. [E]T has one element for each value, in
order, and for x in E (with an index, for x, i in E) goes through them.
Where an Int goes (assigned to one, passed or returned as one, an element or a field that's one), an
enum's value is its number, with no .toInt(). The other way, E.fromInt(n) checks that n is one of
its values. Operators still take two of one type (d == 1 and d + 1 are errors), x := d is the
enum, an index is an Int (an array indexed by the enum is [E]T), and a []E isn't a []Int:
Way :: enum
up, right, down, left
end
twice :: proc(n: Int) -> Int
return n * 2
end
n: Int = Way.down
log(n, twice(Way.left))
2 6
Unions
A union holds a value of one of its types, and remembers which (a tag word, then room for the biggest
type). Its zero is the first type's zero, so listing nil first makes an empty union:
Circle :: struct
r: Float
end
Box :: struct
w, h: Float
end
Shape :: union
nil
Circle, Box
end
s: Shape
log(s == nil)
s = Box{w = 2, h = 3}
log(s is Box)
true
true
Every value of a union takes its biggest type's room, whatever it holds, so a union of a small type
and a big one costs the big one's size for each value (in an array of them, for each element), as a
big array would: rio -m shows where memory goes.
Small :: struct
x: Int
end
Big :: struct
d: [20]Int
end
Shape :: union
Small, Big
end
s: Shape
log(s is Small, sizeOf(Shape))
true 84
Maybes
?T is a maybe: nil, or a T. It's a union of nil and T (a tag word, then the T), so it starts
as nil and works as unions do: a T or nil can be stored in it, x == nil and x != nil test it and
narrow it (x == 4 compares its value, false when nil), and a
switch takes case nil and case T. It can be written anywhere a type can, and every ?T is the
same type, wherever it's written:
Point :: struct
x, y: Int
end
Enemy :: struct
hp: Int
target: ?Point # (nothing to chase, to start)
end
find :: proc(xs: []Int, want: Int) -> ?Int
for x, i in xs
if x == want
return i
end
end
return nil
end
nums := [3]Int{5, 7, 9}
at := find(nums[], 9)
if at is Int
log("at", at) # here, at is the Int
end
log(find(nums[], 4))
e: Enemy
log(e)
e.target = Point{x = 3, y = 4}
log(e.target)
grid: [3]?Int
grid[1] = 5
log(grid)
at 2
nil
Enemy{hp = 0, target = nil}
Point{x = 3, y = 4}
[nil, 5, nil]
Prefixes nest, innermost last: ?[]?Int is a maybe slice of maybe Ints. A ?T can't be used as a
T until it's checked:
x: ?Int = 2
log(x + 1) # error: this may be nil
A union that lists nil already, or a maybe, takes no ?:
y: ??Int # error: this can already be nil
To tell two kinds of nothing apart, a union can name one with an empty struct, which takes no room:
Missing :: struct
end
Lookup :: union
nil
Missing, Int
end
x: Lookup = Missing{}
log(x is Missing, sizeOf(Missing), x)
true 0 Missing{}
A ?T that holds views (?String, ?[]Int) must be a global, as other unions holding them must
(see where views can live).
Maybes with if, not, and and or
A maybe works where a Bool does, as if a Bool were a maybe of nothing (true there, false nil):
| for Bools | for maybes | |
|---|---|---|
if x | when true | when x holds a value, x that value inside (if it's a variable) |
not x | the other | true when x is nil |
x and e | e if x, else false | e if x holds a value (x that value inside e), else nil |
x or y | true if either | x's value if it holds one, else y (y runs only then) |
x or y, for a ?T x, is a T when y is a T (so it takes no checking after it), and a ?T when y
is one too; y can't be of another type, since or joins its two sides into one value. and doesn't
join them, so they needn't agree: reading a Bool as a maybe of nothing, x and e is of e's type when
e can already be nothing (a Bool, or a maybe), and else a maybe of e's type, nil when x was false or
nil:
| gives | |
|---|---|
a and b, for Bools | a Bool |
m and m > 5, m a ?Int | a Bool |
n and n.next, n's next a ?Node | a ?Node (as n?.next would elsewhere) |
t and t.size, t's size an Int | a ?Int |
flag and 3, flag a Bool | a ?Int |
So flag and a or b chooses a or b only when a is neither a Bool nor a maybe (a false or nil a gives
b too): an if value says a choice plainly.
Only Bools and maybes are conditions: an Int isn't, so if count is still an error:
n := "42".toInt() or 0
m := "7".toInt()
if m
log("got", m + 1)
end
if not "x".toInt() do log("not a number")
double :: proc(k: ?Int) -> Int
return k and k * 2 or -1
end
log(n, m and m > 5, double(m), double(nil), true and 3, false and 3)
got 8
not a number
42 true 14 -1 3 nil
A ?Bool isn't a condition, since if x could ask whether it holds a value or whether that value is
true: x or false is the second, x is Bool the first.
Procs
A proc type is written proc(T, U) -> R, or without -> R when there's no result (another name
for one, in parentheses: Less :: (proc(a, b: Int) -> Bool)). Parameter names
are allowed, for reading: proc(x, y: Int) -> Int, and needed for an optional one, proc(x: Int, y?: Int) (see procs). See proc values.
Proc values can be elements too, of arrays, slices, builders and [E]T, with the proc type after the
brackets (but not a maybe: a proc value is unset until given a proc):
sine :: callback proc(t: Float) -> Float
return sin(t * 6.2831853)
end
square :: callback proc(t: Float) -> Float
if t < 0.5
return 1.0
end
return -1.0
end
shapes := [2]proc(Float) -> Float{sine, square}
for shape in shapes
log(shape(0.25))
end
voices: [..4]proc(Float) -> Float
_ = voices.push(square)
log(voices[0](0.75))
1.0
1.0
-1.0
References
&T is a reference: a name for a place that belongs to someone else. References exist only as
parameters and local names, and can't be stored, returned or put in a struct. See
references.
Zero values
Every variable starts as zero: 0, 0.0, false, empty strings, slices and builders, an enum's 0
value, a union's first type, and structs and arrays of zeros.
Small and big values
Values up to 16 words (64 bytes) are small: vectors, colors, 4x4 matrices, most structs. Bigger ones can't be copied without saying so, passed by value or returned. See copies.
Where views can live
Views (slices, String, Blob, builder views) can be locals and parameters, and so can structs,
arrays and unions that hold them, by the rules for views (see procs). One
holding a view of the proc's own memory anywhere in it counts as such a view, as a whole, so it can't
be kept past the call either. A field, or an element at a constant index, goes by what was stored
there (or in the whole).
Named :: struct
name: String
id: Int
end
label :: proc(n: Named) -> String do return n.name
f :: proc()
typed: Blob[4]
typed[0] = 'B'
n := Named{name = typed[0..<1].asString(), id = 2}
log(label(n), n.id)
end
f()
B 2
Named :: struct
name: String
id: Int
end
kept: Named
f :: proc()
typed: Blob[4]
kept = Named{name = "ada", id = 1} # fine: it views a constant
kept = Named{name = typed.asString(), id = 2} # error: holds a view of the proc's own memory
end
A builder holding views, or a big value (over 16 words) holding them, must be a global.
A field marked static (name: static String) holds only views that last the whole program, so
what's read from it can be kept anywhere: see static views.
Type identity
Structs, enums and unions are the same type only if they're the same declaration. Other types are
the same when they're written the same: [4]Int is [4]Int everywhere.
Declarations
:: declares something that doesn't change: a constant, a type, a proc, or another name for one.
:= and : declare variables.
Before use
Every name must be declared before it's used, in the order the source is read. So a proc can't call itself, or a proc declared after it, and Rio has no recursion:
f :: proc()
g() # error: undefined name
end
g :: proc()
end
Constants
NAME :: value names a value known when compiling: a number, Bool or String, or operators and
conversions on those. A constant number takes the type its place needs, as a literal does:
N :: 16
HALF :: N / 2
SCALE :: 1.5
NAME :: "rio"
x: Float = N # 16.0: N is a number, not just an Int
log(HALF, x, NAME)
8 16.0 rio
Constants can be declared in procs too. Top-level constants can be set from outside: see defines.
Variables
count := 0 # the type from the value: Int
speed: Float = 2 # the type written, and a value
grid: [4][4]Int # the type written: starts as zero
log(count, speed, grid[3][3])
0 2.0 0
A variable at the top level is a global, living as long as the program. One in a proc is a local; it starts again each time its declaration runs. A declaration is visible from there to the end of its block. A name is declared once where it's seen:
- At a module's top level (its parts included), a second variable, constant, proc or type of the same name is an error, which keeps a part's globals from quietly clashing with another's.
- A local (a parameter too) can't hide another local still in scope: declaring it again in the same
block or an inner one is an error, so
x := 5written forx = 5can't quietly make a newx. A block that's ended frees its names: two loops one after another can each have ani. - A local may hide a global or a builtin, which a proc's author needn't know all of:
x := 1
f :: proc()
x := 2.5 # a local x, in f only
for i in 0..<2
x += 1.0
end
for i in 0..<1 # (the first i's loop has ended)
log(x)
end
end
f()
log(x)
4.5
1
The REPL is the exception: each line typed may declare a name again, as trying things out needs.
Copies
Assigning, passing and returning copy values. To keep copies cheap and visible, a copy that isn't
written out is limited to 16 words: a bigger x := big is an error. Write the type to copy on
purpose, or take a view (big[]) or a reference (&big). Parameters and results are limited to 16
words; pass bigger values as &T or []T, and fill in a &T parameter instead of returning one.
Plain assignment, b = a, copies any size.
Big :: struct
a: [20]Int
end
g: Big
f :: proc()
copy: Big = g # fine: the type says it's a copy
x := g # error: this copies a big struct
end
Procs
add :: proc(a, b: Int) -> Int
return a + b
end
greet :: proc(name: String)
log("hi", name)
end
greet("ann")
log(add(2, 3))
hi ann
5
A parameter marked with ?, as in scale?: Int, is optional: a call may leave it out, and then it's
zero, as a variable is (nil for a maybe, empty for a String, a struct's fields all zero). Only the
last parameters can be optional, so arguments still go by position, and forgetting any other one is
still an error. A struct last makes a proc's options easy to leave out or give a few of:
Style :: struct
scale: Int
shadow: Bool
end
label :: proc(text: String, x: Int, style?: Style)
log(text, x, style.scale, style.shadow)
end
label("hi", 4)
label("hi", 4, {scale = 2})
hi 4 0 false
hi 4 2 false
f :: proc(a?: Int, b: Int) # error: after an optional parameter (name?: T), the rest are optional too
end
A & parameter can't be optional, since it needs a place. A proc type says which parameters are
optional the same way, proc(a: Int, b?: Int), and it's part of the type: a proc goes where a proc
value does only if the two agree.
Procs are declared at the top level. Parameters are values the proc can change without affecting the
caller, except &T parameters (see references). A proc with a result must
end with return on every path:
sign :: proc(n: Int) -> Int
if n < 0
return -1
end
end # error: missing return
A proc can't return a view of its own locals, or store one where it outlives the call (a global, or
through a & parameter): the next call reuses that memory.
f :: proc() -> []Int
xs: [3]Int
return xs[] # error: this returns a view of the proc's own memory
end
The same goes for a struct, array or union holding views, such as a struct with a String field or a
?String: it can be returned if what it holds views memory other than the proc's own.
Entry :: struct
key: String
n: Int
end
entry :: proc(line: String) -> Entry
for c, i in line
if c == '=' do return Entry{key = line[0..<i], n = line[i + 1..].toInt() or 0}
end
return Entry{key = line}
end
firstWord :: proc(s: String) -> ?String
for c, i in s
if c == ' ' do return s[0..<i]
end
return nil
end
e := entry("hp=12")
log(e.key, e.n, firstWord("hello there") or "-", firstWord("one") or "-")
hp 12 hello -
A view that comes in as a parameter may be one of the caller's own, so it's only borrowed: it can't be stored where it outlives the call either. To keep what it views, copy the bytes:
name := ""
rename :: proc(s: String)
name = s # error: this view came in as a parameter
end
name: Blob[..32]
rename :: proc(s: String)
name.clear()
ok := name.pushAll(s)
end
f :: proc()
typed: Blob[8]
typed[0] = 'A'
rename(typed[0..<1].asString())
end
f()
log(name.asString())
A
What's read through a & parameter or self is the caller's too, so a view read there is only
borrowed in the same way. A call's result, when it's a view or holds one, may view what went in, so it
counts as a view of whatever those were. That includes the places of & arguments and self, when
there's an array or builder in them for a view to view:
Box :: struct
xs: [4]Int
end
front :: proc(b: &Box) -> []Int
return b.xs[0..<2]
end
kept: []Int
f :: proc()
b: Box
kept = front(&b) # error: this view of the proc's own memory would outlive the call
end
Which locals hold such views is worked out in the order the code is written. A store in a local's own
block (the one it's declared in) replaces what it held. A store in an if or a loop inside that block
only adds to it, since it may not run. And in a loop, the code before a store runs after it too, so a
local from before the loop can't start holding such a view there:
kept: []Int
g: [4]Int
f :: proc(c: Bool)
xs: [4]Int
v := xs[]
v = g[] # its own block: v views only g now
kept = v
w := xs[]
if c
w = g[]
end
kept = w # error: this view of the proc's own memory would outlive the call
end
kept: []Int
g: [4]Int
f :: proc()
xs: [4]Int
v := g[]
for _ in 0..<2
kept = v
v = xs[] # error: in a loop, into a variable from before it that held none
end
end
And a call's result, when it's a view or holds one, may view what went in, so it's a view of the caller's own memory if any argument was. Each rule is about one proc's own code, so changing a proc's body never changes what its callers may do.
Static views
A view that lasts the whole program (a literal's, a constant's or a global's) can be kept anywhere.
Marked static, a signature or a struct says that's all it takes, or all it gives, and then it may
keep what it's given. Each use is checked against the claim, never against what a body happens to do:
- A parameter,
s: static String: each call must pass a view that lasts, and the proc may keep it. A static parameter passed on lasts too. - A result,
-> static String: the proc returns only views that last, so a caller may keep the result whatever it passed in. - A field,
name: static String: only views that last are stored there, so what's read from it lasts, even from a local or a borrowed struct. - A method's self,
self: staticfirst in its parameters: the method may keep views ofself(its arrays, say) or of whatselfholds, so it's called only on a global.
said := ""
say :: proc(s: static String)
said = s
end
Thing :: struct
name: static String
hp: Int
end
title :: proc(t: Thing) -> static String
if t.hp > 0 do return t.name
return "gone"
end
f :: proc()
t := Thing{name = "lamp", hp = 3}
say(title(t))
end
f()
log(said)
Menu :: struct
items: [3]String
shown: []String
end
Menu.showAll :: proc(self: static)
self.shown = self.items[]
end
menu := Menu{items = {"tea", "toast", "jam"}}
menu.showAll()
log(menu.shown.len(), menu.shown[1])
lamp
3 toast
said := ""
say :: proc(s: static String)
said = s
end
f :: proc(name: String)
say("hi") # fine: a literal lasts
say(name) # error: a static parameter
end
Thing :: struct
name: static String
end
f :: proc()
typed: Blob[4]
typed[0] = 'A'
t := Thing{name = typed[0..<1].asString()} # error: this field is static
end
Menu :: struct
items: [3]String
shown: []String
end
Menu.showAll :: proc(self: static)
self.shown = self.items[]
end
f :: proc()
m: Menu
m.showAll() # error: self: static
end
static is about how long what's viewed lasts, not about changing it: a static field can be set
again, to another view that lasts. It goes only on a view (a String, a Blob, a []T) or a value
holding views, and not on a & parameter. A proc with a static parameter or self can't be a proc
value yet, since a call through a proc type wouldn't check what's passed. static is a word only in
these places (and on static procs), so it reserves nothing.
Methods
Type.name :: proc declares a method on a type. Inside, self is the value it was called on: for
structs, the caller's own value; for Int, Float, Bool, String and Blob, a copy.
Ship :: struct
x, vx: Float
hp: Int
end
Ship.move :: proc(dt: Float)
self.x += self.vx * dt
end
Ship.hurt :: proc(n: Int) -> Bool
self.hp -= n
return self.hp <= 0
end
Int.double :: proc() -> Int
return self * 2
end
s := Ship{vx = 2, hp = 3}
s.move(0.5)
log(s.x, s.hurt(5), 21.double())
1.0 true 42
Each type has its own method names, apart from plain procs. A method can't have the same name as a
field of its type. Fields are always self.x; a plain x is never a field.
Type.name :: static proc declares a static proc: one called on the type, Type.name(...), with no
self, as a constructor is (static is a word only there, and in static views). It's one of the type's method names, and
travels with the type as its methods do, but a value can't call it, and the type can't call a method:
Rect :: struct
pos, size: [2]Float
end
Rect.of :: static callback proc(x, y, w, h: Float) -> Rect
return Rect{pos = {x, y}, size = {w, h}}
end
Rect.area :: proc() -> Float
return self.size.x * self.size.y
end
r := Rect.of(1, 2, 3, 4)
make := Rect.of # a proc value, as any proc's name is
log(r.area(), make(0, 0, 2, 2).area())
12.0 4.0
Structs, enums and unions
Vec :: struct
x, y: Float # several fields of one type
end
Dir :: enum
north, east, south, west
end
Shape :: union
Circle, Box
end
Field types, and the types in a union, must already be declared, so no type contains itself. See types for what they mean. Types are declared at the top level.
Other names for things
:: with an existing type, proc or module makes another name for it:
add :: proc(a, b: Int) -> Int
return a + b
end
plus :: add
Point :: [2]Float
p: Point
log(plus(1, 2), p.len())
3 2
A proc type takes parentheses, since Less :: proc(a, b: Int) -> Bool alone would start a proc of
that name:
Less :: (proc(a, b: Int) -> Bool)
lt :: callback proc(a, b: Int) -> Bool
return a < b
end
sorted :: proc(xs: []Int, less: Less) -> Bool
for i in 1..<xs.len()
if less(xs[i], xs[i - 1]) do return false
end
return true
end
xs := [3]Int{1, 2, 3}
log(sorted(xs[], lt))
true
Exports
A * after a top-level name exports it: other modules can use it, and the host can find it (see
modules and programs):
Vec* :: struct
x, y: Float
end
score* := 0
update* :: proc()
end
Generic procs
proc[T, U](...) names types a proc works on whatever they are. Each is found at every call, from
the arguments, so each must be in a parameter's type. The proc is compiled once, for every T: a call
passes, unseen, what T is, and so its size. In the body a T's size is known only while running, so a T
is only ever reached through a reference or a slice, never held:
- Where a T goes:
x: &T,xs: []Tandxs: [..]T, as parameters, in a proc type's parameters (less: proc(a, b: &T) -> Bool), and in a variable as[]Tor[..]T. - What a T does: it's copied from place to place (
xs[i] = x,a = b), swapped (xs.swap(i, j)), and passed on, to a generic proc or a proc value as&xs[i]. A[]Tis indexed, sliced and walked withfor x in xs(x is the element itself, as for any slice). A[..]Thas its builder methods too:xs.push(x)copies from a place, andxs.pop()gives the last one's place to copy from (out[i] = xs.pop(),ys.push(xs.pop())). Anything else is an error: comparing (pass in a proc that compares), arithmetic, printing, keeping one in a variable. A generic proc can't return a T, or be a proc value. - What a call checks: each T found agrees everywhere it's found. And a proc that copies its T into
memory it was given can't take a T holding views (a
String, a struct with one): it could keep a view past what it views, as any proc could by storing a borrowed view (xs.swapis fine, since both places are inxs).
sortBy :: proc[T](xs: []T, less: proc(a, b: &T) -> Bool)
for i in 1..<xs.len()
j := i
for j > 0 and less(&xs[j], &xs[j - 1])
xs.swap(j, j - 1)
j -= 1
end
end
end
find :: proc[T](xs: []T, x: &T, eq: proc(a, b: &T) -> Bool) -> Int
for i in 0..<xs.len()
if eq(&xs[i], &x) do return i
end
return -1
end
Player :: struct
name: String
score: Int
end
byScore :: callback proc(a, b: &Player) -> Bool do return a.score < b.score
intEq :: callback proc(a, b: &Int) -> Bool do return a == b
players := [_]{Player{name = "ann", score = 30}, Player{name = "bo", score = 10}}
sortBy(players[], byScore)
nums := [_]{4, 8, 15}
eight := 8
nine := 9
log(players[0].name, find(nums[], &eight, intEq), find(nums[], &nine, intEq))
bo 1 -1
A proc type can take types too, named and then filled in where it's used: Less :: (proc[T](a, b: &T) -> Bool), then Less[Point], or Less[T] in a generic proc. It's the same type as one written
out, so sortBy :: proc[T](xs: []T, less: Less[T]) reads as the one above.
A struct can take types the same way, Table :: struct[K, V], filled in where it's named:
Table[Int, Point], or Table[K, V] in a generic proc, which finds K and V through it. A T goes in a
field only in a []T or a proc type, so every field's size is the same whatever T is: each filled-in
struct is its own type, laid out as the others are, and no code is made per type. Each type parameter
must be in some field's type. A literal can leave the types out, Table{keys = ks[], ...}: each field's
value finds the ones its type has, in the order they're written, and every one must be found by the
end. A {...} going into a field whose type isn't known yet is an error: name the types then.
A generic struct's methods name its types first, in order, as a generic proc does: Table.put :: proc[K, V](key: &K, value: &V), with self a Table[K, V], found from the value it's called on. More
can follow (proc[K, V, U]), found from the arguments. A static proc on one is generic the same way,
found from its arguments, Table.make(ks[], vs[], eq), or named, Table[Int, Point].make(...). Any
type's methods can be generic too: Int.pick :: proc[T](xs: []T) -> T.
Table :: struct[K, V]
keys: []K
values: []V
eq: proc(a, b: &K) -> Bool
end
find :: proc[K, V](t: &Table[K, V], key: &K) -> Int
for i in 0..<t.keys.len()
if t.eq(&t.keys[i], &key) do return i
end
return -1
end
intEq :: callback proc(a, b: &Int) -> Bool do return a == b
ks := [_]{7, 3}
names := [_]{"seven", "three"}
t := Table{keys = ks[], values = names[], eq = intEq} # a Table[Int, String]
three := 3
log(t.values[find(&t, &three)], t)
three {keys = [7, 3], values = ["seven", "three"], eq = proc}
The ideas behind them
Generics follow from the rest of Rio, and these are worth checking new code against:
- Storage gives places; computation gives values.
for x in xs, a&Tparameter,self,xs[i]andp.fare places. A call's result, anext()result andxs.pop()are computed: they're copied, not borrowed (&xs.pop()is an error, since the next push reuses its slot). A T is always a place, since a generic body can't give one a home of its own. - Copies are visible.
a = bcopies, so doesxs.push(x), and every T copy is from place to place. - A proc stores only what it owns. A view or T that came in borrowed can't be stored where it
outlives the call. A generic proc that copies its T into memory it was given takes no T holding
views; moving within one sequence (
swap,remove,swapRemove) is fine. - What depends on the type comes in as a proc: comparing, ordering, hashing (
less,eq,hash). There are no constraints on a T. - Values decide types, in the order written:
[_]{...}, a generic call's arguments, and a generic struct's fields,Table{...}. The first that settles a type wins, and the rest must agree. - Type parameters go on the keyword and are filled in by name:
proc[T],struct[K, V],Name[...]. A call never names them, so[...]after a value is always indexing.
A generic container gives its elements as slices to walk, not through next(), which would return a
T by value.
Host procs
host proc and host struct declare something the host provides: see
host procs. Elsewhere, host is an ordinary name.
Expressions
Precedence
From tightest to loosest. Operators on one line group left to right:
| operators | |
|---|---|
f(x) a[i] a[i..<j] a.b T{...} | calls, indexing, slicing, members, literals |
- ~ | negation, bitwise not |
* / % & << >> >>> | |
+ - | ^ | |
== != < <= > >= is | comparisons don't chain |
not | |
and | |
or ..< ..= | ranges: see ranges |
log(2 + 3 * 4, 1 << 2 + 1, 7 & 3 + 1, -2 * 3)
log(not 1 == 2, true or false and false)
14 5 4 -6
true true
not a == b is not (a == b), as in Python.
Int arithmetic
Int math wraps around at 32 bits. / rounds toward zero, and % takes the sign of the left side.
Dividing by zero is a runtime error; -2147483648 / -1 wraps to itself, and % -1 is 0. Shift counts
use their low 5 bits, >> keeps the sign, and >>> shifts in zeros, as for the bits of an unsigned
number:
big := 2147483647
log(big + 1, 7 / 2, -7 / 2, -7 % 3, 7 % -3)
log(1 << 33, -16 >> 2, -16 >>> 28, 6 & 3, 6 | 3, 6 ^ 3, ~0)
-2147483648 3 -3 -1 1
2 -4 15 2 7 5 -1
n := 0
log(10 / n) # runtime error: division by zero
Float arithmetic
Float math is IEEE single precision: dividing by zero gives an infinity, and 0.0 / 0.0 is NaN,
which isn't equal to anything, itself included. %, & and the other bit operators are for Ints
only (fmod is the Float remainder).
zero := 0.0
log(1.0 / zero, 0.0 / zero, 0.1 + 0.2, 7.0 / 2)
nan := zero / zero
log(nan == nan)
inf nan 0.3 3.5
false
The two sides of an operator have the same type. A literal or constant number becomes a Float
where one is needed; otherwise convert with .toFloat() and .toInt():
x: Float = 1.5
log(x * 2, x + 1, 2.toFloat() / 4)
n := 3
log(x * n) # error: type mismatch
Comparisons and logic
== and != compare numbers, Bools, enums and Strings (the same bytes). <, <=, > and >=
compare numbers, and Strings by their bytes, a prefix first ("apple" < "apples"): for UTF-8 that's
the order of their code points, so "Zebra" < "apple" and "z" < "é". A maybe compares with == and
!= too (see unions). Arrays, structs and unions compare as whole values with == and !=
(not element by element): equal when every part is, each as == is for it, so a String inside by its
text, a Float as a number, and a union by the type it holds, then its value. Only what's made of
numbers, Bools, enums, Strings, Blobs and arrays, structs, unions and maybes of those compares:
another slice, a builder or a proc inside is an error, so == never follows a view past a String's
bytes. They don't order: < is for numbers and Strings. and, or and not take Bools, and and and
or skip their right side when the left decides:
calls := 0
yes :: proc() -> Bool
calls += 1
return true
end
a := false and yes()
b := true or yes()
log(calls, "ab" == "ab", "a" != "b")
0 true true
Dir :: enum
north, south
end
log(Dir.north < Dir.south) # error: enums compare only with == and !=
Conversions
Conversions are methods. to makes a new value; as views the same bytes:
n.toFloat() | Int to Float |
f.toInt() | toward zero; past the Int range it gives the nearest end, and NaN gives 0 |
n.toBool() | n != 0 |
b.toInt() | 1 or 0 |
e.toInt(), E.fromInt(n) | an enum's value (where an Int goes, it's that already); fromInt is a runtime error if n isn't one |
blob.asString() | the same bytes, read-only: a Blob's, a Blob[N]'s, or a Blob[..] builder's text as it is now (as b.asString()) |
s.toInt(), s.toInt(base) | text as an Int, a ?Int: nil if it isn't one |
s.toFloat() | text as a Float, a ?Float: nil if it isn't one |
log(3.9.toInt(), (-3.9).toInt(), (1e20).toInt(), 5.toBool(), true.toInt())
3 -3 2147483647 true 1
Text as numbers
A String, a Blob or a byte builder's text becomes a number with toInt or toFloat. The result
is a maybe, nil when the text isn't a number, so bad input is never a wrong number:
n := "42".toInt()
if n is Int
log(n + 1)
end
log("-17".toInt(), "4x".toInt(), "".toInt(), " 1".toInt())
43
-17 nil nil nil
The text is a sign or none, then digits, and nothing else: no spaces, no _, and no 0x. Letters
are digits past 9 in either case. toInt reads base 10 unless given a base from 2 to 36 (a base of
0 is 10, as leaving it out is; any other is an error). Base 10 must be in the Int range; any other
base is the bits, up to 32 of them, so ffffffff in base 16 is -1, as format writes it:
log("ff".toInt(16), "FF".toInt(16), "ffffffff".toInt(16), "1010".toInt(2), "z".toInt(36))
log("2147483647".toInt(), "-2147483648".toInt(), "2147483648".toInt(), "12".toInt(2))
255 255 -1 10 35
2147483647 -2147483648 nil nil
toFloat reads what a Float literal is, in base 10, with a sign or none: digits, then a point and
more digits if any, then an exponent if any. It gives the same Float as that literal would:
log("1.5".toFloat(), "-2e-3".toFloat(), "7".toFloat(), "3.25E2".toFloat())
log("1.".toFloat(), ".5".toFloat(), "1e".toFloat(), "inf".toFloat())
assert("0.1".toFloat() is Float)
1.5 -0.002 7.0 325.0
nil nil nil nil
Calls
Arguments are evaluated left to right, then the call runs. They must have the parameters' types,
except that number literals adapt. A &T parameter takes &place. See procs
and builtins.
A comma can end the arguments, as it can any list in brackets, so a call over more lines can put one argument on each line:
area :: proc(w: Int, h: Int) -> Int
return w * h
end
log(
area(3, 4),
area(
5,
6,
),
)
12 30
Indexing and slicing
a[i] is element i of an array, slice, builder, String or Blob, counting from 0. An index outside
0 <= i < a.len() is a runtime error (or a compile error, when it's a constant).
a[i..<j] is a view of elements i up to but not including j, and a[i..=j] up to and including j.
a[i..] runs to the end, a[..<j] and a[..=j] start at 0, and a[] is all of it. A range
value works too: a[r] is r.first to r.last. It's a runtime error unless the slice is inside a
(0 <= i <= j <= a.len(), with j one past the last). Slicing an array or builder gives a []T, a
String a String, and a Blob a Blob:
xs: [5]Int
for x, i in xs
x = i * 10
end
mid := xs[1..<4]
s := "hello"
r := 1..=2
log(mid.len(), mid[0], s[1..<3], s[3..], s[..=1], s[r], xs[].len())
n := 2
log(xs[n - 1..<n + 1], xs[n..])
3 10 el lo he el 5
[10, 20] [20, 30, 40]
xs: [3]Int
log(xs[2..<1].len()) # runtime error: slice out of bounds
Inside an index's brackets, end is the last index of what's indexed, a.len() - 1: a[end] is the
last element, and a[end - 2..=end] the last three. The brackets must be the innermost around it, so
in ys[xs[end]] it's xs's, and it means nothing elsewhere:
xs := [5]Int{10, 20, 30, 40, 50}
s := "hello"
log(xs[end], xs[end - 2..=end], s[end], s[..<end])
50 [30, 40, 50] 111 hell
An array indexed by an enum takes the enum's values as indexes, and as slice bounds:
Dir :: enum
north, east, south, west
end
counts: [Dir]Int
counts[.east] += 2
log(counts[.east], counts[.east..].len(), counts.len())
2 3 4
Its indexes are the enum's values, by name: not a number, and not end (which would move to a new
value added at the enum's end).
Ranges
a..<b is the Ints from a up to but not including b, and a..=b up to and including b. Either
is a Range, a built-in struct of its first and last values (inclusive, so it reaches every Int), and
it binds looser than anything but or, so 0..<n + 1 is 0..<(n + 1):
Range :: struct # (built in)
first: Int
last: Int # empty when last < first
end
r.len() is how many values it has (0 when empty) and r.has(i) whether i is one of them. It's
written first..=last (an empty one made by a..<a is a..=a - 1):
r := 2..<5
log(r, r.first, r.last, r.len(), r.has(4), r.has(5), (3..<3).len())
2..=4 2 4 3 true false 0
A range is a slice's bounds (see slicing), and a loop's: for i in r counts
from r.first to r.last. by steps it: a positive step counts up from first, a negative one down
from last, and neither goes past the other end (or wraps, at the ends of Int). The step can be any
Int expression; a step of 0 is a compile error when it's a constant, else a runtime error when the
loop starts. by means this only after a for's range: elsewhere it's a name like any other.
out: Blob[..80]
for i in 0..<10 by 3
_ = out.print(i, " ")
end
for i in 0..<5 by -1 # 4 down to 0
_ = out.print(i, " ")
end
r := 2..=8
step := -3
for i in r by step # from r.last down
_ = out.print(i, " ")
end
log(out[])
0 3 6 9 4 3 2 1 0 8 5 2
step := 0
for _ in 0..<3 by step # runtime error: a loop's step is 0
end
Members
a.f is field f of a struct (or of a struct reached through a reference or a slice element), and
a.m(...) calls method m. The parentheses make it a call; a method isn't a value.
Arrays of 1 to 4 numbers or Bools have swizzles, the letters x y z w or r g b a. One letter
is that element, and can be assigned. Two to four letters make a new array:
v: [3]Float
v.x = 1
v.y = 2
w := v.yx
c: [4]Int
c.a = 255
log(w.x, v.zyx.z, c.ar.x)
2.0 1.0 255
Struct literals
T{field = value, ...} makes a struct. Fields can come in any order, and the ones left out are zero.
Where the type is already decided (a typed declaration, assignment, argument, return, field or
push), T can be left off. A name or a dotted path alone fills the field of the same name as its
last part:
Vec :: struct
x, y: Float
end
Ship :: struct
pos: Vec
hp: Int
end
x := 3.0
a := Vec{y = 2, x = 1}
b: Vec = {x} # {x = x}
s := Ship{pos = {a.y}, hp = 5} # {y = a.y}
s.pos = {y = 9}
log(a.x, b.x, b.y, s.pos.y, s.hp)
1.0 3.0 0.0 9.0 5
v := {x = 1} is an error: nothing says which struct it is.
...x first in a struct literal starts it as a copy of x, a value of the same struct type, and the
fields named after it change the copy; the ones left out keep x's values. It's a copy, so x itself
is untouched, and p = {...p, x = 1} changes just p.x:
Vec :: struct
x, y: Float
end
a := Vec{x = 1, y = 2}
b := Vec{...a, y = 5}
a = {...a, x = a.x + 10}
log(a, b)
Vec{x = 11.0, y = 2.0} Vec{x = 1.0, y = 5.0}
Array literals
[N]T{a, b, ...} makes an array: its values in order, and zero for the elements after them. More
values than the array holds is an error. [..N]T{a, b, ...} makes a builder holding those values. As
with structs, where the type is already decided the type can be left off, so {...} is a struct or
an array by where it's going: a struct's fields are always named, and an array's values never are.
Literals nest:
Vec :: struct
x, y: Float
end
Dir :: enum
north, east, south, west
end
xs := [5]Int{1, 2, 3}
grid := [2][2]Int{{1, 2}, {3, 4}}
pts: [3]Vec = {{x = 1}, {y = 2}}
steps := [Dir]Int{-16, 1, 16, -1} # in the enum's order
todo := [..8]Int{4, 5}
_ = todo.push(6)
log(xs[2], xs[4], grid[1][0], pts[1].y, steps[.south], todo.len())
3 0 3 2.0 16 3
A literal is built each time it runs, so a local one starts over on every call, and changing it changes only that copy:
next :: proc() -> Int
counts := [2]Int{10}
counts[0] += 1
return counts[0]
end
log(next(), next())
11 11
a: [2]Int = {1, 2, 3} # error: more values than the array holds
[_]T{a, b, ...} is sized by its values, and [_]{a, b, ...} takes its element type from the first
value too (a whole number then a fraction is an error: write [_]Float). [N]{a, b} is N long, typed
by its first value, with zeros after the values given. And a {a, b, ...} where no struct, array or
slice is expected is [_]{a, b, ...}: {p.y, p.x} * 2, x := {1, 2}. Field names, {x = 1}, still
need a struct to go to. []T{...} and []{...}
are slice literals: the array is kept where a variable would be, and the literal is a slice of it, so
a {...} can go where a slice is wanted. In a proc that's the proc's own memory, built again each
time the literal runs, so it can't be returned or kept past the call:
sum :: proc(xs: []Int) -> Int
total := 0
for x in xs do total += x
return total
end
primes := [_]Int{2, 3, 5, 7}
names := [_]{"ann", "bo"}
odds := []{1, 3, 5}
odds[0] = 9
log(primes.len(), names[1], sum(odds), sum({1, 2}), sum([]{10, 20}))
4 bo 17 3 30
An array indexed by an enum can name its elements instead, as .value = x, in any order; the rest are
zero. Its values are all named or none are, each once, and a name can't stand for its value as a
struct's can ({.north} is an array holding .north):
Dir :: enum
north, east, south, west
end
Vec :: struct
x, y: Int
end
steps := [Dir]Int{.south = 16, .west = -1, .north = -16}
moves: [Dir]Vec = {.east = {x = 1}, .north = {y = -1}}
log(steps[.north], steps[.east], moves[.east].x, moves[.west].x)
-16 0 1 0
Dir :: enum
north, east
end
steps := [Dir]Int{.north = 1, 2} # error: name each value
Arithmetic on arrays
Arrays of numbers do arithmetic element by element: + - * / % and unary -. Both sides have the
same type, or one is a plain number, used for every element. Nesting works too. Structs don't do
arithmetic as wholes: for a vector, use an array, whose swizzles (.x, .y) name its
elements:
Point :: [2]Float
p := Point{1, 2}
v := Point{10, 20}
p += v * 0.5
grid: [2][2]Int
grid += 3
log(p.x, p.y, grid[1][1], (p - 1.0).x)
6.0 12.0 3 5.0
A result that isn't stored in place is limited to 16 numbers; update bigger arrays in place.
An array literal with no type written takes its partner's type, on the right of an operator whose left
side is an array, or after += and the like: p + {1, 0}, p *= {2, 1}.
The math builtins (abs, min, max, sqrt, floor, round, atan2, pow and the rest), and
toInt and toFloat, work on arrays of numbers element by element too, with a plain number used for
every element, so clamping a point is one line. toInt and toFloat give an array of the same shape:
Point :: [2]Float
p: Point = {12.6, -3.2}
p = max(Point{0, 0}, min(p, 10.0))
log(p, abs(Point{-1.5, 2}), round(p + {0.5, 0}), p.toInt(), [3]Int{1, -2, 3}.toFloat())
[10.0, 0.0] [1.5, 2.0] [11.0, 0.0] [10, 0] [1.0, -2.0, 3.0]
References
&place is a reference to a place: a variable, field or element that can be changed. It's passed to
a &T parameter, or bound to a local name with r := &place. Using the reference uses the place
itself, and the place is checked once, when the reference is made:
Ship :: struct
hp: Int
end
hurt :: proc(s: &Ship, n: Int)
s.hp -= n
end
fleet: [3]Ship
hurt(&fleet[1], 2)
r := &fleet[2]
r.hp = 7
r = {hp = r.hp + 1} # writes fleet[2]
copy := r # a plain := copies the value
copy.hp = 0
log(fleet[1].hp, fleet[2].hp)
-2 8
References can't be stored, returned, put in structs or arrays, or pointed elsewhere, so they never
outlive what they refer to. A String's bytes, constants and call results aren't places.
Proc values
A proc declared callback (name :: callback proc(...), or T.name :: static callback proc(...)) is a
value where a proc type is expected, and a proc value is called like a proc. Their parameter and
result types must match exactly. Host procs are values as they are. callback is a word only there:
twice :: callback proc(n: Int) -> Int
return n * 2
end
apply :: proc(f: proc(Int) -> Int, n: Int) -> Int
return f(f(n))
end
g := twice
log(apply(twice, 3), g(5))
12 10
A proc type's parameters can be &T too, as in proc(a, b: &Point) -> Bool, and are passed as a
proc's are (f(&p, &q)). A proc value can't capture variables. To keep recursion impossible, a
callback can't call through a proc value, or call a proc that does, whether or not anything uses it
as a value yet: it's checked in its own code, so changing another proc's body never changes what
can be a value. Calling a proc value that was never set is a runtime error:
plain :: proc(n: Int) -> Int
return n + 1
end
f := plain # error: only a callback proc can be a proc value: name :: callback proc(...)
apply :: proc(f: proc(Int) -> Int) -> Int
return f(1)
end
run :: callback proc(n: Int) -> Int
return apply(run) # error: recursion is not allowed
end
f: proc(Int) -> Int
log(f(1)) # runtime error: this proc value isn't set
Enum values
E.name is a value of enum E. Where the enum type is already known (a typed declaration,
assignment, argument, return, field, comparison or case), .name is enough:
Dir :: enum
north, east, south, west
end
d := Dir.north
d = .west
log(d, d == .west)
west true
Unions and is
A value of one of a union's types can be used as the union. u is T tests which type it holds (any
type can be written there, u is [3]Int too, as in a case). nil isn't a type: u == nil and
u != nil test for it, and narrow as is does (for a maybe, if x != nil makes x its value). A maybe
also compares with a value, x == 4 (false when x is nil), or with another maybe of its type (equal
when both are nil, or both hold equal values). To
reach the value inside, narrow it: in the body of an if whose condition has u is T as one of
its and-joined parts, or in a case naming one type, a union variable u (or a loop's element, or a
& parameter) means its T value (a read-only copy). The right side of an and is narrowed the
same way by its left side, since it runs only when that's true, so if n is Int and n > 2 works.
Testing a narrowed u with is again is known while compiling. Assigning to u there replaces the
whole union, and from then on u is the union again:
Circle :: struct
r: Float
end
Box :: struct
w, h: Float
end
Shape :: union
nil
Circle, Box
end
s: Shape = Box{w = 2, h = 3}
if s is Box
log(s.w * s.h)
s = Circle{r = s.w}
end
log(s is Circle)
n: ?Int = 4
log(n is Int and n > 2)
6.0
true
true
A test that's false narrows too, when it leaves one type: for a union of two types (a maybe is one, of
nil and T), u is A being false means u holds the other. So not u (for a maybe), u == nil or
not (u is A) narrows u where it's known to be false: on the right side of an or it's the left side
of; in the branches after it (case, else), when it's one of an if condition's or-joined parts;
and after the if, to the end of the block holding it, when its branch and any before it leave (with
return, break or continue), as Swift's guard let:
first :: proc(xs: []String) -> Int
for x in xs
n := x.toInt()
if not n do continue
return n # n is the Int: the if left when it was nil
end
return -1
end
twice :: proc(s: String) -> Int
n := s.toInt()
if n == nil
return 0
else
return n * 2
end
end
words := [3]String{"a", "12", "7"}
m := "5".toInt()
log(first(words[]), twice("21"), twice("x"), not m or m > 3)
12 42 0 true
Statements
A block is the statements up to its end (or the next else or case). Names declared in a block
end with it.
Expressions as statements
Any expression can be a statement, usually a call. If it has a value, that value must be used: one
left over is an error, so a result isn't dropped by accident. _ = f() drops it on purpose. (The
REPL prints a value left over instead.)
b: Blob[..8]
_ = b.print("hi") # print says whether it fit: dropped on purpose
log(b.len())
2
b: Blob[..8]
b.print("hi") # error: this value isn't used: write _ = ... to drop it
Assignment
place = value stores a value, copying it. place op= value is place = place op value, with
the place worked out once, for + - * / % & | ^ << >>. There's no ++.
xs: [3]Int
i := 0
xs[i] = 5
xs[i] += 2
xs[i] <<= 1
log(xs[0])
14
Constants, String bytes and call results can't be assigned:
N :: 5
N = 6 # error: cannot assign to this
Destructuring
{a, b} := value declares new variables from a struct's fields, by name, in any order; as renames.
The value is evaluated once, and the variables are copies. Patterns are one level deep:
QR :: struct
q, r: Int
end
divmod :: proc(a, b: Int) -> QR
return {q = a / b, r = a % b}
end
{q, r} := divmod(17, 5)
{r as rest} := divmod(9, 4)
log(q, r, rest)
3 2 1
if
n := 7
if n > 10
log("big")
case n > 5
log("medium")
else
log("small")
end
medium
The condition is a Bool. if a is short for switch and then case a: a switch with nothing after
it tests each case's condition in turn and runs the first that's true, or else its else, so a chain of
conditions reads the same either way:
n := 7
switch
case n > 10
log("big")
case n > 5
log("medium")
end
medium
n := 7
if n > 10
log("big")
else if n > 5 # error: write case
log("medium")
end
n := 1
if n # error: condition must be Bool
end
if name := value (and case name := value) declares a variable for that branch alone and tests it:
a maybe is true when it has a value, and is that value inside, as if x makes it for a maybe x; a
Bool is the test itself. As switch name := value does for a switch, it keeps a name that's only
for one branch out of the code after it:
Spot :: struct
name: String
end
spots := [2]Spot{{name = "well"}, {name = "gate"}}
find :: proc(name: String) -> ?Spot
for s in spots
if s.name == name do return s
end
return nil
end
if s := find("cave")
log("cave", s.name)
case s := find("gate")
log("found", s.name)
end
found gate
if n := 3 # error: condition must be Bool (or a maybe)
end
for
for has four forms:
for i in 0..<3 # a range: 0, 1, 2
log("range", i)
end
for i in 1..=2 # including the end: 1, 2
log("through", i)
end
n := 0
for n < 2 # while the condition holds
n += 1
end
for # forever, until break or return
break
end
log(n)
range 0
range 1
range 2
through 1
through 2
2
- Ranges:
for i in a..<bsetsitoa, and runs whilei < b, adding 1 after each time.bis evaluated once, before the loop.a..=bisa..<b + 1.iis a newIntvariable; changing it changes the next value. - Sequences:
for x in xsvisits each element of an array, slice, builder,StringorBlob, andfor x, i in xsadds the index. Either name can be_for one not wanted:for _ in 0..<n,for _, i in xs.xis the element itself, not a copy, so changing it changesxs(unlessxsis aString, which is read-only). Over a builder, the loop visits the elements it had when it started. - Enums:
for d in Evisits the enum's values in the order listed (for d, i in Eadds the index). Over an[E]Tarray, the index is the enum value. - Iterators:
for x in it, whereitis a struct with a methodnext() -> ?T, callsit.next()before each turn and ends at the first nil;xis the value inside (a newTvariable). A variable (or a field, or a place a&Treaches) is stepped in place, so after abreakit carries on where it stopped; anything else, such as a struct literal or a call's result, is kept for the loop.for x, i in itadds the turn, from 0.nexttakes nothing, unless its parameters are optional.
xs: [3]Int
for x, i in xs
x = i * 10
end
total := 0
for x in xs
total += x
end
Dir :: enum
north, east
end
for d in Dir
log(d)
end
log(total)
north
east
30
Countdown :: struct
at: Int
end
Countdown.next :: proc() -> ?Int
if self.at == 0 do return nil
self.at -= 1
return self.at + 1
end
for n in Countdown{at = 3}
log(n)
end
c := Countdown{at = 5}
for _, i in c
if i == 1 do break
end
log("left:", c.at)
for n in c
log("then", n)
end
3
2
1
left: 3
then 3
then 2
then 1
break and continue
break leaves the innermost loop, and continue goes on to its next round. A label on a loop
(name: for ...) lets them reach an outer one:
found := -1
rows: for y in 0..<4
for x in 0..<4
if x * y == 6
found = y * 10 + x
break rows
end
end
end
log(found)
23
A label can be used again once its loop has ended.
switch
switch picks the first case that lists the value, with no fallthrough. It works on Ints,
enums, unions and Strings. Case values are constants (or, for a union, its types). else comes last,
and takes what no case did:
kind :: proc(n: Int) -> String
switch n % 3
case 0
return "zero"
case 1, 2
return "other"
end
return "?"
end
log(kind(3), kind(4))
zero other
On a String, cases are string constants, compared as == compares them:
command :: proc(s: String) -> Int
switch s
case "ls", "list"
return 1
case "home"
return 2
else
return 0
end
end
log(command("list"), command("home"), command("hom"))
1 2 0
Without an else, a switch on an enum or union must have a case for every value (or type, nil
included). Each value can appear once:
Dir :: enum
north, east, south
end
d: Dir
switch d
case .north, .east
log("up")
end # error: this switch has no case for .south
On a union variable, a case naming one type narrows the variable to that type inside the case, as
is does in an if. switch name := value declares a variable for the switch, so any value can be
narrowed:
Circle :: struct
r: Float
end
Box :: struct
w, h: Float
end
Shape :: union
Circle, Box
end
area :: proc(s: Shape) -> Float
switch s
case Circle
return 3.0 * s.r * s.r
case Box
return s.w * s.h
end
end
log(area(Box{w = 2, h = 3}), area(Circle{r = 1}))
6.0 3.0
break and continue in a switch are about the loop around it.
if and switch as values
Right after :=, = or return, an if or a switch is a value: each branch's last line is its
value, and the rest of the branch runs before it as usual. Every branch needs one, so an if needs an
else, and so does a switch, unless it has a case for every value of an enum or every type of a
union (adding one later is then a compile error there, rather than a wrong default). A branch that
ends in return or break gives none. With :=, the variable takes its first branch's type unless
its type is written:
Size :: enum
small, medium, large
end
size := Size.medium
width := switch size
case .small do 8
case .medium
base := 12
base + 4
case .large do 24
end
n := 7
label := if n < 5
"low"
case n < 10
"mid"
else
"high"
end
sign :: proc(x: Int) -> Int
return if x < 0
-1
else
1
end
end
log(width, label, sign(-3))
16 mid -1
It's only ever the whole value, never part of an expression (x := 1 + if ... is an error), so a block
never sits inside an expression.
One-line blocks
do puts a block's one statement on the line that starts it, and the block ends with the line. It
works after if, for and a proc's header, and after case and else:
double :: proc(n: Int) -> Int do return n * 2
total := 0
for i in 1..=4 do total += i
if total > 5 do log("big", double(total))
light := 1
switch light
case 0 do log("stop")
case 1 do log("go")
else do log("wait")
end
big 20
go
A one-line case or else is just its line, so case, else or end comes next. A one-line if
has no case or else: one with branches is written out, with its end. The statement after do
can't open a block, one-line or not, so they don't nest:
xs := [3]Int{1, 2, 3}
for x in xs do if x > 1 do log(x) # error: one-line blocks don't nest
n := 1
if n > 0 do log(n); log(2) # error: a one-line block holds one statement
do blocks
do on a line of its own starts a block that only holds names: those declared inside end with it.
do
total := 0
for x in 1..=3 do total += x
log(total)
end
total := "free again"
log(total)
6
free again
return
return leaves the proc, with a value when the proc has a result. See
procs for which paths must return.
Builtins
The builtins are module core, there in every module without an import, and reachable as core.name
too, which still finds a builtin when a program's own name hides it (import core.{max as biggest}
works as for any module):
abs :: proc(x: Int) -> Int # this program's own abs
return x
end
log(abs(-3), core.abs(-3))
-3 3
src/core.rio declares each one with
its types, and the tests check those declarations against the compiler. The ones that would need
generics are written there in comments for now.
Builtins may take more than one type under one name: abs takes an Int or a Float, log any
values, len any sequence, and the math builtins arrays of numbers too. That's for builtins only. A
program's own procs have one name each, one set of parameter types, so a name always means one proc
(for proc values, images and host procs alike); give the variants names of their own.
log
log(a, b, ...) writes its arguments as text on one line, with spaces between, to the host's log (the
CLI prints it). It takes any value: numbers, Bools, Strings, Blobs, enums, and structs, arrays,
slices, builders and unions:
Dir :: enum
north, east
end
log("n", 42, 1.5, true, Dir.east)
log()
log(-0.25, 100.0, 1e9, 1.0 / 3.0, 0.00001, 123456789.0)
n 42 1.5 true east
-0.25 100.0 1.0e9 0.333333 1.0e-5 123456792.0
Structs, arrays, slices, builders and unions are written as Rio writes them, with text inside them quoted:
Point :: struct
x, y: Int
end
Shape :: union
nil
Point
end
s: Shape
log(Point{x = 1, y = 2}, s)
s = Point{x = 3, y = 4}
names := [2]String{"Ann", "Bo"}
log(s, names, names[1..<2])
big: [40]Int
log(big)
Point{x = 1, y = 2} nil
Point{x = 3, y = 4} ["Ann", "Bo"] ["Bo"]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... 30 more]
Bytes that aren't printable text show as escapes in a log (but print keeps them as they are):
Tag :: struct
name: String
end
raw := hexBlob("1b 5b 32 4a ff 48 69")
zeros: Blob[2]
log(raw, "caf\xc3\xa9", Tag{name = "a\tb\x01"}, zeros)
b: Blob[..8]
_ = b.print(raw)
log(b.len(), b[0], b)
\x1b[2J\xffHi café Tag{name = "a\tb\x01"} \x00\x00
7 27 \x1b[2J\xffHi
A log line keeps it short: a long array, slice or builder shows its first 10 elements and how many more,
text inside a value its first 40 bytes, and a value nested more than 8 deep .... A line is cut at the
host's log size too (256 bytes on most hosts). print and format write all of a value, or none of
it when it doesn't fit.
How values become text, in log, print and format (unless format's settings say otherwise):
Int: decimal, with-when negative.Bool:trueorfalse. Enums: the value's name.StringandBlob: inprintandformat, their bytes as they are. Inlog, as shown: other control bytes (but line breaks, tabs and\r), byte 127 and bytes that aren't UTF-8 as\xHH, so binary data can't upset a console; UTF-8 text shows as itself. Inside another value, quoted, with",\, line breaks, tabs,\rand zeros escaped as in Rio's strings, and the rest aslogshows them.- Structs:
Point{x = 1, y = 2}. Arrays, slices and builders:[1, 2, 3](of bytes: as text). Unions: the value they hold, ornil. Proc values:proc. Float:nan,infor-inf, or else digits with one decimal point. Values from1e-4up to (not including)1e9are written plainly; others as a number from 1 to 10 andewith a power of ten, like1.5e12. Either way: about 7 significant digits, at most 6 after the point, rounded, with trailing zeros dropped down to one.
Math
sqrt sin cos tan asin acos atan exp ln floor ceil round | (x: Float) -> Float |
atan2(y, x), pow(x, y), fmod(x, y) | (Float, Float) -> Float |
abs(x) | Int or Float |
min(a, b), max(a, b) | two Ints or two Floats |
clamp(x, lo, hi) | three Ints or three Floats: x kept between lo and hi, as max(lo, min(x, hi)) |
ln is the natural log; round rounds halves away from zero; fmod is the Float remainder, with
the sign of x. A number literal argument becomes a Float where one is needed, so min(2, 3.5) is
2.0. Results are as from the C library's single-precision functions, so the last digit may differ
between hosts. Each also works on arrays of numbers, element by element (see
arithmetic on arrays).
log(sqrt(16), floor(-2.5), round(2.5), round(-2.5), abs(-3), min(2, 3.5), pow(2, 10))
log(clamp(15, 0, 10), clamp(-2.5, 0, 1), clamp([2]Float{-1, 7}, 0, 5))
4.0 -3.0 3.0 -3.0 3 2.0 1024.0
10 0.0 [0.0, 5.0]
assert
assert(condition) or assert(condition, why) is a runtime error, at its line, when the condition is
false:
assert(1 + 1 == 2)
assert(2 + 2 == 5, "math") # runtime error: assertion failed: math
hexBlob
hexBlob("...") is the bytes the hex digits spell, as a writable Blob, decoded while compiling.
Spaces and line breaks can go between pairs of digits (a string over more lines gives it line breaks);
anything else, or an odd number of digits, is a compile error. It takes only a literal. The bytes are stored once, like a global, so each time the same
call runs it gives the same bytes:
b := hexBlob(
"48 69
"21"
)
log(b.len(), b[0], b)
3 72 Hi!
Sequences
Every array, slice, builder, builder view, String and Blob has:
xs.len(): how many elements (for a builder or builder view, how many it has now).xs.cap(): how many it can hold (the same aslenfor the fixed-length kinds).
And every one that can change (not a String) has xs.swap(i, j): elements i and j trade places,
whatever they are (in a generic proc too). An i or j outside it is
a runtime error.
Builders
These change a builder [..N]T or a builder view [..]T (Blob[..N] and Blob[..] too):
xs.push(x) -> Bool | adds one element at the end; false, and no change, when full |
xs.pushAll(ys) -> Bool | adds every element of an array, slice or builder of the same type (a String for byte builders): all or none |
xs.pop() -> T | removes the last element and gives it, to copy (not &xs.pop(): the next push reuses its slot); a runtime error when empty |
xs.clear() | removes them all |
xs.remove(i) | removes element i, keeping the order of the rest |
xs.swapRemove(i) | removes element i, moving the last one into its place |
b.print(...) -> Bool | for byte builders: appends its arguments as text, as log would but without spaces; all or none |
b.format(settings, ...) -> Bool | as print, as its settings say (see format) |
remove and swapRemove with i outside the builder are runtime errors.
xs: [..4]Int
for i in 0..<5
_ = xs.push(i * 10) # the fifth doesn't fit
end
xs.remove(0) # 10 20 30
xs.swapRemove(0) # 30 20
last := xs.pop() # 20; leaves 30
title: Blob[..16]
_ = title.print("hp ", 7, " ", 2.5)
log(xs.len(), xs[0], last, title[])
1 30 20 hp 7 2.5
xs: [..2]Int
log(xs.pop()) # runtime error: pop from empty builder
format
b.format(settings, ...) appends its values as print does, but as its first argument, a Format,
says. A struct literal there needs no type name:
Format :: struct # (built in)
width: Int # numbers: at least this many bytes, padded with spaces (negative: on the right)
digits: Int # numbers: at least this many digits before the point, padded with zeros
places: Int # Floats: exactly this many digits after the point, rounded
base: Int # Ints: 2 to 16, of the bits
textWidth: Int # text, Bools and enums' names: as width does for numbers
end
Each field's 0 is as print writes it. The settings apply to every value after them, and to every
number and name inside a struct, array, slice, builder or union (text inside a value stays quoted, and
isn't padded). A Format after the first argument is just a value. For different settings, use
another call:
b: Blob[..120]
_ = b.format({width = 4}, 7, ":", 42, " ")
_ = b.format({textWidth = -6}, "hp", true)
_ = b.format({digits = 2, places = 1}, 3.14159, " ", -0.25, " ")
_ = b.format({base = 16, digits = 4}, 48879, " ", 10, " ", -1)
log(b[])
b.clear()
_ = b.format({digits = 3}, [3]Int{1, 20, 300})
hex := Format{base = 16}
_ = b.format(hex, hex)
log(b[])
7: 42 hp true 03.1 -00.3 beef 000a ffffffff
[001, 020, 300]Format{width = 0, digits = 0, places = 0, base = 10, textWidth = 0}
base writes an Int's 32 bits, so a negative one has no - (-1 is ffffffff). It's ignored for
Floats, as places is for Ints.
A builder view b: [..]T = array (or a slice of one) builds into that memory, starting empty. Its length
lives in a hidden word next to b, which every copy of b shares:
mem: [4]Int
b: [..]Int = mem
_ = b.push(7)
fill :: proc(out: [..]Int)
_ = out.push(8)
end
fill(b)
log(b.len(), mem[0], mem[1])
2 7 8
A builder view needs a declaration to hold its length, so passing an array straight to a [..]T
parameter is an error. A builder view can't be made over read-only bytes, such as a String.
Packing
Values go into and out of bytes as they are in memory, for files and other binary data. Each of
Int, Float and Bool is 4 bytes, little-endian (a Bool is 0 or 1); a struct or array is its
fields or elements in order, nested ones inline, and a Blob[N] field is its bytes, padded to whole
words:
b.pack(at, x) | x's bytes into Blob b, from byte at |
b.pack(x) -> Bool | for byte builders: appends them; false, and no change, when they don't fit |
b.unpack(at, &x) | the bytes at at into x (it changes x, so it takes &x) |
b.getInt(at, bits) -> Int | an int of 8, 16, 24 or 32 bits at at; negative bits: signed |
b.setInt(at, bits, n) | n's low bits at at |
Header :: struct
tag: Blob[4]
count: Int
scale: Float
end
h := Header{count = 1000, scale = 0.5}
h.tag[0] = 82
file: Blob[16]
file.pack(2, h)
back: Header
file.unpack(2, &back)
log(file[2], file[6], file[7], back.count, back.scale)
file.setInt(0, 16, -2)
log(file.getInt(0, 16), file.getInt(0, -16), file.getInt(0, 8))
82 232 3 1000 0.5
65534 -2 254
Only plain data packs: nothing holding a view (a slice, String, Blob or builder view) or a proc value,
which are addresses, or a builder, whose length (how much of it is there) mustn't come from bytes. A
view's own elements do pack, though, a builder's too: b.pack(at, xs[2..<5]) writes three
elements, and b.unpack(at, xs[]) fills xs's elements (without &, as a view already lets its
elements change). For a byte builder, at counts within its length.
xs := [3]Int{5, 300, 70000}
out: Blob[..16]
_ = out.pack(xs[1..<3])
ys: [2]Int
out.unpack(0, ys[])
log(out.len(), ys[0], ys[1], out.pack(xs[]), out.len())
8 300 70000 false 8
unpack and getInt read a String too; pack and setInt need a Blob. Bytes outside b are
a runtime error, as are bits other than those (and, when it's a constant, a compile error). So is
unpacking a value its type doesn't have, as with E.fromInt: an enum that isn't one of its values
(a bitfield's too), a Bool other than 0 or 1, or a union's tag past its types. Whatever unpack
leaves in x, then, is a value of x's type.
Sizes and offsets
sizeOf(T) is how many bytes a T takes, which is what pack writes for one. It takes a value
too, sizeOf(x) for x's type, but not a view's, whose bytes are its elements: s.len() * sizeOf(T). offsetOf(S, .field) is the byte in struct S where a field starts, through nested
structs too (offsetOf(S, .a.b)), and bitOffsetOf(S, .field), the bit, 8 to a byte. A bitfield's
offsetOf is the byte holding its lowest bit, and bitOffsetOf(S, .f) % 8 is where in that byte
it starts. Each is a constant, so it can size a Blob or a :: constant, and it lets code read or
change one field of a packed record without unpacking all of it:
Shape :: enum
circle, box, tri
end
Rec :: struct
kind: Shape(2)
solid: Bool(1)
height: Int(5)
count: Int
name: Blob[6]
end
SIZE :: sizeOf(Rec)
file: Blob[SIZE * 2]
file.pack(SIZE, Rec{kind = .tri, height = 9, count = 40})
file.setInt(SIZE + offsetOf(Rec, .count), 32, 41)
r: Rec
file.unpack(SIZE, &r)
log(SIZE, sizeOf(Blob[6]), offsetOf(Rec, .name), bitOffsetOf(Rec, .height), r.count)
log(file.getInt(SIZE + offsetOf(Rec, .height), 8) >> (bitOffsetOf(Rec, .height) % 8))
16 8 8 3 41
9
Enums
For an enum E, E.fromInt(n) is the value n (a runtime error if E has no such value, or a
compile error if n is a constant), E.has(n) says whether it has one, and e.toInt() is e's
number:
Tile :: enum
nil
wall
end
n := 1
log(Tile.fromInt(n), Tile.has(2), Tile.wall.toInt())
wall false 1
Conversions
toInt, toFloat, toBool and asString: see conversions, and
text as numbers for toInt and toFloat on text.
Modules
Every file is a module. Its top-level names are private unless they end in *. A module's exported
types bring their exported methods along.
Vec* :: struct
x, y: Float
end
sq :: proc(v: Float) -> Float # private
return v * v
end
Vec.len2* :: proc() -> Float
return sq(self.x) + sq(self.y)
end
count* := 0
import .geo
v := geo.Vec{x = 3, y = 4}
geo.count += 1
log(v.len2(), geo.count)
25.0 1
sq :: proc(v: Float) -> Float
return v * v
end
import .geo
log(geo.sq(2.0)) # error: not exported by that module
import
import .geo # geo.rio next to this file, as geo
import .ui.button as btn # ui/button.rio, as btn
import tween # a package
import tween.{ease, lerp as mix} # just some names, used without tween.
- Local or package. A leading
.is local: a path from the importing file's directory, going only downward. Without it, the first name is a package, which the host finds (the CLI looks in its-Ldirectories). - Files and directories.
.a.bisa/b.rio, or, ifa/bis a directory, its entry filea/b/b.rio. A directory module's own local imports start in its directory. - Names.
import .geodeclaresgeo;aspicks another name..{a, b as c}declares those exported names directly. Imported names are used in expressions, types and literals alike:geo.Vec{x = 1},v: geo.Vec. - Imports go at the top level, and are visible to the rest of the file.
Packages
A package's root module decides what other code sees. Its submodules are private unless the root
publishes them with import .name*:
import .easing*
import .curves
lerp* :: proc(a, b, t: Float) -> Float
return a + (b - a) * t
end
quad* :: proc(t: Float) -> Float
return t * t
end
x* := 1
import tween
import tween.easing
log(tween.lerp(0, 10, 0.5), easing.quad(0.5), tween.easing.quad(1))
5.0 0.25 1.0
Asking for a submodule the root doesn't publish is an error ("that package doesn't publish curves"). Two packages of the same name where the host looks is an error too, not a silent choice.
Exporting other names
There's no bulk re-export, so each exported name has one home. To export something imported, give
it an exported name of your own: Sprite* :: gfx.Sprite. Writing import .a.{x*} is an error that
says so.
include
include "path.rio" makes another file part of this module: the same names, private ones included.
The path is relative to the including file, goes only downward, and names a .rio file. Each file can
be included once. Parts are read in place, so the declare-before-use order runs through them:
double :: proc(x: Int) -> Int
return x * factor
end
factor := 2
include "parts/helpers.rio"
log(double(21))
42
Order
A module is compiled and its top-level code runs once, at its first import. Every importer shares
its globals. So modules run in the order they're first imported, before the code after that import.
Importing a module that's still being compiled (a cycle) is an error.
log("a runs")
x* := 1
log("main starts")
import .a
import .a
log("main has", a.x)
main starts
a runs
main has 1
Host modules
The host can provide modules of its own procs, such as pc with pc.cls. See
host procs.
Programs and hosts
A Rio program runs inside a host: a program that embeds Rio, such as the rio command line tool or
a game console. The host gives the program its memory, its log, its host procs and its modules,
and decides when the program's procs run. How a host does that in C is in the
guide.
Running
- The host compiles the main file. It's rejected as a whole if anything in it, or in what it imports, doesn't compile.
- The top-level code runs, from the top. Imported modules run where they're first imported.
- The host calls the procs it wants: the CLI calls
mainif there is one; a game console might callupdateanddraweach frame. Globals keep their values between calls.
A runtime error stops what's running and reports its line (and file, outside the main file). The
errors are: an index or slice out of bounds, division by zero, pop from an empty builder, a value
that isn't one of an enum's, calling an unset proc value, a failed assert, an error from a host proc,
and being stopped by the host.
What the host can find
The host can find main, and the main file's top-level procs and globals marked with *, the same
mark modules use for exports. A generic proc isn't found, even marked:
the host couldn't say what its T is (other modules can still use it).
score* := 0 # the host can read and change it
update* :: proc() # the host can call it
score += 1
end
Host procs
A host proc is a proc the host provides, written in the host's language. Its parameters and result
can be Int, Float, String and Blob, and its parameters structs. A host proc has a plain name, global like a builtin, or a
module name and a name, such as pc.cls. Host procs in a module are used through that module: with
import pc, or everywhere if the host auto-imports pc. If the host has no source for the module,
the module is just its host procs, all exported.
import pc # a module of host procs (a host that has one)
pc.cls(0)
The CLI's host procs are in its module os (the guide's page): files and
folders, running programs, the environment and arguments, text in and out, and time, for a program
that imports it (import os).
A host proc can't call back into the program while it runs. It can stop the program with a runtime
error. Since it can't call back, a host proc can always be a proc value,
as a proc that calls through no values can: tick := os.clock.
Declaring host procs
host declares what the host provides, and the compiler checks the declaration against it. Such
declarations document a host's API in Rio, and since they're checked, they can't drift. For a host
with a global host proc clock (the CLI's are in its module os, whose source declares them so):
clock* :: host proc() -> Float # the host's clock: checked against it
start := clock()
clock :: host proc() -> Int # error: doesn't match the host's clock: proc() -> Float
-
Host procs:
name :: host proc(...) -> R, a proc type, as for proc values: its parameter and result types must be exactly the host's, except that an enum or aBoolmay stand for anInt, which it is underneath, and a struct parameter for its fields (below); calls then take the declared types. Its last parameters may be optional (t?: Text), and the host gets zeros for those a call leaves out, just as an image made before a host proc gained parameters at its end passes zeros for them. So a host proc can gain options without breaking programs, compiled or not. In a module,nameis the host proc of the module's name (clsinpc.rioispc.cls), else a global one. When the host has a source for a module of host procs (one it gives with its procs, ideally), that source is the module (auto-imported ones too), and it must declare every one of the module's host procs. So a module can give its host procs types of its own:Pointer* :: enum # in pc.rio game, ui, none end pointer* :: host proc(mode: Pointer) # the host's pc.pointer takes an Int -
Struct parameters: a struct goes to the host by address, and the host reads it in place, so it can hold anything a struct can, and be any size. The host's sig gives its layout: each field's name and what it is to C (an enum or a
Boolis anInt), which the declaration's must be. The host only borrows it, as it does views, for the call; it reads it as it is when the call is made:Pos* :: struct # in pc.rio x, y: Int end Text* :: struct at: Pos color: Int(8) big: Bool(1) end text* :: host proc(s: String, t: Text) # the host's sig: "s{at:{x:Int,y:Int},color:Int(8),big:Int(1)}" pc.text("hi", {at = {x = 3, y = 4}, big = true}) # color 0An enum, in a layout or as a parameter, is named by its values (
Enum{game,ui,none}, a word), so one reordered doesn't fit an image made before, while an enum parameter's values added at its end do. (A plainifor an enum parameter works too, unchecked.)A field left out of a literal is zero, so a host proc's options can grow without breaking calls written before: add fields at the end, and make zero mean what calls did before. Images made before then still load: the host reads zeros for the fields they lack. A host writes its side from the module's source, which makes C structs and sigs to match: see the embedding guide.
-
&Tparameters: as for a proc, a host proc may take a place,&T, and change it: anInt, aFloat, a struct, or a point or size ([N]Intor[N]Float, N up to 8) (&i,&f,&{...},&(ii)in its sig). Calls pass&x. Unlike a proc's, a host proc's¶meter may be optional (size?: &[2]Int): left out, the host gets 0 for its address and size, and writes nothing. The host writes no more than the place holds, so a struct an older image made with fewer fields stays as it was past them:Mouse* :: struct # in pc.rio x, y: Int down: Bool end mouse* :: host proc(m: &Mouse) # the host fills it in m: pc.Mouse pc.mouse(&m) -
Points and sizes: an
[N]Intor[N]Floatparameter (N up to 8) goes to the host as its words, one after another, as that manyi(orf) in its sig:rect* :: host proc(pos, size: [2]Int, c: Int)is the host's"iiiii". Calls take any such array, so a literal is typed by the parameter:pc.rect({x, y}, {8, 8}, 7). -
Lists of points: a
[][N]Int(or[][N]Float, N from 2 to 8) is a slice like any other, 2 words: where its elements start and how many there are; its sig writes the element's words in the brackets:polygon* :: host proc(points: [][2]Int, c: Int)is the host's"[ii]i", and the host reads the points asint32_tpairs, x then y. -
Results as points:
pointerAt* :: host proc() -> [2]Intis the host's">ii": it writes the words back in order. -
Results: a host proc returns what a proc may: an
Int,Float,StringorBlob, or a struct, union or maybe of up to 16 words with no views in it (>{...},>Union{...}in its sig). A struct result may gain fields at its end, as a parameter may: an older image gets the fields it holds.mouse* :: host proc() -> Mouse # in pc.rio: rather than taking &Mouse keyDown* :: host proc(k: Int) -> ?Int # nil, or how long it's been down -
Builtins: declared the same way, and checked as calls with those types:
sqrt* :: host proc(x: Float) -> Float.src/core.riodeclares them all. -
Builtin types:
Int* :: host struct. -
Methods: on a named type,
Int.toFloat* :: host proc() -> Float; on any other type, in parentheses:(Blob[..]).push* :: host proc(byte: Int) -> Bool. -
Static host procs: a host proc called on a type, as a static proc is:
at* :: host proc(...)belongs to the module,Pos.at* :: static host proc(x, y: Int) -> Posto its type, calledpc.Pos.at(3, 4). The host registers it asType_name(pc.Pos_at), andrio -Hwrites it so (pc_Pos_at_SIG,X(Pos_at, ...)).
host declarations go at the top level; * exports them, as for other declarations. A name that's
neither a host proc nor a builtin is an error:
nope :: host proc(x: Int) # error: the host has no proc by this name
A host can ship such a module only as documentation, and still make its module straight from its host procs, so nothing is parsed at runtime. Its tests then compile the source against the real host procs.
Defines
The host can set top-level constants from outside, like gcc -D; the CLI takes -D NAME=value.
The value is read as the constant's declared type: -D SCALE=3 gives a Float constant 3.0,
-D DEBUG alone means true, and a String takes the text as it is. A define the program doesn't
declare is still a constant, with its type from its text: 7 an Int, 6.28 a Float, true,
false or nothing a Bool, and anything else a String. A value that doesn't fit is a compile error.
N :: 1000 # rio -D N=20 game.rio makes N 20
DEBUG :: false # rio -D DEBUG game.rio makes it true
Memory
A program's memory is all known when it compiles: its globals, one frame for each proc (procs that never run at the same time can share one), and its strings. Nothing is allocated while it runs. Programs that don't fit are compile errors, as are programs too big for the compiler's tables.
The host sees values in words of 4 bytes, little-endian:
| type | words |
|---|---|
Int, Float, Bool, enums, proc values | 1 |
String, Blob, []T | 2: where the bytes or elements start, and how many |
[..]T, Blob[..] | 3: where the length is, where the elements start, the capacity |
[N]T | N elements, one after another |
[..N]T | the length, then N elements |
Blob[N] | N bytes, padded to whole words |
| structs | the fields in order |
| unions | the type's index (in the order listed), then room for the biggest type |
Positions ("where ... start") are byte offsets in the program's memory. Host procs get their arguments as these words, one after another.
Unused procs
A proc nothing can call is left out of the compiled program: its code, and its frame. So a module's
whole surface can be imported, and a program pays only for the procs it uses. What can run is the
top-level code (each module's too), the procs the host can find (main and name* in the main file,
see What the host can find), and the procs used as values, or declared
callback; then whatever they call, and so on. A dropped proc is still compiled, so its errors are
still errors, and it keeps its place in the proc table (a few bytes). rio -m says how many were
dropped, and how many instructions with them. A REPL keeps them all, since what's typed next may call
any of them. Not dropped (yet): globals and constants only dropped code used, and a dropped proc's big
locals (over 16 words), which are set aside as it compiles.
Building and the CLI
This guide is about the Rio in this repository: a C99 library (compiler and VM) and the rio command
line tool. For the language itself, see the spec.
Building
cmake -S . -B build
cmake --build build --config Release
ctest --test-dir build -C Release
build/rio tests/test.rio # (build/Release/rio.exe with MSVC)
It needs only a C99 compiler and libm, and works on Linux, macOS and Windows. Prebuilt binaries are
in the nightly prerelease, rebuilt
each night main changes (and on demand: Actions > ci > Run workflow), and in releases for tags like
v0.1.0.
On Windows with Visual Studio, CMake uses the ClangCL toolset when it's installed (the "C++ Clang
tools for Windows" component), because clang supports the faster computed-goto dispatch. Otherwise it
falls back to MSVC with switch dispatch. -T <toolset> overrides this, -DRIO_PREFER_CLANGCL=OFF
disables it, and an existing build directory keeps the toolset it was first configured with.
The tests include tests/docs.rio, which runs every example in these docs. With zig on the PATH,
rio tools/zigbuild.rio (run from the repo's folder) cross-builds the rio program for other systems
into build-zig: linux-x86_64 and linux-arm64 (static), and macos-arm64 (not signed).
The CLI
rio a REPL
rio game.rio run the top-level code, then main() if there is one
rio -L libs game.rio with packages from libs/ (each libs/name.rio or libs/name/name.rio)
rio -D N=20 game.rio set a top-level constant (or define one), like gcc -D
rio -c game.c game.rio compile to a standalone C program instead (see C output)
rio -i game.img game.rio compile to an image instead (see Images); rio game.img runs one
rio -m game.rio how near its limits it comes, and where its memory goes, instead of running it
rio -M 256K ... the memory the program gets (default 8M, up to 1G), allocated once at the start
rio -j game.rio compile simple loops to native code first (ARM with Thumb-2 only)
rio fmt game.rio ... the files laid out the one way, printed; -w rewrites the ones that change,
-l lists them (exiting 1 if any)
rio fmt changes only white space: the indent at each line's start (2 for each block it's in), the
gaps between tokens (x := a[i] + f(b, -c)), spaces at line ends (gone), line ends (all as the
file's first, \n or \r\n), and line breaks inside brackets where Rio reads them as spaces. The one
token it adds is a trailing comma, where a list stays over lines. Before it gives code back it checks
that the tokens are the same but for those commas, so the program means what it did. It doesn't wrap
long lines: no rule depends on a line's length.
A list in (), [] or {} with commas is laid out by its trailing comma, and by whether a line break
follows its opener:
f(a, f(a, b, c) no trailing comma, first item on the opener's line: one line
b, c)
f( f( no trailing comma, a break after the opener: the items on a line of
a, a, b, c their own (and so back to one line by joining that line up and
b, c) ) taking the comma off)
f(a, b, c,) f( a trailing comma, first item on the opener's line: an item a line
a,
b,
c,
)
f( f( a trailing comma, a break after the opener: the lines as they are,
a, b, a, b, for tables
c, c,
) )
A comment, or a string over lines, in a list keeps it over lines (with a trailing comma added). A
list over lines that's the last item of another can sit on its line: f(a, [ ... ]). Parentheses
without commas (grouping) keep their lines as written.
It keeps what lines things up: runs of spaces before ::, := or = that line up with the lines
around them, comments in the column they were in, and lines going on (after an operator, or in
grouping parentheses) where they were from their statement's start. Lines from a # nofmt comment
line to a # /nofmt one (or the file's end) are left as they are, but for spaces at their ends; the
two comments are indented as usual, and can have a note after a space (# nofmt (a table)). Code
needn't compile to be laid out, and hosts get it as rio_format (in rio.h), which needs no VM.
Errors print as game.rio:12:7: type mismatch, which terminals and editors can turn into links.
Ctrl-C stops a running program. Arguments after the program's file are the program's (rio tool.rio a b: os.arg). The CLI's host procs are in its module os, for programs that
import os.
In the REPL, globals, procs, types and methods carry over from one input to the next, and a bare
expression prints its value. An unfinished input gets a . prompt for more, as wide as > so the
lines line up; a blank line drops it. A compile error leaves the session as it was. Lines are edited
as they're typed, as os.readLine's are (os): the arrows, Home and End, Ctrl+Left and Right
by words, Ctrl+K, Ctrl+U, Ctrl+W and Ctrl+Y, and Up and Down for the lines typed before, which are kept
in ~/.rio_history. Ctrl+C drops what's typed, and Ctrl+D quits. Code is in colors as it's typed (Rio's
words, types, calls, numbers, strings and comments), unless NO_COLOR is set or TERM is dumb.
Tab completes the name before the cursor, from what the session knows: after p., p's fields and
methods (and its kind's built-in ones, like len and push); after Dir., an enum's values and a
type's static procs; after os., what a module exports. Elsewhere it's the names in scope, the names
the input so far declares (an unfinished proc's parameters and locals), and Rio's words that fit
there: a statement's (if, for, return, and end or else inside a block), an expression's
(not, nil), and after a value, an operator's (and, or, is, and in or do in a header).
Where a type goes (x: , -> ), it's just types. It fills in as much as the names that fit agree on,
and when that's nothing more, it shows them, with their types. At the start of a line, Tab indents.
A line of unfinished input starts at its indent: two spaces for each block and bracket still open.
A line starting end, else or case steps back out once the word is typed, and Backspace in an
indent goes back a whole step. An indent changed by hand stays as it is. Pasted code keeps its own
indents, and its blank lines don't drop it: terminals that mark pastes say where one starts and
ends, and anything already waiting when a line starts counts as pasted too.
The CLI's module os
The rio command has a module of its own, os, for programs it runs: the program's arguments and
environment, text in and out, files and folders, running other programs, and time. A program imports it
(it isn't there unless it does), and it's in the REPL, and in a program's C (rio -c), too. It's the
command's, not Rio's: Rio as a library, riocore, has no os, and a host that embeds Rio has modules of
its own (Rinc's pc). src/os/os.rio declares it, and each proc says what it does there; src/os/os.h has
them in C. All of it is in src/os, apart from Rio itself.
import os
buf: Blob[256]
check := os.fileWrite("os-example.txt", "one\ntwo\n") == 0
n := os.fileRead("os-example.txt", buf[])
os.write(buf[0..<n].asString())
log(check, n, os.fileDelete("os-example.txt"), os.fileKind("os-example.txt"))
one
two
true 8 0 0
As in Rinc's pc, what a proc reads goes into a Blob it's given (as much as fits), and it says the
whole length, or -1 when there's none. What a proc does says 0, or -1 when it couldn't. Paths are as
the system takes them; on Windows, / works as \ does.
| procs | |
|---|---|
argCount, arg, env, envSet, exit | the program's arguments (rio tool.rio a b: a and b), its environment, and its end, with an exit code |
write, writeErr, readLine, readAll | text out (as it is: log adds spaces and a line break) and in |
fileRead, fileWrite, fileAppend, fileSize, fileKind, fileDelete, fileRename | files (and empty folders, deleted) |
dir, dirMake, cwd, cwdSet | folders: a folder's entries (d name and f name lines, folders first, by name), a new one, the current one |
run | another program, with its arguments as they are (no shell, unless asked for), waited for: its exit code, and what it writes (RunOptions) |
clock, time, date, sleep | the processor's time used, seconds since the start, the date and time here, and a pause |
os.run runs a program with a list of arguments, each passed just as it is: there's no shell
between, so nothing needs quoting, and nothing in an argument can run another command. RunOptions,
left out by default, keeps what it writes (out), standard error too (errorsToo), or hands
args[0] to the system's shell as a command line (shell: then its pipes and redirects work, and
its quoting is the command line's to get right):
import os
log(os.run({"git", "status"})[0]) # its exit code (-1: it couldn't run)
buf: Blob[4096]
r := os.run({"git", "log", "-1"}, {out = buf[]})
log(buf[0..<min(r[1], buf.len())].asString())
os.readLine reads a line typed after a prompt. At a terminal it's edited as it's typed, as the
REPL's lines are: the arrows, Home and End, Ctrl+Left and Right (or Alt+B and F) by words, Backspace,
Delete, Ctrl+K and Ctrl+U (cutting to the end or the start), Ctrl+W (a word back), Ctrl+Y (what was
cut, back), and Up and Down (or Ctrl+P and N) for the lines typed before. Ctrl+D on an empty line is the
end of the input (-1), and Ctrl+C stops the program, as it does anywhere. Reading from a pipe or a
file, it reads a line as it comes.
A view into a builder is the builder's bytes as they are now: building two paths in the same builder, the first view shows the second path. Give each its own builder:
import os
a: Blob[..64]
b: Blob[..64]
_ = a.pushAll("os-old.txt")
_ = b.pushAll("os-new.txt")
from := a[0..<a.len()].asString()
to := b[0..<b.len()].asString()
log(os.fileWrite(from, "x"), os.fileRename(from, to), os.fileKind(from), os.fileKind(to), os.fileDelete(to))
0 0 0 1 0
The C API
Everything is in src/rio.h. The tutorial shows the
shape of it; this is the rest.
#include "rio.h"
static uint8_t mem[1 << 20]; // the program's code and data, and the compiler's working memory while compiling
static rio_Vm vm; // runtime state (~1-12 KB depending on limits)
static void host_print(void *ud, const char *s, int n) { fwrite(s, 1, n, stdout); putchar('\n'); }
static void host_rand(rio_Vm *vm, rio_Val *a) { a[0].i = rand(); } // args in a[], result to a[0]
rio_init(&vm, mem, sizeof mem, NULL, 0); // or a separate code buffer: code, its capacity (max 65535)
rio_setLog(&vm, host_print, NULL);
rio_addFfi(&vm, "rand", ">i", host_rand); // sig: i f s b params, '>' result
rio_define(&vm, "LEVEL", "3"); // optional: like -D LEVEL=3
if (rio_compile(&vm, src, len) || rio_run(&vm)) puts(rio_error(&vm));
int f = rio_findProc(&vm, "update"); // procs and globals the host uses are marked: update* :: proc(dt: Float)
rio_procArgs(&vm, f)[0].f = 0.016f; // params are consecutive words (slices 2, structs n)
rio_call(&vm, f);
float r = rio_procResult(&vm, f)->f; // if it returns something
int *score = rio_findGlobal(&vm, "score"); // direct access to globals (score* := 0)
Host procs
rio_addFfi(vm, name, sig, fn) registers a host proc. sig is the parameter types, then optionally
> and the result's: i Int, f Float, s String, b Blob, B a byte builder view, Blob[..] (a
parameter only: 3 words, where its length is, where its bytes start, and its capacity, so the host can
add to it and set its length; calls pass a Blob[..N] or a view), and a struct parameter as its layout
in braces (see structs). name and sig must stay valid until rio_compile (or
rio_loadImage) returns.
- Arguments arrive in
a[]as words, in order (see memory); the result goes ina[0]. AStringorBlobtakes two words;rio_sliceBytes(vm, &a[i])gives its bytes. rio_trap(vm, "msg")stops the program with a runtime error at the line of the call.- Host procs must not call back into the VM.
Modules of host procs. A dotted name, "pc.cls", puts the proc in module pc instead of the
global names, so programs import pc and call pc.cls(0). A host gives the module's source with
its procs, rio_addSource(vm, "pc", src, len), so the declarations go with the code they declare:
that source is the module, checked against the registrations (see declaring host
procs), and rio_hostSource(vm, "pc", &len) gives it back, for
help or an editor to show. (A loader's source for pc works too, when none is registered.) With no
source, the module is made from the registrations, with nothing to parse. rio_autoImport(vm, "pc") makes pc visible everywhere without an import.
When the loader has a source for an auto-imported module, it's compiled before the program (in a REPL,
before the first input), so the module can hold types and constants for its procs (an enum for a
mode, say); without a source, the module is made from the registrations.
Structs
A struct parameter arrives as two words, where it is and its size, and rio_getStruct copies it into
a C struct of the same layout. rio -H pc.h pc.rio writes those C structs from the Rio module that
declares the host procs, so its source is what both sides follow: for each struct a host proc takes, a
typedef, accessors for its bitfields (pc_Text_big(&t), pc_Text_set_big(&t, 1)), a check that its
size is Rio's, and its layout, pc_Text_LAYOUT; and for each host proc, its sig, pc_text_SIG:
#include "pc.h" // made by rio -H pc.h pc.rio
static void text(rio_Vm *vm, rio_Val *a) {
pc_Text t;
rio_getStruct(vm, a + 2, &t, sizeof t); // (a[0] and a[1]: the String)
draw(rio_sliceBytes(vm, a), a[1].i, t.at.x, t.at.y, pc_Text_color(&t), pc_Text_big(&t));
}
...
rio_addFfi(&vm, "pc.text", pc_text_SIG, text);
A &T parameter (&i, &f, or a struct's &{...}) comes the same way, the caller's place and its
size, and rio_putStruct(vm, a + i, &t, sizeof t) writes it back, no more than the place holds. A
struct, union or maybe result (>{...}, >Union{...}) does too: where it goes is a[0] and a[1],
before the parameters, which start at a[2], and the host writes it there with rio_putStruct. For a
union or maybe, the header has a C struct for it, pc_name_Result (a maybe's has and value).
A String or Blob inside is a rio_View, whose bytes rio_viewBytes(vm, v) gives. Compiling checks
each declaration against the sig, so a header older than the module is an error, not a misread. An
image made when a struct had fewer fields at its end still loads, and rio_getStruct fills the rest
with zeros; a struct changed any other way is an error naming the host proc.
The header also has what registering takes: the module's source, pc_SOURCE (and its hash,
pc_HASH), and its host procs in an X macro, pc_HOST_PROCS(X), each X(name, sig), for a host that
names its procs to match:
#define PC(name, sig) rio_addFfi(vm, "pc." #name, sig, pc_##name);
pc_HOST_PROCS(PC)
rio_addSource(vm, "pc", pc_SOURCE, sizeof pc_SOURCE - 1);
rio_hostHeader does what rio -H does, for a host that makes its own: the module may declare host
procs the vm doesn't have.
Modules
rio_setLoader(vm, fn, ud) supplies module sources: it gets a path like "ui/button" or an include
like "parts/hud.rio", flagged as local or package, and returns the source text. The core never
touches a filesystem: a console can read an SD card, and tests can use a table of strings. Instead of
the text, a loader can leave src NULL and set read and readData in its rio_Source, and then
the compiler reads it a part at a time, as rio_compileStream does (see
memory). readData has to stay valid until
compiling ends.
Errors
rio_error(vm) is a ready-to-print string: "12:7: type mismatch" for compile errors and
"40: runtime error: index out of bounds" for runtime errors. For an editor, use the structured form:
rio_Error e = rio_errorInfo(&vm); // after a failed rio_compile / rio_run / rio_call
// e.kind: rio_ErrorKind_compile or rio_ErrorKind_runtime
// e.line, e.col: 1-based (0 = unknown); e.len: width of the offending token, for underlining
// e.msg: the message without the position, e.g. "undefined name near 'nope'"
// e.file: the module's file, or NULL for the main source
- Compile errors point at the token at fault, or, for an error found at the end of an expression, its last token.
- Runtime errors report the line, from a compact table built while compiling (about a byte per line
that has code).
rio_pcLine(vm, pc)exposes the same lookup. - Code from
rio -creports the same lines, through#linedirectives.
A compile stops at its first error, unless the host asks for all of them, as an editor's list of
problems would: with rio_setErrorFn(vm, fn, userData) set, it goes on after an error in a top-level
statement of the main source, or in a proc's body, from the next line that starts at column 1 (not an
end), and calls fn with each error as it's found (e.msg lasts only the call). It still fails, with
the first as rio_error. An "undefined name" for a name whose own declaration failed isn't reported,
since it only repeats that one. The command line and rio lsp both show every error this way.
static void show(void *userData, rio_Error e) { printf("%d:%d: %s\n", e.line, e.col, e.msg); }
rio_setErrorFn(&vm, show, NULL);
if (rio_compile(&vm, src, len)) return 1; // (each already shown)
The REPL
rio_replBegin(&vm, scratch, sizeof scratch, NULL); // limits scaled to the scratch buffer
switch (rio_replEval(&vm, text, len)) { // compiles the text, then runs just that
case rio_ReplResult_ok: break; // ran
case rio_ReplResult_more: /* show a continuation prompt; call again with more text appended */ break;
default: show(rio_error(&vm)); // rio_ReplResult_error: compile errors undo themselves
}
The compiler state stays in scratch for the whole session, so this is the one mode where its tables
cost RAM for good: 8 to 16 KB of scratch gives a comfortable REPL. Each input's strings move into mem
once it compiles. Hosts that echo typing themselves can indent continuation lines: rio_replIndent says
how far (a step per open block or bracket), and rio_replOutdent which first words (end, else,
case) go a step back out.
Stopping a program
rio_interrupt(vm) stops a running program at its next loop iteration, with the runtime error
interrupted. It only sets a flag, so it's safe from a signal handler, an interrupt or another core.
The check sits on backward jumps and costs nothing measurable. Code from rio -c can't be stopped
this way.
What the host can find
rio_findProc and rio_findGlobal find main and the main file's names marked with *. Each costs a
12-byte table entry plus the name. Build with -Drio_EXPORTS_ALL (CMake: -DRIO_EXPORTS_ALL=ON) to
make every top-level proc and global findable, say for a debugger.
Code in an editor
Two calls work on Rio code as text, compiling or not, and need no VM: for a host with an editor (Rinc's
saves through rio_format), or a tool. rio_format lays code out as rio fmt does, and rio_highlight
gives each token's kind, for colors:
static void token(void *userData, uint32_t at, uint32_t len, int kind) {
/* src[at..at+len): rio_Hl_keyword, rio_Hl_type, rio_Hl_call, rio_Hl_number, rio_Hl_string,
rio_Hl_comment, rio_Hl_punct, or rio_Hl_code */
}
rio_highlight(src, len, token, 0);
A third takes what a compiler knows, too: rio_complete gives the names that fit at a cursor, as the
REPL's Tab does. With a REPL session's vm, they're the session's; with a vm that compiled a whole
text in its own scratch (rio_compileScratch, failing or not), they're that text's, as a language
server would have them; with no vm (0), just Rio's words and the names the text declares. Each comes
with a kind (rio_Item_*: a keyword, var, const, type, proc, method, field, module or enum value)
and a detail (its type, or a proc's signature). It returns where the word being completed starts:
static void offer(void *userData, const char *name, int nameLen, int kind, const char *detail, int detailLen) {
/* name[0..nameLen): rio_Item_field with "Float", rio_Item_method with "proc() -> Float", ... */
}
int start = rio_complete(vm, text, cursor, offer, 0); /* the word is text[start..cursor) */
Memory and limits
The library has no static RAM of its own. Everything lives in three buffers the host provides:
rio_Vm, mem and code.
Code and data share one buffer
Unless the host passes a code buffer, the code lives in mem too. While compiling, it grows in the
compiler's working memory: it starts with an eighth of it (rio_Limits.code), and takes more from the
string pool's free room as it needs it, so code and strings share their room. When compiling ends it
moves to just below the strings and tables at the top of memory, taking exactly its own size (8 bytes an
instruction). So one buffer is the whole budget, split between code and data however each program needs.
A REPL with the code in mem keeps a quarter of it for code for the whole session.
The compiler's tables (symbols, names, types, fields, procs, params, constants, slots...) share their room
too. Compiled without a rio_Limits, a program that fills one of them first (too many procs, say), or
fills the room code and strings share, is checked first (a statement at a time, no code kept, as an
editor's check is), in mem's room, which is free till the program runs: that counts what each table
needs, and it's compiled again with just that, an eighth more, the code and strings getting the rest.
(Constants and the slots' map keep their sizes: a check makes fewer constants than a compile does, and
packing the code uses the slots' map too, an entry an instruction.) If the check can't count them (an
error in the program, or tables too big even for it), or that still fails, it guesses: the table that
filled twice as big, the others half as big again as they'd been used, down to half, a few tries. Nothing
is reported for a try that's compiled again; still failing, it's compiled once more as at first, so its
errors are reported as they'd be. Studio's Maps: 397 procs compile (were 300 at most), and about 15,900
instructions (were 14,800).
The compiler borrows the program's memory
While compiling, the compiler writes only constants (at the bottom of mem) and string literals into
mem. Frames, globals and arrays are just address ranges that stay zero until the program runs, so the
compiler keeps its working state (symbol tables, expression stacks, the string pool) on top of them.
When it finishes, it packs frames and globals down right after the constants actually used, lets procs
that never run at the same time share frame memory, moves the strings, the export table and the line
table to their final place, and zeroes the rest. Peak RAM is max(compiling, running), not their sum.
compiling: [consts][ compiler state + string pool ..................................]
running: [consts][ frames/globals | return stack ][ ... ][strings+exports][arrays ]
rio_compileScratch keeps the compiler state in a separate buffer instead, which stays readable after
compiling. The C backend needs that.
Arrays overlap the compiler while it works. A big global (an array or struct over 16 words, such
as a Blob[65536]) takes its room from the top of mem when it's declared, down over the compiler's
state, which is fine because nothing writes it until the program runs. The only check while compiling
is that arrays stay above the program's frames and globals. So in a program whose arrays take most of
mem, nearly all of the compiler's room is the arrays' room too.
The final moves can land on the compiler. When compiling ends, the code and the block of strings
and tables move to just below the arrays. With big arrays, "just below" can be low in mem, on top
of the compiler's own state, or of where the code or the block still is. So the compiler reads what
it needs first, and moves whichever of the two won't write over the other's source first. When
neither order is safe, it's "out of memory", like any other way of not fitting. (Rinc's console, with
232 KB of its 256 in blobs, is such a program: its code lands at about 13 KB, inside the compiler's
state.)
free in the usage report is room while running. It's what's left between the program's frames
and its code, and says nothing about how near compiling came to the limits. That's the tables'
percentages, which can be near 100% with plenty free.
The source can be in mem too. A host with no room to spare, like a microcontroller reading a file,
can put the source at the top of mem and call rio_compile on it there. That memory is the program's
globals and arrays, still zero, so the compiler keeps its state below the source, and the program's final
layout takes it all back once compiling is done. Compiling then needs the source, the compiler's tables,
the constants and the strings to fit in mem together.
Or the source can stay in its file. rio_compileStream(vm, read, ud) reads the source a part at a
time, through a window the compiler keeps at the top of its own memory (2 KB by default;
rio_setSourceWindow sets another size before compiling). read(ud, buf, at, n) fills buf with up to
n bytes from byte at and returns how many it read, 0 at the end, or -1 if it can't. It's
positional, so the compiler can go back a little, which it needs to look ahead now and then. String
literals go into the string pool as they're read, so only the window and the strings take room, not the
whole source. A loader can hand back its sources the same way (see embedding).
The window, and 1.5 KB more for copies of the tokens read and the names a statement keeps, comes out of
the string pool, only when compiling reads this way (rio_compileStream, or rio_setSourceWindow set,
for a loader's sources). The usage report shows it as source window.
static int readFile(void *ud, char *buf, uint32_t at, uint32_t n) {
FILE *f = ud;
if (fseek(f, at, SEEK_SET)) return -1;
return (int)fread(buf, 1, n, f);
}
rio_compileStream(&vm, readFile, file);
Half the window bounds what has to be read at once: a name or number (at most 255 characters
anyway), or one line of a type method's declaration. Something longer is an error that names
rio_setSourceWindow.
How near the limits
With overlapping like this, what fits isn't obvious, so Rio reports it. rio_trackUsage(vm, &usage)
(after rio_init) has each compile fill in a rio_Usage: how full each of the compiler's tables got
against its capacity, the string pool and the source, and, for a program that compiled, where its
memory goes when running. A compile that fails reports as far as it got, which shows what ran out.
rio_usageText makes it readable:
compiler room 234496 bytes
source in mem 14336 bytes
symbols 78 of 1664: 4%
names 422 of 19968: 2%
...
string pool 11131 of 22964: 48%
constants 336 bytes
data 82872 bytes
code 2112 bytes
strings, tables 11620 bytes
free 165204 bytes
The tables are sized to fill the compiler's room, so whichever comes nearest 100% would run out first.
When a big value (an array or struct over 16 words) is what didn't fit, the report ends with it: its
size (big value), and the room there was for it (room for it).
rio -m starts its report with this, from compiling in place as running would.
Limits are chosen per compile
The compiler's tables (symbols, names, types, fields, procs, params, constants, nesting depth) are carved
out of its working memory at the start of each compile, scaled to the space available: rio_compile
scales to mem, and rio_compileScratch to the buffer given. For exact numbers, fill in a rio_Limits:
rio_Limits lim = rio_limitsFor(16 << 10); // a starting point, scaled to 16 KB
lim.procs = 64; // adjust what you need
rio_compileWith(&vm, src, len, scratch, sizeof scratch, &lim); // scratch NULL: overlay mem instead
uint32_t need = rio_limitsSize(&lim); // bytes those tables take (strings need some on top)
rio_limitsFor(n) sizes the tables to about 60% of n and leaves the rest for string literals.
Compiling without a rio_Limits scales the tables to half the room, and the code and the strings share
the rest.
Running out of anything is a clean compile error ("too many symbols", "scratch too small for these
limits", "not enough memory for the compiler").
The tables are fixed shares of the room, scaled from how many symbols fit: as many params as symbols (host procs take many: a host module of declarations can have more params than names), half as many fields, a third as many procs, a quarter as many types, twice as many constants. A program unlike that runs out of one table with room left in the others. The compiler's fixed state comes first, and some tables have floors, so small budgets get the floors:
| budget | symbols | procs | params | constants |
|---|---|---|---|---|
| 8 KB | 64 | 21 | 64 | 128 |
| 16 KB | 64 | 21 | 64 | 128 |
| 64 KB | 350 | 116 | 350 | 700 |
| 512 KB | 4,212 | 1,404 | 4,212 | 8,424 |
The only build-time caps are for what the host registers: rio_MAX_FFI, rio_MAX_DEFINES,
rio_MAX_AUTO_IMPORTS, and the log and error buffers. -Drio_SMALL shrinks those.
Measured
| 64-bit | 32-bit | |
|---|---|---|
rio_Vm (runtime state, rio_SMALL) | 968 B | 624 B |
smallest mem that compiles and runs a 64-ball physics demo | 6,570 B | 6,314 B |
smallest mem for the full test suite (automatic limits) | 30.6 KB | 30.2 KB |
| bytecode | 8 B per instruction | same |
| C stack while running | a few hundred bytes (return addresses live in mem) | same |
On a Cortex-M33, the library compiles to about 68 KB of flash at -Os (clang), plus libm and
memcpy/memset; the VM alone (see images) is about 11 KB. The compiler doesn't use
setjmp: an error makes the rest of the source read as its end, so it unwinds by returning, and the
whole thing builds for plain wasm (compiler and VM: 112 KB, 46 KB gzipped).
Shared frames
With no recursion, the compiler knows exactly which procs can be running at once: a proc and
everything it can call. Procs that never run together share frame memory, so frames cost the heaviest
chain of calls rather than the sum of all procs, and the return stack is sized by the longest chain.
A proc keeps its own frame if any of its slots has its address taken (by &, a view of a local array,
a for over one, and so on), since a view of that memory may outlive the call. Because of the
sharing, a program can't be started again while it runs: rio_run and rio_call from inside a host
proc return an error.
rio -m game.rio reports where a program's memory goes: constants, globals, the shared frame area and
the procs with their own frames, the call stack and the runtime tables, then the biggest procs and the
heaviest call chain.
Images
An image is a compiled program as bytes, ready to run: the bytecode, the constants, and the strings and
tables that sit at the top of mem (everything else starts as zero). A host can load one without the
compiler, and loading is just copying.
rio -M 256K -i game.img game.rio # compile for a vm with 256 KB of mem, and save the image
rio game.img # run an image (the CLI tells images from source by their first bytes)
uint32_t n = rio_saveImage(&vm, NULL, 0); // after compiling, before running: the size
rio_saveImage(&vm, buf, n); // returns n, or 0 if it doesn't fit
rio_init(&vm2, mem, sizeof mem, NULL, 0);
rio_addFfi(&vm2, "clock", ">f", host_clock); // the same host procs, in any order
if (rio_loadImage(&vm2, buf, n) || rio_run(&vm2)) puts(rio_error(&vm2));
A host without room for a whole image beside the vm, such as one saving to a file, can write and read it a part at a time, straight from and into the vm's memory:
static int put(void *f, const void *b, uint32_t n) { return fwrite(b, 1, n, f) != n; } // 0: written
static int get(void *f, void *b, uint32_t n) { return fread(b, 1, n, f) != n; } // 0: all n read
uint32_t n = rio_writeImage(&vm, put, file); // after compiling, before running: the size, or 0
if (rio_readImage(&vm2, get, file, n) || rio_run(&vm2)) puts(rio_error(&vm2));
- Addresses are absolute, so compile for the memory the program will run in (
-M, default 8 MB in the CLI) and load into at least that much. Code compiled intomemloads back there; code compiled into a separate buffer needs a loading vm with one too. - Host procs are bound by name when loading, only the ones the code calls, each to a host proc
with the same sig, or one with more parameters at its end and the same result: the image passes
zeros for those, and a struct parameter's layout may have more fields at its end (the host reads
zeros for them), so host procs can grow without breaking older images, as long as zero means what
it meant before. One that's missing or doesn't fit is an error naming it, and, when its module's
source was registered (
rio_addSource), both sources' hashes: the image keeps the name and hash of each one it was made with. -Drio_NO_COMPILERbuilds a VM that only loads images, leaving out the compiler and the REPL: on a Cortex-M33 at-Os, about 11 KB of flash instead of 68 KB. As wasm (zig cc -target wasm32-wasi -mexec-model=reactor -Os), a minimal browser host is 28 KB, 13 KB gzipped.tests/vm.cis such a host; ctest runs the test suite through it.- Images are trusted like code: the loader checks the header and sizes, but not the bytecode, so load only images you made.
- The format isn't stable yet. Images carry a version, and a vm refuses other versions; for now, rebuild images along with Rio. Little-endian hosts only.
Runtime errors from an image report lines and module file names as usual; the main file has no name in the image, so the host names it.
C output
rio -c game.c game.rio # writes a standalone C program
cc -O2 game.c -lm -o game # any C99 compiler; MSVC works too
The output is one C file with no dependency on Rio. Because Rio has no recursion, each proc becomes a
plain C function, and its frame slots become C locals unless their address is taken. Constants are
written inline, and each bytecode op becomes one C statement. Globals, arrays and strings live in a
static memory image identical to the VM's, so behavior is the same, bounds checks and wrapping math
included. The C compiler then optimizes it like any other C code. Runtime errors report Rio lines,
through #line directives.
Host procs are called as void rio_ffi_<name>(rio_Val *a), with a dotted name's dots as _
(rio_ffi_pc_cls). For a program that imports os, the CLI includes module os's code (os.h),
and main passes it the program's arguments; link your own for other host procs (and build with
-Drio_NO_HOST_FFI to drop the CLI's). ctest runs the test suite both in the
VM and through C.
Native loops on ARM
On ARM with Thumb-2, such as the RP2350's Cortex-M33, rio_jit(vm, buf, size) turns on a small
ahead-of-time compiler: from then on, everything that compiles or loads (programs, REPL inputs and
images) also has its simple loops and procs compiled to machine code in buf before running. buf
must be memory the CPU can run code from (any SRAM on the RP2350).
- Which loops: ones made of integer and float math (math builtins included), compares, branches
(nested loops,
break,continueand labels, andforover arrays), array and field reads and writes,log, and calls to host procs and to native procs. Others stay bytecode (calls through proc values, for one). - Which procs: whole procs made of the same things, except memory reads and writes (a proc with
those does better with only its loops compiled, which keep values in registers). Native code calls a
native proc directly; with one frame per proc, a call is just a branch.
sqrt,abs,floorandceilare single instructions (floorandceilon ARMv8, such as the M33); the other math builtins andlogcall into C. - Same behavior: values stay in the VM's memory (a loop's busiest values and constants sit in
registers while it runs), so the interpreter and native code mix freely. A runtime error in native
code is reported with its line, as if the VM had run it, and
rio_interruptstops native code too. - Measured on the Fruit Jam at 252 MHz, native vs the VM:
for n < 10_000_000 / n += 10.33 s vs 1.75 s; a millionn += i % 70.09 s vs 0.28 s; 300,000 calls to a small proc 0.087 s vs 0.168 s; 500 particles (structs of floats) for 100 steps 0.015 s vs 0.042 s; filling the screen withpset0.019 s vs 0.040 s; 100,000sincalls 0.078 s vs 0.090 s (mostlysinitself). - Size: native code is about 4.3 times the bytecode it replaces, but only loops and qualifying procs
get it (the 1,100-line test suite: 9.5 KB for 47 loops and procs). When
bufruns out, the rest stays bytecode.
Elsewhere, rio_jit returns -1 and changes nothing. rio -j uses it on ARM Linux, which is how it's
tested: under qemu-arm, as ARMv7 and ARMv8, the test suite, tests/jit*.rio and the VM-vs-C
differential tester all agree.
Performance
From bench/, against Lua 5.5 on the same Windows machine. Seconds, best of 5.
| benchmark | VM (clang, computed goto) | VM (MSVC, switch) | C output (clang -O2) | Lua 5.5 |
|---|---|---|---|---|
| loop: 100M int ops | 0.46 | 0.55–0.64 | 0.006 | 1.5–1.7 |
| calls: 30M proc calls | 0.36 | 0.34 | 0.010 | 1.3–1.5 |
| particles: 10k structs × 1000 steps | 0.28 | 0.39 | 0.014 | 0.9–1.0 |
| sieve: 2M, ×10 | 0.48 | 0.49 | 0.14 | 1.4–1.6 |
- VM: about 3–4× faster than Lua here. On Linux with a faster Lua build, particles measured 0.29 s
vs 0.59 s, about 2×, so expect roughly 2–4× depending on the Lua build. The speed comes from static
types (no tag checks), absolute-slot operands (static frames), constants preloaded in memory,
compare-and-branch fusion, fused index+load/store, bottom-tested
whileloops, a dedicatedforloop op, and destination retargeting that removes most moves. - C output: sieve is about 3.5× faster than the VM. The other three run in milliseconds because the C compiler sees through those loops entirely (inlining, vectorizing or folding them), so treat them as an upper bound rather than typical.
- The particles sums differ from Lua only because Rio's
Floatis 32-bit: Lua with 32-bit rounding emulated gives the identical 43926.92. switchdispatch on MSVC is sensitive to code layout: the same VM source has measured 0.34 s or 0.65 s oncallsdepending only on how unrelated code shifted. Expect build-to-build variation with MSVC; ClangCL avoids it.
Source layout
src/rio.h the public API (and the fixed-size state struct)
src/internal.h what Rio's files share: the instruction set, symbol and type kinds, runtime tables
the VM (all a host needs to run images):
src/vm.c the interpreter
src/runtime.c setting up a vm, finding procs and globals, errors, the line table
src/image.c saving and loading images
src/common.c number formatting, error messages, math builtins
the compiler (single pass, no recursion; left out with rio_NO_COMPILER):
src/compiler.h its state and tables, and what its files share
src/lexer.c tokens, and reporting compile errors
src/tables.c names, symbols, types and fields
src/codegen.c emitting code; slots, constants and memory; moving values; peepholes
src/operators.c unary and binary operators, element-by-element arithmetic, unions' `is`
src/expr.c the expression parser (shunting-yard): calls, indexing, members, literals
src/builtins.c log, math, assert, and the methods of sequences, builders, enums and numbers
src/decls.c types as written; procs, methods, structs, unions, enums and variables
src/statements.c statements and their blocks: if, loops, switch, return, assignment
src/modules.c import and include
src/host.c host declarations, checked; modules of host procs
src/compile.c limits, setup, and finishing: frame sharing, the line table, final layout
src/repl.c REPL sessions
src/jit.c native loops on ARM Thumb-2 (elsewhere, rio_jit does nothing)
src/core.rio the builtins, declared with host (compiled by the tests, not by programs)
src/aot.c bytecode to C (CLI only; not needed for embedding)
src/main.c the CLI host (loads modules from files and -L paths; the REPL)
src/os/ the CLI's module os, apart from Rio: os.rio declares it, os.h has it in C (os_host.h,
os_text.h: made from them)
tests/ ctest runs these, in the VM and through C:
test.rio the main suite
errors.c compile and runtime errors: kind, line, column, width and message
docs.py every example in docs/
... modules, host procs, the REPL, images, exports, fuzzing, VM-vs-C differences
docs/ this documentation: SUMMARY.md sets the order; mdbook builds it as a site
bench/ Rio vs Lua benchmarks
Everything Rio defines in C starts with rio_: functions are rio_camelCase, types rio_PascalCase,
enum values rio_EnumType_value, and macros rio_UPPER_CASE (the CMake options keep CMake's RIO_
style). library.cmake lists the sources (RIO_VM_SOURCES, RIO_COMPILER_SOURCES) for builds that pick
them. Comments in the source point to the spec section a piece of code implements, as
docs/spec/lexical.md.