From 83d5fe2cf6023be63935a0f1ca76a364dca8447d Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Mon, 26 Oct 2026 14:01:40 +0000 Subject: [PATCH] Revert "site: v0.24.0" This reverts commit 0809378c88a5cd8f493da02d3404b9053ff8f94e. --- diff --git a/site/public/_headers b/site/public/_headers new file mode 100644 index 0000000..deb5444 --- /dev/null +++ b/site/public/_headers @@ -0,0 +1,78 @@ + + +# BEGIN ladle source +/source/* + X-Content-Type-Options: nosniff + Content-Security-Policy: default-src 'none'; style-src 'self'; img-src 'self' https:; base-uri 'none'; form-action 'none'; frame-ancestors 'none' +/source/raw/* + Content-Type: text/plain; charset=utf-8 +/source/commit/*.patch + Content-Type: text/plain; charset=utf-8 +/source/feed.xml + Content-Type: application/atom+xml; charset=utf-8 +/source/releases.xml + Content-Type: application/atom+xml; charset=utf-8 +/source/objects/* + Content-Type: application/octet-stream + Cache-Control: public, max-age=31536000, immutable +/source/HEAD + Content-Type: text/plain; charset=utf-8 + Cache-Control: no-cache +/source/line + Content-Type: text/plain; charset=utf-8 + Cache-Control: no-cache +/source/info/refs + Content-Type: text/plain; charset=utf-8 + Cache-Control: no-cache +/source/objects/info/packs + ! Content-Type + ! Cache-Control + Content-Type: text/plain; charset=utf-8 + Cache-Control: no-cache +/source/releases/* + Content-Type: application/octet-stream +/source/releases/*.sha256 + ! Content-Type + Content-Type: text/plain; charset=utf-8 +/source/releases/index.html + ! Content-Type + Content-Type: text/html; charset=utf-8 +/source/releases/:version/index.html + ! Content-Type + Content-Type: text/html; charset=utf-8 +/source/releases/ + ! Content-Type + Content-Type: text/html; charset=utf-8 +/source/releases/:version/ + ! Content-Type + Content-Type: text/html; charset=utf-8 +/source/raw/*.png + ! Content-Type + Content-Type: image/png +/source/raw/*.jpg + ! Content-Type + Content-Type: image/jpeg +/source/raw/*.jpeg + ! Content-Type + Content-Type: image/jpeg +/source/raw/*.gif + ! Content-Type + Content-Type: image/gif +/source/raw/*.webp + ! Content-Type + Content-Type: image/webp +/source/raw/*.avif + ! Content-Type + Content-Type: image/avif +/source/raw/*.ico + ! Content-Type + Content-Type: image/x-icon +/source/raw/*.bmp + ! Content-Type + Content-Type: image/bmp +/source/raw/*.svg + ! Content-Type + Content-Type: image/svg+xml + ! Content-Security-Policy + Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; img-src data:; font-src data:; sandbox; frame-ancestors 'none' +# END ladle source diff --git a/site/public/_redirects b/site/public/_redirects new file mode 100644 index 0000000..22ac5bf --- /dev/null +++ b/site/public/_redirects @@ -0,0 +1 @@ +/download/latest /download/raz-0.23.0-linux-x86_64.tar.gz 302 diff --git a/site/public/advanced/allocators.html b/site/public/advanced/allocators.html new file mode 100644 index 0000000..42a1d92 --- /dev/null +++ b/site/public/advanced/allocators.html @@ -0,0 +1,202 @@ + + + + + +Writing an allocator - More Raz + + + + + + + + + + + + +
+
+

The library · lesson 6 of 18

Writing an allocator

+

An allocator is a record of two procedures, and that is all Mem.Allocator is:

+
type Allocator* = record
+    alloc*: proc(a: ^Allocator; size, align: INT): ^U8;   (* nil if out of room *)
+    free*:  proc(a: ^Allocator; p: ^U8);
+end;
+

NEW(p, a) calls a^.alloc(a, SIZE(T), alignment) and zeroes what it gets. Buf, List and Map call the same procedures. So anything that fills in these two fields is an allocator, and everything in the library works with it.

+

An allocator over a fixed array

+

Here is one that needs no system calls at all: it hands out memory from an array in the program, a bump allocator. This is the kind a program with no operating system, or no room for a heap, uses. free has nothing to do; reset forgets everything.

+

The trick that lets one procedure find its state is the same one Arena uses: the record puts base: Mem.Allocator first, so a ^Mem.Allocator and a ^Bump are the same address, and the procedure converts one to the other.

+
Bump.raz
module Bump;
+import Mem;
+
+type
+    Bump* = record
+        base*: Mem.Allocator;       (* first, so that ^Bump(a) finds the rest *)
+        mem: ^U8;
+        size, used*: INT;
+    end;
+
+proc alloc(a: ^Mem.Allocator; size, align: INT): ^U8;
+var b: ^Bump; at: INT;
+begin
+    b := ^Bump(a);
+    at := (b^.used + align - 1) div align * align;      (* round up to align *)
+    if (size < 0) or (at + size > b^.size) then return nil; end;
+    b^.used := at + size;
+    return b^.mem + at;
+end;
+
+proc free(_a: ^Mem.Allocator; _p: ^U8);
+begin
+end;
+
+(* a bump allocator over the size bytes at mem *)
+proc init*(b: ^Bump; mem: ^U8; size: INT);
+begin
+    b^.base := {alloc: alloc, free: free};
+    b^.mem := mem;
+    b^.size := size;
+    b^.used := 0;
+end;
+
+(* everything forgotten, the memory used again *)
+proc reset*(b: ^Bump);
+begin
+    b^.used := 0;
+end;
+
+end Bump.
+
Bumping.raz
module Bumping;
+import Out, Bump;
+
+type Point = record x, y: INT; end;
+
+var arena: [256]U8;           (* the allocator's whole world *)
+
+proc main*;
+var b: Bump.Bump; p, q: ^Point; many: INT; r: ^Point;
+begin
+    Bump.init(ADR(b), ADR(arena[0]), 256);
+    NEW(p, ADR(b.base));
+    NEW(q, ADR(b.base));
+    p^.x := 1; q^.y := 2;
+    Out.int(b.used); Out.str(" bytes used by two points\n");
+    many := 2;
+    repeat
+        NEW(r, ADR(b.base));
+        if r # nil then INC(many); end;
+    until r = nil;
+    Out.int(many); Out.str(" points fit in 256 bytes\n");
+    Bump.reset(ADR(b));
+    NEW(r, ADR(b.base));
+    if r # nil then Out.str("room again after a reset\n"); end;
+end;
+
+end Bumping.
+
32 bytes used by two points
+16 points fit in 256 bytes
+room again after a reset
+
+

An allocator that runs out says so with nil, and the caller decides what that means. Nothing else in the program is touched.

+

An allocator that counts

+

An allocator can wrap another. This one forwards to whatever it is given and keeps count, which is how to find out what a piece of code allocates, or to prove that a path allocates nothing.

+
Counted.raz
module Counted;
+import Mem;
+
+type
+    Counted* = record
+        base*: Mem.Allocator;       (* first *)
+        inner: ^Mem.Allocator;
+        allocs*, frees*, bytes*: INT;
+    end;
+
+proc alloc(a: ^Mem.Allocator; size, align: INT): ^U8;
+var c: ^Counted; p: ^U8;
+begin
+    c := ^Counted(a);
+    p := Mem.alloc(c^.inner, size, align);
+    if p # nil then INC(c^.allocs); INC(c^.bytes, size); end;
+    return p;
+end;
+
+proc free(a: ^Mem.Allocator; p: ^U8);
+var c: ^Counted;
+begin
+    c := ^Counted(a);
+    INC(c^.frees);
+    Mem.free(c^.inner, p);
+end;
+
+(* a counting allocator in front of inner *)
+proc init*(c: ^Counted; inner: ^Mem.Allocator);
+begin
+    c^.base := {alloc: alloc, free: free};
+    c^.inner := inner;
+    c^.allocs := 0;
+    c^.frees := 0;
+    c^.bytes := 0;
+end;
+
+end Counted.
+
Audit.raz
module Audit;
+import Fmt, Heap, Mem, Buf, Counted, Names := List([]U8);
+
+proc main*;
+var c: Counted.Counted; b: Buf.Buf; l: Names.List; i: INT; p: ^U8;
+begin
+    Counted.init(ADR(c), Heap.heap);
+    Buf.init(b, ADR(c.base));
+    for i := 1 to 200 do Buf.str(b, "0123456789"); end;
+    Fmt.print("a buffer of {} bytes took {} allocations\n",
+        [Fmt.int(b.len), Fmt.int(c.allocs)]);
+    Buf.done(b);
+
+    Names.init(l, ADR(c.base));
+    for i := 1 to 10 do _ := Names.push(l, "x"); end;
+    Fmt.print("{} allocations in all, {} frees so far\n", [Fmt.int(c.allocs), Fmt.int(c.frees)]);
+    Names.clear(l);
+    Fmt.print("{} frees after clear\n", [Fmt.int(c.frees)]);
+
+    p := Mem.alloc(ADR(c.base), 64, 8);
+    Mem.free(ADR(c.base), p);
+end;
+
+end Audit.
+
a buffer of 2000 bytes took 6 allocations
+16 allocations in all, 6 frees so far
+16 frees after clear
+
+

A Buf grows by doubling, so two thousand bytes took a handful of allocations and not two hundred. That is the sort of thing a counting allocator is for.

+

What to take from this

+
  • An allocator is a value, so it is passed, wrapped, swapped in a test and replaced by a bump allocator in a program with no heap.
  • A library function that needs memory takes the allocator as a parameter, so its caller owns the policy.
  • An allocator can use the record-first trick to carry any state it needs, because converting a pointer to a record's first field and back is the same address.

Save a program under its module’s name and run it with raz run Name.raz.

+
+ + + diff --git a/site/public/advanced/asm.html b/site/public/advanced/asm.html new file mode 100644 index 0000000..04432aa --- /dev/null +++ b/site/public/advanced/asm.html @@ -0,0 +1,259 @@ + + + + + +Procedures in assembly - More Raz + + + + + + + + + + + + +
+
+

The machine · lesson 11 of 18

Procedures in assembly

+

Sometimes a program needs an instruction the language has no word for: reading the cycle counter, asking the CPU what it is, counting bits in one instruction, a square root in the hardware. A procedure whose body is code is machine code, written by hand in the target's assembly language, one instruction to each ;, up to end.

+

The compiler doesn't look past what the instructions say. It trusts you, and you owe it a few rules.

+

A first one

+

This reads the processor's time stamp counter. The result of a procedure goes in rax; rdtsc leaves the counter in edx:eax, so the two halves are joined first.

+
Cycles.raz
module Cycles;
+import Out;
+
+proc rdtsc*: U64;
+code
+    rdtsc;
+    shl rdx, 32;
+    or rax, rdx;
+    ret;
+end rdtsc;
+
+proc main*;
+var a, b: U64;
+begin
+    a := rdtsc();
+    b := rdtsc();
+    if b > a then Out.str("the counter moves forward\n"); end;
+end;
+
+end Cycles.
+
the counter moves forward
+
+

A code procedure is called like any procedure. Everything in it is yours, ret included.

+

The convention

+

A code procedure follows the System V convention, as every raz procedure does:

+
  • Integer and pointer arguments arrive in rdi, rsi, rdx, rcx, r8 and r9; F32 and F64 ones in xmm0 to xmm7.
  • The result goes in rax (and rdx for a second) or xmm0.
  • It must keep rbx, rbp, rsp and r12 to r15 as it found them. rax, rcx, rdx, rsi, rdi and r8 to r11 are free to change.
  • A slice is two integers, its address and its length, as System V passes a struct of two. As a parameter it takes two registers in a row; as the result its address goes in rax and its length in rdx.
  • Its parameters and results are therefore of the types C can take, or slices: at most six integer and eight real parameters, and two results, a slice being the only one.
+

That is why the next one is so short: the argument is already in rdi.

+
Bits.raz
module Bits;
+import Out;
+
+(* the bytes of x in the opposite order: bswap rax, which the assembler
+   doesn't know, written as its bytes *)
+proc swap64(x: U64): U64;
+code
+    mov rax, rdi;
+    db 48H, 0FH, 0C8H;
+    ret;
+end swap64;
+
+(* the number of bits set in x *)
+proc ones(x: U64): INT;
+code
+    popcnt rax, rdi;
+    ret;
+end ones;
+
+proc main*;
+begin
+    Out.str("0x"); Out.hex(swap64(0102030405060708H), 16); Out.ln;
+    Out.int(ones(0FFH)); Out.char(' ');
+    Out.int(ones(0)); Out.char(' ');
+    Out.int(ones(0FFFFFFFFFFFFFFFFH)); Out.ln;
+end;
+
+end Bits.
+
0x0807060504030201
+8 0 64
+
+

db writes any bytes, for an instruction the assembler doesn't know. Which instructions it knows is the implementation's business: this one knows popcnt but not bswap, and db keeps you from waiting for it to learn one. (bswap r64 is REX.W 0F C8+r in the processor manuals.)

+

Labels and loops

+

A label, name:, names the place of the instruction after it, within the procedure. Jumps go to labels, and a constant of the module may stand wherever a number does. This sums a slice of INTs, whose address arrives in rdi and its length in rsi:

+
Sum.raz
module Sum;
+import Out;
+
+(* the sum of the INTs of a *)
+proc sum(a: []INT): INT;
+code
+    xor eax, eax;
+    test rsi, rsi;
+    jle done;
+again:
+    add rax, [rdi];
+    add rdi, 8;
+    dec rsi;
+    jnz again;
+done:
+    ret;
+end sum;
+
+(* the same in raz, to check it against *)
+proc sumRaz(a: []INT): INT;
+var i, t: INT;
+begin
+    for i := 0 to LEN(a) - 1 do t := t + a[i]; end;
+    return t;
+end;
+
+proc main*;
+var a: [6]INT; i: INT;
+begin
+    for i := 0 to 5 do a[i] := (i + 1) * 100; end;
+    Out.int(sum(a)); Out.char(' ');
+    Out.int(sumRaz(a)); Out.char(' ');
+    Out.int(sum(a[2..4])); Out.char(' ');
+    Out.int(sum(a[0..0])); Out.ln;
+end;
+
+end Sum.
+
2100 2100 700 0
+
+

The procedure trusts the length it is given, as it must: the checks of the language end where its code begins.

+

A slice comes back the same way, its address in rax and its length in rdx. This one returns what is left of a string past its leading blanks:

+
Trim.raz
module Trim;
+import Out;
+
+(* s past its leading blanks *)
+proc trim(s: []U8): []U8;
+code
+    mov rax, rdi;
+    mov rdx, rsi;
+again:
+    test rdx, rdx;
+    jz done;
+    cmp byte [rax], 32;
+    jne done;
+    inc rax;
+    dec rdx;
+    jmp again;
+done:
+    ret;
+end trim;
+
+proc main*;
+begin
+    Out.char('['); Out.str(trim("   raz")); Out.str("]\n");
+    Out.char('['); Out.str(trim("raz")); Out.str("]\n");
+    Out.char('['); Out.str(trim("    ")); Out.str("]\n");
+end;
+
+end Trim.
+
[raz]
+[raz]
+[]
+
+

A procedure may have up to 64 labels. The check against the raz version is the habit worth keeping: write the procedure in raz first, then in assembly, and compare their results on awkward inputs.

+

Two results, and reals

+

A second result goes in rdx. That is exactly where idiv leaves the remainder, so divmod is four instructions. Reals travel in the xmm registers.

+
Divmod.raz
module Divmod;
+import Out, Fmt;
+
+(* quotient and remainder, as idiv gives them: rax and rdx *)
+proc divmod(a, b: INT): (INT, INT);
+code
+    mov rax, rdi;
+    cqo;
+    idiv rsi;
+    ret;
+end divmod;
+
+(* a * x + b, on F64s in xmm0 to xmm2 *)
+proc fma(a, x, b: F64): F64;
+code
+    mulsd xmm0, xmm1;
+    addsd xmm0, xmm2;
+    ret;
+end fma;
+
+proc main*;
+var q, r: INT;
+begin
+    q, r := divmod(-17, 5);
+    Out.int(q); Out.char(' '); Out.int(r); Out.ln;
+    Fmt.print("{}\n", [Fmt.real(fma(2.0, 3.5, 0.25), 2)]);
+end;
+
+end Divmod.
+
-3 -2
+7.25
+
+

idiv by zero stops the program with the machine's own division fault. It isn't a check the compiler added, since the compiler doesn't look inside a code procedure.

+

Keeping what isn't yours

+

A procedure that uses rbx must put it back. cpuid clobbers rbx, so the vendor-string example saves it with push and restores it with pop, and keeps the buffer's address in r8 while it works:

+
Vendor.raz
module Vendor;
+import Out;
+
+(* the 12 bytes of the processor vendor, in buf (rdi) *)
+proc vendor(buf: ^U8);
+code
+    push rbx;
+    mov r8, rdi;
+    xor eax, eax;
+    cpuid;
+    mov [r8], ebx;
+    mov [r8 + 4], edx;
+    mov [r8 + 8], ecx;
+    pop rbx;
+    ret;
+end vendor;
+
+proc main*;
+var buf: [12]U8; i: INT; ok: BOOL;
+begin
+    vendor(ADR(buf[0]));
+    ok := true;
+    for i := 0 to 11 do
+        if (buf[i] < ' ') or (buf[i] > '~') then ok := false; end;
+    end;
+    if ok then Out.str("the vendor is 12 printable bytes\n"); end;
+end;
+
+end Vendor.
+
the vendor is 12 printable bytes
+
+

What goes wrong

+

A code procedure that breaks its rules breaks the program, and what follows isn't defined. Writing through a wrong pointer, a changed rbx, a missing ret, a stack left unbalanced: the language can't help, because it doesn't see inside. Keep them short, give each a comment that says what it expects in which register, test each against a raz twin, and use them for what only the machine can do.

Save a program under its module’s name and run it with raz run Name.raz.

+
+ + + diff --git a/site/public/advanced/atomics.html b/site/public/advanced/atomics.html new file mode 100644 index 0000000..4268768 --- /dev/null +++ b/site/public/advanced/atomics.html @@ -0,0 +1,204 @@ + + + + + +Atomics - More Raz + + + + + + + + + + + + +
+
+

Shared memory · lesson 15 of 18

Atomics

+

A volatile access is one access. An atomic is one *indivisible* step: nothing can happen between its read and its write, so two threads using it can't lose each other's work. There are three, built into the language as procedures, and they are sequentially consistent on every target:

+
CallDoes
XADD(p, x)adds x to p^ and returns the value before
XCHG(p, x)sets p^ := x and returns the value before
CAS(p, old, new)if p^ = old, sets p^ := new and returns true; otherwise false
+

p is a ^T or ^VOLATILE T where T is INT, UINT or a pointer type (INT or UINT for XADD). They compile to single x86-64 instructions: lock xadd, xchg (which is always locked when it touches memory) and lock cmpxchg:

+
Ops.raz
module Ops;
+
+var counter: INT;
+
+proc main*;
+begin
+    _ := XADD(ADR(counter), 5);
+    _ := XCHG(ADR(counter), 100);
+    _ := CAS(ADR(counter), 100, 7);
+end;
+
+end Ops.
+
$ raz -S Ops.raz | grep -i "lock\|xchg"
+            23  lock xadd [r8], rax
+     8      _ := XCHG(ADR(counter), 100);
+            43  xchg [r8], rax
+            67  lock cmpxchg [r8], r10
+

What each one gives you

+

XADD is a counter, or a ticket dispenser: every caller gets a different number. XCHG takes the old value and leaves a new one, which is a flag, a swap, or the release of a lock. CAS is the general one: "if nobody changed it since I looked, change it". Most lock-free code is a loop around it.

+
Tickets.raz
module Tickets;
+import Out, Thread;
+
+var
+    next: INT;                  (* the next ticket to give out *)
+    seen: [4000]U8;             (* which tickets were taken, one byte each *)
+
+proc work(_arg: ^U8);
+var i, t: INT;
+begin
+    for i := 1 to 1000 do
+        t := XADD(ADR(next), 1);      (* a ticket no other thread gets *)
+        seen[t] := 1;
+    end;
+end;
+
+proc main*;
+var th: [4]^Thread.Thread; i, taken: INT; err: ERROR;
+begin
+    for i := 0 to 3 do
+        th[i], err := Thread.spawn(work, nil);
+        if err # nil then Out.str(MSG(err)); Out.ln; return; end;
+    end;
+    for i := 0 to 3 do Thread.join(th[i]); end;
+    for i := 0 to 3999 do taken := taken + seen[i]; end;
+    Out.int(next); Out.char(' '); Out.int(taken); Out.ln;
+end;
+
+end Tickets.
+
4000 4000
+
+

Four thousand tickets, four thousand different numbers, no two threads with the same one. Each thread writes into its own bytes of seen, so no plain write is shared.

+

A compare-and-swap loop

+

Anything that can be computed from the old value can be made atomic with a loop around CAS: read the value, compute the new one, and try to swap it in; if someone got there first, read again. Here is an atomic maximum, which no single instruction does.

+
Peak.raz
module Peak;
+import Out, Thread;
+
+var peak: INT;
+
+(* raises peak to v if v is bigger, however many threads call it *)
+proc raise(v: INT);
+var seen: INT;
+begin
+    seen := peak;
+    while seen < v do
+        if CAS(ADR(peak), seen, v) then return; end;
+        seen := peak;                  (* someone changed it: look again *)
+    end;
+end;
+
+proc work(arg: ^U8);
+var i, base: INT;
+begin
+    base := INT(arg);
+    for i := 0 to 999 do raise(base + i * 7 mod 1001); end;
+end;
+
+proc main*;
+var th: [4]^Thread.Thread; i: INT; err: ERROR;
+begin
+    for i := 0 to 3 do
+        th[i], err := Thread.spawn(work, ^U8(i * 1000));
+        if err # nil then Out.str(MSG(err)); Out.ln; return; end;
+    end;
+    for i := 0 to 3 do Thread.join(th[i]); end;
+    Out.int(peak); Out.ln;
+end;
+
+end Peak.
+
3994
+
+

The result doesn't depend on how the threads interleave: it is the largest value any of them offered. That is the test of a correct atomic algorithm, and why this kind of code is written once, carefully, and used everywhere.

+

A lock, from first principles

+

A lock is a word that is 0 when free and 1 when held. To take it, CAS it from 0 to 1; if that fails, someone holds it, so try again. To give it up, XCHG it back to 0. This is exactly the library's Lock, printed from lib/Lock.raz:

+
$ sed -n '/^type Lock/,/^proc main/p' $RAZLIB/Lock.raz | head -n -2
+type Lock* = record held: INT; end;
+
+(* Takes l, waiting while another thread holds it. *)
+proc take*(var l: Lock);
+var tries: INT;
+begin
+    tries := 0;
+    while not CAS(ADR(l.held), 0, 1) do
+        INC(tries);
+        if tries = 64 then Sys.yield; tries := 0; end;
+    end;
+end;
+
+(* Gives up l, which the caller holds. *)
+proc give*(var l: Lock);
+begin
+    _ := XCHG(ADR(l.held), 0);
+end;
+

And here is a use of it: a structure with two fields that must stay in step, which no single atomic can protect.

+
Account.raz
module Account;
+import Out, Lock, Thread;
+
+var
+    lock: Lock.Lock;
+    deposits, balance: INT;      (* balance = 3 * deposits, always, under lock *)
+
+proc work(_arg: ^U8);
+var i: INT;
+begin
+    for i := 1 to 20000 do
+        Lock.take(lock);
+        INC(deposits);
+        INC(balance, 3);
+        Lock.give(lock);
+    end;
+end;
+
+proc main*;
+var th: [4]^Thread.Thread; i: INT; err: ERROR;
+begin
+    for i := 0 to 3 do
+        th[i], err := Thread.spawn(work, nil);
+        if err # nil then Out.str(MSG(err)); Out.ln; return; end;
+    end;
+    for i := 0 to 3 do Thread.join(th[i]); end;
+    Out.int(deposits); Out.char(' '); Out.int(balance); Out.ln;
+    if balance = 3 * deposits then Out.str("in step\n"); end;
+end;
+
+end Account.
+
80000 240000
+in step
+
+

A Lock spins, giving up the processor now and then, so it is for sections of a few instructions. Thread.Mutex sleeps on a futex, so it is for longer ones. A spinning lock held for a long time, or by a thread that was descheduled, burns processors; that is the price of its speed when contention is short.

+

Choosing

+
  • A counter, a ticket, a flag: XADD or XCHG.
  • A value computed from the old one: a CAS loop.
  • Several variables that must change together: a Lock or a Mutex. Don't try to be clever with several atomics; the one invariant spanning them is the thing that breaks.
+

All three act on a word. For anything bigger, the thing you swap is a pointer to the bigger thing: the next lessons do exactly that.

Save a program under its module’s name and run it with raz run Name.raz.

+
+ + + diff --git a/site/public/advanced/bytes.html b/site/public/advanced/bytes.html new file mode 100644 index 0000000..ec23646 --- /dev/null +++ b/site/public/advanced/bytes.html @@ -0,0 +1,247 @@ + + + + + +Strings and bytes - More Raz + + + + + + + + + + + + +
+
+

The library · lesson 2 of 18

Strings and bytes

+

A []U8 is both a string and a block of bytes. Str has what is done with them: comparing, finding, hashing, copying into memory of your own, UTF-8, numbers, and the fixed byte orders of file formats and network protocols. Bytes has the searches, made fast.

+

Ordering and hashing

+

Str.cmp gives -1, 0 or 1, byte by byte, so it orders UTF-8 text by code point. Str.eq is equality. Str.hash is FNV-1a, 64 bits; it is what a Map of strings uses.

+
Order.raz
module Order;
+import Out, Str, Fmt;
+
+proc main*;
+var names: [4][]U8; i, j: INT; t: []U8;
+begin
+    names := ["pear", "Apple", "fig", "apple"];
+    (* a small insertion sort, with Str.cmp *)
+    for i := 1 to 3 do
+        t := names[i];
+        j := i - 1;
+        while (j >= 0) and (Str.cmp(names[j], t) > 0) do
+            names[j + 1] := names[j];
+            DEC(j);
+        end;
+        names[j + 1] := t;
+    end;
+    for i := 0 to 3 do Out.str(names[i]); Out.char(' '); end;
+    Out.ln;
+    Fmt.print("{}\n", [Fmt.hex(Str.hash("raz"))]);
+    if Str.hash("raz") = Str.hash("raz") then Out.str("stable\n"); end;
+end;
+
+end Order.
+
Apple apple fig pear 
+89F6BC1960FF4912
+stable
+
+

Upper case sorts before lower, since 'A' is 65 and 'a' is 97: Str.cmp doesn't pretend to know a language's alphabet.

+

Keeping a string

+

A slice of a string constant lives forever, but a slice of a buffer lives only as long as the buffer. To keep one past that, Str.copy takes memory from an allocator and says whether it got any.

+
Keep.raz
module Keep;
+import Out, Str, Heap, Mem;
+
+type Entry = record name: []U8; n: INT; end;
+
+var entries: [3]Entry;
+
+(* remembers a name that the caller will overwrite *)
+proc remember(slot: INT; name: []U8);
+var copy: []U8; ok: BOOL;
+begin
+    copy, ok := Str.copy(Heap.heap, name);
+    if ok then entries[slot].name := copy; entries[slot].n := slot; end;
+end;
+
+proc main*;
+var scratch: [16]U8; i: INT;
+begin
+    for i := 0 to 2 do
+        scratch := "name-";
+        scratch[5] := U8('0' + i);
+        remember(i, scratch[0..6]);
+        scratch := "overwritten!";
+    end;
+    for i := 0 to 2 do
+        Out.str(entries[i].name); Out.char(' ');
+        Mem.free(Heap.heap, ^U8(ADR(entries[i].name[0])));
+    end;
+    Out.ln;
+end;
+
+end Keep.
+
name-0 name-1 name-2 
+
+

Searching

+

Bytes finds bytes many at a time: Bytes.index and Bytes.last give the first and the last place of a byte in a []U8, or -1, Bytes.count how many places it has, and Bytes.find where one []U8 first starts in another (Str.find is the same). Each is what a loop over the bytes would give, only faster: the library's own body compares eight bytes at once in a U64, and on x86-64 a file of its own, Bytes.x86_64.raz, compares sixteen with SSE2, in code procedures.

+
Paths.raz
module Paths;
+import Out, Fmt, Bytes;
+
+(* the last part of a path: what follows its last slash *)
+proc base(path: []U8): []U8;
+begin
+    return path[Bytes.last(path, '/') + 1..LEN(path)];
+end;
+
+proc main*;
+var text: []U8; at, n, line: INT;
+begin
+    Out.str(base("/usr/local/lib/raz/Bytes.raz")); Out.char(' ');
+    Out.str(base("Out.raz")); Out.ln;
+
+    text := "one line\nanother line\nthe line with raz in it\nthe last\n";
+    Fmt.print("{} lines\n", [Fmt.int(Bytes.count(text, 10))]);
+    at := Bytes.find(text, "raz");
+    if at >= 0 then
+        (* the line it is on: the newlines before it, plus one *)
+        line := Bytes.count(text[0..at], 10) + 1;
+        n := Bytes.index(text[at..LEN(text)], 10);
+        Fmt.print("raz on line {}, at {}, and the line goes on {} more\n",
+            [Fmt.int(line), Fmt.int(at), Fmt.int(n)]);
+    end;
+    Fmt.print("{} {}\n", [Fmt.int(Bytes.find(text, "zzz")), Fmt.int(Bytes.find(text, ""))]);
+end;
+
+end Paths.
+
Bytes.raz Out.raz
+4 lines
+raz on line 3, at 36, and the line goes on 9 more
+-1 0
+
+

When the byte isn't there, Bytes.last gives -1, so base of a name with no slash is the whole name. A search of a slice gives places in the slice, counted from its own start: add the place the slice starts at to get one in the whole.

+

Binary formats

+

A file format or a network protocol has a byte order of its own, not the machine's. Str.le and Str.be read an unsigned number of up to 8 bytes in a fixed order (little- or big-endian) and Str.putLE and Str.putBE write one. They work on any slice, so a header is read where it lies, with no struct to overlay and no byte swapping to forget.

+

Here is a small record format: a 4-byte tag, a 2-byte big-endian length, a 4-byte little-endian checksum, then the data.

+
Frame.raz
module Frame;
+import Out, Fmt, Str;
+
+const HeaderSize = 10;
+
+(* the sum of the bytes of data, all mod 2^32 *)
+proc checksum(data: []U8): U32;
+var i: INT; sum: U32;
+begin
+    for i := 0 to LEN(data) - 1 do sum := sum + U32(data[i]); end;
+    return sum;
+end;
+
+(* writes a frame to out, which must have room; its length *)
+proc pack(out: []U8; tag, data: []U8): INT;
+begin
+    COPY(out[0..4], tag);
+    Str.putBE(out[4..6], U64(LEN(data)));
+    Str.putLE(out[6..10], U64(checksum(data)));
+    COPY(out[HeaderSize..HeaderSize + LEN(data)], data);
+    return HeaderSize + LEN(data);
+end;
+
+proc main*;
+var buf: [64]U8; n, len: INT; sum: U32; i: INT;
+begin
+    n := pack(buf, "DATA", "hello");
+    for i := 0 to n - 1 do
+        Out.hex(U64(buf[i]), 2); Out.char(' ');
+    end;
+    Out.ln;
+    (* and back *)
+    len := INT(Str.be(buf[4..6]));
+    sum := U32(Str.le(buf[6..10]));
+    Fmt.print("tag {}, {} bytes, checksum {}, ", [Fmt.str(buf[0..4]), Fmt.int(len), Fmt.hex(U64(sum))]);
+    if sum = checksum(buf[HeaderSize..HeaderSize + len]) then
+        Out.str("valid: "); Out.str(buf[HeaderSize..HeaderSize + len]);
+    else
+        Out.str("corrupt");
+    end;
+    Out.ln;
+end;
+
+end Frame.
+
44 41 54 41 00 05 14 02 00 00 68 65 6C 6C 6F 
+tag DATA, 5 bytes, checksum 214, valid: hello
+
+

The output is the same on a little-endian and a big-endian machine, because the bytes are written one at a time in the order the format says.

+

Numbers and text

+

Str.toInt reads a decimal number with an optional sign and nothing else, and says whether it was one; Str.toHex reads hexadecimal digits, and Math.toReal a real, as a constant is written but with e for E too, to the nearest F64 exactly. Str.fromInt goes the other way into an array of 20 bytes, with no allocator, and Fmt does the rest. Str.encode and Str.decode move between characters and UTF-8, as the first tour showed.

+
Numbers.raz
module Numbers;
+import Out, Str, Math, Fmt;
+
+(* the sum of the numbers in a comma separated list, or -1 if any isn't *)
+proc total(s: []U8): I64;
+var part: []U8; sum, n: I64; ok, more: BOOL;
+begin
+    more := true;
+    while more do
+        part, s, more := Str.cut(s, ",");
+        n, ok := Str.toInt(part);
+        if not ok then return -1; end;
+        sum := sum + n;
+    end;
+    return sum;
+end;
+
+proc main*;
+var u: U64; x: F64; ok: BOOL; digits: [20]U8; k: INT;
+begin
+    Out.int(total("10,20,-5,+7")); Out.ln;
+    Out.int(total("10,x,20")); Out.ln;
+    Out.int(total("10,,20")); Out.ln;
+    u, ok := Str.toHex("ff00");
+    if ok then Out.hex(u, 1); Out.ln; end;
+    x, ok := Math.toReal("-1.5e3");
+    if ok then Fmt.print("{}\n", [Fmt.real(x, 1)]); end;
+    digits, k := Str.fromInt(-9223372036854775807 - 1);
+    Out.str(digits[0..k]); Out.ln;
+end;
+
+end Numbers.
+
32
+-1
+-1
+FF00
+-1500.0
+-9223372036854775808
+

Save a program under its module’s name and run it with raz run Name.raz.

+
+ + + diff --git a/site/public/advanced/collections.html b/site/public/advanced/collections.html new file mode 100644 index 0000000..c7c3d47 --- /dev/null +++ b/site/public/advanced/collections.html @@ -0,0 +1,192 @@ + + + + + +Lists, arrays, maps and sorting - More Raz + + + + + + + + + + + + +
+
+

The library · lesson 3 of 18

Lists, arrays, maps and sorting

+

The four generic modules are instantiated like any other generic module, with the types and procedures they need. All four take their memory from an allocator you give them; none of them allocates anything you didn't ask for.

+

List(T)

+

A singly linked list with push at the front, pop from the front, and the nodes exported, so a program walks it itself. Both can fail if the allocator is out of room, and say so.

+
Pile.raz
module Pile;
+import Out, Heap, Ints := List(INT);
+
+proc main*;
+var l: Ints.List; n: ^Ints.Node; v: INT;
+begin
+    Ints.init(l, Heap.heap);
+    defer Ints.clear(l);
+    for v := 1 to 5 do _ := Ints.push(l, v * v); end;
+    Ints.reverse(l);                    (* oldest first *)
+    n := l.head;
+    while n # nil do Out.int(n^.val); Out.char(' '); n := n^.next; end;
+    Out.ln;
+    v, _ := Ints.pop(l);
+    Out.int(v); Out.str(" popped, "); Out.int(l.len); Out.str(" left\n");
+end;
+
+end Pile.
+
1 4 9 16 25 
+1 popped, 4 left
+
+

Vec(T)

+

A growable array: one block of elements that doubles when it is full, for what a program learns the length of only as it reads. push adds at the end, add adds a zero element and gives a pointer to fill it in place, resize cuts it short or grows it with zeros. all gives the elements as a slice, indexed and checked as any slice is; the slice is good until the array next grows. Running out of memory stops the program, as with Buf: an element dropped silently would be wrong data. room asks first, for a program that can do better.

+
Squares.raz
module Squares;
+import Out, Heap, Ints := Vec(INT);
+
+proc main*;
+var v: Ints.Vec; i: INT; s: []INT;
+begin
+    Ints.init(v, Heap.heap);
+    defer Ints.done(v);
+    for i := 1 to 1000 do Ints.push(v, i * i); end;
+    s := Ints.all(v);
+    Out.int(v.len); Out.str(" squares, the last "); Out.int(s[LEN(s) - 1]); Out.ln;
+    Ints.resize(v, 3);
+    for i := 0 to v.len - 1 do Out.int(Ints.all(v)[i]); Out.char(' '); end;
+    Out.ln;
+end;
+
+end Squares.
+
1000 squares, the last 1000000
+1 4 9 
+
+

Map(K, V; hash, eq)

+

A hash map. Its key's hash and equality are procedure arguments, so any type can be a key. put replaces what a key maps to; get says what it maps to and whether it maps to anything; remove says whether the key was there. next walks the map: from 0, it gives the next entry and the number to pass for the one after, and -1 when there are no more.

+
Ages.raz
module Ages;
+import Out, Fmt, Str, Heap, Book := Map([]U8, INT, Str.hash, Str.eq);
+
+proc main*;
+var m: Book.Map; age: INT; found, ok: BOOL; i: INT; v: INT;
+begin
+    Book.init(m, Heap.heap);
+    _ := Book.put(m, "ada", 36);
+    _ := Book.put(m, "grace", 45);
+    _ := Book.put(m, "alan", 41);
+    _ := Book.put(m, "ada", 37);                (* replaces *)
+    age, found := Book.get(m, "ada");
+    Fmt.print("ada: {} ({})\n", [Fmt.int(age), Fmt.bool(found)]);
+    age, found := Book.get(m, "linus");
+    Fmt.print("linus: {} ({})\n", [Fmt.int(age), Fmt.bool(found)]);
+    ok := Book.remove(m, "alan");
+    Fmt.print("{} entries, removed {}\n", [Fmt.int(m.len), Fmt.bool(ok)]);
+    v := 0;
+    i, _, age := Book.next(m, 0);
+    while i >= 0 do
+        INC(v, age);
+        i, _, age := Book.next(m, i);
+    end;
+    Out.int(v); Out.str(" years in all\n");
+end;
+
+end Ages.
+
ada: 37 (true)
+linus: 0 (false)
+2 entries, removed true
+82 years in all
+
+

A map's order is its own, so a program that wants an order collects the entries and sorts them, as the next section does.

+

Sort(T; less)

+

An in-place sort of a slice, by a less procedure, in n log n at most and with no memory of its own. Elements equal by less may change places.

+

Putting them together

+

Counting words, then listing them by count and then alphabetically: a Map for the counts, a Vec of records to sort, however many words there are, and Sort with a two-level less.

+
Freq.raz
module Freq;
+import Fmt, Str, Heap,
+    Count := Map([]U8, INT, Str.hash, Str.eq),
+    Entries := Vec(Entry),
+    Rank := Sort(Entry, before);
+
+type Entry = record word: []U8; n: INT; end;
+
+const Text = "the cat and the hat and the bat sat on the mat and the cat sat";
+
+(* more first; equal counts alphabetically *)
+proc before(a, b: Entry): BOOL;
+begin
+    if a.n # b.n then return a.n > b.n; end;
+    return Str.cmp(a.word, b.word) < 0;
+end;
+
+proc main*;
+var
+    m: Count.Map; entries: Entries.Vec; i, k, found: INT;
+    w, rest: []U8; key: []U8; v: INT; all: []Entry;
+begin
+    Count.init(m, Heap.heap);
+    defer Count.done(m);
+    w, rest := Str.field(Text);
+    while LEN(w) > 0 do
+        k, _ := Count.get(m, w);
+        _ := Count.put(m, w, k + 1);
+        w, rest := Str.field(rest);
+    end;
+    Entries.init(entries, Heap.heap);
+    defer Entries.done(entries);
+    found, key, v := Count.next(m, 0);
+    while found >= 0 do
+        Entries.push(entries, {word: key, n: v});
+        found, key, v := Count.next(m, found);
+    end;
+    all := Entries.all(entries);
+    Rank.sort(all);
+    for i := 0 to LEN(all) - 1 do
+        Fmt.print("{} {}\n", [Fmt.int(all[i].n), Fmt.str(all[i].word)]);
+    end;
+end;
+
+end Freq.
+
5 the
+3 and
+2 cat
+2 sat
+1 bat
+1 hat
+1 mat
+1 on
+
+

The keys here are slices of the constant text, so they outlive the map; a program whose keys come from a buffer it will reuse copies them first with Str.copy, and gives each back with Str.free before Count.done gives back the map's own memory.

+

Choosing

+

Use a List when you push and pop at one end and walk it in order. Use a Vec when you add at the end and index, and don't know how many will come; an array when you do. Use a Map when you look things up by key. Use Sort on either's slice when you want an order. When none of them fits, they are each under a hundred lines of raz in lib/, and the advanced tour's allocator lesson shows what is underneath.

Save a program under its module’s name and run it with raz run Name.raz.

+
+ + + diff --git a/site/public/advanced/files.html b/site/public/advanced/files.html new file mode 100644 index 0000000..30d7ee3 --- /dev/null +++ b/site/public/advanced/files.html @@ -0,0 +1,277 @@ + + + + + +Files and the command line - More Raz + + + + + + + + + + + + +
+
+

The library · lesson 4 of 18

Files and the command line

+

Files is for the common case: a whole file read or written in one call. Sys is the system underneath, for everything else. Opt reads a command line from a table, so that the help and the error messages can't drift from the code.

+

A whole file

+

Files.write(path, data) makes the file hold data, and Files.read(path, b) adds the whole file to a Buf. Both say whether they worked.

+
Notes.raz
module Notes;
+import Out, Files, Buf, Heap;
+
+proc main*;
+var b: Buf.Buf; ok: BOOL;
+begin
+    ok := Files.write("notes.txt", "first line\nsecond line\n");
+    if not ok then Out.str("can't write\n"); return; end;
+    Buf.init(b, Heap.heap);
+    defer Buf.done(b);
+    ok := Files.read("notes.txt", b);
+    if ok then
+        Out.int(b.len); Out.str(" bytes: "); Out.str(Buf.bytes(b));
+    end;
+    ok := Files.read("missing.txt", b);
+    if not ok then Out.str("missing.txt: not there\n"); end;
+    if Files.load("missing.txt", b) = -2 then Out.str("missing.txt: ENOENT\n"); end;
+end;
+
+end Notes.
+
23 bytes: first line
+second line
+missing.txt: not there
+missing.txt: ENOENT
+
+

When the reason matters, Files.load says it: 0, or minus the errno of what failed, -2 (ENOENT) for no such file, -13 (EACCES) for one not allowed.

+

Descriptors

+

Underneath, a file is a descriptor, an INT. Sys.open takes the path and the way to open it as a set; read, write, seek and close do what they say. A result that can fail is a number, and minus an errno if it failed, as on Linux itself. Reading in a loop is the pattern for anything too big to hold at once.

+
Count.raz
module Count;
+import Out, Sys;
+
+(* the lines of the file at path, or minus an errno *)
+proc lines(path: []U8): INT;
+var fd, n, i, count: INT; buf: [4096]U8;
+begin
+    fd := Sys.openRead(path);
+    if fd < 0 then return fd; end;
+    defer Sys.close(fd);
+    n := Sys.read(fd, buf);
+    while n > 0 do
+        for i := 0 to n - 1 do
+            if buf[i] = '\n' then INC(count); end;
+        end;
+        n := Sys.read(fd, buf);
+    end;
+    if n < 0 then return n; end;
+    return count;
+end;
+
+proc main*;
+var fd: INT; pos: I64;
+begin
+    fd := Sys.create("log.txt");
+    _ := Sys.write(fd, "a\nb\nc\n");
+    pos := Sys.seek(fd, 2, false);              (* from the start *)
+    Out.int(pos); Out.ln;
+    Sys.close(fd);
+    Out.int(lines("log.txt")); Out.str(" lines\n");
+    Out.int(lines("/no/such/file")); Out.ln;     (* -2: ENOENT *)
+    fd := Sys.open("log.txt", {Sys.writing, Sys.appending});
+    _ := Sys.write(fd, "d\n");
+    Sys.close(fd);
+    Out.int(lines("log.txt")); Out.str(" lines now\n");
+end;
+
+end Count.
+
2
+3 lines
+-2
+4 lines now
+
+

Looking at a file, and a directory

+

Sys.info says a file's size, modification time, permissions, and whether it is a directory, a regular file or a link. Sys.openDir and nextEntry list a directory, in no particular order, so a program that prints one sorts it first. A name from nextEntry is good only until the next call, so the program keeps a copy.

+
Tree.raz
module Tree;
+import Out, Sys, Str, Heap, Mem, Buf, Order := Sort([]U8, before);
+
+proc before(a, b: []U8): BOOL;
+begin
+    return Str.cmp(a, b) < 0;
+end;
+
+(* a file made to hold text *)
+proc put(path, text: []U8);
+var fd: INT;
+begin
+    fd := Sys.create(path);
+    _ := Sys.write(fd, text);
+    Sys.close(fd);
+end;
+
+proc main*;
+var
+    d: Sys.Dir; name, copy: []U8; more, ok: BOOL; i, n: INT;
+    info: Sys.Info; err: INT; names: [16][]U8; path: Buf.Buf;
+begin
+    _ := Sys.makeDir("proj");
+    _ := Sys.makeDir("proj/src");
+    put("proj/b.txt", "bb");
+    put("proj/a.txt", "a");
+    if Sys.openDir(d, "proj") < 0 then return; end;
+    n := 0;
+    name, more := Sys.nextEntry(d);
+    while more do
+        copy, ok := Str.copy(Heap.heap, name);
+        if ok and (n < 16) then names[n] := copy; INC(n); end;
+        name, more := Sys.nextEntry(d);
+    end;
+    Sys.closeDir(d);
+    Order.sort(names[0..n]);
+    Buf.init(path, Heap.heap);
+    for i := 0 to n - 1 do
+        Buf.reset(path);
+        Buf.str(path, "proj/");
+        Buf.str(path, names[i]);
+        info, err := Sys.info(Buf.bytes(path));
+        Out.str(names[i]);
+        if err < 0 then Out.str(" ?");
+        elsif info.dir then Out.str("/");
+        else Out.str(", "); Out.int(info.size); Out.str(" bytes");
+        end;
+        Out.ln;
+        Mem.free(Heap.heap, ^U8(ADR(names[i][0])));
+    end;
+    Buf.done(path);
+end;
+
+end Tree.
+
a.txt, 1 bytes
+b.txt, 2 bytes
+src/
+
+

Modes, links, and a lock

+

Sys.openMode is open with the permissions a file it makes should have, less those the umask takes away: 1EDH (755) for a script, 124H (444) for a file never to be written. Sys.linkInfo looks at a symbolic link itself, where info follows it, so a link whose target is gone is still seen. Info.ino is the file's inode: a file renamed over another has a new one, though its size and time may match, which is how a program knows a file it cached is still the same.

+

Sys.lock takes the lock on an open file, which one open file holds at a time; another that asks for it waits, or with wait false gets -11 at once. The lock goes when the file is closed or the program ends, however it ends, so it can't go stale as a lock file can. Sys.syncAll puts everything written to a file system on the disk at once, before the one file that names it all is written: a database's or a version control system's commit.

+
Store.raz
module Store;
+import Fmt, Sys;
+
+proc main*;
+var fd, other: INT; named, target: Sys.Info;
+begin
+    fd := Sys.openMode("run.sh", {Sys.writing, Sys.creating, Sys.truncating}, 1EDH);
+    _ := Sys.write(fd, "echo hi\n");
+    _ := Sys.syncAll(fd);
+    Sys.close(fd);
+    target, _ := Sys.info("run.sh");
+    Fmt.print("its owner may run it: {}\n", [Fmt.bool(target.mode & 40H # 0)]);
+
+    _ := Sys.remove("current");
+    _ := Sys.symlink("run.sh", "current");
+    named, _ := Sys.linkInfo("current");
+    Fmt.print("a link: {}, of {} bytes\n", [Fmt.bool(named.symlink), Fmt.int(named.size)]);
+    named, _ := Sys.info("current");
+    Fmt.print("the same file: {}\n", [Fmt.bool(named.ino = target.ino)]);
+
+    fd := Sys.openRead("run.sh");
+    other := Sys.openRead("run.sh");
+    Fmt.print("{} {}\n", [Fmt.int(Sys.lock(fd, false)), Fmt.int(Sys.lock(other, false))]);   (* -11: held *)
+    Sys.close(fd);
+    Fmt.print("{}\n", [Fmt.int(Sys.lock(other, false))]);   (* free again *)
+    Sys.close(other);
+end;
+
+end Store.
+
its owner may run it: true
+a link: true, of 6 bytes
+the same file: true
+0 -11
+0
+
+

A command line, from a table

+

A program describes its options once, in a table of Opt.Rows: its synopsis lines, its subcommands and its options. The help and the error messages are made from the table. The parser reads by the rules of the C library's getopt with GNU's long options, so -vn3, -n 3, --count=3 and --count 3 all work, and -- ends the options.

+
Tool.raz
module Tool;
+import Out, Fmt, Opt;
+
+const count = 1;                   (* the key of --count, which has no letter *)
+
+proc main*;
+var p: Opt.Parser; verbose: BOOL; n, i: INT; w: []U8; ok: BOOL;
+begin
+    n := 1;
+    Opt.init(p, "tool", [
+        Opt.usage("", "tool [-v] [--count n] word ..."),
+        Opt.option("", 'v', "verbose", "", "say more"),
+        Opt.option("", count, "count", "n", "repeat each word n times")]);
+    while Opt.next(p) do
+        if p.letter = 'v' then verbose := true;
+        elsif p.letter = count then n := INT(Opt.number(p, 1, 5));
+        end;
+    end;
+    w, ok := Opt.operand(p);
+    if not ok then Opt.fail(p, "no words; see tool -h"); end;
+    while ok do
+        for i := 1 to n do
+            if verbose then Out.str("word: "); end;
+            Fmt.print("{}\n", [Fmt.str(w)]);
+        end;
+        w, ok := Opt.operand(p);
+    end;
+end;
+
+end Tool.
+
$ raz Tool.raz
+$ ./Tool -h
+usage: tool [-v] [--count n] word ...
+
+  -v, --verbose   say more
+      --count n   repeat each word n times
+  -h, --help      print this and exit
+$ ./Tool -v hello world
+word: hello
+word: world
+$ ./Tool --count 9 hello; echo "status $?"
+tool: --count wants a number from 1 to 5, not '9'
+usage: tool [-v] [--count n] word ...
+status 2
+$ ./Tool -x; echo "status $?"
+tool: unknown option -x
+usage: tool [-v] [--count n] word ...
+status 2
+$ ./Tool; echo "status $?"
+tool: no words; see tool -h
+status 2
+

-h and --help are Opt's: the program never sees them. A mistake on the command line is a sentence on standard error with the program's name first, then the synopsis, and status 2. Nothing in Tool wrote any of that.

+

A mistake in the table itself, such as an option given twice, is the program's, and init says so and ends with status 1 before it reads a word.

Save a program under its module’s name and run it with raz run Name.raz.

+
+ + + diff --git a/site/public/advanced/fmt.html b/site/public/advanced/fmt.html new file mode 100644 index 0000000..fbe8d1b --- /dev/null +++ b/site/public/advanced/fmt.html @@ -0,0 +1,198 @@ + + + + + +Output and formatting - More Raz + + + + + + + + + + + + +
+
+

The library · lesson 1 of 18

Output and formatting

+

The first tour used Out for everything it printed. Two modules do the work: Out, which owns standard output and its buffer, and Fmt, which turns values into text.

+

What Out does with its buffer

+

Out keeps a buffer of 4 KB. It writes it out when it is full, at each line feed when standard output is a terminal, at Out.flush, and when the program ends by Rt.exit (which a normal end and a failed check both are). A lock keeps what each call writes together when threads write at once.

+

You can see the effect with strace, which lists the system calls a program makes. A program that prints three lines to a file makes one write:

+
Three.raz
module Three;
+import Out;
+
+proc main*;
+begin
+    Out.str("one\n");
+    Out.str("two\n");
+    Out.str("three\n");
+end;
+
+end Three.
+
$ raz Three.raz
+$ strace -e trace=write ./Three > /dev/null
+write(1, "one\ntwo\nthree\n", 14)       = 14
++++ exited with 0 +++
+

Three lines, one system call. That is why Out is cheap, and why a program that mixes it with C's printf, which keeps a buffer of its own, must flush one before the other.

+

Fmt.print

+

Fmt.print(format, args) writes to standard output. Each {} in the format takes the next argument, and {{ and }} stand for the braces. The arguments are a slice of Fmt.Arg, a variant, so each is built with the constructor for its kind: int, uint, hex, str, char, bool and real, which takes the number of digits after the point.

+
Kinds.raz
module Kinds;
+import Fmt;
+
+proc main*;
+var big: U64; small: I8;
+begin
+    big := 0FFFFFFFFFFFFFFFFH;
+    small := -5;
+    Fmt.print("int {}, uint {}, hex {}\n",
+        [Fmt.int(-42), Fmt.uint(big), Fmt.hex(255)]);
+    Fmt.print("str {}, char {}, bool {}\n",
+        [Fmt.str("hi"), Fmt.char('x'), Fmt.bool(1 < 2)]);
+    Fmt.print("real {} and {} and {}\n",
+        [Fmt.real(3.14159, 2), Fmt.real(2.5, 0), Fmt.real(1.0 / 3.0, 9)]);
+    Fmt.print("an I8: {}; braces: {{ and }}\n", [Fmt.int(I64(small))]);
+end;
+
+end Kinds.
+
int -42, uint 18446744073709551615, hex FF
+str hi, char x, bool true
+real 3.14 and 3 and 0.333333333
+an I8: -5; braces: { and }
+
+

An argument whose type is wrong doesn't compile: there is no %d that disagrees with its argument. A {} with no argument left prints nothing, and arguments left over are not printed, so a mismatch shows up as missing text, never as a crash or as memory read by mistake.

+

Into a buffer

+

Fmt.write(b, format, args) does the same into a Buf instead of standard output. That is how a message is built to send somewhere else: a file, a socket, a window, a string kept for later.

+
Message.raz
module Message;
+import Out, Buf, Fmt, Heap;
+
+(* "name (age n)", built in a Buf the caller owns *)
+proc describe(var b: Buf.Buf; name: []U8; age: INT);
+begin
+    Fmt.write(b, "{} (age {})", [Fmt.str(name), Fmt.int(age)]);
+end;
+
+proc main*;
+var b: Buf.Buf;
+begin
+    Buf.init(b, Heap.heap);
+    defer Buf.done(b);
+    describe(b, "Ada", 36);
+    Buf.str(b, "; ");
+    describe(b, "Grace", 45);
+    Out.str(Buf.bytes(b)); Out.ln;
+    Out.int(b.len); Out.str(" bytes\n");
+end;
+
+end Message.
+
Ada (age 36); Grace (age 45)
+28 bytes
+
+

Columns

+

Fmt writes values as they are, with no widths. A program that wants columns pads in one small procedure and uses it everywhere, which is easier to read than a format language.

+
Table.raz
module Table;
+import Out;
+
+(* s, then spaces up to width *)
+proc left(s: []U8; width: INT);
+var i: INT;
+begin
+    Out.str(s);
+    for i := LEN(s) to width - 1 do Out.char(' '); end;
+end;
+
+(* n, right aligned in width *)
+proc right(n: INT; width: INT);
+var digits: INT; v: INT; i: INT;
+begin
+    digits := 1;
+    v := n;
+    if v < 0 then INC(digits); v := -v; end;
+    while v >= 10 do INC(digits); v := v div 10; end;
+    for i := digits to width - 1 do Out.char(' '); end;
+    Out.int(n);
+end;
+
+proc row(name: []U8; qty, price: INT);
+begin
+    left(name, 10);
+    right(qty, 5);
+    right(price, 8);
+    right(qty * price, 9);
+    Out.ln;
+end;
+
+proc main*;
+begin
+    Out.str("item        qty   price    total\n");
+    row("bolts", 120, 3);
+    row("washers", 1000, 1);
+    row("gears", 8, 250);
+    row("shims", 12, -4);
+end;
+
+end Table.
+
item        qty   price    total
+bolts       120       3      360
+washers    1000       1     1000
+gears         8     250     2000
+shims        12      -4      -48
+
+

Writing numbers in other bases

+

Out.hex(n, digits) writes n in hexadecimal, padded with zeros to digits. A binary dump is a for loop over a slice, one Out.hex(U64(b), 2) to a byte.

+
Dump.raz
module Dump;
+import Out;
+
+proc dump(data: []U8);
+var i: INT;
+begin
+    for i := 0 to LEN(data) - 1 do
+        if i > 0 then Out.char(' '); end;
+        Out.hex(U64(data[i]), 2);
+    end;
+    Out.ln;
+end;
+
+proc main*;
+begin
+    dump("raz\n");
+    dump("\u{3BB}");
+end;
+
+end Dump.
+
72 61 7A 0A
+CE BB
+

Save a program under its module’s name and run it with raz run Name.raz.

+
+ + + diff --git a/site/public/advanced/index.html b/site/public/advanced/index.html new file mode 100644 index 0000000..956f9e8 --- /dev/null +++ b/site/public/advanced/index.html @@ -0,0 +1,60 @@ + + + + + +More Raz + + + + + + + + + + + + +
+
+

More Raz

+

The second tour, for the part of raz that sits close to the machine. It +assumes you have taken Raz, Set, Go or know +Pascal or C well enough not to need it.

+

It has four parts: The library, the modules every program +reaches for; Standing alone, programs that need no C and no +run time; The machine, procedures written in assembly and +direct system calls; and Shared memory, volatile accesses, +atomics and threads. Every program is compiled and run when this page is +made, as before.

+

The library

    +
  1. Output and formatting Out's buffer, Fmt's arguments, formatting into a Buf, and laying out columns.
  2. +
  3. Strings and bytes Copying, hashing and ordering strings, searching bytes many at a time, and reading and writing binary formats.
  4. +
  5. Lists, arrays, maps and sorting List(T), Vec(T), Map(K, V) and Sort(T), put together in a word-frequency program.
  6. +
  7. Files and the command line Whole files with Files, descriptors and directories with Sys, and options with Opt.
  8. +
  9. Time, randomness and other programs Clocks, sleeping, random bytes, running a program with its output piped back, and signals.
  10. +
  11. Writing an allocator Mem.Allocator is two procedures; make one over a fixed array, and one that counts.
  12. +
+

Standing alone

    +
  1. A program with no run time What is in an executable, what isn't, and how to see it.
  2. +
  3. Threads without C, and keeping the two apart link static, what a module that makes its own system calls promises, and the error when it breaks.
  4. +
  5. Starting, ending, and signals What runs before main, what runs after, and how to wait for a signal.
  6. +
  7. One module, one file per target Portable programs, the code that isn't, and how the compiler keeps them in step.
  8. +
+

The machine

    +
  1. Procedures in assembly code procedures: the convention, registers, labels, db for what the assembler doesn't know.
  2. +
  3. System calls SYSCALL directly: the numbers, the arguments, negative errno, and a cat without a library.
  4. +
  5. What the compiler makes raz -S, reading a listing, what a check costs and what check off removes.
  6. +
+

Shared memory

    +
  1. Volatile ^VOLATILE T: memory that something else may change, laid over with a record.
  2. +
  3. Atomics XADD, XCHG and CAS; a compare-and-swap loop; a lock built from them.
  4. +
  5. Ordering and publication Why a flag isn't enough, what FENCE and the atomics order, and the pattern that works.
  6. +
  7. A lock-free stack CAS on pointers, a push loop that never blocks, and the ABA problem that makes pop harder.
  8. +
  9. A ring buffer between threads A single-producer, single-consumer queue, put together from what the tour has covered.
  10. +
+
+ + + diff --git a/site/public/advanced/lifecycle.html b/site/public/advanced/lifecycle.html new file mode 100644 index 0000000..1521f54 --- /dev/null +++ b/site/public/advanced/lifecycle.html @@ -0,0 +1,164 @@ + + + + + +Starting, ending, and signals - More Raz + + + + + + + + + + + + +
+
+

Standing alone · lesson 9 of 18

Starting, ending, and signals

+

With no run time, the life of a program is short enough to say in a few lines. What happens, in order:

+

1. The entry code sets up a stack for signal handlers and installs the handlers for SIGSEGV and SIGFPE. A program that uses C starts through C instead, so that C's own set-up runs. 2. The bodies of the modules run, each once, imported modules first. 3. The main module's main runs. 4. Rt.exit runs the procedures registered with Rt.atExit, the last registered first, and ends the program with main's status.

+

Bodies, then main

+

The first tour showed bodies running before main. They are the place to set a module up, and they can end early with return;.

+
Order.raz
module Order;
+import Out;
+
+var steps*: INT;
+
+proc note(what: []U8);
+begin
+    INC(steps);
+    Out.int(steps); Out.str(". "); Out.str(what); Out.ln;
+end;
+
+begin
+    note("the body runs before main");
+    if steps > 5 then return; end;
+    note("and carries on if it isn't ended early");
+end Order.
+
1. the body runs before main
+2. and carries on if it isn't ended early
+
+

That file is a module with a body and no main: it can be imported, or its body run as a program. Add the main and see both:

+
Both.raz
module Both;
+import Out, Order;
+
+proc main*;
+begin
+    Out.str("main: "); Out.int(Order.steps); Out.str(" steps happened first\n");
+end;
+
+end Both.
+
1. the body runs before main
+2. and carries on if it isn't ended early
+main: 2 steps happened first
+
+

Things to do at the end

+

Rt.atExit(p) registers a procedure with no parameters to run when the program ends by Rt.exit: at the end of main, by a call to Rt.exit, or by a failed check, after its message. It is where a program restores a terminal or removes a lock file. At most 32 are registered, and each runs at most once. Out's buffer is flushed this way, which is why a program that ends in a failure still shows what it printed.

+
Cleanup.raz
module Cleanup;
+import Out, Rt;
+
+proc first;
+begin
+    Out.str("registered first, runs last\n");
+end;
+
+proc second;
+begin
+    Out.str("registered second, runs first\n");
+end;
+
+proc main*;
+begin
+    _ := Rt.atExit(first);
+    _ := Rt.atExit(second);
+    Out.str("main is done\n");
+end;
+
+end Cleanup.
+
main is done
+registered second, runs first
+registered first, runs last
+
+

Two ways to leave in a hurry

+

Rt.exit(status) ends the program after the atExit procedures. Sys.exit(status) ends it at once, without them. A failed check and Rt.exit also skip the defer statements still pending in the calls under way. Sys.exit is for a child process that must not run what it inherited, and for nothing else.

+
Hurry.raz
module Hurry;
+import Out, Rt, Sys;
+
+proc bye;
+begin
+    Out.str("atExit ran\n");
+end;
+
+proc main*;
+begin
+    _ := Rt.atExit(bye);
+    defer Out.str("a deferred statement ran\n");
+    Out.str("leaving\n");
+    Out.flush;
+    Sys.exit(3);
+end;
+
+end Hurry.
+
$ raz Hurry.raz
+$ ./Hurry; echo "status $?"
+leaving
+status 3
+

Neither the deferred statement nor bye ran. That's the rule, and the reason to keep cleanup that matters (a terminal, a lock file) in atExit and use Rt.exit for ending.

+

Signals

+

A program is stopped by a signal it doesn't catch, with a message that names the place for SIGSEGV and SIGFPE, and without one for the others, and ends with status 2. A program that wants to handle one, say SIGTERM for a clean shutdown, doesn't write a handler that runs at an arbitrary moment. It asks for the signals to arrive as data: Sys.catch takes a list of signals and gives a descriptor that is ready to read when one comes, and Sys.caught says which. So the program waits for signals the way it waits for input.

+
Terms.raz
module Terms;
+import Out, Sys;
+
+proc main*;
+var fd, sig: INT;
+begin
+    fd := Sys.catch([Sys.sigTerm, Sys.sigWinch]);
+    Out.str("asking myself to stop\n");
+    _ := Sys.kill(Sys.pid(), Sys.sigTerm);
+    if Sys.ready(fd, 1000) then
+        sig := Sys.caught(fd);
+        if sig = Sys.sigTerm then Out.str("caught SIGTERM, stopping cleanly\n"); end;
+    end;
+    sig := Sys.caught(fd);
+    Out.int(sig); Out.str(" waiting after that\n");     (* 0: none *)
+end;
+
+end Terms.
+
asking myself to stop
+caught SIGTERM, stopping cleanly
+0 waiting after that
+
+

Sys.ready(fd, ms) waits up to ms milliseconds for something to read; with Sys.readyOf it waits on several descriptors, so one loop serves a socket, a terminal and a stop signal together. Sys.ignore(sig, true) makes a signal do nothing, as a shell ignores SIGTTOU.

Save a program under its module’s name and run it with raz run Name.raz.

+
+ + + diff --git a/site/public/advanced/linkstatic.html b/site/public/advanced/linkstatic.html new file mode 100644 index 0000000..0d7305e --- /dev/null +++ b/site/public/advanced/linkstatic.html @@ -0,0 +1,122 @@ + + + + + +Threads without C, and keeping the two apart - More Raz + + + + + + + + + + + + +
+
+

Standing alone · lesson 8 of 18

Threads without C, and keeping the two apart

+

A program without C can do things a program with C can't. The most useful is to make threads of its own: C's thread functions rely on C's own set-up, which a program that never started C has not done. Thread creates threads directly with the clone system call and gives each a stack of its own.

+

A module like that says so, with link static; after its imports. It means: "I make my own system calls or my own threads, which the C library wouldn't know about; a program that includes me must not use C." static isn't a reserved word; it is only meaningful after link.

+

What Thread does

+

Thread is a module of raz, in the library, that says link static; and makes the clone, mmap and futex system calls itself. Here is its beginning, printed from the library:

+
$ sed -n '1,22p' $RAZLIB/Thread.linux-x86_64.raz
+(* Threads, made with the clone system call in a program without C.
+   Each runs on a stack of its own, mmaped, with a page below it that
+   can't be touched, so that running off the stack stops the program
+   rather than spoiling what lies below; above it, a little stack for
+   Rt's signal handlers, so that they can say so. join waits on the
+   thread's id, which the kernel clears, and wakes it for, when the
+   thread ends; a Mutex sleeps on a futex.
+
+   A program that uses C makes them with C's pthread_create instead,
+   since C keeps things of each thread's own, errno and its buffers,
+   that a thread clone makes wouldn't have. The compiler's entry point
+   finds cCreate and cJoin by name and stores C's calls in them, as it
+   stores C's exit in Rt.cExit; so this module uses no C itself, and
+   serves both kinds of program. C's thread has a stack and a guard
+   page of C's; the mapping here holds only the handlers' stack and
+   the Thread. Its test uses Check. *)
+module Thread;
+import Sys, Rt, Check;
+
+const
+    Failed*: ERROR = "can't start a thread";
+    Stack = 1 shl 20;
+

A program that imports it is therefore a static executable, and every thread it spawns is a Linux thread with a stack of its own, mapped with a page below it that can't be touched, so that running off the stack ends the program with a message and not with corruption.

+
Hello.raz
module Hello;
+import Out, Thread;
+
+var done: INT;
+
+proc greet(arg: ^U8);
+begin
+    Out.str("hello from thread "); Out.int(INT(arg)); Out.ln;
+    _ := XADD(ADR(done), 1);
+end;
+
+proc main*;
+var t: ^Thread.Thread; err: ERROR;
+begin
+    t, err := Thread.spawn(greet, ^U8(7));
+    if err # nil then Out.str(MSG(err)); Out.ln; return; end;
+    Thread.join(t);
+    Out.str("joined; done = "); Out.int(done); Out.ln;
+end;
+
+end Hello.
+
$ raz Hello.raz
+$ ./Hello
+hello from thread 7
+joined; done = 1
+$ file Hello | sed 's/,.*statically/, statically/'
+Hello: ELF 64-bit LSB executable, statically linked, with debug_info, not stripped
+

When you mix them

+

C's pthread_create and Thread can't share a process, and the compiler won't let you try. A program that imports a module that says link static; and another that uses C is an error, and the error names both:

+
Mixed.raz
module Mixed;
+import Out, Thread, C;
+
+proc main*;
+begin
+    Out.str(MSG(Thread.Failed)); Out.ln;
+    _ := C.printf("%d\n", I32(1));
+    Out.str("and Out\n");
+end;
+
+end Mixed.
+
$ raz Mixed.raz
+

Which one you want depends on what the program is for. A program that calls a C library (a window system, a database client) uses C's threads, C.pthread_create, because the library may assume them. A program that talks only to the kernel uses Thread, and is a static executable.

+

The same promise for your own modules

+

The rule isn't special to Thread. A module of yours that makes SYSCALLs directly, or relies on being the only owner of signal handlers, or sets up its own stacks, says link static; too, and then the compiler keeps C away from it for you. The module is documenting a fact about itself, and the compiler checks it where the program is assembled.

Save a program under its module’s name and run it with raz run Name.raz.

+
+ + + diff --git a/site/public/advanced/listing.html b/site/public/advanced/listing.html new file mode 100644 index 0000000..3f64dbb --- /dev/null +++ b/site/public/advanced/listing.html @@ -0,0 +1,264 @@ + + + + + +What the compiler makes - More Raz + + + + + + + + + + + + +
+
+

The machine · lesson 13 of 18

What the compiler makes

+

The compiler has no optimizer and no intermediate form. It reads the source once and writes x86-64 machine code as it goes, so the code is what the source says, in the order it says it. That makes the output readable, and there is a switch for reading it: raz -S Main.raz prints the main module's code instead of writing it, each line of source and under it the instructions made for it, at their offsets in the procedure.

+

A small procedure

+
Add.raz
module Add;
+
+proc add*(a, b: INT): INT;
+begin
+    return a + b;
+end;
+
+proc main*;
+begin
+    _ := add(1, 2);
+end;
+
+end Add.
+
$ raz -S Add.raz
+
+Add.main:
+     8  proc main*;
+             0  push rbp
+             1  mov rbp, rsp
+             4  sub rsp, 16
+    10      _ := add(1, 2);
+            11  mov qword [rbp - 8], 2
+            19  mov qword [rbp - 16], 1
+            27  mov r8, [rbp - 16]
+            31  add r8, [rbp - 8]
+    11  end;
+            35  leave
+            36  ret
+

Every procedure starts by saving the caller's frame pointer and making its own (push rbp; mov rbp, rsp) and reserves room for what it needs. The arguments arrive in rdi and rsi, as the convention says, and the result leaves in rax. A call is mov rdi, 1; mov rsi, 2; call Add.add. Nothing is hidden: the frame pointer chain is what lets a failure show the calls under way with their variables.

+

A loop with its checks

+

This is the dot product of two slices. A slice is a pointer and a length, and it travels in two registers:

+
Dot.raz
module Dot;
+
+(* the dot product of two slices of equal length *)
+proc dot*(a, b: []INT): INT;
+var i, sum: INT;
+begin
+    for i := 0 to LEN(a) - 1 do
+        sum := sum + a[i] * b[i];
+    end;
+    return sum;
+end;
+
+proc main*;
+var x, y: [3]INT;
+begin
+    x := [1, 2, 3];
+    y := [4, 5, 6];
+    _ := dot(x, y);
+end;
+
+end Dot.
+
$ raz -S Dot.raz | sed -n '/^Dot.dot:/,/^$/p'
+Dot.dot:
+     4  proc dot*(a, b: []INT): INT;
+             0  push rbp
+             1  mov rbp, rsp
+             4  sub rsp, 64
+            11  mov [rbp - 56], rbx
+            15  xor ebx, ebx
+            17  mov [rbp - 48], r12
+            21  xor r12d, r12d
+            24  mov [rbp - 40], r13
+            28  xor r13d, r13d
+            31  mov [rbp - 32], rdx
+            35  mov [rbp - 24], rcx
+     7      for i := 0 to LEN(a) - 1 do
+            39  xor ebx, ebx
+            41  mov r8, rsi
+            44  lea r8, [r8 - 1]
+            48  mov r13, r8
+            51  cmp rbx, r13
+            54  jg 175
+            60  jmp 100
+            65  nop
+            73  nop
+            81  nop
+            89  nop
+            96  add rbx, 1
+     8          sum := sum + a[i] * b[i];
+           100  cmp rbx, rsi
+           103  jae 192
+           109  mov r10, rbx
+           112  cmp r10, [rbp - 24]
+           116  jae 203
+           122  shl r10, 3
+           126  add r10, [rbp - 32]
+           130  mov r10, [r10]
+           133  mov r9, [rdi + rbx * 8]
+           137  imul r9, r10
+           141  add r12, r9
+           144  cmp rbx, r13
+           147  jl 96
+           153  cmp rbx, r13
+           156  je 175
+           162  add rbx, 1
+           166  cmp rbx, r13
+           169  jle 100
+    10      return sum;
+           175  mov rax, r12
+    11  end;
+           178  mov rbx, [rbp - 56]
+           182  mov r12, [rbp - 48]
+           186  mov r13, [rbp - 40]
+           190  leave
+           191  ret
+     8          sum := sum + a[i] * b[i];
+           192  mov rax, rbx
+           195  mov rcx, rsi
+           198  call Rt.check0
+           203  mov rax, r10
+           206  mov rcx, [rbp - 24]
+           210  call Rt.check0
+

Read it from the top. a arrives in rdi and rsi, pointer and length; b in rdx and rcx, which the procedure saves in its frame. i and sum live in rbx and r12, which the procedure saves and restores because the convention says they belong to the caller. The loop's test is at the bottom, and its limit, LEN(a) - 1, is taken once.

+

In the body, each index has a check: cmp rbx, rsi; jae compares i with a's length in a single instruction and jumps to a stub at the end of the procedure, which calls Rt.check0 with the values it needs to say what failed. When the index is in range, which is nearly always, the cost is one compare and a branch that isn't taken.

+

Taking the checks out

+

check off; after the imports leaves out the module's own checks of indexes and slice bounds. Here is the same procedure with it:

+
Dot2.raz
module Dot2;
+check off;
+
+proc dot*(a, b: []INT): INT;
+var i, sum: INT;
+begin
+    for i := 0 to LEN(a) - 1 do
+        sum := sum + a[i] * b[i];
+    end;
+    return sum;
+end;
+
+proc main*;
+var x, y: [3]INT;
+begin
+    x := [1, 2, 3];
+    y := [4, 5, 6];
+    _ := dot(x, y);
+end;
+
+end Dot2.
+
$ raz -S Dot2.raz | sed -n '/^Dot2.dot:/,/^$/p'
+Dot2.dot:
+     4  proc dot*(a, b: []INT): INT;
+             0  push rbp
+             1  mov rbp, rsp
+             4  sub rsp, 64
+            11  mov [rbp - 56], rbx
+            15  xor ebx, ebx
+            17  mov [rbp - 48], r12
+            21  xor r12d, r12d
+            24  mov [rbp - 40], r13
+            28  xor r13d, r13d
+            31  mov [rbp - 32], rdx
+            35  mov [rbp - 24], rcx
+     7      for i := 0 to LEN(a) - 1 do
+            39  xor ebx, ebx
+            41  mov r8, rsi
+            44  lea r8, [r8 - 1]
+            48  mov r13, r8
+            51  cmp rbx, r13
+            54  jg 156
+            60  jmp 100
+            65  nop
+            73  nop
+            81  nop
+            89  nop
+            96  add rbx, 1
+     8          sum := sum + a[i] * b[i];
+           100  mov r10, rbx
+           103  shl r10, 3
+           107  add r10, [rbp - 32]
+           111  mov r10, [r10]
+           114  mov r9, [rdi + rbx * 8]
+           118  imul r9, r10
+           122  add r12, r9
+           125  cmp rbx, r13
+           128  jl 96
+           134  cmp rbx, r13
+           137  je 156
+           143  add rbx, 1
+           147  cmp rbx, r13
+           150  jle 100
+    10      return sum;
+           156  mov rax, r12
+    11  end;
+           159  mov rbx, [rbp - 56]
+           163  mov r12, [rbp - 48]
+           167  mov r13, [rbp - 40]
+           171  leave
+           172  ret
+$ raz -S Dot.raz | sed -n '/^Dot.dot:/,/^$/p' | wc -l
+61
+$ raz -S Dot2.raz | sed -n '/^Dot2.dot:/,/^$/p' | wc -l
+50
+

The compares, the branches and the stubs are gone. It is faster, and it is no longer safe: an index out of range reads or writes whatever memory it reaches, and what follows isn't defined. A program turns checks off where it has measured and is sure, and says so at the top of the module, where a reader can see it.

+

Comparing with C

+

make kernels in the compiler's sources measures test/bench's kernels against the same kernels written in Pascal and compiled by Free Pascal at -O2. The compiler's own guide, doc/compiler.md, gives the numbers and says what the compiler does and doesn't do. It is not the fastest code: it is code whose every instruction you can account for.

+

Tools that read what it made

+
  • gdb finds procedures by name and lines by number, since the executable carries them: break Dot.dot and list work, and so does stepping a line at a time.
  • RAZ_PROFILE=1 samples the program every millisecond and says which procedures and lines took the time.
  • objdump -d disassembles what is really in the file, if you want to see the bytes behind a listing.
+
$ raz -o Dot Dot.raz
+$ objdump -d -M intel --no-show-raw-insn Dot | sed -n '/<Dot.dot>:/,/ret/p' | head -12
+0000000000403c60 <Dot.dot>:
+  403c60:	push   rbp
+  403c61:	mov    rbp,rsp
+  403c64:	sub    rsp,0x40
+  403c6b:	mov    QWORD PTR [rbp-0x38],rbx
+  403c6f:	xor    ebx,ebx
+  403c71:	mov    QWORD PTR [rbp-0x30],r12
+  403c75:	xor    r12d,r12d
+  403c78:	mov    QWORD PTR [rbp-0x28],r13
+  403c7c:	xor    r13d,r13d
+  403c7f:	mov    QWORD PTR [rbp-0x20],rdx
+  403c83:	mov    QWORD PTR [rbp-0x18],rcx
+

The listing is what the encoder meant; objdump is what the processor will read. They tell the same story.

Save a program under its module’s name and run it with raz run Name.raz.

+
+ + + diff --git a/site/public/advanced/lockfree.html b/site/public/advanced/lockfree.html new file mode 100644 index 0000000..6ffff59 --- /dev/null +++ b/site/public/advanced/lockfree.html @@ -0,0 +1,167 @@ + + + + + +A lock-free stack - More Raz + + + + + + + + + + + + +
+
+

Shared memory · lesson 17 of 18

A lock-free stack

+

CAS works on pointers as well as integers, and a pointer is how a bigger thing is swapped in atomically: build the new structure privately, then make it visible by changing one word. The classic example is a stack as a linked list whose head is that word.

+

Push

+

To push a node: point its next at the current head, then CAS the head from what you saw to the new node. If another thread pushed first, the CAS fails, because the head is no longer what you saw, so look again and retry. No thread ever waits for another, and none can stop the others by being slow.

+
Treiber.raz
module Treiber;
+import Out, Thread;
+
+type Node = record next: ^Node; val: INT; end;
+
+const Threads = 4; Each = 5000;
+
+var
+    top: ^Node;                          (* the head, changed only by CAS *)
+    nodes: [Threads * Each]Node;         (* every node a thread will push *)
+
+(* n onto the stack, without a lock *)
+proc push(n: ^Node);
+var old: ^Node;
+begin
+    old := top;
+    n^.next := old;
+    while not CAS(ADR(top), old, n) do
+        old := top;                      (* lost the race: look again *)
+        n^.next := old;
+    end;
+end;
+
+proc work(arg: ^U8);
+var first, i: INT;
+begin
+    first := INT(arg) * Each;
+    for i := 0 to Each - 1 do
+        nodes[first + i].val := first + i;
+        push(ADR(nodes[first + i]));
+    end;
+end;
+
+proc main*;
+var th: [Threads]^Thread.Thread; i, count, sum: INT; err: ERROR; n: ^Node;
+begin
+    for i := 0 to Threads - 1 do
+        th[i], err := Thread.spawn(work, ^U8(i));
+        if err # nil then Out.str(MSG(err)); Out.ln; return; end;
+    end;
+    for i := 0 to Threads - 1 do Thread.join(th[i]); end;
+    n := top;
+    while n # nil do
+        INC(count);
+        sum := sum + n^.val;
+        n := n^.next;
+    end;
+    Out.int(count); Out.char(' '); Out.int(sum); Out.ln;
+    Out.int(Threads * Each * (Threads * Each - 1) div 2); Out.ln;
+end;
+
+end Treiber.
+
20000 199990000
+199990000
+
+

Twenty thousand nodes pushed by four threads at once; every one is on the stack exactly once, and the sum of their values is the sum of 0 to 19999. Nothing was lost, and there is no lock anywhere in the program.

+

The loop in push is the shape of every lock-free algorithm: read, compute, CAS, and read again on failure. The CAS is sequentially consistent, so the node's val and next, written before it with ordinary stores, are visible to a thread that finds the node through top.

+

Pop, and the ABA problem

+

Pop takes the head off: read top, read its next, CAS the head from top to next. It looks as easy as push, and it isn't. Between the two reads and the CAS, other threads may pop that node, pop others, and push the same node back, now with a different next. The head is the same pointer again, so the CAS succeeds, and installs a next that is stale: nodes disappear, or the stack points into freed memory. This is the ABA problem: the word changed from A to B and back to A, and the CAS can't tell.

+

There are three common ways out, and each has a cost:

+
  • Never reuse a node while anyone might hold it. Nodes from an arena that is reset only when all threads are done, as the nodes above come from a fixed array, can't come back as a different node.
  • Add a counter to the head, so that A-B-A is A1-B2-A3. That is a word and a counter swapped together, and raz's CAS is for one word, so a program packs a small index and a counter into one UINT.
  • Don't pop concurrently. Many threads push and one thread, at the end, takes everything with a single XCHG(ADR(top), nil) and walks the list in peace. A stack used this way for work lists and logs needs no more.
+
Drain.raz
module Drain;
+import Out, Thread;
+
+type Node = record next: ^Node; val: INT; end;
+
+const Threads = 3; Each = 1000;
+
+var
+    top: ^Node;
+    nodes: [Threads * Each]Node;
+
+proc push(n: ^Node);
+var old: ^Node;
+begin
+    old := top;
+    n^.next := old;
+    while not CAS(ADR(top), old, n) do
+        old := top;
+        n^.next := old;
+    end;
+end;
+
+proc work(arg: ^U8);
+var first, i: INT;
+begin
+    first := INT(arg) * Each;
+    for i := 0 to Each - 1 do
+        nodes[first + i].val := 1;
+        push(ADR(nodes[first + i]));
+    end;
+end;
+
+proc main*;
+var th: [Threads]^Thread.Thread; i, count: INT; err: ERROR; all, n: ^Node;
+begin
+    for i := 0 to Threads - 1 do
+        th[i], err := Thread.spawn(work, ^U8(i));
+        if err # nil then Out.str(MSG(err)); Out.ln; return; end;
+    end;
+    for i := 0 to Threads - 1 do Thread.join(th[i]); end;
+    all := XCHG(ADR(top), nil);          (* take the whole stack, atomically *)
+    n := all;
+    while n # nil do INC(count); n := n^.next; end;
+    Out.int(count); Out.str(" taken at once, "); 
+    if top = nil then Out.str("none left\n"); end;
+end;
+
+end Drain.
+
3000 taken at once, none left
+
+

The atomic exchange takes everything pushed so far in one step, so the walk that follows races with nobody.

+

When to use it

+

A lock-free structure is worth it when a lock would be held by a thread that can be descheduled, when the critical section is a single pointer, or when a signal handler or an interrupt must share data with the code it interrupts. Everywhere else a Mutex is shorter, easier to check, and fast enough. The advantage of knowing how to write the other kind is that you understand what the lock is doing for you.

Save a program under its module’s name and run it with raz run Name.raz.

+
+ + + diff --git a/site/public/advanced/ordering.html b/site/public/advanced/ordering.html new file mode 100644 index 0000000..f0738cd --- /dev/null +++ b/site/public/advanced/ordering.html @@ -0,0 +1,131 @@ + + + + + +Ordering and publication - More Raz + + + + + + + + + + + + +
+
+

Shared memory · lesson 16 of 18

Ordering and publication

+

Atomics make one word safe. The harder question is about the *other* words: if one thread writes a value and then raises a flag, can another thread that sees the flag be sure it sees the value?

+

The report is careful. Only volatile accesses, CAS, XCHG, XADD and FENCE are exact. Any other access is ordinary: an implementation may keep a variable in a register, leave out a write that nothing reads, and change the order of ordinary accesses, as long as each thread, on its own, does what the report says. A variable that one thread writes while another reads or writes it, unless both use volatile accesses or the atomic built-ins, or a FENCE orders them, holds no particular value then: a read of it gives a value it had or was given, or a mixture of their bytes. Nothing else of the program becomes undefined by it.

+

In plain words: two threads that share an ordinary variable with no atomic, volatile or fence between them get no guarantee about what each sees.

+

The pattern that is guaranteed: publish through an atomic

+

The simplest correct way to hand a value to another thread: write it with ordinary stores, then store a flag with an atomic. The reader loops on the flag with an atomic read, and then reads the data. XCHG is the store; XADD(p, 0) is the load, which adds nothing and returns the value. Both are sequentially consistent, so everything written before the flag is visible after it is seen.

+
Publish.raz
module Publish;
+import Out, Sys, Thread;
+
+type Message = record id: INT; text: [32]U8; len: INT; end;
+
+var
+    msg: Message;          (* ordinary memory, written once, then published *)
+    ready: INT;            (* the flag: only touched by atomics *)
+
+proc producer(_arg: ^U8);
+begin
+    Sys.sleep(10);
+    msg.id := 7;
+    msg.text := "built before the flag";
+    msg.len := 21;
+    _ := XCHG(ADR(ready), 1);               (* publish *)
+end;
+
+proc main*;
+var t: ^Thread.Thread; err: ERROR;
+begin
+    t, err := Thread.spawn(producer, nil);
+    if err # nil then Out.str(MSG(err)); Out.ln; return; end;
+    while XADD(ADR(ready), 0) = 0 do Sys.yield; end;     (* wait for it *)
+    Out.int(msg.id); Out.char(' '); Out.str(msg.text[0..msg.len]); Out.ln;
+    Thread.join(t);
+end;
+
+end Publish.
+
7 built before the flag
+
+

The reader's loop makes no ordinary read of ready: it can't be kept in a register and read once, which is the danger of while ready = 0 do end. And the write of msg can't be delayed past the XCHG.

+

The same with a fence

+

FENCE is a full memory barrier: it orders the program's ordinary accesses against those of other processors and devices. With volatile accesses for the flag and a fence between the data and the flag, the same handoff works. This is the form device code takes, as in the last lesson.

+
Fenced.raz
module Fenced;
+import Out, Sys, Thread;
+
+var
+    data: INT;                   (* ordinary *)
+    flag: INT;                   (* only reached through a volatile pointer *)
+
+proc producer(_arg: ^U8);
+var f: ^VOLATILE INT;
+begin
+    f := ^VOLATILE INT(ADR(flag));
+    Sys.sleep(10);
+    data := 1234;
+    FENCE;                       (* data is written before the flag is *)
+    f^ := 1;
+end;
+
+proc main*;
+var t: ^Thread.Thread; err: ERROR; f: ^VOLATILE INT;
+begin
+    f := ^VOLATILE INT(ADR(flag));
+    t, err := Thread.spawn(producer, nil);
+    if err # nil then Out.str(MSG(err)); Out.ln; return; end;
+    while f^ = 0 do Sys.yield; end;
+    FENCE;                       (* and read after the flag is seen *)
+    Out.int(data); Out.ln;
+    Thread.join(t);
+end;
+
+end Fenced.
+
1234
+
+

Both sides need a fence. A fence on the writer only says the data is written first; the reader must not read data before it has seen the flag.

+

The version that is not guaranteed

+

This is what *not* to write, and it is the most common bug in this area:

+
var data, ready: INT;
+
+(* thread A *)  data := 42;  ready := 1;
+(* thread B *)  while ready = 0 do end;  use(data);
+

Both threads use ordinary accesses to shared variables. B's loop may read ready once into a register and spin forever; A's two writes may reach memory in either order; B may read data before the flag, or an old copy. On a particular machine with a particular compiler it may well work, until it is changed. The language says it holds no particular value, and it means it.

+

The lesson of the three versions

+
  • Shared and written by someone: reach it through an atomic, a volatile pointer or a fence, every time, on both sides.
  • To hand over a bundle, publish a single atomic word *after* writing the bundle, and read the bundle only *after* seeing the word.
  • Everything under a Lock or a Mutex is ordered by the lock itself, so the data it guards can be ordinary variables. That is the simplest discipline, and the one to prefer until it is measured to be too slow.

Save a program under its module’s name and run it with raz run Name.raz.

+
+ + + diff --git a/site/public/advanced/processes.html b/site/public/advanced/processes.html new file mode 100644 index 0000000..aa84c78 --- /dev/null +++ b/site/public/advanced/processes.html @@ -0,0 +1,213 @@ + + + + + +Time, randomness and other programs - More Raz + + + + + + + + + + + + +
+
+

The library · lesson 5 of 18

Time, randomness and other programs

+

Everything here is in Sys, and is the same procedures on every target raz supports: through system calls on Linux, through the C library elsewhere.

+

Clocks and sleeping

+

Sys.clock is a clock that only goes forward, in nanoseconds: the one to measure a duration with. Sys.now is the wall clock, in nanoseconds since 1970 UTC, which can be set backwards, so it is for dates, not durations. Sys.sleep waits some milliseconds.

+
Timing.raz
module Timing;
+import Out, Sys;
+
+proc main*;
+var t0, t1, elapsed: I64; wall: I64;
+begin
+    t0 := Sys.clock();
+    Sys.sleep(25);
+    t1 := Sys.clock();
+    elapsed := (t1 - t0) div 1000000;        (* milliseconds *)
+    if (elapsed >= 25) and (elapsed < 1000) then
+        Out.str("slept about 25 ms\n");
+    end;
+    wall := Sys.now();
+    if wall > 1700000000000000000 then Out.str("after 2023\n"); end;
+end;
+
+end Timing.
+
slept about 25 ms
+after 2023
+
+

Every duration is an I64 of nanoseconds, because a 32-bit INT would hold only a couple of seconds of them. The library's rule is that what may overflow a small target's INT is an I64.

+

Random bytes

+

Sys.random fills a slice with random bytes from the system. Anything else is made from that: a number in a range, a shuffle.

+
Dice.raz
module Dice;
+import Out, Sys, Str;
+
+(* a number from 0 up to n, without bias *)
+proc below(n: INT): INT;
+var b: [8]U8; x, limit: U64;
+begin
+    limit := 0FFFFFFFFFFFFFFFFH - (0FFFFFFFFFFFFFFFFH mod U64(n)) - 1;
+    Sys.random(b);
+    x := Str.le(b);
+    while x > limit do
+        Sys.random(b);
+        x := Str.le(b);
+    end;
+    return INT(x mod U64(n));
+end;
+
+proc main*;
+var counts: [6]INT; i: INT; ok: BOOL;
+begin
+    for i := 1 to 6000 do INC(counts[below(6)]); end;
+    ok := true;
+    for i := 0 to 5 do
+        if (counts[i] < 800) or (counts[i] > 1200) then ok := false; end;
+    end;
+    if ok then Out.str("all six faces came up about a thousand times\n"); end;
+end;
+
+end Dice.
+
all six faces came up about a thousand times
+
+

Running a program

+

Sys.spawn starts the program at a path with its arguments, environment, working directory and standard streams in a Sys.Program record. A zero field means this program's own. Sys.wait waits for it to end and says how: exited with its status, killed by a signal, or stopped.

+
Run.raz
module Run;
+import Out, Sys;
+
+proc main*;
+var p: Sys.Program; pid, status: INT; how: Sys.Status;
+begin
+    p := {path: "/bin/echo", args: ["echo", "hello from a child"]};
+    pid := Sys.spawn(p);
+    if pid < 0 then Out.str("can't start\n"); return; end;
+    Out.flush;                      (* so that our text isn't behind the child's *)
+    _, how, status := Sys.wait(pid, true);
+    if how = Sys.exited then
+        Out.str("it exited with "); Out.int(status); Out.ln;
+    end;
+end;
+
+end Run.
+
hello from a child
+it exited with 0
+
+

Capturing its output

+

A program's standard output can be a pipe. Sys.pipe gives the descriptor to read and the one to write; give the write end to the child as fds[1], close it here, and read until the end. This is how a program drives another: ls, a compiler, a script.

+
Capture.raz
module Capture;
+import Out, Sys, Buf, Heap;
+
+proc main*;
+var
+    p: Sys.Program; pid, rd, wr, n, status: INT; how: Sys.Status;
+    chunk: [256]U8; b: Buf.Buf;
+begin
+    rd, wr := Sys.pipe();
+    p := {path: "/bin/sh", args: ["sh", "-c", "echo one; echo two; exit 7"]};
+    p.fds[1] := wr;
+    pid := Sys.spawn(p);
+    Sys.close(wr);                      (* only the child writes now *)
+    Buf.init(b, Heap.heap);
+    defer Buf.done(b);
+    n := Sys.read(rd, chunk);
+    while n > 0 do
+        Buf.str(b, chunk[0..n]);
+        n := Sys.read(rd, chunk);
+    end;
+    Sys.close(rd);
+    _, how, status := Sys.wait(pid, true);
+    Out.str("captured: "); Out.str(Buf.bytes(b));
+    Out.str("status "); Out.int(status); Out.ln;
+    if how = Sys.exited then Out.str("(a normal exit)\n"); end;
+end;
+
+end Capture.
+
captured: one
+two
+status 7
+(a normal exit)
+
+

Closing the write end in the parent matters: the read ends only when every holder of the write end has closed it.

+

Environment and working directory

+

Sys.env("HOME") is an environment variable's value, or an empty string if it is unset. Sys.workDir and Sys.setWorkDir read and change the directory. The Sys.Program record's env, onlyEnv and dir give a child its own.

+
Where.raz
module Where;
+import Out, Sys;
+
+proc main*;
+var p: Sys.Program; pid, rd, wr, n: INT; chunk: [64]U8;
+begin
+    if Sys.env("RAZ_SURELY_UNSET") = "" then Out.str("unset reads as empty\n"); end;
+    rd, wr := Sys.pipe();
+    p := {path: "/bin/sh", args: ["sh", "-c", "echo $GREETING from $(pwd)"],
+          env: ["GREETING=hello"], dir: "/tmp"};
+    p.fds[1] := wr;
+    pid := Sys.spawn(p);
+    Sys.close(wr);
+    n := Sys.read(rd, chunk);
+    Out.str(chunk[0..n]);
+    Sys.close(rd);
+    _, _, _ := Sys.wait(pid, true);
+end;
+
+end Where.
+
unset reads as empty
+hello from /tmp
+
+

Signals

+

A signal, Ctrl-C's sigInt or sigTerm from kill, ends a program unless it says otherwise. Sys.catch takes signals away from what they would do and gives an fd that is ready to read when one comes, so a program that waits on fds anyway, with Sys.readyOf, waits for signals the same way; Sys.caught gives each in turn. Sys.handle is for a program that waits inside a system call, as a shell waits for its program: the signal is noted for Sys.came, and the call it comes during fails with -4 (EINTR) rather than going on. Nothing of the program runs when the signal comes; it looks after the call returns.

+
Signals.raz
module Signals;
+import Out, Sys;
+
+proc main*;
+var fd: INT;
+begin
+    fd := Sys.catch([Sys.sigUsr1]);
+    _ := Sys.kill(Sys.pid(), Sys.sigUsr1);
+    if Sys.ready(fd, 1000) and (Sys.caught(fd) = Sys.sigUsr1) then Out.str("caught sigUsr1\n"); end;
+    _ := Sys.handle(Sys.sigUsr2);
+    _ := Sys.kill(Sys.pid(), Sys.sigUsr2);
+    if Sys.came(Sys.sigUsr2) then Out.str("sigUsr2 came\n"); end;
+    if not Sys.came(Sys.sigUsr2) then Out.str("and was seen once\n"); end;
+end;
+
+end Signals.
+
caught sigUsr1
+sigUsr2 came
+and was seen once
+

Save a program under its module’s name and run it with raz run Name.raz.

+
+ + + diff --git a/site/public/advanced/ring.html b/site/public/advanced/ring.html new file mode 100644 index 0000000..dcef777 --- /dev/null +++ b/site/public/advanced/ring.html @@ -0,0 +1,139 @@ + + + + + +A ring buffer between threads - More Raz + + + + + + + + + + + + +
+
+

Shared memory · lesson 18 of 18

A ring buffer between threads

+

To finish, here is a small piece of real concurrent code that uses nearly everything in this part of the tour: a queue through which one thread sends numbers to another, with no lock and no allocation.

+

The design

+

The queue is a fixed array of slots, used as a circle, and two counters that only ever grow: tail, the number of items the producer has put in, and head, the number the consumer has taken out. The item n lives in slot n mod Size. The queue is empty when the two are equal, and full when they differ by Size.

+

The design rule is that each counter has exactly one writer. Only the producer changes tail; only the consumer changes head. Each thread reads its own counter with an ordinary read, since nobody else changes it, and the other thread's with an atomic one. No CAS is needed, because there is never a race to resolve: only a handoff.

+

The handoff is the publish pattern of the ordering lesson. The producer writes the slot, then publishes it with an atomic store of tail; the consumer sees the new tail with an atomic load and only then reads the slot. In the other direction, the consumer frees a slot by storing head, and the producer only reuses it after loading head and seeing that.

+

The module

+
Ring.raz
module Ring;
+import Sys;
+
+const Size* = 64;
+
+type
+    Ring* = record
+        slots: [Size]INT;
+        head, tail: INT;      (* items taken, items put; each has one writer *)
+    end;
+
+(* v into the ring, waiting while it is full *)
+proc put*(r: ^Ring; v: INT);
+var t: INT;
+begin
+    t := r^.tail;                                    (* mine: an ordinary read *)
+    while t - XADD(ADR(r^.head), 0) = Size do Sys.yield; end;   (* full *)
+    r^.slots[t mod Size] := v;
+    _ := XCHG(ADR(r^.tail), t + 1);                  (* publish the slot *)
+end;
+
+(* the next value, waiting while the ring is empty *)
+proc take*(r: ^Ring): INT;
+var h, v: INT;
+begin
+    h := r^.head;                                    (* mine *)
+    while XADD(ADR(r^.tail), 0) = h do Sys.yield; end;          (* empty *)
+    v := r^.slots[h mod Size];
+    _ := XCHG(ADR(r^.head), h + 1);                  (* give the slot back *)
+    return v;
+end;
+
+end Ring.
+

Using it

+

One thread sends the numbers 1 to 100000 through a ring of 64 slots, so it is stopped by a full ring many times over and has to wait for the consumer. The consumer checks each number arrives in order, and adds them.

+
Pipe.raz
module Pipe;
+import Out, Fmt, Ring, Thread;
+
+const Count = 100000;
+
+var
+    ring: Ring.Ring;
+    sum, outOfOrder: INT;
+
+proc producer(_arg: ^U8);
+var i: INT;
+begin
+    for i := 1 to Count do Ring.put(ADR(ring), i); end;
+end;
+
+proc consumer(_arg: ^U8);
+var i, v: INT;
+begin
+    for i := 1 to Count do
+        v := Ring.take(ADR(ring));
+        if v # i then INC(outOfOrder); end;
+        sum := sum + v;
+    end;
+end;
+
+proc main*;
+var p, c: ^Thread.Thread; err: ERROR;
+begin
+    p, err := Thread.spawn(producer, nil);
+    if err # nil then Out.str(MSG(err)); Out.ln; return; end;
+    c, err := Thread.spawn(consumer, nil);
+    if err # nil then Out.str(MSG(err)); Out.ln; return; end;
+    Thread.join(p);
+    Thread.join(c);
+    Fmt.print("{} items, sum {}, {} out of order\n",
+        [Fmt.int(Count), Fmt.int(sum), Fmt.int(outOfOrder)]);
+end;
+
+end Pipe.
+
100000 items, sum 5000050000, 0 out of order
+
+

The sum of 1 to 100000 is 5000050000, and nothing arrives out of order. sum and outOfOrder are written only by the consumer thread and read by main after Thread.join, which is the synchronization that makes them visible: a join is the thread's end, observed.

+

What it used

+
  • Modules (Ring, with its record's own fields unexported).
  • Atomics for the handoff, and an ordering argument for why a slot is complete when its counter moves.
  • Threads from Thread, with no C in the program.
  • The checks, which stay on: slots[t mod Size] is an indexed array access that can't leave the array, whatever the counters do.
+

It is not a finished library: it is one producer and one consumer, and a second of either breaks the one-writer rule. That is the sort of statement a comment above put and take should make, and the sort a reader should demand.

+

Where next

+

That is the end of the tour. A few places to continue:

+
  • The report defines the language, and is short enough to read through.
  • doc/compiler.md in the sources is a guide to reading the compiler, file by file; it is a model of the style the project is written in.
  • lib/ is the library, in raz. Each module's own main is its test. Reading Heap, Map, Opt and Thread is the best remaining education.
  • tools/Doc.raz prints what a module exports with its comments: raz -o Doc tools/Doc.raz && ./Doc lib/Str.raz.
  • examples/ holds small programs with the output each should give, and conform/ holds what any implementation must do.

Save a program under its module’s name and run it with raz run Name.raz.

+
+ + + diff --git a/site/public/advanced/static.html b/site/public/advanced/static.html new file mode 100644 index 0000000..d87ed2a --- /dev/null +++ b/site/public/advanced/static.html @@ -0,0 +1,152 @@ + + + + + +A program with no run time - More Raz + + + + + + + + + + + + +
+
+

Standing alone · lesson 7 of 18

A program with no run time

+

Most languages arrive with a run time: a collector, a loader of libraries, start-up code you didn't write. A raz program that doesn't use C has none of that. The executable holds the code the program reaches, a few lines of start-up code, and nothing else. This part of the tour looks at what that means in practice, and what a program can do when nothing stands between it and the kernel.

+

The smallest program

+

This program imports nothing. It makes the write system call itself, with the built-in SYSCALL, and returns.

+
Bare.raz
module Bare;
+
+const Msg = "hello from raw system calls\n";
+
+proc main*;
+begin
+    _ := SYSCALL(1, 1, ADR(Msg[0]), LEN(Msg));
+end;
+
+end Bare.
+
$ raz Bare.raz
+$ ./Bare
+hello from raw system calls
+$ file Bare
+Bare: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, with debug_info, not stripped
+$ ldd Bare
+	not a dynamic executable
+$ ls -l Bare | awk '{print $5, "bytes"}'
+26488 bytes
+

It is statically linked: no interpreter, no shared libraries, no libc. ldd says so.

+

What it does when it runs

+

strace lists every system call a program makes. This is the whole of it:

+
$ strace ./Bare 2>&1 >/dev/null | sed -e 's/0x[0-9a-f]\{5,\}/ADDR/g' -e 's/[0-9]* vars/N vars/'
+execve("./Bare", ["./Bare"], ADDR /* N vars */) = 0
+sigaltstack({ss_sp=ADDR, ss_flags=0, ss_size=16384}, NULL) = 0
+rt_sigaction(SIGSEGV, {sa_handler=ADDR, sa_mask=[], sa_flags=SA_RESTORER|SA_ONSTACK|SA_RESETHAND|SA_SIGINFO, sa_restorer=ADDR}, NULL, 8) = 0
+rt_sigaction(SIGFPE, {sa_handler=ADDR, sa_mask=[], sa_flags=SA_RESTORER|SA_ONSTACK|SA_RESETHAND|SA_SIGINFO, sa_restorer=ADDR}, NULL, 8) = 0
+write(1, "hello from raw system calls\n", 28) = 28
+exit_group(0)                           = ?
++++ exited with 0 +++
+

The start-up code does four things before main runs: it sets up a stack of its own for signal handlers (sigaltstack), and installs handlers for SIGSEGV and SIGFPE. That is what turns a nil pointer or a division by zero into a message that names the place, instead of a bare "Segmentation fault". Then main runs its single write, and the program ends with exit_group. Nothing is mapped, loaded, or looked up.

+

Programs that use C

+

A program that declares an extern procedure, or links a library, is a different animal. It is linked dynamically and starts through the C library, so that C's own set-up and clean-up run. Compare the same kind of hello, with C's printf:

+
Cprint.raz
module Cprint;
+
+extern proc puts(s: ^U8): I32;
+
+proc main*;
+begin
+    _ := puts("hello from C");
+end;
+
+end Cprint.
+
$ raz Cprint.raz
+$ ./Cprint
+hello from C
+$ file Cprint
+Cprint: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, with debug_info, not stripped
+$ ldd Cprint | sed 's/ (0x[0-9a-f]*)//'
+	linux-vdso.so.1
+	libc.so.6 => /usr/lib/libc.so.6
+	/lib64/ld-linux-x86-64.so.2 => /usr/lib64/ld-linux-x86-64.so.2
+

Both are fine. The point is that you choose, and the language says which you chose: a program uses C exactly when a module of it has an extern or a link of a library.

+

Only what is reached

+

The compiler keeps only what can be reached from main and the module bodies. Unused procedures, variables and strings are left out. Here are two programs that differ by one large procedure that nothing calls.

+
Lean.raz
module Lean;
+import Out;
+
+proc main*;
+begin
+    Out.str("same program\n");
+end;
+
+end Lean.
+
Heavy.raz
module Heavy;
+import Out;
+
+var table: [100000]INT;
+
+(* exported, but never called, so never in the executable *)
+proc unused*(n: INT): INT;
+var i, s: INT;
+begin
+    for i := 0 to 99999 do table[i] := n * i; s := s + table[i]; end;
+    Out.str("a long string that nobody will ever print, to give it some weight");
+    return s;
+end;
+
+proc main*;
+begin
+    Out.str("same program\n");
+end;
+
+end Heavy.
+
$ raz Lean.raz
+$ raz Heavy.raz
+$ ls -l Lean Heavy | awk '{print $9, $5}'
+Heavy 28680
+Lean 28672
+

The sizes differ by a few bytes, not by the hundreds of kilobytes that the table and the procedure would take: they are not in the executable at all. You can link in a library module without worrying what else it offers.

+

Stripping

+

-s leaves out what is there for finding faults: the symbols and line numbers, the places a failure is told by, and the profiler. It is for the final build of a size-conscious program; the default keeps them so that gdb and failure messages work.

+
$ raz -s -o Lean-stripped Lean.raz
+$ ls -l Lean Lean-stripped | awk '{print $9, $5}'
+Lean 28672
+Lean-stripped 6920
+$ ./Lean-stripped
+same program
+

raz -S Lean.raz is the other direction: it prints the machine code the compiler made, one source line at a time. The next two parts of the tour use it.

Save a program under its module’s name and run it with raz run Name.raz.

+
+ + + diff --git a/site/public/advanced/syscalls.html b/site/public/advanced/syscalls.html new file mode 100644 index 0000000..c4474b7 --- /dev/null +++ b/site/public/advanced/syscalls.html @@ -0,0 +1,199 @@ + + + + + +System calls - More Raz + + + + + + + + + + + + +
+
+

The machine · lesson 12 of 18

System calls

+

Under Sys there is one built-in: SYSCALL(n, x1, ..., x6). It makes Linux system call number n with up to six arguments, each a pointer or an integer no wider than INT, and gives the raw result, an INT. A negative result is -errno. That is all the interface there is; Sys.write, Sys.open and the rest of lib/Sys.linux-x86_64.raz are written with it, in raz, in a few lines each.

+

SYSCALL exists only on Linux targets. Other systems have no stable system call interface, which is why their Sys calls the C library instead.

+

The shape of a call

+

write(fd, buf, count) is call number 1. The arguments are the descriptor, a pointer to the bytes, and how many.

+
Raw.raz
module Raw;
+
+const Msg = "straight to the kernel\n";
+
+proc main*;
+var n: INT;
+begin
+    n := SYSCALL(1, 1, ADR(Msg[0]), LEN(Msg));
+    if n # LEN(Msg) then _ := SYSCALL(60, 1); end;      (* exit(1), if it came up short *)
+end;
+
+end Raw.
+
$ raz -Werror Raw.raz
+$ ./Raw
+straight to the kernel
+

That program has no Out, no Sys, and no output buffer. What it needs of the library is Rt's start-up, which the compiler links in anyway.

+

Reading the result

+

A result that is negative is a failure, and its negation is the errno. open is call 2 and wants a C string: the path's bytes followed by a zero. A [N]U8 made from a string literal is zero-filled past its length, so there is always a terminator.

+
Open.raz
module Open;
+import Out;
+
+proc main*;
+var path: [32]U8; fd: INT;
+begin
+    path := "/no/such/file";
+    fd := SYSCALL(2, ADR(path[0]), 0, 0);        (* open(path, O_RDONLY) *)
+    Out.str("open gave "); Out.int(fd); Out.ln;   (* -2: ENOENT *)
+    path := "/dev/null";
+    fd := SYSCALL(2, ADR(path[0]), 0, 0);
+    if fd >= 0 then
+        Out.str("opened /dev/null\n");
+        _ := SYSCALL(3, fd);                      (* close *)
+    end;
+end;
+
+end Open.
+
open gave -2
+opened /dev/null
+
+

The library's Sys.openRead does exactly this, and Sys.close too. Reading lib/Sys.linux-x86_64.raz is the best reference there is for what each call wants.

+

A call that fills a structure

+

uname (call 63) fills a structure of six 65-byte fields: the system name, node name, release, version, machine and domain. It is not a type raz knows; it is an array of bytes, with a ADR of it given to the kernel.

+
Who.raz
module Who;
+import Out;
+
+(* the length of the zero-ended string at the start of s *)
+proc cstr(s: []U8): INT;
+var n: INT;
+begin
+    n := 0;
+    while (n < LEN(s)) and (s[n] # 0) do INC(n); end;
+    return n;
+end;
+
+proc main*;
+var u: [390]U8;
+begin
+    if SYSCALL(63, ADR(u[0])) = 0 then
+        Out.str("system: "); Out.str(u[0..cstr(u[0..65])]); Out.ln;
+        Out.str("machine: "); Out.str(u[260..260 + cstr(u[260..325])]); Out.ln;
+    end;
+end;
+
+end Who.
+
system: Linux
+machine: x86_64
+
+

Memory straight from the kernel

+

mmap is call 9: six arguments, the most one call can take. This asks for a page of anonymous, zeroed memory, writes in it, and gives it back with munmap (call 11). It is what Mem.pages does, and so what every allocator is ultimately made of.

+
Pages.raz
module Pages;
+import Out;
+
+proc main*;
+var p: ^U8; i: INT; total: INT;
+begin
+    (* length 4096; PROT_READ|WRITE = 3; MAP_PRIVATE|ANONYMOUS = 22H; no fd *)
+    p := ^U8(SYSCALL(9, 0, 4096, 3, 22H, -1, 0));
+    if INT(p) < 0 then Out.str("no memory\n"); return; end;
+    Out.int(INT(p[0]) + p[4095]); Out.str(" (zero, as promised)\n");
+    for i := 0 to 4095 do p[i] := U8(i); end;
+    for i := 0 to 4095 do INC(total, p[i]); end;
+    Out.int(total); Out.ln;
+    _ := SYSCALL(11, p, 4096);
+end;
+
+end Pages.
+
0 (zero, as promised)
+522240
+
+

A cat with no library

+

Reading and writing in a loop is all cat does. With system calls, it is one procedure. Call 0 is read and call 1 is write; 0 and 1 are standard input and output.

+
Cat.raz
module Cat;
+
+proc main*: INT;
+var buf: [4096]U8; n, wrote, at: INT;
+begin
+    n := SYSCALL(0, 0, ADR(buf[0]), LEN(buf));
+    while n > 0 do
+        at := 0;
+        while at < n do                   (* a write may be partial *)
+            wrote := SYSCALL(1, 1, ADR(buf[at]), n - at);
+            if wrote < 0 then return 1; end;
+            INC(at, wrote);
+        end;
+        n := SYSCALL(0, 0, ADR(buf[0]), LEN(buf));
+    end;
+    if n < 0 then return 1; end;
+    return 0;
+end;
+
+end Cat.
+
$ raz Cat.raz
+$ echo "through the pipe" | ./Cat
+through the pipe
+$ ./Cat < /dev/null; echo "status $?"
+status 0
+$ echo "see the calls" | strace -e trace=read,write ./Cat 2>&1 >/dev/null | grep -v '^+++'
+read(0, "see the calls\n", 4096)        = 14
+write(1, "see the calls\n", 14)         = 14
+read(0, "", 4096)                       = 0
+

The partial-write loop is the kind of detail Sys.write leaves to the caller on purpose: it returns the bytes written, and the program decides what to do about the rest.

+

In a code procedure

+

A system call is also an instruction. syscall takes its number in rax and its arguments in rdi, rsi, rdx, r10, r8 and r9, which is not quite the order a procedure's arguments arrive in, since r10 takes the place of rcx, and syscall itself clobbers rcx and r11.

+
Ppid.raz
module Ppid;
+import Out;
+
+(* getppid, call 110: no arguments *)
+proc getppid: INT;
+code
+    mov eax, 110;
+    syscall;
+    ret;
+end getppid;
+
+proc main*;
+begin
+    if (getppid() > 0) and (SYSCALL(110) = getppid()) then
+        Out.str("two ways to ask, one answer\n");
+    end;
+end;
+
+end Ppid.
+
two ways to ask, one answer
+
+

SYSCALL is the right tool nearly always: the compiler puts the arguments where they belong, and the result is checked in the open. A code procedure is for the rare call you want to make from inside another piece of assembly.

Save a program under its module’s name and run it with raz run Name.raz.

+
+ + + diff --git a/site/public/advanced/targets.html b/site/public/advanced/targets.html new file mode 100644 index 0000000..d474557 --- /dev/null +++ b/site/public/advanced/targets.html @@ -0,0 +1,112 @@ + + + + + +One module, one file per target - More Raz + + + + + + + + + + + + +
+
+

Standing alone · lesson 10 of 18

One module, one file per target

+

raz is first made for x86-64 Linux, but the language is written to be implemented elsewhere, and the library is arranged for it. The part of a program that depends on the system goes in a module of its own, one file per target. This is how Sys is made, and it is how your own code should keep its system-dependent parts apart.

+

The files

+

A module Name lives in Name.raz. A module whose code depends on the system comes in one file per target, Name.linux-x86_64.raz, which the compiler looks for first. The library has Sys.linux-x86_64.raz, which makes system calls, and Sys.raz, which calls the C library instead, for every other system. A program that imports Sys doesn't know or care which it got.

+
$ ls $RAZLIB | grep -i "^sys\|^thread"
+Sys.linux-x86_64.raz
+Sys.raz
+Thread.linux-x86_64.raz
+$ cd $RAZLIB && grep -c SYSCALL Sys.linux-x86_64.raz Sys.raz
+Sys.linux-x86_64.raz:151
+Sys.raz:0
+

A module of your own

+

Here is a module with two files. Clock.linux-x86_64.raz is for this target; Clock.raz is what any other target would use. Both say what they are in Name, and both make ticks.

+
Clock.linux-x86_64.raz
module Clock;
+import Sys;
+
+const Name* = "the linux-x86_64 file";
+
+(* a number that only grows *)
+proc ticks*: I64;
+begin
+    return Sys.clock();
+end;
+
+end Clock.
+
Clock.raz
module Clock;
+import Sys;
+
+const Name* = "the portable file";
+
+(* a number that only grows *)
+proc ticks*: I64;
+begin
+    return Sys.clock();
+end;
+
+end Clock.
+

A program that imports Clock gets the first of them here:

+
Show.raz
module Show;
+import Out, Clock;
+
+proc main*;
+begin
+    Out.str("using "); Out.str(Clock.Name); Out.ln;
+    if Clock.ticks() > 0 then Out.str("and it ticks\n"); end;
+end;
+
+end Show.
+
using the linux-x86_64 file
+and it ticks
+
+

Held to one interface

+

Two files can't be told apart by their callers, so the compiler holds them to the same interface. Here is the pair again with ticks changed in the portable file to return an INT:

+
$ mkdir drift && cp Clock*.raz Show.raz drift && cd drift
+$ sed -i 's/proc ticks\*: I64/proc ticks*: INT/; s/return Sys.clock()/return INT(Sys.clock())/' Clock.raz
+$ raz Show.raz
+raz: ./Clock.raz: ticks isn't exported as in ./Clock.linux-x86_64.raz
+

The program stops compiling on every target, including the ones that would never have used that file. A mismatch is found where it is made, not where someone first builds for a second target.

+

What the compiler checks

+

When it takes one of Name.*.raz, it also reads the declarations of the others beside it, and of Name.raz if there is one, and reports an error unless they all export the same names, each the same kind of thing: a constant of the same type (its value may differ), a type of the same kind with the same exported fields, a variable of the same type, a procedure of the same signature. The code, the unexported fields, and so the size and layout, may differ.

+

So a program written against the interface works on every target that has the module, and the places where it doesn't are the compiler's to find, not yours.

+

What stays the same everywhere

+

The core of the library is what every target must have: Rt, Out, Mem, Arena, Lock, Str and Buf, and of Sys what they need. A program that keeps to the core runs on every target. Thread, link and extern, and most of Sys, are what a target may leave out when its system can't give them.

Save a program under its module’s name and run it with raz run Name.raz.

+
+ + + diff --git a/site/public/advanced/volatile.html b/site/public/advanced/volatile.html new file mode 100644 index 0000000..9d9debf --- /dev/null +++ b/site/public/advanced/volatile.html @@ -0,0 +1,154 @@ + + + + + +Volatile - More Raz + + + + + + + + + + + + +
+
+

Shared memory · lesson 14 of 18

Volatile

+

Most memory is the program's own: only it reads and writes it, so the compiler may keep a variable in a register, leave out a write that nothing reads, and change the order of accesses, as long as the program does what the report says. Some memory is not: a device's registers, memory another processor or thread is changing, a page the kernel fills. There, each access matters, and its order.

+

A variable reached through a ^VOLATILE T is volatile, and so is any field or element of it. Each read or write of one of a basic, enumeration, set or pointer type is exactly one memory access, of exactly its size, and volatile accesses happen in the order the program writes them.

+

A device laid over memory

+

The classic use is a device's registers: a record that says what is at which offset, laid over the address the hardware answers at. The record's layout is C's, so it is the same as the datasheet's struct. Here a page of the program's own stands in for the device.

+
Uart.raz
module Uart;
+import Out;
+
+type
+    Regs = record
+        data: U32;       (* offset 0 *)
+        status: U32;     (* offset 4 *)
+        control: U8;     (* offset 8 *)
+    end;
+
+var page: [64]U8;        (* where the device would be *)
+
+proc main*;
+var dev: ^VOLATILE Regs; i: INT;
+begin
+    dev := ^VOLATILE Regs(ADR(page));      (* the conversion is written *)
+    dev^.control := 1;
+    dev^.status := 0FFH;
+    for i := 0 to 2 do
+        dev^.data := U32('a' + i);
+        Out.char(U8(dev^.data));
+    end;
+    Out.ln;
+    FENCE;
+    Out.int(INT(page[8])); Out.char(' '); Out.int(INT(dev^.status)); Out.ln;
+end;
+
+end Uart.
+
abc
+1 255
+
+

On real hardware the address would be a constant, ^VOLATILE Regs(0FEC00000H), which is a legal conversion since an integer constant converts to a pointer. The program is otherwise unchanged.

+

What each access is

+

The listing shows what the guarantee means: each field access is one instruction of the field's size, and so is a write to a field that is never read afterwards, which an optimizer would be allowed to drop from an ordinary variable.

+
$ raz -S Uart.raz | grep -n "dword\|byte" | head -2
+15:            34  mov byte [rbx + 8], 1
+17:            38  mov dword [rbx + 4], 255
+

The U8 control byte is written with a byte store, and the U32 status with a dword one. Never a wider access that touches the neighbour, never two narrower ones.

+

Waiting for something else to change

+

Where a program waits for another thread or a device to change a value, the loop must read the value each time. A volatile read does. This "device" is a thread that sets a bit in a status word after a delay; the main thread polls.

+
Poll.raz
module Poll;
+import Out, Sys, Thread;
+
+type Dev = record status: INT; data: INT; end;
+
+var dev: Dev;
+
+proc device(_arg: ^U8);
+var d: ^VOLATILE Dev;
+begin
+    d := ^VOLATILE Dev(ADR(dev));
+    Sys.sleep(20);
+    d^.data := 42;
+    FENCE;                          (* data before the flag that announces it *)
+    d^.status := 1;
+end;
+
+proc main*;
+var t: ^Thread.Thread; err: ERROR; d: ^VOLATILE Dev; spins: INT;
+begin
+    d := ^VOLATILE Dev(ADR(dev));
+    t, err := Thread.spawn(device, nil);
+    if err # nil then Out.str(MSG(err)); Out.ln; return; end;
+    while d^.status = 0 do INC(spins); Sys.yield; end;
+    Out.int(d^.data); Out.ln;
+    if spins > 0 then Out.str("it waited for the device\n"); end;
+    Thread.join(t);
+end;
+
+end Poll.
+
42
+it waited for the device
+
+

The FENCE between the two writes matters. It is a full memory barrier, ordering the program's ordinary accesses against those of other processors and devices. Without it, volatile accesses are ordered among themselves, but nothing says another processor sees data before status. The next lessons are about this.

+

What volatile is not

+
  • Not atomic across a read-modify-write. INC(d^.count) reads and then writes: two accesses, even through a volatile pointer. XADD is the atomic one.
  • Not a lock. It says each access happens as written; it says nothing about what happens between them.
  • Not for whole records or arrays. Copying a whole record through a volatile pointer isn't allowed, since it can't be one access. A field of a packed record can't be reached volatilely at all, since a misaligned access can't be promised as one.
  • Not silently dropped. A ^VOLATILE T doesn't convert to a ^T without a written conversion, so the volatile can't be lost by accident.
+

The compiler holds the line on each of them:

+
Wrong.raz
module Wrong;
+
+type Pair = record a, b: U32; end;
+
+var cell: Pair;
+
+proc main*;
+var v: ^VOLATILE Pair; p: ^Pair; copy: Pair;
+begin
+    v := ^VOLATILE Pair(ADR(cell));
+    p := v;
+    copy := v^;
+end;
+
+end Wrong.
+
$ raz Wrong.raz
+Wrong.raz:11:10: error: can't use ^VOLATILE Pair as ^Pair
+   11 |     p := v;
+      |          ^
+Wrong.raz:12:13: error: can't copy through a volatile pointer
+   12 |     copy := v^;
+      |             ^^
+raz: 2 errors

Save a program under its module’s name and run it with raz run Name.raz.

+
+ + + diff --git a/site/public/index.html b/site/public/index.html new file mode 100644 index 0000000..10f8708 --- /dev/null +++ b/site/public/index.html @@ -0,0 +1,143 @@ + + + + + +raz: a small systems language + + + + + + + + + + + + +
+
+
+

raz

+

A small systems language in Wirth’s tradition, for x86-64 Linux. + Raz is Polish for one, as in counting.

+ +
+ +

A raz program can lay a record over a device’s registers, read and +write memory exactly as written, take part in lock-free algorithms, make +system calls and call C libraries. It has no garbage collector and no hidden +run time: what the program does is what its text says.

+ +

The compiler is written in raz, about 10,700 lines, and builds itself. It makes +x86-64 machine code and the ELF file itself, with no assembler or linker, in +one pass, at about 500,000 lines a second.

+ +
+ ~10,700 lines of compiler + ~500K lines compiled a second + 1 report, 35 pages + static executables, no run time to install +
+ +
+
+

A taste

+
Taste.raz
+
(* Several results, slices, and checks that say what failed. *)
+module Taste;
+import Out;
+
+proc divmod(a, b: INT): (INT, INT);
+begin
+    return a div b, a mod b;
+end;
+
+proc sum(s: []INT): INT;
+var i, t: INT;
+begin
+    for i := 0 to LEN(s) - 1 do t := t + s[i]; end;
+    return t;
+end;
+
+proc main*;
+var q, r: INT; a: [5]INT; i: INT;
+begin
+    for i := 0 to 4 do a[i] := i * i; end;
+    q, r := divmod(sum(a), 7);
+    Out.int(q); Out.str(" remainder "); Out.int(r); Out.ln;
+    Out.int(sum(a[1..3])); Out.ln;
+end;
+
+end Taste.
+
4 remainder 2
+5
+
+
+

What it has

+
    +
  • Integers of 8 to 64 bits, signed and unsigned, which wrap; BOOL, F32, F64. Nothing converts unless it is written.
  • +
  • Arrays, checked slices, pointers, records laid out as C lays them out, packed records, enumerations, sets, and variants with match.
  • +
  • Every index and slice is checked; a failure says where it was, with the values, and the calls under way.
  • +
  • Strings of UTF-8 bytes, raw strings over lines that keep the code's indent, and match on a string.
  • +
  • Every variable starts at zero. Behaviour is defined everywhere but through pointers.
  • +
  • No garbage collector: memory comes from an allocator the program chooses and passes.
  • +
  • Several results, ERROR values and defer, in place of exceptions.
  • +
  • Modules with bodies, and generic modules: Map(K, V; hash, eq).
  • +
  • ^VOLATILE T and the atomics CAS, XCHG, XADD, FENCE, for devices and lock-free code.
  • +
  • extern procedures and variables from C, code procedures in assembly, and SYSCALL.
  • +
  • Threads without C, a library of Out, Str, Bytes, Fmt, Map, Sort and more, and gdb that knows your lines.
  • +
  • A formatter, a documentation tool, and editor support for vim and emacs.
  • +
+
+
+ +

Learn it

+

Raz, Set, Go is a tour of the +language in 15 lessons, each with programs you can run. More Raz is the second tour: +the library, programs with no run time, procedures in assembly, system calls, +volatile accesses, atomics and lock-free code, in 18 more.

+ +

The language, in writing

+

The language is defined by the report, which is +short on purpose: whatever it doesn’t allow, raz doesn’t have. +Its second volume describes the library. Both are on one page, and each is +a PDF: the language (35 pages) and +the library.

+ +

Download

+

raz 0.23.0 is a tarball for x86-64 Linux with the compiler, raz, +its library, lib/, which it finds beside itself, the formatter +and the documentation tool as sources in tools/, and the manual +pages. It needs nothing else installed.

+
+ Download raz 0.23.0 + SHA-256 +
+
$ tar xzf raz-0.23.0-linux-x86_64.tar.gz
+$ ln -s $PWD/raz-0.23.0-linux-x86_64/raz ~/.local/bin/raz
+$ raz run Hello.raz
+

The link works since raz finds lib/ beside its real path. The +manual pages are in man/: man ./man/raz-tutorial.7. +The address download/latest always leads to the newest release, +and download/raz-0.23.0-linux-x86_64.tar.gz to this one, for +good. Earlier releases: 0.22.0, 0.21.0, 0.20.0, 0.19.0, 0.18.1, 0.18.0, 0.17.2, 0.17.1, 0.17.0, 0.16.0, 0.15.0, 0.14.0, 0.13.0, 0.12.0, 0.11.1, 0.11.0, 0.10.1, 0.10.0, 0.9.1, 0.9.0, 0.8.0, 0.7.1; each has its SHA-256 beside it, with +.sha256 added to its name.

+

SHA-256 103eb421a7fcca1c1495c1a9c699297d460ab72067fa04854da8f21edc07347c

+

Release pages give each +version's commit, notes, compiler and source archives, with checksums. +Browse the source and history, or clone: +git clone https://raz.lucelad.workers.dev/source/.

+ +
+ + + diff --git a/site/public/raz-lib.pdf b/site/public/raz-lib.pdf new file mode 100644 index 0000000..73e855a Binary files /dev/null and b/site/public/raz-lib.pdf differ diff --git a/site/public/raz.pdf b/site/public/raz.pdf new file mode 100644 index 0000000..5cb5dce Binary files /dev/null and b/site/public/raz.pdf differ diff --git a/site/public/spec.html b/site/public/spec.html new file mode 100644 index 0000000..0a57ffd --- /dev/null +++ b/site/public/spec.html @@ -0,0 +1,1745 @@ + + + + + +The raz report + + + + + + + + + + + + +
+
+

Volume 1 as a PDF · Volume 2 as a PDF

+ +

raz is a small systems language, first made for x86-64 Linux. A raz program can lay a record over a device’s registers, read and write a device’s memory exactly as written, take part in lock-free algorithms, make system calls and call C libraries. It has no garbage collector and no hidden run time: what the program does is what its text says.

+

This is the first volume of the report: the language, what an implementation chooses, and the grammar. The second, doc/raz-lib.md, is the library, which sections 3 and 10 and appendix A name.

+

This report defines the language. It is short on purpose. Whatever it doesn’t allow, raz doesn’t have.

+

This is version 2026-10.37 of the report; section 11 says where each version’s changes are told. 2026-10.11 and 2026-10.12 are a thaw the owner chose, for a language anyone can build again. They break programs written for 2026-10.10 and before: for 2026-10.9, say, the report of compiler 0.5.0, the last release before them; and 2026-10.12 breaks code procedures written for 2026-10.11. 2026-10.20 is a third, for try (section 7.8); it breaks a program that has a name try. 2026-10.25 is a fourth, for strings: raw strings, which may run over lines and may be indented with the code around them (section 2), and match on a string (section 7.4); it breaks no program. 2026-10.26 is a fifth: an INT widens to an I64 wherever it goes to one, in an expression too (sections 5.10 and 6.1); and a view, v.(T), reads and writes the bytes of a variable as a T (section 6.9); it breaks no program. 2026-10.27 mends a defect: returning a slice of the procedure’s own frame is an error (section 7.3), which breaks only a program that read memory already gone. 2026-10.28 mends another: an array a call returns lives to the end of its statement, and a slice of it kept past that is undefined (sections 8 and 10). 2026-10.29 is a sixth thaw: an array constant typed []T takes its length from its literal (section 4); it breaks no program. 2026-10.30 mends a defect: [] used as a slice is the empty slice, which may be returned (sections 6.5 and 7.3); it breaks no program. 2026-10.31 is a seventh thaw: INT is at least 16 bits, and U8, I8 and I16 widen to it (sections 5.1, 5.10 and 6.1); an enumeration’s name may be written with its type, and must be where another declaration shares it (section 5.7); and continue (section 7.2), which breaks a program that has a name continue. 2026-10.32 is an eighth thaw: a constant typed []T may be [], the empty slice (section 4); it breaks no program. 2026-10.33 is a ninth: a const parameter, the caller’s variable read in place (section 8), and a variant in a constant (section 4), which break no program; and the library’s procedures that took a pointer to what they work on take a var parameter, a const one or a value instead (the library volume), which breaks a program that calls them with ADR. 2026-10.34 is a tenth: PTR(s), the address a slice starts at, even an empty one (section 6.8); it breaks no program. 2026-10.35 is an eleventh: ROL(x, n) and ROR(x, n), a word rotated (sections 6.1 and 6.8); it breaks no program. 2026-10.36 is a twelfth: MIN(T) and MAX(T), the limits of an integer type, and CLZ, CTZ and POPCOUNT, which count bits (sections 6.1 and 6.8); ABS(x), a number without its sign (sections 6.1 and 6.8); INT(b), a BOOL as an integer (section 6.7); OFFSET(T, f) and SIZE(T.f), where a field lies and how big it is; BYTES(x), the bytes of a variable or a slice (sections 4 and 6.8); FILL(d, x), an array or a slice set to one value (section 6.8); a qualified case in a match arm (section 7.4); a slice part written as a literal, and an ERROR constant named by another (sections 4 and 5.8); and a const parameter’s slice returned (section 7.3); and a procedure type’s parameter or result may name a type declared later in its type section (sections 4 and 5.9); it breaks no program. 2026-10.37 is a thirteenth thaw, for safety. It mends a defect: an array a call returns, or a record or variant holding one, lives to the end of the procedure the call is in, so a slice of it may be kept (section 8). CAS, XCHG and XADD take the variable they work on (section 6.8). []const T is a slice whose elements can’t be written through it, which a string literal, a slice of a constant, MSG and a slice of a const parameter’s array are (sections 4, 5.3, 5.10, 6.8 and 8). And import SYSTEM is what a module says to reach memory other than through its variables: SYSTEM.ADR, SYSTEM.PTR, SYSTEM.SYSCALL and SYSTEM.ARGV, a pointer’s arithmetic and conversions, C, code procedures and check off; (section 3); section 10 says what is left undefined outside such modules. It breaks a program that gives an atomic a pointer, writes through a string or a constant, or does what SYSTEM holds without importing it; raz 0.23 still takes all of these as before, until 0.24.

+

The language is frozen, softly, from this version on: it changes only to mend a defect, and its library grows only by what breaks no program written for it. What anyone wishes it had waits on a list, for a later thaw.

+

1. A first look

+
module Hello;
+import Out;
+
+proc main*;
+begin
+    Out.str("hello, world\n");
+end;
+
+end Hello.
+

A program is a set of modules. The one named on the command line is the main module, and it exports a procedure main; the program starts there, once every module’s body has run (section 3). Saved as Hello.raz, it is compiled with raz Hello.raz, which writes the executable Hello.

+

2. Words and symbols

+

A program is written in UTF-8. The compiler rejects a file that isn’t valid UTF-8: a malformed or overlong sequence, a surrogate, or a code point beyond 10FFFFH, and a file with a NUL byte. Everything outside strings, characters and comments is ASCII. Spaces, tabs and line breaks separate symbols and are otherwise ignored.

+

Identifiers are an ASCII letter or _ followed by letters, digits and _, up to 63 characters. Case matters: count and Count are different names. _ alone isn’t a name: it is the blank, which stands only to the left of := (section 7.1).

+

Reserved words are lowercase, except VOLATILE:

+
and begin break by code const continue defer div do else elsif end
+extern for forward if import in link match mod module not of or packed
+proc record repeat return set shl shr then to try type until var
+variant VOLATILE while xor
+

static, in link static; (section 3), and check and off, in check off; (section 3), aren’t reserved.

+

Predeclared names are the basic types (section 5.1), ERROR, true, false, nil and the built-in procedures (section 6.8). They belong to a scope around every module, so a module or a procedure may declare the same name for something else, which hides them there.

+

Numbers. 123 is decimal. 0FFH is hexadecimal: it starts with a digit, its digits are 0 to 9 and A to F, and it ends in H, all in capitals. 1.5 and 2.0E-3 are reals; a real always has a digit on both sides of its point, and its exponent, if it has one, is E, a sign if wanted, and digits. A decimal number above the largest I64, or a hexadecimal one above the largest U64, is an error; so is a real above the largest F64. A real below the least F64 is 0.

+

An integer is an untyped constant, which takes the type it is used as, up to the largest I64. A hexadecimal number above that, such as 0FFFFFFFFFFFFFFFFH, has type U64: so -1 never fits a U64, and the big number goes nowhere else without a conversion. Arithmetic on untyped constants doesn’t wrap: a result beyond the I64s, such as 9223372036854775807 + 1, is an error.

+

A real is an untyped constant too. It is read as the nearest F64 (a tie goes to the even one), and takes F32 or F64, whichever it is used as: an F32 is the nearest to that F64. Where nothing says which, it is an F64. A real never becomes an integer, nor an integer a real, without a conversion: x := 1; is an error for x: F64, and x := 1.0; is right.

+

Characters. 'a' is the code point of one character, an integer: 'a' is 97 and 'é' is 233.

+

Strings. "héllo\n" is a sequence of bytes, the UTF-8 of its text: "é" is the two bytes 0C3H, 0A9H. Both characters and strings take the escapes \n (line feed), \t (tab), \r (carriage return), \0 (zero), \\, \', \", \u{H...} (the code point with hexadecimal value H…, up to 10FFFFH, in a string its UTF-8) and, in strings only, \xHH (the byte with hexadecimal value HH, which needn’t make valid UTF-8). In an escape, the hexadecimal digits may be capitals or not. A character, or a string in double quotes, ends on the line it starts on.

+

Raw strings. `C:\tmp\"a b"` is a string written between backquotes: its bytes are the text between them as it stands, with no escapes, so \ and " are themselves. A raw string may run over lines, and each line break in it is a line feed, part of the string; a carriage return in it is left out.

+

A raw string whose opening backquote ends its line, and whose closing backquote has only blanks (spaces and tabs) before it on its line, is indented: the text is its lines between those two, each without the closing line’s blanks at its start, and each ending in a line feed. So a long text may stand at the indentation of the code around it:

+
proc usage;
+begin
+    Out.str(`
+        usage: tool [-v] file ...
+          -v  say what is done
+        `);
+end;
+

writes "usage: tool [-v] file ...\n -v say what is done\n". Each line of an indented raw string must start with the closing line’s blanks, the same spaces and tabs in the same order, or it is an error; a line holding only blanks is an empty line of the text. A raw string that isn’t indented is the text between its backquotes as it stands.

+

A raw string can’t hold a backquote; a text that needs one joins it with +, as "`". Everywhere else a raw string is a string, as one in double quotes is.

+

Messages give the line and the column, counted in characters (section 10).

+

Comments are (* … *) and nest. A comment ends at the *) that closes it, wherever that stands, so one that quotes *), as in x*) of a pattern, writes it apart: x* ). By convention, the comment just before an exported declaration is its documentation, and the one before module is the module’s.

+

Operators and delimiters:

+
+  -  *  /  &  |  ~  =  #  <  <=  >  >=  :=  :  ;  ,  .  ..  ...  (  )  [  ]  {  }  ^
+

| is also what starts an arm of match (section 7.4); an arm comes where a statement could, never after an operand, so the two don’t mix.

+

3. Modules

+
Module     = "module" ident [ "(" ModParams ")" ] ";"
+             { Import } { Link } [ Check ] { Declaration }
+             [ "begin" Statements ] "end" ident "." .
+ModParams  = ident { "," ident } { ";" ident ":" "proc" Signature } .
+Import     = "import" ImportItem { "," ImportItem } ";" .
+ImportItem = ident [ ":=" ident [ "(" Type { "," Type } ")" ] ] .
+Link       = "link" ( string | "static" ) ";" .
+Check      = "check" "off" ";" .
+

A module lives in a file of its own name: module Out is Out.raz. The name after end repeats the module’s name.

+

Exports. A name declared at the top of a module with * after it is exported: other modules can use it as Module.name. Record fields are exported the same way. Everything else is private to the module. An exported variable can be read by the modules that import it, but only its own module changes it. Outside it, the variable is a value, not a variable: nothing that could write it, or let something else write it, may name it or a field or element of it. So it can’t be assigned, passed as a var argument, changed by INC, DEC or NEW, or given to SYSTEM.ADR; an array in it is sliced, or used where a slice is expected (the silent conversion of an array, section 5.10), only as a []const T, whose elements can’t be written (section 5.3); a slice in it may be sliced, since that makes a new slice and can’t change the variable; in match, its arms’ names stand for the fields of a copy. It can be read, copied and compared, and a copy is the importer’s own. What a pointer or a slice in it points at is another variable, and isn’t held to this: with s: []U8 exported, M.s[0] := 0 writes what M.s points at, not M. A module that means to share an array for reading exports it; for writing, it exports a pointer to it, or a procedure that returns a slice of it.

+

Imports. import Out; makes Out’s exports available as Out.x. import O := Out; uses the name O instead. A module can’t import itself, directly or through others.

+

import SYSTEM. SYSTEM is no file but a module the language gives, of the operations that reach memory other than through the program’s variables, or let something outside the program do so. A module that does any of these says import SYSTEM;, and it is an error to do them in one that doesn’t:

+ +

SYSTEM can’t be imported under another name, so that every module that reaches memory so says it by that name. What such a module does is its own to get right: section 10 says what isn’t defined. A module that imports one that says import SYSTEM needn’t say it itself; it trusts that module as it trusts the library, whose Rt, Mem, Heap, Sys, Thread and others say it.

+

Generic modules take types as parameters:

+
module List(T);
+type
+    Node* = record next*: ^Node; val*: T; end;
+...
+end List.
+

An import gives the arguments: import Ints := List(I64);. Each distinct list of arguments makes one instance: the module compiled with T standing for I64. Two imports of List(I64), in any modules, share one instance, its variables and its ERRORs with it: two lists of arguments are the same when their types are the same (section 5.10), an alias as what it stands for, and their procedures are the same procedures. Since every instance is checked on its own, an operation the argument type doesn’t support (adding two records, say) is reported as an error in that instance.

+

An instance is made where its module is first used, not at the import: so the arguments may name types the importing module declares after its imports, as long as they are declared before that first use. The instance is made before the code of the procedure, or the module body, that first uses it, and its arguments are read in the scope there.

+
import Table := Map([]U8, Colour, Str.hash, Str.eq);
+
+type Colour = (red, green, blue);
+
+var names: Table.Map;   (* the instance is made here *)
+

What a generic module needs to do with its types, beyond moving them about, it is given as procedures, after the types:

+
module Map(K, V; hash: proc(k: K): U64; eq: proc(a, b: K): BOOL);
+
import Names := Map([]U8, I64, Str.hash, Str.eq);
+

A procedure argument names a procedure, not a variable or an expression, and its signature, with the type arguments put in, must be the parameter’s. Inside the module, hash(k) calls it directly. Two imports make the same instance only if their types and their procedures are the same.

+

Finding modules. The compiler looks for module Name in the main module’s directory, then in each directory given with -I, then in the user library directories, then in the lib directory beside the compiler. User libraries live in $HOME/.raz/lib by default. RAZ_PATH, when set, replaces that default with a colon-separated list of directories; an empty value disables user libraries. Empty entries are ignored. With no nonempty HOME, there is no default. Paths are not searched recursively; relative paths are relative to the compiler’s working directory, and ~ and variables inside them are not expanded. Install a library’s source files directly in one of these directories, with its target-specific files beside them. In each directory the compiler takes the first of Name.OS-ARCH.raz, Name.OS.raz, Name.ARCH.raz and Name.raz that exists, where OS-ARCH is the target, for now only linux-x86_64. So a module whose code depends on the machine or the system comes in one file per target, and the modules that import it don’t change. Machine code (section 8) and system calls belong in such files.

+

One module to a name. A program has one module of each name, so the compiler reports an error, naming the files, if a module it looks for has files in more than one of these directories, rather than take the first: a Buf.raz beside a program would otherwise stand in for the library’s Buf in every module that imports it, the library’s own among them. A link is the exception: a file that is a symbolic link to one of the module’s files in a later directory chooses that file, so that a directory holding a link to lib/Sys.raz builds a program over the C library’s Sys on Linux too.

+

Names are flat. The names of a program’s modules are one space, with no packages or paths. So the names of the library’s modules (the library, doc/raz-lib.md) are kept for it: a program or another library doesn’t name a module of its own Arena, Buf, C, Files, Fmt, Guarded, Heap, List, Lock, Map, Math, Mem, Opt, Out, Rt, Sort, Str, Sys, SYSTEM, Task or Thread, nor any name the library takes later. The modules of any other library share a prefix of their own, as an X11 library’s Xauth and Xkeys do, and a program that wants a shorter name imports one: import Auth := Xauth;.

+

The compiler holds every file of such a module to the same interface. When it takes one of Name.*.raz, it also reads the declarations of the others beside it, and of Name.raz if there is one, and reports an error unless they all export the same names, each the same kind of thing:

+ +

Two types here are the same if they are built alike, a name in one file standing for the same name in another.

+

Module bodies. A module may end with begin and statements, its body. Every module’s body runs once, before the main module’s main: a module’s body runs after the bodies of the modules it imports, in the order of its imports, and once however many modules import it. Each instance of a generic module has its body run once. Module variables are zero before any body runs. return; ends a body early.

+

link "libX11.so.6"; names a shared library to load at run time, for the extern declarations of section 9, in a module that imports SYSTEM. link static; says the module needs a program without C (section 10): it makes its own system calls, or its own threads, which the C library wouldn’t know about.

+

check off;, after the links, in a module that imports SYSTEM, leaves out of the module’s own code the checks of indexes and slice bounds of section 6.5, and that a slice of a pointer doesn’t run backwards (section 6.4), for speed where the program is sure of them. An index out of range there reads or writes whatever memory it reaches, and what follows isn’t defined. Every other check stays, and the module’s callers keep theirs. An instance of a generic module follows the generic module’s own check line, not that of the module that made it.

+

4. Declarations

+
Declaration = "const" { IdentDef [ ":" Type ] "=" Expr ";" }
+            | "type" { IdentDef "=" Type ";" }
+            | "var" { IdentList ":" Type ";" }
+            | ProcDeclaration ";"
+            | ExternDeclaration ";" .
+IdentDef    = ident [ "*" ] .
+IdentList   = IdentDef { "," IdentDef } .
+

A name must be declared before it is used, with two exceptions: the base type of a pointer may name a type declared later in the same type section (so that two records can point at each other), and so may a parameter or a result of a procedure type there, however passed (so that a record’s callback can take the record, section 5.9); and a procedure may be declared forward and defined later (section 8).

+

Constants are evaluated by the compiler. Their expressions use only literals, other constants, operators, conversions, SIZE, OFFSET, the LEN of arrays and strings, MIN, MAX, ABS, ROL, ROR, CLZ, CTZ, POPCOUNT, and a variant’s cases. A constant is an integer, a real, a BOOL, a name of an enumeration, a set, a string, an array, a record, a variant or an ERROR. A constant of an integer type wraps as the program would: U8(250) + 10 is 4. Dividing by zero in a constant is an error, and so is dividing the smallest value of a signed type by -1, with div or mod, which stops a program (section 6.1). A string constant can be indexed and sliced as an array of U8 is, and its LEN is its length in bytes. + joins two string constants into one:

+
const Text = "the cat";
+    Line = Text + "\n";
+...
+w := Text[4..7];    (* "cat" *)
+

A constant with a type is an ERROR (section 5.8), an array, a record or a variant, and the value of an array or record constant is a literal (section 6.5) of constants, that of a variant one a case built from constants, as a program builds one (section 5.6). Its elements and fields are integers, reals, BOOLs, enumerations, sets, ERRORs, procedures, nil, a string for a []const U8, an array constant, an array literal or the empty slice for a []const T of its element type, and arrays, records and variants of these; no other pointer. A named constant stands for its literal wherever an array, record or variant is wanted. A variant constant must have a type: const D = dot; is an error, const D: Shape = dot; isn’t.

+
const Primes: [5]I64 = [2, 3, 5, 7, 11];
+type Rule = record class: []const U8; tag: INT; float: BOOL; end;
+const Rules: [2]Rule = [{class: "firefox", tag: 2}, {class: "mpv", float: true}];
+const Shapes: []Shape = [circle(1.0), rect(2.0, 3.0), dot];   (* Shape of section 5.6 *)
+const Rows: [][]const INT = [[1, 2], [3]]; (* each row an array constant of its own *)
+...
+p := Primes[i];
+

It is used as a variable of that type is, but can’t be changed: an array constant can be indexed and sliced and its LEN is n, a record constant’s fields can be read, and either can be assigned, compared as its type allows, and passed. A slice of it, or of an array in it, is a []const T (section 5.3), as a string’s is. A part of it isn’t a constant, even at a constant index.

+

An array constant may be typed []T, with no length: its length is then its literal’s, as a string constant’s is the string’s, and it is an array constant of that length, [n]T, in all else. If its literal is [], it is no array but the empty slice, as a slice variable starts: a value of type []T, used as a slice is, and LEN of it is 0 but not a constant.

+
const Wide: [][2]I32 = [[1100H, 115FH], [2E80H, 303EH], [0AC00H, 0D7A3H]];
+    Count = LEN(Wide);        (* 3, a constant *)
+    Narrow: [][2]I32 = [];    (* the empty slice *)
+

Variables of a module live as long as the program; variables of a procedure live as long as its call. Both start at zero: every byte of them is zero. So a number starts as 0 (0.0 for F32 and F64), a BOOL as false, a pointer, procedure or ERROR as nil, a slice as the empty slice (ptr is nil, len is 0), a variant as its first case with its fields zero, a set as the empty set, and an enumeration as its first name. No variable is ever read before it has a value.

+

5. Types

+
Type      = QualIdent
+          | "[" Expr "]" Type                 (* array *)
+          | "[" "]" [ "const" ] Type          (* slice *)
+          | "^" [ "VOLATILE" ] Type           (* pointer *)
+          | [ "packed" ] "record" { IdentList ":" Type ";" } "end"
+          | "variant" { Case ";" } "end"
+          | "(" ident { "," ident } ")"       (* enumeration *)
+          | "set" "of" QualIdent
+          | "proc" Signature .
+Case      = ident [ "(" FieldList { ";" FieldList } ")" ] .
+FieldList = ident { "," ident } ":" Type .
+QualIdent = [ ident "." ] ident .
+

5.1 Basic types

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TypeSizeValues
I8 I16 I32 I641, 2, 4, 8signed integers, two’s complement
INTan address’s: 8 on x86-64signed, as big as an address
UINTan address’sunsigned, as big as an address
U8 U16 U32 U641, 2, 4, 8unsigned integers
BOOL1false (0), true (1)
F324IEEE 754 single precision
F648IEEE 754 double precision
+

INT is the everyday integer: lengths, indexes and sizes are INTs. It is as big as an address, and at least 16 bits, as UINT is, on every target; so it is the integer a pointer converts to (section 6.7), and a word the atomic built-ins work on (section 6.8). INT and I64 are two types, even where they have the same size: an INT goes silently into an I64 wherever it meets one, in an expression too (sections 5.10 and 6.1), and an I64 becomes an INT only by INT(x), which may drop bits on a smaller target. A type bigger than the largest INT in bytes is an error.

+

F32 and F64 exist only on a target that has reals (appendix A). On one that hasn’t, a real literal, and a use of F32, F64 or of a name whose type is made of them, is an error; a declaration that no used code names isn’t, so a module like Fmt keeps one interface on every target.

+

Each is aligned as the target’s C aligns it: to its size on x86-64. So are ERROR (section 5.8), pointers and procedures, each as big as an address; a slice is aligned as an address is.

+

5.2 Arrays

+

[n]T is n elements of type T, one after another. n is a constant greater than zero. Arrays are values: assigning one copies it.

+

5.3 Slices

+

[]T is a view of elements that live elsewhere: a pointer to the first and a count, two addresses’ worth, 16 bytes on x86-64.

+
Slice = record ptr: ^T; len: INT; end;    (* its layout *)
+

A slice is made from an array (a[2..5], or an array used where a slice is wanted), from another slice, or from a pointer (p[0..n]). It doesn’t own what it points at. LEN(s) is its count, and SYSTEM.PTR(s) its pointer (section 6.8).

+

[]const T is a slice whose elements can’t be written through it. It is laid out as []T is. Its elements are read, and it is sliced, and a slice of it is a []const T too; but an element of it isn’t assigned, given to COPY or FILL as the destination, changed by INC or DEC, passed as a var argument, or written through a view, and SYSTEM.ADR of one is an error. A []T and an array of T go silently where a []const T is wanted, never the other way (section 5.10). So a procedure that only reads a slice takes a []const T, and every caller’s slice or array fits it:

+
proc count(s: []const U8; c: U8): INT;   (* reads s, and says so *)
+

A string literal and a slice of a constant are []const T (sections 4 and 5.10). Another slice may still point at the same elements and write them: const says what this slice may do, not what the elements are.

+

5.4 Pointers

+

^T is the address of a T, as big as an INT. nil is the pointer to nothing.

+

^VOLATILE T is the address of a T that something besides the program may read or change: a device register, memory shared with another process. Section 7.6 says what that promises.

+

5.5 Records

+
type Cell = record ch: U8; attr: U8; end;
+

Fields are laid out in order as C lays them out: each at the next multiple of its own alignment, and the whole record padded to a multiple of its largest alignment. A record declared like a C struct has the same layout as that struct. A record may have no fields; its size is then 0.

+

A packed record has no padding: each field starts at the byte after the field before it, and the record’s alignment is 1. So a field of a packed record may sit at any address. It is read and written like any other, on every target, even one whose machine can’t reach a misaligned word in one access: the compiled code reaches it in parts there. But a field of a packed record whose type is aligned to more than 1 byte, and anything inside it, has no address: SYSTEM.ADR of it, a var parameter of it and a slice of it are errors. Nor can it be reached through a ^VOLATILE pointer, since a misaligned access can’t be promised as one access (section 7.6). Its value can be copied out and back in.

+

The bytes of a value of more than one byte are in the target’s order (appendix A). A file or a message in an order of its own is read and written a byte at a time, as Str.le, Str.be, Str.putLE and Str.putBE do (the library, doc/raz-lib.md).

+

5.6 Variants

+

A variant holds one of several cases, each with its own fields:

+
type
+    Shape* = variant
+        circle(r: F64);
+        rect(w, h: F64);
+        dot;
+    end;
+

The case names are declared in the scope around the type, so circle can be used directly, and as Shapes.circle from another module if Shape is exported. A case with fields is built by calling it like a procedure, circle(2.0); a case without fields is just dot. The only way to read the fields is match (section 7.4).

+

Layout: an INT tag (0 for the first case, 1 for the second, and so on), then the space for the fields. Each case’s fields are laid out in that space as a record’s would be, after the tag, and the cases share it, so the variant is as big as its largest case needs, padded to its alignment, the largest of an INT‘s and its fields’. variant a(x: U8); b(y: I64; z: U8); end is 24 bytes on x86-64. A variant that starts at zero therefore holds its first case.

+

5.7 Enumerations and sets

+
type
+    Color* = (red, green, blue);
+    Colors* = set of Color;
+

An enumeration is a list of names, in order. Like the cases of a variant, the names are declared in the scope around the type. An enumeration has at most 256 names and takes 1 byte; the first name is 0, the next 1, and so on.

+

A name of an enumeration may also be written with its type, Color.red, and one imported with the type’s module, M.Color.red. Two enumerations of a scope may share a name, and an enumeration may have a name that something else of its scope has, a constant, a variable or a procedure: such a name is written with its type, Elem.bold. Written alone, it names the one declaration of it that isn’t an enumeration’s, if there is one, and is an error if there isn’t:

+
type
+    Style = (bold, italic);
+    Elem = (para, bold, rule);
+proc rule;                  (* a procedure, beside Elem's rule *)
+...
+s := Style.bold;  e := Elem.bold;  e := Elem.rule;
+e := para;                  (* para is Elem's alone *)
+rule;                       (* the procedure *)
+s := bold;                  (* an error: write Style.bold or Elem.bold *)
+

The type is never taken from where the name stands: s := bold is an error though s is a Style.

+

set of E, for an enumeration E of at most 64 names, holds any choice of E’s names: bit i stands for the name at position i. It takes the smallest of 1, 2, 4 and 8 bytes that has a bit for each name, so a set can stand for a C flags word.

+

5.8 Errors

+
const NotFound*: ERROR = "not found";
+

An ERROR is how a procedure says it failed: by convention the last of its results, and nil when nothing failed. A caller that can’t deal with a failure itself passes it on with try (section 7.8).

+

ERROR is a basic type as big as an address. A value of it is made only by a constant declared as above, and each such declaration makes an error different from every other, whatever its message: two modules that both declare "not found" have two different errors. A generic module makes its errors once per instance. nil is no error. Only a string makes a new error: an ERROR constant whose value is another ERROR constant is that same error, so const Short*: ERROR = PictBase.Short; passes on an error of another module, and Short = PictBase.Short holds.

+

Errors compare with = and # only, by which declaration made them, never by their message. MSG(e) is the message, a []const U8; MSG(nil) is "".

+
proc find*(key: I64): (^Node, ERROR);
+...
+n, err := Table.find(7);
+if err = Table.NotFound then ... end;
+

5.9 Procedure types

+
type Compare = proc(a, b: I64): BOOL;
+

A value of a procedure type is the address of a procedure with that signature, as big as an address, or nil. Two signatures are alike when their parameters have the same types, each var, const or neither alike, in order, and their results are the same types; the parameters’ names don’t matter.

+

A parameter or a result of a procedure type in a type section may name a type declared later in it, a record that is being declared too:

+
type Lines = record each: proc(var r: Lines; s: []U8); n: INT; end;
+

A procedure value is an address whatever its signature, so the record’s size doesn’t depend on it; the type is whole when a call is made. A field of the record’s own type, by value, is still an error, since nothing would be big enough.

+

5.10 Same and assignable

+

Two named types are the same only if they are the same declaration. Two anonymous pointer, array, slice, set or procedure types are the same if they are built alike: ^I64 is ^I64 wherever it is written. A record, variant or enumeration, though, is a type of its own wherever it is written, named or not: two record x: I64; end are two types. A named and an anonymous type are the same if the named one is built like the anonymous one, so that p := SYSTEM.ADR(n) works for p: NodePtr with type NodePtr = ^Node. Sameness doesn’t pass through the anonymous type: with type P1 = ^Node; P2 = ^Node;, each of P1 and P2 is the same as ^Node, but they are two declarations, so not the same as each other.

+

A type declared with only a name on the right, type Count = I64;, is another name for that type, not a new one.

+

A value of type A can be assigned to a variable of type B (and passed to a parameter of type B, and returned as a B) if they are the same type, or if:

+ +

A string’s bytes are constant. A string literal, or a slice of a string constant, is a []const U8, so writing them is an error. A [n]U8 made from a string is a copy, the program’s to change. A ^U8 made from one, for C, points at the constant bytes, and writing through it isn’t defined (section 10).

+

Nothing else converts silently. In particular, there is no other conversion between integer types, between integers and reals, or between F32 and F64, without a written conversion (section 6.7). An INT widens to I64, and a UINT to U64, wherever its value goes where an I64 is wanted: in a, b := f(x) and return f(x) as in any other assignment, to the bounds of a for and the step of INC and DEC whose variable is an I64, and in an expression, where it meets an I64 (section 6.1). The types themselves stay two: a ^INT isn’t a ^I64, an INT variable isn’t passed to a var parameter of type I64, and a procedure returning an INT isn’t of a procedure type returning an I64.

+

A U8, I8 or I16 widens to INT, and a U8 or U16 to UINT, in the same places, as an INT to I64: assigned, passed, returned, in a, b := f(x), to a for’s bounds and INC and DEC’s step, and in an expression, where it meets an INT or a UINT (section 6.1); not in return f(x), which passes f’s results on as they are. They widen only that far: a U8 meets an I64 only as INT(b) or I64(b). And they widen only as values that are moved: a variable, an element, a field, a call’s result or a conversion’s. What an operator gives on them doesn’t: it was computed in their type, and has wrapped there. With a, b: U8 holding 200 and 100, a + b is 44, so n := a + b, for an INT n, is an error; n := INT(a) + b is 300, and says where the sum is made.

+
var s: []U8; n, d: INT;
+n := s[i];                  (* an element: widens *)
+n := n * 10 + s[i] - '0';   (* n * 10 + s[i] is an INT, and so the rest *)
+d := s[i] - '0';            (* an error: a U8, which may have wrapped *)
+d := INT(s[i]) - '0';       (* below '0' too, it is negative *)
+

6. Expressions

+
Expr       = Conjunct { "or" Conjunct } .
+Conjunct   = Relation { "and" Relation } .
+Relation   = SimpleExpr [ RelOp SimpleExpr ] .
+RelOp      = "=" | "#" | "<" | "<=" | ">" | ">=" | "in" .
+SimpleExpr = [ "-" ] Term { AddOp Term } .
+AddOp      = "+" | "-" | "|" | "xor" .
+Term       = Factor { MulOp Factor } .
+MulOp      = "*" | "/" | "div" | "mod" | "&" | "shl" | "shr" .
+Factor     = number | char | string | Designator | "(" Expr ")"
+           | "not" Factor | "~" Factor
+           | "[" [ Expr { "," Expr } ] "]"
+           | "{" [ Element { "," Element } ] "}"
+           | "^" [ "VOLATILE" ] Type "(" Expr ")"
+           | "try" Designator .
+Element    = Expr | ident ":" Expr .
+Designator = QualIdent { Selector } .
+Selector   = "." ident | "^" | "[" Expr [ ".." Expr ] "]"
+           | "(" [ Expr { "," Expr } ] ")" | "." "(" Type ")" .
+

The operators bind in the order of the grammar: not, ~ and try (section 7.8) most tightly, then the multiplying operators, then the adding ones, then the relations, then and, then or. So a + b * c = d is (a + (b * c)) = d, x & 0FH = 0 is (x & 0FH) = 0, and i < n and a[i] # 0 or done is ((i < n) and (a[i] # 0)) or done. A unary minus applies to the first term: -a * b is -(a * b).

+

and, or and not are for BOOLs only; &, |, xor and ~ are for integers only.

+

A pointer to a record isn’t the record: its fields are p^.f, never p.f, and the elements of a pointer to an array are p^[i]. A statement starts with a name or try, so ^T(x)^ := v isn’t one; a view, mem[a].(I64) := v (section 6.9), says it without a pointer.

+

6.1 Integers

+

Both operands of + - * div mod & | xor, and of a relation, have the same integer type, or one is an untyped constant that takes the other’s type, which it must fit, or one is an INT and the other an I64 (a UINT and a U64), and the INT widens to I64, or one is an INT and the other a U8, I8 or I16 (a UINT and a U8 or U16) that no operator gave, and it widens to INT (section 5.10). So do v and k in INC(v, k) and DEC(v, k), where only k widens: an I64 k isn’t added to an INT v. The result has that type and wraps around at its width: in U8, 200 + 100 is 44. A unary minus wraps too: for x of an unsigned type, -x is 0 - x. Other integer types are never mixed, whatever their sizes: with i: I32, i < LEN(s) is an error, and i should be an INT; with c: U8, c < LEN(s) is an INT comparison. With pos: I64, pos + LEN(s) is an I64.

+

Where the report asks for an integer and names no type, as an index, a slice’s bound, a shift’s count, a pointer’s offset i in p + i, or a conversion’s operand, any integer type will do, and its value is taken. On a target whose INT is narrower, a pointer’s offset is cut to an INT.

+

SIZE(T), SIZE(T.f), OFFSET(T, f), and LEN of an array or a string constant, are untyped constants, like a literal.

+

div rounds toward zero and mod takes the sign of the dividend, as in C: -7 div 2 is -3, -7 mod 2 is -1. Dividing by zero, and dividing the smallest value of a signed type by -1, stop the program (section 10), whatever the type and the target.

+

& (and), | (or), xor and ~ (not) work on every bit. x shl n and x shr n shift by n modulo the width of x’s type, in bits: for x: U8, x shl 9 is x shl 1. shr brings in copies of the sign bit for signed types and zeros for unsigned ones. n may be of any integer type. The result has x’s type, cut to its width: in U8, 0C0H shl 1 is 80H. If x is an untyped constant, so is the result, and it doesn’t wrap: 1 shl 9 is 512, which doesn’t fit a U8.

+

ROL(x, n) and ROR(x, n) (section 6.8) rotate x left and right by n bits modulo its width: the bits shifted out at one end come back in at the other. For x: U8 holding 81H, ROL(x, 1) is 03H and ROR(x, 1) is 0C0H. x is of an unsigned integer type, U8, U16, U32, U64 or UINT, and the result has its type; n may be of any integer type. An untyped constant has no width, so ROL(1, 3) is an error, and ROL(U32(1), 3) is 8. Hashes and ciphers are written with rotations, which machines do in one instruction, and which two shifts and an or say only at more length: ROR(x, 7) is x shr 7 | x shl 25 for a U32 x.

+

CLZ(x) and CTZ(x) (section 6.8) count the zero bits above the highest one in x and below the lowest one, and POPCOUNT(x) counts its one bits. x is of an unsigned integer type, and the result is an INT; for x: U8, CLZ(x) is 7 when x is 1, and CLZ(x) and CTZ(x) are 8 when x is 0. The width is the type’s, as for ROL; an untyped constant has none, so CLZ(1) is an error, and CLZ(U64(1)) is 63. POPCOUNT(x) may also take a set, and counts its members. MIN(T) and MAX(T) are the smallest and the largest value of the integer type T, untyped constants: MAX(U8) is 255 and MIN(I16) is -32768; MAX(U64) and MAX(UINT), above the largest I64, have their own type, as a hexadecimal number above it has (section 2). Each of the five, given constants, is a constant (section 4).

+

ABS(x) (section 6.8) is x without its sign, of x’s type, for an integer or a real. For a signed integer it is -x if x < 0, so the smallest value of the type gives itself, as -x does; for an unsigned type it is x. For a real it clears the sign bit: ABS(-0.0) is 0.0, ABS of a NaN is a NaN, and of minus infinity is infinity. Of a constant it is a constant; of an untyped one, an untyped one, ABS(-5) is 5, and a result beyond the I64s, ABS(MIN(I64)), is an error, as for any arithmetic on untyped constants (section 2).

+

Relations compare as signed or unsigned according to the type.

+

6.2 Booleans

+

and and or evaluate their right operand only when it decides the result. not negates, and = and # compare; # is “different”.

+

6.3 Reals

+

+ - * / and the relations work on F32 and on F64. Both operands have the same type, or one is a real constant, which takes the other’s type (section 2). The result has that type: F32 arithmetic is done in single precision, rounded at each step as C rounds float. A constant expression of reals is evaluated in double precision, then rounded once to the type it takes.

+

Relations are IEEE 754’s: a NaN is equal to nothing, itself included, so for a NaN x, x # x is true and every other relation with it is false. Dividing by zero gives an infinity or a NaN; arithmetic on reals never stops the program.

+

6.4 Pointers

+ +

p + i, p - i, p[i] and p[lo..hi] reach memory no variable of the program names, and are allowed only in a module that imports SYSTEM (section 3). p^, p - q and comparing are allowed in any.

+

6.5 Arrays and slices

+

a[i] is an element of an array or slice, and a[lo..hi] is the slice of the elements from lo up to but not including hi. Both are checked: i must be below the length, and 0 <= lo <= hi <= length. A check that fails prints to standard error where it is, as file, line and column, and what failed, with the values involved (index 7 is out of range for a length of 5), and stops the program with status 2. An index or a bound may be of any integer type, and is checked by its value, whatever its type: a negative I8, or a U64 past the length, fails like any other. A module that says check off; (section 3) leaves these checks out of its code.

+

Literals. [e1, e2, ...] builds an array, and {f: e, g: e, ...} a record, where the type it must have is known: assigned to a variable, passed to a parameter, returned, compared with a value of that type, or an element of a bigger literal. The elements must be assignable to the element type, and an array literal for [n]T has exactly n of them. A record literal names its fields, in any order, each at most once; the fields it leaves out are zero, so {} is the record with every field zero. An array literal used as a slice is a hidden variable of the procedure, and lives as long as its call; the empty one, [], is the empty slice, as a slice variable starts (section 4), and no variable at all.

+
c := {ch: 'A', attr: 7};
+Fmt.print("{} of {}\n", [Fmt.int(n), Fmt.int(m)]);
+

Arrays and strings compare. Two operands that are each a []T or a [n]T, of the same element type T, are = when they have the same length and the same elements, and # otherwise, where T is an integer type, BOOL, an enumeration, a set or a pointer type. A string literal compares as a []const U8. The comparison is code of its own where it stands, a check of the lengths and then of the bytes, not a call.

+

Arrays of reals don’t compare this way, since -0.0 = 0.0 and a NaN is equal to nothing, though their bytes say otherwise; nor do arrays of records, variants or procedures, nor records and variants themselves. Write a loop. Ordering strings is the library’s Str.cmp.

+

6.6 Enumerations and sets

+

Enumerations compare with all six relations, by position, and an enumeration can be the variable of a for loop and the expression of a match (section 7.4).

+

{red, blue} is a set, of the set type of its names’ enumeration; {} is the empty set, where the type it must have is known. On two sets of the same type, + is union, * intersection and - difference; = and # compare, and <= and >= are “is a subset of” and “is a superset of”. x in s is true if x, a value of the enumeration, is in the set s.

+

6.7 Conversions

+

A type name applied like a procedure converts: I32(x), F64(n), ^Cell(addr). A pointer type written out uses the ^ form of the grammar: ^VOLATILE U32(0FEE00000H).

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FromToResult
integerintegerthe value cut to the new width, or extended by its sign (signed) or zeros (unsigned)
integerF32, F64the nearest real
F32, F64integerrounded toward zero; a NaN, or a real out of the range of I64, gives the smallest I64, then cut
F32F64the same value
F64F32the nearest F32; too big a value gives an infinity
enumerationintegerits position
integerenumerationthe name at that position; a position out of range is a failed check (6.5), and in a constant an error
BOOLinteger0 for false, 1 for true
setintegerits bits
integersetthe low bits, as many as the set has
INT, UINTpointer, procedurethe address
pointer, procedureINT, UINTthe address
pointer, procedurepointer, procedurethe same address, seen as the new type
+

There are no others: none from an integer to BOOL (x # 0 says it), none between pointers and integers other than INT and UINT, and none to or from records, arrays, slices, variants or ERROR. The last three rows, from an integer to a pointer or a procedure, back, and from one pointer or procedure type to another, are allowed only in a module that imports SYSTEM (section 3). An untyped integer constant converts to a pointer as an INT does, as in ^VOLATILE U32(0FEE00000H); it isn’t assigned to a pointer without the conversion. A conversion of a constant is made by the compiler, by the same rules: U8(300) is 44. U64(a = b) is 0 or 1, and 0 - U64(a = b) is a mask; this is how a comparison is used with no if.

+

6.8 Built-in procedures

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CallResult
SIZE(T)the size of type T in bytes, an untyped constant; T is a type, not a variable
SIZE(T.f)the size of field f of the record type T, an untyped constant
OFFSET(T, f)the byte offset of field f in the record type T, an untyped constant
SYSTEM.ADR(x)the address of variable x, a ^T
LEN(a)the number of elements of an array or a string constant (an untyped constant) or of a slice (an INT)
SYSTEM.PTR(s)the address the slice s starts at, a ^T for s: []T or []const T, unchecked; for an array a, that of a[0..LEN(a)]
BYTES(x)the bytes of x as a []U8: for a slice s: []T, its LEN(s) * SIZE(T) bytes, a []const U8 for a []const T; for a variable of any other type T, its SIZE(T) bytes
NEW(p, a)sets p: ^T to a fresh, zeroed T from the allocator a: ^Mem.Allocator, or to nil if a has no room
MSG(e)the message of the error e, a []const U8
COPY(d, s)copies the elements of s to the start of d, both arrays or slices of one type T; LEN(s) must be at most LEN(d)
FILL(d, x)sets every element of d, an array or a slice of elements of type T, to x, a value of T
SYSTEM.SYSCALL(n, x1, ..., x6)Linux system call n with up to six arguments, each a pointer or an integer no wider than INT; the raw result, an INT (a negative number is -errno)
INC(v), INC(v, k)adds 1, or k, to the integer variable v; it wraps, like +
DEC(v), DEC(v, k)subtracts 1, or k, from v
FENCEa full memory barrier
CAS(v, old, new)if v = old, sets v := new and returns true; atomically
XCHG(v, x)sets v := x and returns the value before, atomically
XADD(v, x)adds x to v and returns the value before, atomically
ABS(x)x without its sign, of x’s type; for an integer, -x if x < 0, so the smallest I64 gives itself, as -x does; for a real, the sign cleared; x of a numeric type (section 6.1)
ROL(x, n), ROR(x, n)x rotated left, or right, by n bits modulo its width; x of an unsigned integer type (section 6.1)
CLZ(x), CTZ(x)the number of zero bits above the highest one in x, or below the lowest one, an INT; the width of x’s type if x is 0; x of an unsigned integer type
POPCOUNT(x)the number of one bits in x, or of members of the set x, an INT; x of an unsigned integer type or a set
MIN(T), MAX(T)the smallest, or the largest, value of the integer type T, an untyped constant; any other type is an error
ARGC()the number of command line arguments, an INT
SYSTEM.ARGV()the arguments, a ^^U8 (C strings)
+

SYSTEM.SYSCALL exists only on Linux targets. Other systems have no stable system call interface, and their modules call the C library instead (section 9).

+

NEW(p, a) calls a^.alloc(a, SIZE(T), A), where A is the alignment of T, and zeroes the bytes it gets if they aren’t nil. Mem.Allocator (the library, doc/raz-lib.md) is the one type of the library the language names.

+

SIZE(T.f) and OFFSET(T, f) ask about a type’s field, not about storage, so SIZE still takes no variable. f is one field name: not a path, a.b, and not a case of a variant, whose cases share their place. A record handed to C is checked against C’s struct with them, as C checks one with offsetof and sizeof.

+

BYTES(x) is the bytes of x, as a []U8 that can be read and written: for a slice s: []T, the LEN(s) * SIZE(T) bytes it holds; for a variable of any other type T, its SIZE(T) bytes.

+
n := Sys.write(fd, BYTES(samples));     (* samples: []I32 *)
+n := Sys.read(fd, BYTES(h));             (* fills h: Header, a record *)
+

T must be a type a view may take (section 6.9), since writing through the slice must not make a value mean nothing: a BOOL, a set, an enumeration, a slice, a variant, a procedure type, ERROR, or a record or array holding one, is an error; and, outside a module that imports SYSTEM, so is a pointer, or a record or array holding one. The slice is made, and checked, as any slice of the variable is, so its bytes follow the rules for it: the bytes of a local can’t be returned (section 7.3). Of a slice they are its elements, as SYSTEM.PTR(s) gives them, whatever holds the slice, and can be written only if the slice can. Of any other variable they are its own, as SYSTEM.ADR gives them: a const parameter, another module’s variable, a view and a field of a packed record are errors, as they are for SYSTEM.ADR, and so is a volatile variable. x must be a variable: a constant, a string constant too, is an error. The bytes are in the target’s order (appendix A).

+

SYSTEM.PTR(s) is the first of the two words of s (section 5.3), and is not checked. For a slice that isn’t empty it is SYSTEM.ADR(s[0]); for an empty one, where s[0] would stop the program, it is what the slice holds: nil for a slice variable as it starts (section 4) and for [], and for one cut empty from another, t[3..3], an address that mustn’t be read through, as the end of an array mustn’t. So a slice becomes a pointer and a length, for a record or for C, with no test for the empty one first:

+
type Value = record n: INT; p: ^U8; end;
+
+proc valueOf(s: []const U8): Value;
+begin
+    return {n: LEN(s), p: SYSTEM.PTR(s)};      (* "" too *)
+end;
+

and v.p[0..v.n] is the slice again (section 6.4), empty when v.n is 0, whatever v.p is. Reading through the pointer is as unchecked as through any pointer. SYSTEM.PTR(a) of an array may be taken wherever the slice a[0..LEN(a)] may be made, and is an error wherever it may not.

+

COPY is a statement, as INC is. It copies the bytes of LEN(s) elements as one block, as an assignment of an array does, and is right when d and s overlap, as in COPY(a[1..n], a[0..n - 1]). It is checked as a slice is: past LEN(d), it stops the program, unless the module says check off;.

+

FILL is a statement too. d is written as COPY’s destination is, and x is assigned to each element as by :=:

+
FILL(row[a..b], U32(bg));    (* a row of pixels *)
+FILL(window, 0.0);           (* window: [576]F32 *)
+

It is no wipe: it may be left out when nothing reads what it wrote, as any write may (section 7.6).

+

INC and DEC evaluate v once, so INC(a[f(i)]) calls f once. They read v and then write it: two accesses, even through a ^VOLATILE pointer, and not atomic; XADD is the atomic one.

+

For CAS, XCHG and XADD, v is a variable, as for INC, of type INT, UINT or a pointer type (INT or UINT for XADD), on every target, and may be volatile: a counter shared between threads is XADD(count, 1), one reached through a pointer XADD(p^, 1). It is evaluated once, and must have an address, so a field of a packed record and a view are errors, as they are for SYSTEM.ADR. They are sequentially consistent, on every target; how a machine without atomic instructions makes them so is the implementation’s choice (appendix A). ### 6.9 Views

+

A view reads and writes the bytes of a variable as a value of another type. v.(T), with v a variable, is the T whose bytes start where v starts:

+
var mem: [4096]U8; n: I64; x: F64; bits: U64;
+
+mem[16].(I64) := -1;     (* the 8 bytes mem[16] to mem[23] now hold -1 *)
+n := mem[16].(I64);      (* and are read back as an I64: n is -1 *)
+bits := x.(U64);         (* the 8 bytes of x, as a U64 *)
+

A view is a variable, not a value: mem[16].(I64) is made of the 8 bytes mem[16] to mem[23], as p^ is the variable p points at. Reading it reads those bytes; assigning it writes them, and so changes mem. Nothing is copied to make it. It stands wherever a variable may: on the left of :=, as the variable of INC, and with selectors after it:

+
type Header = record magic: U32; count: U32; end;
+var buf: [512]U8; k: U32;
+
+k := buf[0].(Header).count;    (* bytes 4 to 7 of buf, as a U32 *)
+buf[0].(Header).count := 0;
+INC(mem[a].(I64), 8);
+

A view isn’t a conversion. A conversion works on a value, a view on bytes. With x: F64 holding 1.5, I64(x) is 1, the number rounded toward zero, while x.(I64) is 3FF8000000000000H, the bits that hold 1.5. With n: I64 holding 258, U8(n) is 2, the number cut to its low byte, while n.(U8) is the first byte of n in memory, which is the low one only on a target that puts its low byte first (appendix A). When the program means a number, it wants a conversion; when it means the bytes as they lie, a view.

+

The types. T is an integer type, a real type, a pointer type, or a record or array made of these alone, at any depth: the types for which any bytes at all are a value. BOOL, an enumeration, a set, a slice, a variant, a procedure type and ERROR are left out, since bytes that are none of their values would make the program mean nothing. To read one of them from bytes, view the integer and convert it: Colour(mem[a]). v may be of any type, and is a variable: a name of one, a field or element of one, or what a pointer points at; not a constant, nor the result of a call or of an operator.

+

A view makes values from bytes, so where those bytes could be made into an address the module must import SYSTEM (section 3): a view whose T holds a pointer, and a view written over a variable v whose type holds anything but integers and reals, which would change a pointer, a BOOL or a slice behind its type. Reading any variable through a view of integers and reals is allowed in any module.

+

Where its bytes lie. The T lies within the variable v is part of:

+ +

This is checked, as an index is: by the compiler when it can tell, otherwise while the program runs, where a view that runs past the end is a failed check (section 6.5), unless the module says check off;. An element reached through a pointer, p[i].(T), is checked no more than p[i] is, since a pointer has no length.

+

Any address. The T may start at any byte: mem[3].(I64) is an I64 whose first byte is mem[3]. As a field of a packed record is (section 5.5), it is read and written on every target, in parts where the machine needs that; and, as such a field, a view has no address: SYSTEM.ADR of it, a var argument of it and a slice of it are errors. Copy it out to a variable, and back in. A view of a volatile variable is an error too, since its access can’t be promised as one (section 7.6): a device’s registers are reached through a ^VOLATILE pointer to a record of them.

+

Byte order. The bytes are in the target’s order (appendix A). A file or a message whose format fixes an order of its own is read with Str.le, Str.be and the like (section 5.5), if the program is to read it right on every target.

+

Before views. A program used to make a pointer for each access, and may still: mem[a].(I64) := n does what

+
p := ^I64(SYSTEM.ADR(mem[a]));
+p^ := n;
+

does, but with a checked against the length of mem, no pointer variable, and no address of a word that may be misaligned, and no import SYSTEM.

+

v is evaluated once, and its check made, before the bytes are read or written.

+

7. Statements

+
Statements = { Statement ";" } .
+Statement  = Designator [ ":=" Expr ]
+           | "_" ":=" Expr
+           | Target "," Target { "," Target } ":=" Expr
+           | "if" Expr "then" Statements
+             { "elsif" Expr "then" Statements } [ "else" Statements ] "end"
+           | "while" Expr "do" Statements "end"
+           | "repeat" Statements "until" Expr
+           | "for" ident ":=" Expr "to" Expr [ "by" Expr ] "do" Statements "end"
+           | "match" Expr "of" { "|" Arm } "end"
+           | "return" [ Expr { "," Expr } ]
+           | "break"
+           | "continue"
+           | "defer" Statement
+           | "try" Designator .
+Arm        = ( ident { "." ident } [ "(" ident { "," ident } ")" ]
+             | Label { "," Label } | "else" ) ":" Statements .
+Label      = Expr [ ".." Expr ] .
+Target     = Designator | "_" .
+

Every statement ends in ;, including the ones that end in end or until.

+

7.1 Assignment and calls

+

x := e evaluates e and stores it in x; arrays, records, slices and variants are copied. A designator on its own is a call, and any result it returns is dropped: Out.ln;, write(fd, buf);.

+

a, b := f(x); assigns the results of a procedure that returns several (section 8), in order.

+

The blank, _, drops what would be assigned to it: _ := e; evaluates e and drops it, and n, _ := f(x); keeps the first result and drops the second. What is dropped is still evaluated as any expression is: its calls are made, and a volatile variable in it is read (section 7.6). A result dropped by a call standing on its own is a lint an implementation may warn of (section 10); one dropped through _ says it is meant.

+

7.2 Conditions and loops

+

if, while and repeat take BOOL expressions. repeat runs its body at least once and stops when the condition is true.

+

for i := a to b by s do ... end; sets i to a, a + s, … while i <= b (or i >= b if s is negative). i is a variable of an integer or enumeration type, named by its name alone; a and then b are evaluated once, before the first round; s is a constant other than zero, and 1 if left out. a and b have i’s type, or are untyped constants that take it, or are INTs that widen to an I64 i, as with + (section 6.1): so in for i := 0 to LEN(s) - 1, i is an INT or an I64.

+

The loop never steps past b, so i can’t wrap: afterwards i holds the last value it took, or a if the body never ran. The body may assign i. Precisely, for a positive s: at the end of a round, if i <= b and b - i < s, the loop ends with i as it is; otherwise i becomes i + s, wrapping, and the loop goes on while i <= b. A negative s is the same, the other way round.

+

break ends the innermost while, repeat or for it stands in, and the program goes on after it. continue ends the round of the innermost one, as reaching the end of its body would: a while tests its condition again, a repeat tests its until, and a for steps its variable, or ends. There is no goto.

+

A continue passes over the rest of the body, the step of a while or a repeat included, if it stands there: so the step comes first.

+
while i < LEN(t) do
+    ch, n := Str.decode(t[i..LEN(t)]);
+    i := i + n;                         (* before any continue *)
+    if ch = 0ADH then continue; end;    (* a soft hyphen, passed over *)
+    ...
+end;
+

7.3 Return

+

return e; ends the procedure with the result e; return a, b; with several results; return f(x); with the several results of f, if they are the procedure’s own (section 8); return; from a procedure without results. A procedure with results that runs off its end returns zeros, each result as a variable of its type starts (section 4).

+

A slice returned must not point into the procedure’s own frame, which is gone once it returns. It is an error to return, as a slice, a local array, a value parameter that is an array, an array literal other than [], or an array a call returns, or a slice of one, or the BYTES of a local variable, a field or an element of one included:

+
proc short(h: Hex): []U8;      (* Hex = [64]U8 *)
+begin
+    return h[0..8];            (* an error: h is the procedure's copy *)
+end;
+

A slice of a var or const parameter, of a module variable, or of what a pointer points at may be returned: none of them is this procedure’s frame. For a const parameter given a temporary, the slice lives to the end of the caller’s procedure (section 8). A slice of a frame that leaves it some other way isn’t caught, and is the exception of section 10: one held in a local slice variable, or in a record, that is returned; one stored in a module variable or through a pointer; and one that came back from a call, as the slice of a var parameter does to the caller whose local it is.

+

7.4 Match

+
match s of
+| circle(r):  area := 3.14159 * r * r;
+| rect(w, h): area := w * h;
+| dot:        area := 0.0;
+end;
+

match takes a variant, an enumeration, an integer type (a U8 included) or a string, a []U8 or a []const U8; other types are an error. It runs the arm of the case s holds. An arm may name the case’s fields, in order, all of them; the names stand for those fields of s itself, so assigning to one changes s; if s is a constant or a const parameter, they can’t be assigned; if s isn’t a variable, they stand for the fields of a copy. An arm may also leave the fields unnamed. Every case must have an arm, and only one, unless there is an | else: arm, which must come last.

+

match on an enumeration works the same way: each arm names one of the enumeration’s names, or several, separated by commas, for the arm to run when the value is any of them:

+
match op of
+| sPlus, sMinus: kind := additive;
+| sTimes:        kind := multiplicative;
+| else:
+end;
+

Every name must have an arm, and only one, unless there is an | else: arm. A variant’s arm names one case: the fields it may name belong to that case alone.

+

An arm on an enumeration or a variant names its case alone or as it is written anywhere else, with its type, its module, or both (done, Kind.done, Xml.done, Xml.Kind.done), and a qualified name must be a case of the matched type.

+

match on an integer runs the arm whose labels hold its value:

+
match ch of
+| ' ', '\t':      skip := true;
+| '0' .. '9':     digit := true;
+| else:
+end;
+

A label is a constant, or lo .. hi, the constants from lo to hi, both included (unlike a slice, which leaves hi out; lo may not be above hi). Each must fit the integer’s type, and no value may be in two labels. An integer match must have an | else: arm, which may be empty.

+

match on a string, a []U8, a []const U8 or what converts to one (section 5.10), runs the arm one of whose labels it equals, as = compares strings (section 6.5):

+
match word of
+| "add", "plus": op := add;
+| "sub":         op := sub;
+| else:          op := none;
+end;
+

A label is a string constant, and no two labels may be equal; there are no ranges. A match on a string must have an | else: arm, which may be empty. Whether an arm names a case or gives labels is set by the type matched: | Max: is a case of a variant or an enumeration, and a constant for an integer or a string.

+

7.5 Order of evaluation

+

Operands, arguments and the designators of an assignment are evaluated from left to right, and the designators of an assignment before its right side: a[i()] := g() calls i and then g.

+

7.6 Volatile

+

A variable reached through a ^VOLATILE T is volatile, and so is any field or element of it. Each read or write of a volatile variable of a basic, enumeration, set or pointer type is exactly one memory access, of exactly its size, and volatile accesses happen in the order the program writes them. Copying a whole record or array through a volatile pointer is not allowed, since it can’t be one access.

+

A ^VOLATILE T doesn’t convert to ^T without a written conversion, and a volatile variable isn’t passed as a var argument, which would lose its volatility.

+

FENCE also orders the program’s ordinary accesses against those of other processors and devices.

+

Ordinary variables. Only volatile accesses, CAS, XCHG, XADD and FENCE are exact. Any other access is ordinary: an implementation may keep a variable in a register, leave out a write that nothing reads, and change the order of ordinary accesses, as long as each thread, on its own, does what this report says. A variable that one thread writes while another reads or writes it, unless both use volatile accesses or the atomic built-ins, or a FENCE orders them, holds no particular value then: a read of it gives a value it had or was given, or a mixture of their bytes. For a variable of a basic, enumeration or set type, or a record or array of these, nothing else of the program becomes undefined by it. For one that holds a pointer, a procedure, a slice, an ERROR or a variant, a mixture may be an address no variable has, or a slice’s address with another’s length, or a case’s tag with another’s fields, and what follows isn’t defined (section 10). A program that shares such a variable between threads orders their accesses, with a lock or the atomic built-ins.

+

7.7 Defer

+

defer s; runs the statement s when the program leaves the statement list the defer stands in: at its end, or by a return, or by a break or continue out of it. Statements deferred in the same list run in the opposite order to their defers, and only those whose defer has been reached run.

+
module Head;
+import Sys, Out;
+
+(* Prints the first line of the file at path. *)
+proc head(path: []U8): BOOL;
+var fd, n, i: INT; buf: [256]U8;
+begin
+    fd := Sys.openRead(path);
+    if fd < 0 then return false; end;
+    defer Sys.close(fd);
+    n := Sys.read(fd, buf);
+    if n < 0 then return false; end;
+    for i := 0 to n - 1 do
+        if buf[i] = 10 then n := i; break; end;
+    end;
+    Out.str(buf[0..n]);
+    Out.ln;
+    return true;
+end;
+
+proc main*;
+begin
+    if not head("/etc/hostname") then Out.str("no hostname\n"); end;
+end;
+
+end Head.
+

return e; evaluates e before the deferred statements run. A deferred statement can’t contain defer, nor a return, break, continue or try that would leave it. A failed check, Rt.exit and Sys.exit end the program without running the deferred statements still pending.

+

7.8 Try

+

A procedure that can fail returns an ERROR as its last result (section 5.8), nil when it didn’t. A caller that can’t deal with the failure passes it on to its own caller, which try does in a word:

+
proc total(words: [][]U8): (INT, ERROR);
+var i, sum: INT;
+begin
+    for i := 0 to LEN(words) - 1 do
+        sum := sum + try number(words[i]);
+    end;
+    return sum, nil;
+end;
+

try c, where c is a call (below) of a procedure whose last result is an ERROR, makes the call and looks at that error. If it is nil, the program goes on, and try c is what c returned without the error. If it isn’t, the procedure try stands in returns at once, as return does (section 7.3): its last result is that error, and every other result is zero, as a variable of its type starts (section 4). Nothing more of the statement try stands in is done; in the example, sum isn’t assigned. So

+
x := try f(a);
+

is, with e a variable the program can’t name, and 0 standing for a zero of each of the procedure’s other results:

+
x, e := f(a);
+if e # nil then return 0, e; end;
+

The error is the one c returned, and compares with = as it did there. try has no handler and keeps no state: it is a return, written where the call is, so that every place a procedure can leave is in its text. A program that means to deal with an error tests it, as section 5.8 shows.

+

What try is applied to. c is a designator that ends in a call: f(x), Mod.f(x), p^.next(x), or a call through a variable of procedure type. Where the procedure has no parameters its parentheses may be left out, as in a statement (section 7.1), and try calls it: try setup;. A conversion, a built-in procedure (section 6.8) and the case of a variant are written like calls and aren’t procedures’; try can’t be applied to them.

+

What try c is. c’s results but the last.

+ +

As a statement, try c; drops the values of c that it has, and a dropped value is a lint, as a call that drops a result is (section 10); _ := try c; and a, _ := try c; say it is meant (section 7.1). The error is never dropped: try is the way of passing it on.

+

Where try may stand. Every use of try is an error unless:

+ +

A generic module is checked in each instance (section 3), so a procedure of an instance whose last result, by its type arguments, is no ERROR and uses try is an error in that instance.

+

Order. The arguments of c are evaluated from left to right, then c is called, and then its error is looked at (section 7.5). The designators on the left of an assignment are evaluated before its right side as always, so in a[i()] := try g(), i is called, then g; if g fails, nothing is assigned. A try in the right operand of and or or is reached only when that operand is evaluated (section 6.2).

+

Deferred statements. When try returns, the statements deferred in the procedure and not yet run are run, the last first, as for a return (section 7.7), after the error and the zero results have been chosen; no deferred statement can change them.

+

8. Procedures

+
ProcDeclaration   = "proc" IdentDef Signature ";"
+                    ( "forward" | { LocalDeclaration } "begin" Statements "end" [ ident ]
+                    | "code" { [ ident ":" ] [ Instruction ] ";" } "end" [ ident ] ) .
+LocalDeclaration  = "const" { ident [ ":" Type ] "=" Expr ";" }
+                  | "type" { ident "=" Type ";" }
+                  | "var" { ident { "," ident } ":" Type ";" } .
+Signature         = "(" [ Params { ";" Params } [ ";" "..." ] ] ")" [ ":" Results ]
+                  | [ ":" Results ] .
+Params            = [ "var" | "const" ] ident { "," ident } ":" Type .
+Results           = Type | "(" Type { "," Type } ")" .
+

A procedure without parameters may leave out the parentheses, both where it is declared (proc main*;) and where it is called (Out.ln). Used without parentheses in an expression, a procedure is a procedure value, not a call.

+

Parameters. A value parameter is a copy: the procedure may change it, and the caller’s variable stays as it was. A var parameter is the caller’s variable itself; its argument must be a variable of exactly the parameter’s type.

+

A const parameter is the caller’s variable too, read in place, whatever its size, with nothing copied; the procedure may only read it. It may not assign it or a part of it (a field, an element of an array in it), give it or a part of it to a var parameter, take the SYSTEM.ADR of either, write it through a view (section 6.9), or assign the names a match arm gives its fields. What a slice or a pointer in it points at isn’t part of it: the procedure may write through them, as it may through a value parameter’s; but a slice it makes of an array in it is a []const T (section 5.3), so it can’t write the caller’s array through it. const keeps the procedure from changing the variable, not what its slices and pointers point at. Its argument is any expression of the parameter’s type: a variable or a constant is passed in place, anything else as a temporary, of the procedure if it holds an array, as an array a call returns is (below). If the variable changes while the procedure runs, through a var parameter, a pointer or another thread, the procedure sees the change.

+
type Parser = record args: [][]U8; at: INT; (* ... *) end;
+
+proc current(const p: Parser): []U8;     (* reads p, many words, in place *)
+begin
+    return p.args[p.at];
+end;
+
+proc advance(var p: Parser);             (* changes p *)
+begin
+    INC(p.at);
+end;
+

A procedure takes what it reads as a value when it is a single value or a slice, and as const when it is a record or an array; what it changes, as var; and a pointer only for what it keeps past the call, what may be nil, an allocator, or what C or the system takes.

+

Results. A procedure returns nothing, one value, or several. A call that returns several values can only stand on the right of a multiple assignment, alone as a statement, or alone after return in a procedure whose results are of the same types, in the same order, which then returns them as they are: return divmod(n, 2);. A procedure that can fail has an ERROR as its last result (section 5.8), which try passes on (section 7.8).

+

An array a call returns, or a record or variant holding one, is a hidden variable of the procedure the call is in, as an array literal used as a slice is (section 6.5), and lives to the end of that procedure’s call. A slice of it may be kept in a variable and used for the rest of the procedure; in a loop, the hidden variable holds what the latest call returned. Like any slice of the frame, it may not be returned (section 7.3):

+
s := f('a')[0..4];     (* f returns a [8]U8: s is good to the end of the procedure *)
+t := f('b')[0..4];     (* a hidden variable of its own: s is unchanged *)
+
module Divide;
+import Out;
+
+proc divmod(a, b: I64): (I64, I64);
+begin
+    return a div b, a mod b;
+end;
+
+proc main*;
+var q, r: I64;
+begin
+    q, r := divmod(17, 5);
+    Out.int(q); Out.str(" rest "); Out.int(r); Out.ln;
+end;
+
+end Divide.
+

forward. proc f(x: I64): I64; forward; declares f so that it can be called before its body appears; the body comes later in the module, with the same signature, though its parameters may have other names; a forward with no body is an error.

+

A name after a procedure’s end, if written, is the procedure’s own.

+

Procedures don’t nest.

+

Code procedures. A procedure whose body is code is machine code, written by hand in the target’s assembly language (appendix A), in a module that imports SYSTEM: one instruction to each ;, and labels for jumps, up to end:

+
proc rdtsc*: U64;
+code
+    rdtsc;
+    shl rdx, 32;
+    or rax, rdx;
+    ret;
+end rdtsc;
+

A label, name:, names the place of the instruction after it, within the procedure. A constant of the module may stand wherever a number does. Any bytes may be written with db, as in db 0FH, 31H;, for an instruction the assembler doesn’t know.

+

It is called like any procedure, with the System V convention: integer and pointer arguments, and the addresses of var and const ones, arrive in rdi, rsi, rdx, rcx, r8 and r9, F32 and F64 ones in xmm0 to xmm7, and the result goes in rax (and rdx for a second) or xmm0. Its parameters and results are therefore of the types C can take (section 9), or slices, at most six integer and eight real parameters, and at most two results. A slice is two integers, as System V passes a struct of them: as a parameter its address arrives in one register and its length in the next, the two counting among the six; as the result its address goes in rax and its length in rdx, and it is the only result. The instructions are the whole procedure, ret included; they must keep rbx, rbp, rsp and r12 to r15 as they found them. The compiler doesn’t look past what they say.

+

9. Calling C

+
ExternDeclaration = "extern" ( "proc" IdentDef Signature
+                             | "var" IdentDef ":" Type ) .
+
link "libX11.so.6";
+extern proc XOpenDisplay(name: ^U8): ^U8;
+extern proc printf(format: ^U8; ...): I32;
+extern var environ: ^^U8;
+

An extern procedure or variable is found by its name in the C libraries the program links, and is declared only in a module that imports SYSTEM (section 3), since C can reach any memory: the C library always, and each library named by link.

+

An extern procedure’s parameters and result are integers, BOOL, F32, F64, pointers or procedures; a record goes to C by pointer, never by value. ... accepts any number of further arguments of those types, and is allowed only in an extern. C takes no float there, so an F32 given to ... is an error: the program writes F64(x). Past the parameters, a real constant goes as an F64, an integer constant as an INT, and a string literal as a pointer to its bytes followed by a zero byte.

+

An extern variable is C’s variable itself: reading it reads C’s, assigning it writes C’s. It can be of any type, declared as C declares it, a record laid out as C lays it out (section 5.5); the compiler can’t check that it is. A C variable that is local to each thread, such as errno, can’t be reached this way; the C library has a procedure for it (__errno_location).

+

A C union has no raz type. A program reads one as an array of words, and the member it wants through a pointer conversion:

+
var ev: [24]I64;                       (* XEvent: 192 bytes *)
+...
+XNextEvent(dpy, SYSTEM.ADR(ev));
+if I32(ev[0]) = KeyPress then
+    key := ^XKeyEvent(SYSTEM.ADR(ev));
+    ...
+end;
+

Every raz procedure uses the System V calling convention, so a raz procedure whose parameters and result are of those types can be given to C as a callback.

+

10. Programs

+

Any module may export a procedure main, declared proc main*; or proc main*: INT;. The program runs the bodies of all its modules (section 3), then the main module’s main, if it has one, and ends with status 0, or with the status main returns, by calling Rt.exit. The main of an imported module is an ordinary procedure, which runs only if something calls it; so a library module can carry a main that tests it. A program uses C if any of its modules has an extern declaration or a link of a library; a module’s other files, read only to check its interface (section 3), don’t count. A program that doesn’t is a static executable with no run time besides the code it uses. One that does is linked dynamically and starts through the C library, so that C’s own set-up and clean-up run. A program with a module that says link static; must not use C, and the compiler reports an error if it does.

+

Ending. Rt.exit(status) ends the program. First it runs the procedures registered with Rt.atExit, the last registered first, each at most once; then it ends the program with status, through C’s exit in a program that uses C, so that C flushes its own buffers. A program that stops (below), a failed check (section 6.5) included, runs them too, after its message, so that Out’s buffer is written out, and ends with status 2. Sys.exit ends the program at once, and a program killed by a signal from outside runs none of them.

+
proc atExit*(p: proc): ERROR;   (* Rt.Full if 32 are registered *)
+proc exit*(status: INT);
+proc trace*;                    (* the calls under way, on standard error *)
+

Rt.trace says on standard error the calls under way, from the one that calls it out, each with its variables, as a program that stops does.

+

Defined behaviour. Every variable starts at zero, integers wrap, and indexing arrays and slices is checked, so a program’s behaviour is defined by this report, with one exception: memory reached other than through a checked variable. In any module, three things reach it: a pointer used after the memory it points at was given back (by Heap’s free or an arena’s reset, say), a slice kept after the call whose frame holds what it points at (section 7.3), and a race on a variable that holds a pointer, a slice or a variant (section 7.6). In a module that imports SYSTEM, so does what that module does there (section 3): a made-up pointer, indexing through a pointer, an index out of range under check off;, writing a string’s bytes through a ^U8, a code procedure that breaks its rules, and C code. Each can read or write any memory, and what follows isn’t defined. Dereferencing nil, dividing by zero, calling a nil procedure and running out of stack stop the program, on every target, with status 2, as a failed check does. Before it stops, the program prints to standard error where it was, as file, line and column, and why, as far as it can tell: a nil pointer, a nil procedure, a stack overflow, a bad address or a division fault; then the calls under way, each with its variables of a basic, enumeration, set or pointer type. Whether the machine catches these or the compiled code checks for them is the implementation’s choice (appendix A); that they stop the program isn’t.

+

Separate compilation. An importer depends only on a module’s interface: what it exports, as an importer sees it, never its source or its code. An implementation that compiles modules on its own makes the same program as if every module were compiled together (appendix A).

+

Errors. A program that breaks a rule of this report that says it is an error isn’t a raz program, and an implementation must reject it: say what is wrong and make no executable. Such a rule is one whose breach would leave the program with no meaning this report can give: a mistake of types, a name that isn’t declared or is declared twice, an assignment to what is read-only, a call with the wrong number of arguments, a type name or a procedure with no result used as a value, type arguments given to a module that isn’t generic, or too many, an import that can’t be found, a procedure declared forward and never defined, a module that imports itself. A fault that is only a lint isn’t an error: a name declared and never used, or a result that a call standing on its own drops (Sys.write(fd, s);, where _ := Sys.write(fd, s); says it is meant). A program with one is valid, and an implementation may warn of it. The text of its messages, how many it reports and which warnings it gives are its own (appendix A).

+

11. Versions

+

A version of this report is named by the month it was made in and a count: 2026-10.0, then 2026-10.1 for the next change that month. raz --version says which version the compiler follows.

+

The history of the versions, what each changed, is in doc/report-history.md.

+

Appendix A. What an implementation chooses

+

Everything in this report binds every implementation of raz, except what follows, which each chooses for itself and documents. This compiler’s choices are in doc/compiler.md, under “This compiler’s choices”. The programs in conform/ are how an implementation shows that it follows this report: it passes them all, its reals aside where its target has none; conform/check.sh runs them.

+ +

The core. A target may leave out what the system under it can’t give: Sys past writing, ending the program and getting memory, Thread, link and extern. What it must have, besides the whole language, reals aside, is the core of the library: Rt, Out, Mem, Arena, Lock, Str and Buf, and of Sys what they need. A program that keeps to the core runs on every target. The rest of the library (Heap, Fmt, List, Map, Vec, Sort, Math, Files, Opt, Width, Rand, Check, Prop and the rest of Sys) is the standard library: a target may leave a module out, and one that has it gives what doc/raz-lib.md says. conform/ tests the core only.

+

Appendix B. The grammar

+

The whole syntax of raz, gathered from the sections above, with the symbols of section 2. { x } is any number of x, [ x ] is x or nothing, and ( x | y ) is one of them.

+
ident      = letter { letter | digit } .
+letter     = "A" .. "Z" | "a" .. "z" | "_" .
+digit      = "0" .. "9" .
+hexDigit   = digit | "A" .. "F" .
+number     = digit { digit }
+           | digit { hexDigit } "H"
+           | digit { digit } "." digit { digit } [ "E" [ "+" | "-" ] digit { digit } ] .
+char       = "'" ( character | escape ) "'" .
+string     = '"' { character | escape | "\x" anyHex anyHex } '"'
+           | "`" { rawChar } "`" .
+escape     = "\n" | "\t" | "\r" | "\0" | "\\" | "\'" | '\"'
+           | "\u{" anyHex { anyHex } "}" .
+anyHex     = hexDigit | "a" .. "f" .
+
+Module     = "module" ident [ "(" ModParams ")" ] ";"
+             { Import } { Link } [ Check ] { Declaration }
+             [ "begin" Statements ] "end" ident "." .
+ModParams  = ident { "," ident } { ";" ident ":" "proc" Signature } .
+Import     = "import" ImportItem { "," ImportItem } ";" .
+ImportItem = ident [ ":=" ident [ "(" Type { "," Type } ")" ] ] .
+Link       = "link" ( string | "static" ) ";" .
+Check      = "check" "off" ";" .
+
+Declaration = "const" { IdentDef [ ":" Type ] "=" Expr ";" }
+            | "type" { IdentDef "=" Type ";" }
+            | "var" { IdentList ":" Type ";" }
+            | ProcDeclaration ";"
+            | ExternDeclaration ";" .
+IdentDef    = ident [ "*" ] .
+IdentList   = IdentDef { "," IdentDef } .
+
+Type      = QualIdent
+          | "[" Expr "]" Type
+          | "[" "]" [ "const" ] Type
+          | "^" [ "VOLATILE" ] Type
+          | [ "packed" ] "record" { IdentList ":" Type ";" } "end"
+          | "variant" { Case ";" } "end"
+          | "(" ident { "," ident } ")"
+          | "set" "of" QualIdent
+          | "proc" Signature .
+Case      = ident [ "(" FieldList { ";" FieldList } ")" ] .
+FieldList = ident { "," ident } ":" Type .
+QualIdent = [ ident "." ] ident .
+
+Expr       = Conjunct { "or" Conjunct } .
+Conjunct   = Relation { "and" Relation } .
+Relation   = SimpleExpr [ RelOp SimpleExpr ] .
+RelOp      = "=" | "#" | "<" | "<=" | ">" | ">=" | "in" .
+SimpleExpr = [ "-" ] Term { AddOp Term } .
+AddOp      = "+" | "-" | "|" | "xor" .
+Term       = Factor { MulOp Factor } .
+MulOp      = "*" | "/" | "div" | "mod" | "&" | "shl" | "shr" .
+Factor     = number | char | string | Designator | "(" Expr ")"
+           | "not" Factor | "~" Factor
+           | "[" [ Expr { "," Expr } ] "]"
+           | "{" [ Element { "," Element } ] "}"
+           | "^" [ "VOLATILE" ] Type "(" Expr ")"
+           | "try" Designator .
+Element    = Expr | ident ":" Expr .
+Designator = QualIdent { Selector } .
+Selector   = "." ident | "^" | "[" Expr [ ".." Expr ] "]"
+           | "(" [ Expr { "," Expr } ] ")" | "." "(" Type ")" .
+
+Statements = { Statement ";" } .
+Statement  = Designator [ ":=" Expr ]
+           | "_" ":=" Expr
+           | Target "," Target { "," Target } ":=" Expr
+           | "if" Expr "then" Statements
+             { "elsif" Expr "then" Statements } [ "else" Statements ] "end"
+           | "while" Expr "do" Statements "end"
+           | "repeat" Statements "until" Expr
+           | "for" ident ":=" Expr "to" Expr [ "by" Expr ] "do" Statements "end"
+           | "match" Expr "of" { "|" Arm } "end"
+           | "return" [ Expr { "," Expr } ]
+           | "break"
+           | "continue"
+           | "defer" Statement
+           | "try" Designator .
+Arm        = ( ident { "." ident } [ "(" ident { "," ident } ")" ]
+             | Label { "," Label } | "else" ) ":" Statements .
+Label      = Expr [ ".." Expr ] .
+Target     = Designator | "_" .
+
+ProcDeclaration   = "proc" IdentDef Signature ";"
+                    ( "forward" | { LocalDeclaration } "begin" Statements "end" [ ident ]
+                    | "code" { [ ident ":" ] [ Instruction ] ";" } "end" [ ident ] ) .
+LocalDeclaration  = "const" { ident [ ":" Type ] "=" Expr ";" }
+                  | "type" { ident "=" Type ";" }
+                  | "var" { ident { "," ident } ":" Type ";" } .
+Signature         = "(" [ Params { ";" Params } [ ";" "..." ] ] ")" [ ":" Results ]
+                  | [ ":" Results ] .
+Params            = [ "var" | "const" ] ident { "," ident } ":" Type .
+Results           = Type | "(" Type { "," Type } ")" .
+ExternDeclaration = "extern" ( "proc" IdentDef Signature
+                             | "var" IdentDef ":" Type ) .
+

character is any character but a line break, and in a string any but " and \, in a character any but ' and \. rawChar is any character but `, line breaks included. A procedure argument of a generic module (section 3) is written as a QualIdent, which is a Type here. ... comes last in a Signature, and only in an extern. An Instruction is written in the target’s assembly language (appendix A).

+

The library, volume 2

+

The second volume of the report on raz. The first, doc/raz.md, defines the language; this one defines the modules that come with it, and refers to the first’s sections by number, as “section 6.8”. Only the core binds every implementation (appendix A of the first volume); the rest is the standard library, Rand, Check and Prop among it.

+

The library grows only by what breaks no program written for it. If a change must break programs, the old form stays for one minor version beside the new; the release notes list the old forms, and the next version removes them. Nothing marks an old form in the source.

+

Modules written in raz, in the compiler’s lib directory:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ModuleWhat
Rtending the program, exit, exitStatus and atExit; stop, which ends it with a message; trace, the calls under way; what the compiler’s checks call when they fail
Syssystem calls: open, openMode, openRead, create, read, write, seek, position, truncate, sync, syncAll, lock, lockShared, close, closeChecked, dup, dupTo, dupAbove, keepOnExec, mmap, munmap, mapRead, protect, isTerminal, yield, exit; files and directories, rename, remove, removeDir, makeDir, makeDirMode, chmod, setTime, access, umask, symlink, readLink, info, linkInfo, infoOf, openDir, nextEntry, entryKind, closeDir; the terminal, rawMode, restoreMode, getMode, setMode, termSize, ready; the environment, env, findEnv, envAt, setEnv, workDir, setWorkDir; programs, spawn, exec and execve, pipes and signals; the user, the machine, time used and limits; time, clock, now, sleep; random; errors, by name, and what one means, errorText; sockets, among them datagrams served and files passed; and memory shared through a file. One file per target, and Sys.raz over the C library for the others, which takes what each C library fixes from CAbi
Outwriting text and numbers to standard output, buffered; safe to call from several threads
Cthe parts of the C library the others use, and printf, fflush, stdout, pthread_create; a program that imports it uses C
Locka lock for short sections, for C’s threads and Thread’s alike
Threadthreads, spawn, join and signal, and Mutex, in any program; in one that uses C, made by C’s pthread_create
Taska thread given a value of its own, Task(T): spawn copies it, with no cast
Guardeda value with its lock, Guarded(T): reached only through with
MemAllocator, the interface of every allocator, and pages from the system
Heapa general allocator, Heap.heap, safe to call from several threads; freeing a block twice, or one it never gave out, stops the program; RAZ_HEAP=debug finds writes past a block’s end and after free
Arenaan allocator that frees everything at once; ADR(arena.base) is its allocator
Stroperations on []U8 strings: comparing, hashing, finding, trimming and cutting, case, joining and replacing, UTF-8, numbers to and from text
Bytessearches of bytes, many at a time: index, last, count and find in a []U8; one file per target where the target has instructions for it
Bufa growable byte buffer
Fmtformatted output: Fmt.print("{} of {}\n", [Fmt.int(n), Fmt.real(x, 2)]), into a Buf with Fmt.write, or to standard error with Fmt.eprint
Lista generic singly linked list, List(T)
Mapa generic hash map, Map(K, V; hash, eq)
Veca generic growable array, Vec(T), indexed as a slice
Sortsorting a slice in place, Sort(T; less)
Mathroots, powers, logarithms, rounding and trigonometry, and pi, for F64
Filesan argument as a string, and a whole file read or written
Opta command line read through one table, by getopt’s rules with long options; its help and its mistakes
Widthhow many columns of a terminal a character, or a string, takes: 0, 1 or 2, as wcwidth says
Randa seeded random number generator, splitmix64: the same seed, the same numbers; for tests and simulations, not secrets
Checkchecks for a test: ok, str and int say what failed on standard error, and the program ends with status 1 if any did
Propproperty tests and fuzzing: a property draws values, a failing case is shrunk and saved, and run first next time
+

Lengths, counts, file descriptors, process ids and statuses are INTs, and a character is an I32. What may pass an INT on a small target is an I64: a file’s size and position, a time in nanoseconds, and a number read from text.

+

What follows is each module’s interface, as tools/Doc.raz prints it from the module’s file; ... stands for fields that are the module’s own. A module’s main, where it has one, is its test, and is left out here.

+
module Rt;
+const Full*: ERROR = "too many procedures to run at exit";
+proc atExit*(p: proc): ERROR;   (* p run when the program ends by exit *)
+proc exit*(status: INT);        (* the atExit procedures, the last first, then the end *)
+proc exitStatus*: INT;          (* the status exit was given, in an atExit procedure; 0 before *)
+proc stop*(msg: []U8);          (* msg, and a line feed, on standard error, then exit with status 2 *)
+proc trace*;                    (* the calls under way, and their variables, on standard error *)
+

Rt also holds what the compiler’s checks call when they fail, and the handlers of the signals that stop a program (section 10). exit takes each procedure off the list before it runs it, so it runs once even if it fails or calls exit itself; in a program that uses C, it ends through C’s exit, so that C flushes its buffers too. exitStatus is the status exit was given, which a procedure atExit registered can read, to note a crash: a failed check and stop both end with 2. It is 0 before exit is called.

+
module Mem;
+type
+    Allocator* = record
+        alloc*: proc(a: ^Allocator; size, align: INT): ^U8;   (* nil if out of room *)
+        free*:  proc(a: ^Allocator; p: ^U8);
+    end;
+const Page* = 4096;
+proc pages*(size: INT): ^U8;         (* size bytes, in whole pages, zeroed; or nil *)
+proc unmap*(p: ^U8; size: INT);      (* pages given back *)
+proc alloc*(a: ^Allocator; size, align: INT): ^U8;   (* a^.alloc(a, size, align) *)
+proc free*(a: ^Allocator; p: ^U8);   (* a^.free(a, p) *)
+
+module Heap;
+proc debug*(on: BOOL);       (* debug mode on or off, for the blocks given from now on *)
+var heap*: ^Mem.Allocator;
+var sure*: ^Mem.Allocator;   (* heap, but running out of memory stops the program *)
+
+module Arena;
+type Arena* = record
+    base*: Mem.Allocator;     (* first, so that ^Arena(a) finds the rest *)
+    ...
+end;
+proc init*(var ar: Arena; size: INT): BOOL;   (* an arena of size bytes; false if the system has none *)
+proc mark*(const ar: Arena): INT;             (* where ar stands now, for release *)
+proc release*(var ar: Arena; m: INT);         (* all allocated since mark m freed; a mark past where it stands stops the program *)
+proc reset*(var ar: Arena);                   (* every allocation forgotten; the memory used again *)
+proc done*(var ar: Arena);                    (* its memory given back *)
+

NEW(p, a) calls a^.alloc. Heap is the general allocator; Heap.heap gives nil when memory runs out, and Heap.sure stops the program instead, as Buf does, so that NEW(p, Heap.sure) needs no check.

+

Heap has a debug mode, a light AddressSanitizer, chosen by RAZ_HEAP=debug in the environment or by Heap.debug(true). Normal mode pays nothing for it. In debug mode each block given has 8 guard bytes after its last, and a freed block is filled with 0DEH bytes and held in a quarantine, the last 1,024 frees, before it may be given again. A broken guard, a write past the block’s end, is found when the block is freed; a block that leaves the quarantine with a byte not 0DEH, a write after free, is found then. Either stops the program, saying what was found and the block’s address and size, with the calls under way, and status 2. A big block, which has pages of its own, is not quarantined: its guard is checked and its pages unmapped, so a later use of it faults. debug changes only the blocks given after it, so call it before the first allocation; a block is freed as it was given, in either mode. Only writes are found, not reads, and not those past the guard or after the quarantine. An arena hands out memory from one block: its free does nothing, and reset forgets everything.

+
module Lock;
+type Lock* = record ... end;
+proc take*(var l: Lock);
+proc give*(var l: Lock);
+
+module Thread;
+const Failed*: ERROR = "can't start a thread";
+type
+    Thread* = record ... end;
+    Mutex* = record ... end;     (* zero is free *)
+proc spawn*(p: proc(arg: ^U8); arg: ^U8): (^Thread, ERROR);   (* p(arg) in a new thread *)
+proc join*(t: ^Thread);         (* waits for t to end, then frees its stack *)
+proc signal*(t: ^Thread; sig: INT): INT;   (* sig sent to t alone: 0, or minus an errno *)
+proc lock*(var m: Mutex);
+proc unlock*(var m: Mutex);
+
+module Task(T);
+proc spawn*(p: proc(var x: T); x: T): (^Thread.Thread, ERROR);   (* p run on a copy of x in a new thread *)
+
+module Guarded(T);
+type Guarded* = record ... end;       (* a value and its Thread.Mutex; zero is ready *)
+proc with*(var g: Guarded; p: proc(var x: T));   (* p run on the value, under the lock *)
+

Task(T) starts a thread without a cast: import Jobs := Task(Job); t, e := Jobs.spawn(work, job); is the safe form of Thread.spawn(work, ^U8(ADR(job))). spawn copies x into a block from Heap before it returns, so the caller may change or drop its x at once. The thread owns the copy: work changes it freely, and the thread frees it when work returns. The thread is joined with Thread.join; Thread.Failed comes back if there is no memory for the copy or the thread. A result goes back through a pointer in x, read after join.

+

Guarded(T) is a T with its Thread.Mutex, for sharing a container between threads: the value is reached only through with, which holds the lock while p runs. A zeroed Guarded is ready. p must not call with on the same Guarded, nor keep a pointer into its x.

+

A Lock is for short sections: a thread that finds it taken tries again, giving up the processor now and then. A Mutex sleeps. Each of Thread’s threads runs on a stack of its own, with a page below it that can’t be touched, so that running off the stack stops the program with a message, as in the main thread. In a program that uses C, Thread makes its threads with C’s pthread_create, so that C’s library knows of them; in one that doesn’t, with the system’s own calls. The program is the same either way.

+

Sys.kill signals a program, and the system gives the signal to any of its threads; signal gives it to t alone, until t is joined, and is -3 (ESRCH) once t has ended. With Sys.handle(sig), a call t waits in, a read or a ready, fails with -4, so that one thread can break into another’s wait, as ^C breaks into the main thread’s. A signal sent before t begins its wait is only noted, so a program sends it again until t says it has stopped.

+
module Out;
+proc str*(s: []U8);
+proc char*(c: U8);
+proc ln*;                        (* a line feed *)
+proc int*(n: I64);               (* n in decimal *)
+proc hex*(n: U64; digits: INT);  (* n in hexadecimal, digits digits at least *)
+proc flush*;
+proc lines*(on: BOOL);           (* written at each line feed, or only when full *)
+

Out and C’s stdio. Out keeps a buffer of Sys.outSize bytes, 4 KB on Linux. It writes it out when it is full, at each line feed when standard output is a terminal, at Out.flush, and when the program ends by Rt.exit. lines(true) has it written at each line feed whatever standard output is, as a filter of a stream that comes slowly wants through a pipe, as grep’s --line-buffered; lines(false), only when full, at a terminal too. A lock keeps what each call writes together when threads write at once. C’s stdio keeps a buffer of its own for the same standard output. A program that writes with both flushes one before writing with the other, or the text comes out of order:

+
module Both;
+import Out, C;      (* C: printf, fflush and C's FILE *stdout *)
+
+proc main*;
+begin
+    Out.str("from raz\n");
+    Out.flush;
+    C.printf("from C\n");
+    C.fflush(C.stdout);
+    Out.str("from raz again\n");
+end;
+
+end Both.
+

Sys gives every target the same procedures, so that a program that needs only these runs wherever raz does: through system calls on Linux, through the C library elsewhere. A result that can fail is a number, minus an errno, as on Linux; 0 is success. The number is Linux’s on every target: Sys over another system’s C library gives the Linux errno of the same name, and a program tests it by the names below; one with no Linux twin keeps its own number. Sys.raz, the Sys over C, keeps to POSIX’s names; what a C library fixes for its target, the layouts of its structs, its numbers and the names that differ, it takes from CAbi, one file per target, which tools/cabi.c, compiled there, writes.

+
module Sys;
+const
+    stdin* = 0; stdout* = 1; stderr* = 2;
+    outSize* = 4096;    (* the bytes Out keeps; each target has its own *)
+    (* signals, by their numbers on Linux; each target has its own *)
+    sigHup* = 1; sigInt* = 2; sigQuit* = 3; sigKill* = 9; sigPipe* = 13;
+    sigTerm* = 15; sigChld* = 17; sigCont* = 18; sigStop* = 19;
+    sigTstp* = 20; sigTtin* = 21; sigTtou* = 22; sigWinch* = 28;
+    sigUsr1* = 10; sigUsr2* = 12; sigAlrm* = 14;
+    (* the limits limit and setLimit take, by their numbers on Linux; each target has its own *)
+    limitCpu* = 0; limitFileSize* = 1; limitData* = 2; limitStack* = 3;
+    limitCore* = 4; limitProcs* = 6; limitFiles* = 7; limitMemory* = 9;
+    (* errors, minus Linux's errnos on every target *)
+    errPerm* = -1; errNoEntry* = -2; errNoProcess* = -3; errIntr* = -4;
+    errIo* = -5; errBadFd* = -9; errChild* = -10; errAgain* = -11;
+    errNoMemory* = -12; errDenied* = -13; errExists* = -17;
+    errNotDir* = -20; errIsDir* = -21; errInvalid* = -22;
+    errNotTerminal* = -25; errNoSpace* = -28; errPipe* = -32;
+    errNameTooLong* = -36; errNotEmpty* = -39; errLoop* = -40;
+    errAddrInUse* = -98; errNetUnreach* = -101; errConnAborted* = -103; errConnReset* = -104;
+    errTimedOut* = -110; errRefused* = -111; errHostUnreach* = -113;
+    errInProgress* = -115;
+
+type
+    Access* = (reading, writing, creating, exclusive, truncating, appending, executing, nonblocking);
+    Accesses* = set of Access;
+    Info* = record
+        size*: I64;      (* in bytes *)
+        mtime*: I64;     (* when its contents last changed, in nanoseconds since 1970 *)
+        seconds*: I64;   (* mtime in whole seconds, rounded down: exact past 2262 and before 1677, where mtime wraps *)
+        mode*: INT;      (* its permission bits, as chmod takes them: 1EDH is rwxr-xr-x *)
+        dir*: BOOL;      (* a directory *)
+        file*: BOOL;     (* a regular file: not a directory, device, pipe or socket *)
+        symlink*: BOOL;  (* the path itself is a symbolic link *)
+        ino*: U64;       (* its inode, which a rename keeps and a new file doesn't *)
+        dev*: U64;       (* the file system it is on; with ino, it names the file *)
+        links*: U64;     (* how many names it has: 1 for a file no hard link shares *)
+        special*: INT;   (* its set-user-id, set-group-id and sticky bits, as chmod takes them: 800H, 400H, 200H *)
+        uid*: INT;       (* its owner's user number *)
+        gid*: INT;       (* its group's number *)
+    end;
+    Kind* = (unknown, isFile, isDir, isLink, isOther);   (* what a directory says a name in it is *)
+    Dir* = record ... end;   (* an open directory; its fields are the target's *)
+    Program* = record
+        path*: []U8;
+        args*: [][]U8;      (* the first is its name *)
+        env*: [][]U8;       (* NAME=value, each added to this program's environment *)
+        onlyEnv*: BOOL;     (* env is its whole environment *)
+        dir*: []U8;         (* its working directory; "" for this program's *)
+        fds*: [3]INT;       (* its standard input, output and error; 0 for this program's own *)
+        group*: INT;        (* the process group it joins: 0 for this program's, -1 a new one it leads *)
+        foreground*: BOOL;  (* its group takes the terminal on standard input *)
+        tty*: INT;          (* a pseudo-terminal's fd, to start a session on; 0 for none *)
+        more*: []INT;       (* fds above 2 passed on to it, at the same numbers *)
+        keepIgnored*: BOOL; (* signals this program ignores stay ignored in it *)
+    end;
+    Status* = (running, exited, killed, stopped);
+    Mode* = record ... end;   (* a terminal's modes; its fields are the target's *)
+    Peer* = record ... end;   (* whom a datagram came from *)
+    Remote* = record          (* who is at the other end of a connected socket *)
+        unix*: BOOL;          (* a Unix socket: uid and pid say who *)
+        ipv6*: BOOL;          (* addr is 16 bytes of IPv6, else 4 bytes of IPv4 then zeros *)
+        addr*: [16]U8;
+        port*: INT;
+        uid*, pid*: INT;
+    end;
+    Poll* = record            (* a descriptor for poll to wait on *)
+        fd*: INT;
+        read*, write*: BOOL;  (* wait until it may be read, written *)
+        ready*: BOOL;         (* set by poll *)
+    end;
+
+proc write*(fd: INT; s: []U8): INT;     (* the bytes written *)
+proc read*(fd: INT; buf: []U8): INT;    (* the bytes read; 0 at the end *)
+proc open*(path: []U8; how: Accesses): INT;   (* its fd, closed on exec *)
+proc openMode*(path: []U8; how: Accesses; mode: INT): INT;   (* open, a file it makes given mode *)
+proc openRead*(path: []U8): INT;         (* open(path, {reading}) *)
+proc create*(path: []U8): INT;           (* open(path, {writing, creating, truncating}) *)
+proc seek*(fd: INT; pos: I64; fromEnd: BOOL): I64;  (* the new position *)
+proc position*(fd: INT): I64;            (* where the next read or write is *)
+proc truncate*(fd: INT; size: I64): INT; (* the file made size bytes long *)
+proc sync*(fd: INT): INT;                (* what was written to it, on the disk *)
+proc syncAll*(fd: INT): INT;             (* all that was written to its file system, on the disk *)
+proc lock*(fd: INT; wait: BOOL): INT;    (* the file's lock, held until fd is closed *)
+proc lockShared*(fd: INT; wait: BOOL): INT;   (* lock, shared with others that ask it so *)
+proc close*(fd: INT);
+proc closeChecked*(fd: INT): INT;        (* close, and 0 or minus the errno it failed with *)
+proc dup*(fd: INT): INT;                 (* a new fd for the same file, the lowest free *)
+proc dupTo*(fd, into: INT): INT;         (* into made the same file as fd, closing what it was *)
+proc dupAbove*(fd, least: INT): INT;     (* a new fd for the same file, the lowest free from least on, closed on exec *)
+proc keepOnExec*(fd: INT; yes: BOOL): INT;   (* fd left open, or not (as at first for a file made by open or pipe), in the program exec runs *)
+proc isTerminal*(fd: INT): BOOL;
+proc mapRead*(fd, size: INT): ^U8;     (* the first size bytes of fd, which may be open only to read, mapped read only; or nil *)
+proc protect*(p: ^U8; size: INT; read, write: BOOL): INT;   (* the pages at p readable and writable as asked; neither, and touching them stops the program *)
+proc mmap*(size: INT): ^U8;              (* size bytes of zeroed memory, in whole pages; or nil *)
+proc munmap*(p: ^U8; size: INT);
+proc yield*;                             (* the processor given to another thread *)
+proc exit*(status: INT);                 (* the program ended at once, without Rt's atExit *)
+
+proc rename*(old, new: []U8): INT;       (* replaces what new names *)
+proc remove*(path: []U8): INT;           (* a file, not a directory *)
+proc removeDir*(path: []U8): INT;        (* an empty directory *)
+proc makeDir*(path: []U8): INT;          (* readable by all, writable by its owner *)
+proc makeDirMode*(path: []U8; mode: INT): INT;   (* makeDir, given mode *)
+proc chmod*(path: []U8; mode: INT): INT;
+proc chown*(path: []U8; uid, gid: INT): INT;   (* its owner and group; -1 leaves one as it is *)
+proc makeFifo*(path: []U8; mode: INT): INT;    (* a named pipe, given mode *)
+proc setTime*(path: []U8; sec: I64; nsec: INT): INT;   (* its mtime, and the time it was read, made sec and nsec *)
+proc access*(path: []U8; how: Accesses): INT;   (* 0 if this user may read, write or execute it *)
+proc umask*(mask: INT): INT;             (* the bits taken from every file made; the mask it was *)
+proc symlink*(target, path: []U8): INT;  (* path made a link to target *)
+proc readLink*(path: []U8): ([]U8, INT); (* what the link names, good until the next call *)
+proc info*(path: []U8): (Info, INT);     (* following a symbolic link *)
+proc linkInfo*(path: []U8): (Info, INT); (* the link itself *)
+proc infoOf*(fd: INT): (Info, INT);      (* the open file's *)
+proc space*(path: []U8): (I64, I64, INT);   (* the bytes free and in all on path's file system *)
+
+proc openDir*(var d: Dir; path: []U8): INT;
+proc nextEntry*(var d: Dir): ([]U8, BOOL);  (* a name, good until the next call; false at the end *)
+proc entryKind*(const d: Dir): Kind;        (* what the name nextEntry gave last is *)
+proc closeDir*(var d: Dir);
+
+proc rawMode*(fd: INT): BOOL;      (* the terminal on fd: no echo, no lines, no signals *)
+proc restoreMode*(fd: INT);        (* as rawMode found it *)
+proc getMode*(fd: INT): (Mode, INT);     (* the terminal's modes, to set again *)
+proc setMode*(fd: INT; m: Mode): INT;    (* once what was written to it is sent *)
+proc termSize*(fd: INT): (INT, INT);   (* columns and rows; 80 and 24 if unknown *)
+proc ready*(fd, ms: INT): BOOL;          (* something to read within ms, or ever if ms < 0 *)
+proc readyOf*(fds: []INT; ms: INT): INT;   (* the first of fds with something to read within ms, or -1 *)
+proc readyFor*(reads, writes: []INT; ms: INT): INT;   (* readyOf, and the first of writes with room to write *)
+proc poll*(var fds: []Poll; ms: INT): INT;   (* sets each fd's ready, as each read and write say; the number ready, 0 on a timeout, or minus an errno *)
+proc setBlocking*(fd: INT; yes: BOOL): INT;   (* if not yes, a read or write that would wait is -11 at once *)
+proc blocking*(fd: INT): INT;            (* 1 if reads and writes wait, 0 if they are -11 at once, or minus an errno *)
+
+proc errorText*(err: INT): []U8;   (* what errno err, or minus it, means, as C's strerror says *)
+
+proc env*(name: []U8): []U8;       (* the environment variable's value; "" if unset *)
+proc findEnv*(name: []U8): ([]U8, BOOL);   (* the value and true; "" and false if unset, "" and true if empty *)
+proc envAt*(i: INT): ([]U8, BOOL); (* the environment's ith NAME=value, from 0; false past the last *)
+proc setEnv*(name, value: []U8): INT;   (* name set to value, for env and the programs started *)
+proc workDir*: ([]U8, INT);        (* the working directory, good until the next call *)
+proc setWorkDir*(path: []U8): INT;
+
+proc pipe*: (INT, INT);            (* the fd to read and the fd to write; or minus an errno and -1 *)
+proc openPty*: INT;                (* a pseudo-terminal: the fd of its controlling side *)
+proc setTermSize*(fd, cols, rows: INT): INT;   (* the size its programs are told of *)
+proc spawn*(p: Program): INT;      (* a program started: its process id *)
+proc exec*(p: Program): INT;       (* p run in this program's place; returns only if it can't *)
+proc execve*(path: []U8; args, env: [][]U8): INT;   (* as the kernel's execve: no search *)
+proc fork*: INT;                   (* this program copied: 0 in the copy, its process id in this one *)
+proc setsid*: INT;                 (* a session of its own, led by this program: its process id, or minus an errno *)
+proc wait*(pid: INT; block: BOOL): (INT, Status, INT);   (* which program, how, and its code *)
+proc waitExit*(pid: INT): (INT, Status, INT);   (* as wait, but only for a program to end *)
+proc kill*(pid, signal: INT): INT;
+proc pid*: INT;                    (* this program's process id *)
+proc group*: INT;                  (* the process group this program is in *)
+proc setGroup*(pid, group: INT): INT;    (* pid 0 is this program; group 0 a new one pid leads *)
+proc foreground*(fd, group: INT): INT;   (* the terminal on fd gives its keys to group *)
+proc foregroundOf*(fd: INT): INT;  (* the group the terminal on fd gives its keys to *)
+proc uid*: INT;                    (* the user this program runs as *)
+proc euid*: INT;                   (* the user whose rights it has: 0 is root *)
+proc hostName*: ([]U8, INT);       (* this machine's name, good until the next call *)
+proc processors*: INT;             (* the processors this program may run on, at least 1 *)
+proc cpuTime*(children: BOOL): (I64, I64);   (* ns used in the program and in the system; or by its children *)
+proc limit*(which: INT): (I64, I64, INT);    (* the soft limit and the hard; -1 for none *)
+proc setLimit*(which: INT; soft, hard: I64): INT;
+
+proc catch*(sigs: []INT): INT;     (* sigs caught: an fd to wait on *)
+proc caught*(fd: INT): INT;        (* the next signal caught, or 0 if none is waiting *)
+proc ignore*(sig: INT; yes: BOOL): INT;  (* sig ignored; or, if not yes, back to what it does at first *)
+proc ignored*(sig: INT): BOOL;     (* whether sig does nothing now *)
+proc handle*(sig: INT): INT;       (* sig noted, for came; a system call it comes during is -4 *)
+proc came*(sig: INT): BOOL;        (* whether sig came since the last time it was asked *)
+
+proc clock*: I64;                  (* nanoseconds, on a clock that only goes forward *)
+proc now*: I64;                    (* nanoseconds since 1970-01-01, UTC *)
+proc sleep*(ms: INT);
+proc random*(b: []U8);             (* b filled with random bytes; stops the program if it can't be *)
+
+proc connect*(path: []U8): INT;    (* a stream socket, connected to the Unix socket at path: its fd *)
+proc connectTcp*(addr: []U8; port: INT): INT;   (* addr an IPv4 or IPv6 address, as numbers *)
+proc connectUdp*(addr: []U8; port: INT): INT;
+proc listen*(path: []U8): INT;     (* a Unix socket made at path, taking connections *)
+proc listenTcp*(addr: []U8; port: INT): INT;
+proc accept*(fd: INT): INT;        (* the next connection, waiting for one *)
+proc send*(fd: INT; s: []U8): INT; (* write, to a socket: -32 (EPIPE), not a signal, if it is closed *)
+proc sendNow*(fd: INT; s: []U8): INT;   (* send, but -11 (EAGAIN) where it would wait *)
+proc connectTcpWithin*(addr: []U8; port, ms: INT): INT;   (* connectTcp, or -110 (ETIMEDOUT) after ms *)
+proc listenUdp*(addr: []U8; port: INT): INT;   (* a socket of datagrams on port at addr *)
+proc receive*(fd: INT; buf: []U8): (INT, Peer);   (* the next datagram, in buf, and who sent it *)
+proc reply*(fd: INT; peer: Peer; s: []U8): INT;   (* s, as one datagram, to peer *)
+proc localPort*(fd: INT): INT;     (* the port the socket fd is bound to *)
+proc closeWrite*(fd: INT): INT;    (* no more writing to the socket fd; the other end reads an end *)
+proc peer*(fd: INT): (Remote, INT);   (* who is at the other end of the connected socket fd *)
+proc socketPair*: (INT, INT, INT); (* two connected stream sockets, and 0 *)
+proc sendFds*(fd: INT; s: []U8; fds: []INT): INT;   (* send, and with it fds, to a Unix socket *)
+proc receiveFds*(fd: INT; buf: []U8; fds: []INT): (INT, INT);   (* read, and the fds that came with it *)
+
+proc memFile*(size: INT): INT;     (* a file of size zero bytes, in memory, with no name: its fd *)
+proc mapFile*(fd, size: INT): ^U8; (* the first size bytes of fd, shared; munmap gives them back; or nil *)
+

info follows a symbolic link: size, dir and file are those of what it names, and symlink says the path was a link, so that a program walking a tree can choose not to follow one back up it. A link to nothing is -ENOENT, as a missing file is. file lets a walk open only what holds data: opening a pipe would wait for a program to write to it.

+

nextEntry gives every name in the directory except . and .., in no particular order. entryKind says what the name it gave last is, a file, a directory, a symbolic link (whatever it names) or something else, as the directory itself records it, so that a program walking a tree needn’t ask linkInfo of every name, a system call each; where the file system doesn’t record it, it is unknown, and linkInfo must be asked. rawMode turns off what the terminal does with keys before the program reads them (echo, line editing, signals, flow control), and NL to CR NL on output. A program that turns it on restores it before it ends: Rt.atExit is the place.

+

Files. open gives a file for what how asks: reading, writing or both; creating it if it is missing, readable by all and writable by its owner; with exclusive, failing with -17 (EEXIST) if it is there, as a program does that makes a lock or a file of its own; truncating it to nothing; appending, each write going to its end, however other programs write it too. openMode is open that gives a file it makes the bits mode, less those the umask takes away: 1EDH (755) for a program, 124H (444) for a file never to be written; open gives 1A4H (644). seek moves to pos from the start of the file, or from its end if fromEnd, where a negative pos reads back from the end; position says where the file is, without moving. truncate makes the file size bytes long, cutting it or adding zeros, and leaves the position where it was. sync returns once what was written to the file is on the disk, as a program needs before it says a file is saved; syncAll returns once everything written to the file system that holds the file is on the disk, at once rather than a file at a time, and may flush other file systems too. lock takes the file’s lock for one open file alone: another that asks for it waits if wait, and otherwise fails with -11 (EAGAIN). The lock goes when the file is closed or the program ends, however it ends, so it never goes stale as a file made with exclusive does. lockShared takes it shared, as a program that only reads asks it: any number may hold it so at once, and lock waits, or fails, until the last has let it go, as a shared one waits for the one that lock took. Both are flock’s, so they agree with any other program that takes the file’s lock so. closeChecked closes as close does, and says if that failed: a file system may say only then that what was written never reached it, a full disk or a quota over NFS, so a program that must know its writes landed, as one that copies a backup, asks it. The fd is closed either way, so a failed closeChecked, -4 (EINTR) too, is never tried again. infoOf is info of an open file: its size is what it holds now, however it was written; linkInfo is info of a symbolic link itself, not what it names, so that symlink is true, dir and file false, and size the length of what it names, which need not be there. Info.mtime is what a program checks to see whether a file changed under it, and Info.ino whether it is still the same file, not one renamed over it; 0 on a target whose files have none. Info.dev is the file system the file is on: two files are one only if both dev and ino agree, which is how a program following links finds that one has led it back into a directory it is already in. Info.links is how many names the file has: more than 1 if a hard link shares it, so that writing to it writes to a file named elsewhere too; 0 on a target that doesn’t say. Info.mode holds the nine bits of rwxrwxrwx, and chmod sets them, 1EDH (755) for a program, 1A4H (644) for data; Info.special holds the three above them, set-user-id 800H, set-group-id 400H and sticky 200H, which chmod sets too, with mode | special, as a program that copies a file keeps them. Info.uid and Info.gid are the owner’s and the group’s numbers; chown sets them, with -1 for one to leave as it is, so that a program that saves a file by writing another and renaming it over the first can give it the first’s owner (only root may give a file to another user). makeFifo makes a named pipe, given the bits mode as makeDirMode is; Info of one has file and dir false, and open with nonblocking doesn’t wait for its other end. makeDirMode is makeDir that gives the directory the bits mode, less those the umask takes away, as openMode gives a file: 1C0H (700) for one only its owner may enter. Of the three above them, Linux gives a new directory only sticky; it takes set-group-id from the directory it is made in. setTime sets the file’s time, following a symbolic link, and the time it was last read with it, as a program that copies or restores a file keeps its time, so that a later run sees it unchanged: sec seconds and nsec, from 0 to 999999999, nanoseconds since 1970. Info.mtime holds the time in nanoseconds, which an I64 holds from 1677 to 2262 only; Info.seconds holds it in whole seconds, rounded down, whatever it is, so a program that copies times exactly takes Info.seconds, and the nanoseconds as mtime - seconds * 1000000000, which is right in any year, since the wrapping cancels out (section 6.1).

+

Programs. openPty makes a pseudo-terminal, a terminal that a program, a terminal emulator, plays the screen and the keyboard of: what it writes to the fd is typed, and what the programs on the terminal write it reads.

+

spawn starts the program at p.path, with p.args as its arguments, the first being its name. A p.path without a / is looked for as a shell looks for a command, and as C’s execvp does: in each directory of this program’s PATH in turn, an empty one being the working directory, or of /bin:/usr/bin if PATH is unset or empty; the first that runs is the program. If there is none, spawn says so, -2 (ENOENT) or -13 (EACCES), before it makes a child: no program is started, and no process id given for a program that was never there. A p.path with a / is not looked at first, and a program that is there but that the kernel then refuses to run (not a program, a bad interpreter) is a child that ends with status 127. Its environment is this program’s with each NAME=value of p.env added or put in place of the old value, or, if p.onlyEnv, p.env alone. It starts in p.dir. Its standard input, output and error are p.fds; a 0 gives it this program’s own, so {path: "ls", args: ["ls"]} runs ls as a shell runs it, with every other field zero. It gets no other open file but those of p.more, each at its own number, as a shell passes 3<file on, every signal does what it does at first, and none is blocked; with p.keepIgnored, a signal this program ignores stays ignored in it, as the kernel’s execve leaves it, which is what a program run under nohup wants of the programs it starts. If p.tty is a pseudo-terminal’s fd, the program starts a session on that terminal: it is its controlling terminal, and its standard input, output and error, but that a p.fds[i] that is not 0 is that file instead, as for a job that reads /dev/null; p.group is not used.

+

p.group puts the program in a process group, the programs that a shell’s job is made of: -1 makes it the first of a new group, whose number is its process id, and the other programs of the job join that number. The terminal gives its keys, and the signals of Ctrl-C and Ctrl-Z, to one group, the one in its foreground: p.foreground puts the program’s group there before it starts, and foreground puts any group there, as a shell does to take the terminal back. setGroup moves a program to a group, as the shell does for each program it starts, for whichever of the two runs first; a shell runs in a group of its own, setGroup(0, 0).

+

exec runs the program p describes in this program’s place, as a shell’s exec cmd does, found and started as spawn would start it, p.tty, p.group, p.foreground, p.fds and p.dir included, except that it keeps this program’s other open files: each stays open in the program unless it is closed on exec, as the files open, pipe, a socket or memFile gives are, unless keepOnExec(fd, true) was said of them; dup and dupTo give files that stay open; and those of p.more are kept. It returns only if the program can’t run: -2 (ENOENT) or -13 (EACCES) if there is none to run, with nothing done; or, if the program is found but won’t start, minus the errno, with what p asks of the terminal, the group, the files and the directory done, and this program’s signals as they were.

+

execve(path, args, env) is the kernel’s execve, for a shell, which has looked for the program along its own PATH and set up the child already: the program at path is run with args and with env, NAME=value, for its whole environment. Nothing is searched for, and every fd and signal stays as it is, but that a handled signal does what it does at first: an ignored one stays ignored, as trap '' HUP wants of the command it comes before. It returns only if it can’t: minus an errno, with nothing changed.

+

A shell moves its own files with dup and dupTo, for 2>&1 and exec >log and around a builtin: dupTo(fd, into) makes into the same open file as fd, closing what into was, and dup gives a new fd for it, the lowest free, as a shell saves a file to give it back. dupAbove(fd, 10) gives one at 10 or above, closed on exec, out of the way of the fds a script names (3>log), as a shell keeps its own. fork copies this program, which goes on from there in both: it is 0 in the copy and the copy’s process id in this one, as a shell runs a builtin or a procedure as a stage of a pipe. Only the thread that calls it is copied, so a program with threads mustn’t; and what Out keeps is copied too, to be written twice, so Out.flush comes first. setsid gives the copy a session of its own, with no controlling terminal, as a daemon does so that closing its terminal doesn’t reach it; it is -1 (EPERM) for a program that leads a process group already, which the copy doesn’t. group is the process group this program is in: a shell starting on a terminal waits until it is foregroundOf(0) before it takes it. access says whether this user, by its real ids, may read, write or execute a file, as test -r, -w and -x ask, which Info.mode alone can’t say; an empty how asks only whether it is there. open refuses executing, with -22 (EINVAL). nonblocking opens a file without waiting: a fifo opened to write waits for a reader and a fifo opened to read waits for a writer, but with nonblocking the open returns at once (-6, ENXIO, for a write with no reader), and a read or write that would wait is -11 later, as setBlocking(fd, false) makes it, and blocking(fd) says which: 1 if they wait, 0 if not. A file open, openMode, openRead or create gives is closed in a program exec or execve starts, as pipe’s are, so that a fifo or a log one program holds doesn’t reach every program it runs; keepOnExec(fd, true) keeps one open, and spawn is unchanged, since it passes its fds and more as before. umask sets the bits taken away from the mode of every file this program, and those it starts, make, and says what they were. envAt gives the environment one variable at a time, from 0, for a shell to list it and to pass it on whole with onlyEnv. env gives “” for a variable that is unset and for one set to nothing; findEnv tells them apart, as TZ needs, unset meaning the local time and empty meaning UTC. setEnv refuses a name that is empty or holds an =, and a 0 in either, with -22; as C’s setenv, it isn’t safe while another thread reads the environment, and what env gave for a variable may be gone once it sets that variable again. getMode reads a terminal’s modes, and setMode sets them again once what was written is sent, so that a shell keeps them for each job: a program stopped by Ctrl-Z with its terminal raw gets it back raw, and the shell its own between. cpuTime says how long the processor ran this program, in its own code and in the system for it, or, if children, the programs it started and has waited for, as time and times say. limit gives a limit, limitFiles say, soft and hard, and setLimit sets them, as ulimit does: a program may raise its soft limit up to the hard one, and lower either. uid is the user this program runs as, euid the one whose rights it has, 0 for root, as a prompt shows #; hostName is the machine’s name. processors counts the processors the program may run on, as the system’s affinity mask allows, for a program that makes a thread to each; it is never less than 1.

+

wait waits for the program pid to change, for any of this program’s if pid is -1, or for any of the group g if pid is -g, as a shell waits for a job’s programs, and says which one, and how: exited, with its exit status; killed, with the number of the signal that ended it; or stopped, by Ctrl-Z or a signal, with the signal’s number. Without block it doesn’t wait, and is 0 and running if no program changed. A program that has nothing to wait for is -10 (ECHILD). waitExit(pid) is wait that blocks until a program ends, and not for one that is stopped, so that a program waiting for its editor isn’t woken by Ctrl-Z. kill sends a program a signal, sigTerm to end it; to a group, if pid is minus its number.

+

Signals. catch takes the signals sigs away from what they would do, ending the program most of them, and gives an fd that is ready to read when one comes, so that a program waits for signals with ready and readyOf as it waits for keys or a server. caught gives each signal that came, in turn. A later catch adds to the signals caught and gives the same fd. Catching sigKill or sigStop, or the signals Rt reports, SIGSEGV and SIGFPE, is -22 (EINVAL). ignore makes a signal do nothing, as a shell ignores sigTtou so that it can take its terminal back, and ignore(sig, false) gives it back what it does at first. On a signal that catch took, either gives it up: the signal is no longer caught, with its default action or ignored, and catch’s fd gives the signals still caught. A program that spawn starts begins with neither. ignored(sig) says whether a signal does nothing now, because the program ignored it or because the one that started this one left it so, as a program in the background or under nohup finds sigInt and sigHup: it should leave those alone, and handle or catch the rest.

+

To wait for a child, a signal or a time, whichever is first, catch sigChld with the other signals and wait in ready on catch’s fd: a child that ends makes sigChld ready there, as a signal that came before the wait does, since catch holds it until caught takes it, so none falls between a wait that found nothing and the sleep after it. When the fd is ready, call caught, then wait(pid, false). handle can’t do this: a signal noted just before the call it should break isn’t seen by it.

+

handle is for a program that must see a signal while it waits in a system call, as a shell waiting for its foreground program, or for a key, sees Ctrl-C: the signal is noted, and the call it comes during, wait, read, ready and the rest, fails with -4 (EINTR) rather than going on; sleep sleeps its time all the same. came(sig) says whether it came since the last time it was asked. Nothing else runs when the signal comes, so the program does what it does after it, in its own time; Out and Files try again after -4. ignore(sig, false) gives the signal back what it does at first, and the signals catch refuses, handle refuses too.

+

Time. clock is for measuring how long something takes: it never goes back, and says nothing of the date. now is the date and time, which a person or the network may set back. sleep waits ms milliseconds.

+

Sockets. connect is for talking to a server on the same machine, an X server at /tmp/.X11-unix/X0 say; connectTcp for one across the network, given its address as numbers, "127.0.0.1" or "::1": turning a name into an address is a library’s work over these. connectUdp gives a socket of datagrams, each send one message to that address and each read one message from it, as a program asks a name server. What a socket receives comes by read, what it sends goes by send, and close ends it. send is write for a socket, except when the other end has closed it: write would stop the program with the signal SIGPIPE, where send returns -32 (EPIPE), so that a program learns its server has gone and can end as it wants. listen and listenTcp are the other side: a server’s socket, on path, which must not be there yet, or on port at addr, "0.0.0.0" or "::" for every address the machine has; accept gives each connection that comes, as a socket of its own. A server started on port 0 gets a port the system chooses, which localPort says, as a test does that must not take a port in use. connectTcp waits as long as the system does, minutes for a host that never answers; connectTcpWithin gives up after ms milliseconds, with -110 (ETIMEDOUT).

+

listenUdp is the server’s side of connectUdp: a socket of datagrams from anyone, as a name server has. receive gives the next datagram, at most LEN(buf) bytes of it, the rest lost, and a Peer that reply sends an answer to.

+

closeWrite ends this side’s writing to a socket, so that the other end reads an end of input and can still answer on the same socket: a client sends its request, says it is done, and reads the reply. peer says who is at the other end of a connected socket: for a TCP one its address and port; for a Unix one the user and process that made the connection, as the system recorded them, so that a server can check that its client is the same user instead of trusting a directory’s mode. sendNow is send that never waits: where the socket has no room it gives -11 (errAgain), without making reads on it non-blocking too. socketPair makes two connected stream sockets at once, as a listen, connect and accept would, with no name on disk. Each is closed in a program exec starts. accept gives -103 (errConnAborted) for a client that went before it was taken.

+

Passing files and sharing memory. A program can give another an open file over a Unix socket: sendFds sends s, at least one byte, and with it fds, at most 16, each a file the other program then has open too; receiveFds reads into buf as read does, puts the fds that came with it in fds, as many as there is room for, closing the rest, and says how many bytes and how many fds. Each is closed in a program exec starts. memFile makes a file that lives in memory, of size zeroed bytes, and mapFile maps it, or any file, so that what one program writes there another sees at once: so a program hands an X server or a Wayland compositor its pixels, by sendFds of a memFile both map, rather than by copying them down a socket. mapFile needs a file open to read and write; mapRead maps one that is open only to read, a dictionary that isn’t the user’s to write, for reading only: a write there stops the program. protect changes what may be done with pages mmap gave, from a page boundary: read, write, both, or neither, so that touching them stops the program, as a guard page after a buffer does, or a reserve mapped in full and opened as it fills. It takes the address as the system does, so with a C library it is that library’s whether an address not on a page boundary is -22 (EINVAL) or rounded down.

+

readyOf waits on several file descriptors at once, as a program does that listens to a server and a terminal both; a descriptor at its end, or failed, counts as ready, since a read of it won’t wait. It looks at the first 64 of fds, and connect and listen take a path of at most 107 bytes, as struct sockaddr_un holds; a longer one is -36 (ENAMETOOLONG). A path that starts with a zero byte is one of Linux’s abstract names (D-Bus’s unix:abstract=), which has no file: the address is as long as the name, with no zero after it.

+

poll is readyFor without its limits. Each Poll names a descriptor fd and whether to wait to read from it, to write to it, or both; poll waits up to ms milliseconds (as long as it takes if ms < 0), sets every one’s ready, and gives how many are: all of them, in one call, not the first. It takes any number of descriptors (the list the system wants is on the stack for 64 or fewer, and in memory from mmap, given back before it returns, for more; -12 if there is none). A descriptor at its end or failed is ready, as for readyOf; so is one that isn’t open, and a read or a write of it is -9 (EBADF); a negative fd is never ready. A timeout is 0 and a failure minus an errno (-4, if a signal handle took broke in), where readyFor gives -1 for both. readyFor and readyOf are written over it.

+

A program that both reads from a descriptor and writes much to it, as a terminal writes what is pasted to its program while it reads what the program writes back, must not wait on either: the program may be waiting for its own writes to be read. setBlocking(fd, false) has a read or a write on fd that would wait return -11 (EAGAIN) at once, a write having written what there was room for; readyFor waits, as readyOf does, for something to read on any of reads or for room to write on any of writes. A descriptor in both is given once, when it is ready for either; the 64 it looks at are reads, then writes.

+

Strings, buffers and collections.

+
module Str;
+proc cmp*(a, b: []U8): INT;           (* -1, 0 or 1 as a sorts before, with or after b, byte by byte *)
+proc eq*(a, b: []U8): BOOL;
+proc eqFold*(a, b: []U8): BOOL;       (* eq, an ASCII letter's capital and small the same *)
+proc copy*(a: ^Mem.Allocator; s: []U8): ([]U8, BOOL);   (* s's bytes in memory from a; false if a has none *)
+proc free*(a: ^Mem.Allocator; s: []U8);                 (* what copy gave from a, given back; "" is none *)
+proc hash*(s: []U8): U64;             (* FNV-1a, 64 bits *)
+proc find*(s, sub: []U8): INT;        (* where sub first starts in s, or -1 *)
+proc findFrom*(s, sub: []U8; from: INT): INT;   (* where sub first starts in s at or after from, or -1 *)
+proc findLast*(s, sub: []U8): INT;    (* where sub last starts in s, or -1 *)
+proc hasPrefix*(s, p: []U8): BOOL;
+proc hasSuffix*(s, x: []U8): BOOL;
+proc trim*(s: []U8): []U8;            (* s without the spaces at either end *)
+proc trimLeft*(s: []U8): []U8;        (* s without the spaces at its start *)
+proc trimRight*(s: []U8): []U8;       (* s without the spaces at its end *)
+proc cut*(s, sep: []U8): ([]U8, []U8, BOOL);   (* what comes before the first sep, and after it *)
+proc field*(s: []U8): ([]U8, []U8);   (* the first run of bytes in s that aren't spaces, and what follows it *)
+proc isDigit*(c: U8): BOOL;           (* 0 to 9 *)
+proc isLetter*(c: U8): BOOL;          (* A to Z, a to z *)
+proc isSpace*(c: U8): BOOL;           (* a space, as trim takes it *)
+proc isPunct*(c: U8): BOOL;           (* printable, and neither a letter, a digit nor the blank *)
+proc hexVal*(c: U8): INT;             (* c's value as a hexadecimal digit, or -1 *)
+proc lower*(s: []U8);                 (* s's ASCII capitals made small, in place *)
+proc upper*(s: []U8);                 (* s's ASCII small letters made capitals, in place *)
+proc join*(var b: Buf.Buf; parts: [][]U8; sep: []U8);   (* the parts added to b, sep between each two *)
+proc replace*(var b: Buf.Buf; s, old, new: []U8);       (* s added to b, with new for each old in it *)
+proc encode*(c: I32): ([4]U8, INT);   (* c in UTF-8: its bytes, and how many *)
+proc decode*(s: []U8): (I32, INT);    (* the character s starts with, and its length in bytes *)
+proc decodeLast*(s: []U8): (I32, INT);   (* the character s ends with, and its length in bytes *)
+proc next*(s: []U8; i: INT): (I32, INT);  (* the character at i, and where the next starts; -1 at the end *)
+proc valid*(s: []U8): BOOL;           (* s is UTF-8, every character rightly spelled *)
+proc chars*(s: []U8): INT;            (* the characters in s, as decode reads them *)
+proc toInt*(s: []U8): (I64, BOOL);    (* s, in decimal; false if it isn't a number an I64 holds *)
+proc toHex*(s: []U8): (U64, BOOL);    (* s, in hexadecimal; false if it isn't a number a U64 holds *)
+proc toU64*(s: []U8): (U64, BOOL);    (* s, decimal digits only; false if it isn't one, or a U64 can't hold it *)
+proc fromC*(p: ^U8): []U8;            (* the bytes at p up to its zero byte, not copied; "" for nil *)
+proc toC*(s, out: []U8): ^U8;         (* s copied into out with a zero byte after it, which holds LEN(s) + 1 bytes at least: PTR(out) *)
+const Base64*, Base64Url*;            (* the digits of RFC 4648, sections 4 and 5 *)
+proc base64With*(s, out, alphabet: []U8; pad: BOOL): INT;   (* s in base64 with alphabet's 64 digits into out, which holds base64Size(LEN(s)) bytes at least, padded with = if pad: the bytes written *)
+proc unbase64With*(s, out, alphabet: []U8; pad: BOOL): (INT, BOOL);   (* s, base64 as base64With wrote it, into out, which holds (LEN(s) + 3) div 4 * 3 bytes at least: the bytes written; false if s is not that *)
+proc base64Size*(n: INT): INT;        (* the bytes base64 makes of n bytes: 4 for each 3, or part of 3 *)
+proc base64*(s, out: []U8): INT;      (* s in base64 into out, which holds base64Size(LEN(s)) bytes at least: the bytes written *)
+proc unbase64*(s, out: []U8): (INT, BOOL);   (* s, base64, into out, which holds LEN(s) div 4 * 3 bytes at least: the bytes written; false if s is not base64 *)
+proc fromInt*(n: I64): ([20]U8, INT); (* n in decimal: its bytes, and how many *)
+proc le*(s: []U8): U64;               (* s, at most 8 bytes, the first the lowest *)
+proc be*(s: []U8): U64;               (* s, at most 8 bytes, the first the highest *)
+proc putLE*(s: []U8; v: U64);         (* v into s, the lowest byte first *)
+proc putBE*(s: []U8; v: U64);         (* v into s, the highest byte first *)
+
+module Buf;
+type Buf* = record len*: INT; ... end;
+proc init*(var b: Buf; a: ^Mem.Allocator);
+proc room*(var b: Buf; n: INT): BOOL;    (* room for n more bytes; false if the allocator has none *)
+proc add*(var b: Buf; c: U8);
+proc str*(var b: Buf; s: []U8);
+proc spare*(var b: Buf; n: INT): []U8;   (* room for n more bytes, and those bytes, to fill *)
+proc bytes*(const b: Buf): []U8;         (* what it holds, until it next grows *)
+proc cut*(var b: Buf; n: INT);           (* only the first n bytes kept, its memory kept *)
+proc reset*(var b: Buf);                 (* emptied, its memory kept *)
+proc done*(var b: Buf);                  (* its memory given back *)
+
+module Fmt;
+type Arg* = variant
+    int(i: I64);
+    uint(u: U64);
+    hex(h: U64);
+    lowHex(h: U64);
+    str(s: []U8);
+    char(c: U8);
+    bool(b: BOOL);
+    real(r: F64; places: INT);
+end;
+const ShortMost* = 24;                      (* the longest Fmt.short *)
+proc short*(x: F64; var out: [ShortMost]U8): []U8; (* x in the fewest digits that read back, in out *)
+proc print*(f: []U8; args: []Arg);              (* to standard output *)
+proc eprint*(f: []U8; args: []Arg);             (* to standard error, once Out is flushed *)
+proc write*(var b: Buf.Buf; f: []U8; args: []Arg); (* added to b *)
+proc into*(out: []U8; f: []U8; args: []Arg): (INT, BOOL); (* into out: the bytes, and false if cut short *)
+
+module List(T);
+type
+    Node* = record next*: ^Node; val*: T; end;
+    List* = record head*: ^Node; len*: INT; ... end;
+proc init*(var l: List; a: ^Mem.Allocator);
+proc push*(var l: List; v: T): BOOL;     (* v at the front; false if the allocator has no room *)
+proc pop*(var l: List): (T, BOOL);       (* the front value, taken off; false if the list is empty *)
+proc reverse*(var l: List);
+proc clear*(var l: List);
+
+module Map(K, V; hash: proc(k: K): U64; eq: proc(a, b: K): BOOL);
+type Map* = record len*: INT; ... end;
+proc init*(var m: Map; a: ^Mem.Allocator);
+proc put*(var m: Map; k: K; v: V): BOOL;         (* k now maps to v; false if there was no room *)
+proc remove*(var m: Map; k: K): BOOL;            (* false if k wasn't there *)
+proc get*(const m: Map; k: K): (V, BOOL);        (* what k maps to, and whether it maps to anything *)
+proc next*(const m: Map; i: INT): (INT, K, V);   (* the entry after i *)
+proc done*(var m: Map);                          (* its memory given back, leaving it empty *)
+
+module Vec(T);
+type Vec* = record len*: INT; ... end;
+proc init*(var v: Vec; a: ^Mem.Allocator);
+proc room*(var v: Vec; n: INT): BOOL;    (* room for n more; false if the allocator has none *)
+proc push*(var v: Vec; x: T);            (* x added at the end *)
+proc pop*(var v: Vec): (T, BOOL);        (* the last element, taken off; false if the array is empty *)
+proc add*(var v: Vec): ^T;               (* a new element at the end, zero, to fill in place *)
+proc tryPush*(var v: Vec; x: T): BOOL;   (* push; false, and v as it was, if there is no room *)
+proc tryAdd*(var v: Vec): (^T, BOOL);    (* add; nil and false, and v as it was, if there is no room *)
+proc resize*(var v: Vec; n: INT);        (* n elements: cut short, or the new ones zero *)
+proc insert*(var v: Vec; i, n: INT);     (* n zero elements opened at i; stops the program if there is no room *)
+proc remove*(var v: Vec; i, n: INT);     (* the n elements from i taken out, those after moved down *)
+proc all*(const v: Vec): []T;            (* the elements, until it next grows *)
+proc reset*(var v: Vec);                 (* emptied, its memory kept *)
+proc done*(var v: Vec);                  (* its memory given back *)
+
+module Sort(T; less: proc(a, b: T): BOOL);
+proc sort*(s: []T);
+
+module Math;
+const pi* = 3.141592653589793;
+proc sqrt*(x: F64): F64;
+proc pow*(x, y: F64): F64;            (* x to the power y *)
+proc floor*(x: F64): F64;
+proc ceil*(x: F64): F64;
+proc round*(x: F64): F64;             (* to the nearest whole number; a half away from 0 *)
+proc roundEven*(x: F64): F64;         (* to the nearest whole number; a half to the even one *)
+proc exp*(x: F64): F64;
+proc ln*(x: F64): F64;
+proc log2*(x: F64): F64;
+proc log10*(x: F64): F64;
+proc sin*(x: F64): F64;
+proc cos*(x: F64): F64;
+proc tan*(x: F64): F64;
+proc tanh*(x: F64): F64;              (* from -1 to 1 *)
+proc asin*(x: F64): F64;              (* from -pi/2 to pi/2 *)
+proc acos*(x: F64): F64;              (* from 0 to pi *)
+proc atan*(x: F64): F64;              (* from -pi/2 to pi/2 *)
+proc atan2*(y, x: F64): F64;          (* the angle of (x, y) from the x axis, from -pi to pi *)
+proc bits*(x: F64): U64;              (* the bits of x, as IEEE 754 lays them out *)
+proc fromBits*(u: U64): F64;          (* the F64 whose bits are u *)
+proc mul*(a, b: U64): (U64, U64);     (* a times b: the low 64 bits of the product, and the high *)
+proc divMod*(hi, lo, d: U64): (U64, U64); (* hi, lo divided by d: the quotient and the remainder; hi < d *)
+proc toReal*(s: []U8): (F64, BOOL);   (* s as a real, the F64 nearest it; false if it isn't one *)
+

A Buf, a List, a Map and a Vec take their memory from the allocator init gives them. Buf.add, str and spare stop the program, as a failed check does, if the allocator has no room; room asks first. A program reads into a Buf through spare, then adds what it read to len: s := Buf.spare(b, 4096); n := Sys.read(fd, s); if n > 0 then INC(b.len, n); end;. cut takes back what was added, to a length it had: start := b.len; ...; Buf.cut(b, start);; a length past len stops the program, as an index past the end does. A Vec is Buf for any T: one block, which doubles when it is full, so push costs the same on average however long it grows. all gives the elements as a slice, indexed and checked as any is, and v.len is their number; the slice, and what add gives, are good until the array next grows. pop takes the last element off, keeping the memory. push, add and resize stop the program, as Buf.add does, if the allocator has no room; room asks first: import Lines := Vec([]U8);. Fmt’s format takes the next argument at each {}; {{ and }} stand for { and }. A Map hashes and compares its keys with the procedures it is given: import Count := Map([]U8, INT, Str.hash, Str.eq);.

+

Str reads and writes UTF-8. encode writes a character, of at most 10FFFFH, in one to four bytes; a number that isn’t one becomes FFFDH, the character that stands for a wrong one. decode reads the first character of s, and gives FFFDH and 1 for a byte that doesn’t start one rightly, and 0 and 0 for an empty s: a continuation, a byte followed by too few continuations, a surrogate, a character beyond 10FFFFH or one spelled in more bytes than it needs. decodeLast reads the last character in the same way, to walk a string backwards. valid says that decode finds no such byte in s, and chars counts the characters, each such byte one. next walks a string a character at a time, as decode reads them: from 0, it gives the character at i and where the one after it starts, and 0 and -1 when i is at the end, or past it:

+
c, i := Str.next(s, 0);
+while i >= 0 do
+    ...                               (* c is a character of s *)
+    c, i := Str.next(s, i);
+end;
+

A string is bytes, and Str takes no more of Unicode than UTF-8: lower, upper and eqFold change and match ASCII letters alone, the character tests know ASCII alone, and nothing says how wide a character is on a terminal, nor which spellings of a text are the same.

+

A space, to isSpace, trim, trimLeft, trimRight and field, is a blank, a tab, a line feed, a carriage return, a vertical tab or a form feed. cut gives what comes before the first sep in s, what comes after it, and true; or s, an empty string and false if s has no sep. field passes the spaces at the start of s and gives the bytes up to the next space or the end, and the rest of s from there; two empty strings if s holds only spaces. They take a string apart without memory of their own, each part a slice of s:

+
line, rest, more := Str.cut(text, "\n");     (* the first line, and the others *)
+key, val, ok := Str.cut(line, "=");
+w, rest := Str.field(line);                 (* the words of a line *)
+while LEN(w) > 0 do
+    Out.str(w); Out.ln;
+    w, rest := Str.field(rest);
+end;
+

lower and upper write s’s bytes, so they take a variable’s, not a string literal’s (section 5.10). join and replace add to a Buf as Buf.str does; an empty old adds s as it is.

+

toInt reads a decimal number, with a - or + before it if any, and nothing else. toHex reads hexadecimal digits, capitals or not, and nothing else: no sign, 0x or H. fromInt writes a number as Out.int does, with a - if it is negative, its bytes the first of the 20 it gives. toU64 reads a decimal number as toInt does, but digits only (no sign), up to the largest U64: what Fmt.uint writes.

+

fromC and toC are the two ends of a call to C. fromC makes a slice of the bytes at a pointer up to its zero byte, without copying them; nil gives "". toC copies s into out, puts a zero after it and gives PTR(out), so a call reads C.realpath(Str.toC(path, room), ...). out holds LEN(s) + 1 bytes at least; a shorter one stops the program, as any slice does.

+

base64With and unbase64With take the 64 digits as alphabet and say with pad whether = pads a last group: Base64Url is section 5’s, with - and _, and Base64 section 4’s. Without padding a last group has 2 or 3 digits, and a length 1 more than a multiple of 4 is no base64. base64 and unbase64 are Base64 with padding. In detail, base64 writes s as RFC 4648 (section 4) does: the digits A to Z, a to z, 0 to 9, + and /, and = to pad a last group of 1 or 2 bytes to four. unbase64 reads that and nothing else: its length a multiple of 4, = only as the last one or two bytes, and the bits of the digit before the padding that no byte uses all 0, so a byte string has the one spelling base64 gives it. Line breaks, missing padding and the - and _ of base64url are the caller’s to mend first; unbase64 of such a string is false, and what it wrote into out is not to be used. The caller gives the room, as Fmt does: an out shorter than the comment says stops the program, as indexing past a slice does.

+

le and be read an unsigned number of up to 8 bytes in a fixed order, little-endian or big-endian, whatever the machine’s own, and putLE and putBE write one; more than 8 bytes stops the program. They are how a file format or a network protocol is read and written:

+
len := U32(Str.le(header[4..8]));
+Str.putBE(packet[0..2], U64(port));
+

Math.toReal reads a real as a constant is written (section 2), with a - or + before it if any, its point and the digits after it, or its exponent, left out if it has none, and e taken as E: 2, -0.5 and 1.5e-3 are reals to it. It gives the F64 nearest the number, and false for anything else, or a number too big for an F64.

+

Map.next walks a map: from 0, it gives the next entry and the number to pass for the one after it, and -1 when there are no more. A walk sees each entry once if the map doesn’t change during it:

+
i, k, v := Names.next(names, 0);
+while i >= 0 do
+    Fmt.print("{} is {}\n", [Fmt.str(k), Fmt.int(v)]);
+    i, k, v := Names.next(names, i);
+end;
+

Sort.sort puts s in the order less gives, in place, without memory of its own, in time n log n at most; two elements equal by less may change places. Math’s procedures are as C’s math.h has them, to within the last bit or so; roundEven is IEEE 754’s default rounding, as Pascal’s Round, where round is C’s. Fmt.real(x, places) writes x with places digits after the point, at most 9, rounded to the nearest; from 1E15 on, with an exponent, as 1.50E17; and nan, inf and -inf as themselves. Fmt.short(x, out) writes x into out, from 0, and gives those bytes: the fewest significant digits that Math.toReal reads back as the same F64, and of two such the nearer x: 0.1, not 0.10000000000000001; 42, with no point; 0.0001; and below 1E-4 or from 1E15 on with an exponent, as 1.5E17 or 5E-324. Zero keeps its sign, 0 or -0, and nan and inf are as real writes them. The longest is Fmt.ShortMost bytes, so a call is var d: [Fmt.ShortMost]U8; Fmt.print("{}", [Fmt.str(Fmt.short(x, d))]);, and a width goes with str. The bytes are out’s: a second call with the same out overwrites them. hex writes capitals and lowHex lower case, neither with a 0x. A width between the braces pads an argument to that many bytes: {2} with spaces on the left, {02} with zeros on the left, after a sign ({04} of -7 is -007), {-10} with spaces on the right. A longer argument is written whole. A { followed by anything but } or a width is dropped, as before. Fmt.print("{2}:{02} U+{04}", [Fmt.int(3), Fmt.int(7), Fmt.hex(0E9H)]) writes 3:07 U+00E9. Fmt.into formats into a slice the caller gives, with no memory of its own, for a library that has no heap: it gives the bytes written, and false if the slice was too short and the text is cut there.

+

Files and Opt are what most programs need of their command line. Files.writeAll writes again after a short write or a signal, as a pipe or a socket needs, and write is made over it. realPath adds to b the absolute path of what path names, with no ., .. or symbolic link in it, and leaves the working directory alone: -2 (ENOENT) if a part isn’t there, -20 (ENOTDIR) if a file is used as a directory, and -40 (ELOOP) after 40 links. b is left as it was on an error. removeTree removes a file, or a directory with all it holds; a symbolic link is removed itself and never followed.

+
module Files;
+proc arg*(i: INT): []U8;                     (* argument i; 0 is the program's name; "" if there is none *)
+proc read*(path: []U8; var b: Buf.Buf): BOOL;   (* the whole file added to b *)
+proc load*(path: []U8; var b: Buf.Buf): INT;    (* as read: 0, or minus the errno that stopped it *)
+proc write*(path, data: []U8): BOOL;         (* the file made to hold data; false if it or its close failed *)
+proc writeAll*(fd: INT; s: []U8): INT;       (* all of s written to fd; 0, or minus the errno *)
+proc realPath*(path: []U8; var b: Buf.Buf): INT;   (* the absolute path of path, plain, added to b; 0, or minus an errno *)
+proc removeTree*(path: []U8): INT;           (* the file, or the directory and all in it, removed; 0, or minus the first errno *)
+
+module Opt;
+type
+    Row* = variant
+        usage(scope, line: []U8);           (* a synopsis line, without "usage: " *)
+        sub(scope, name, help: []U8);       (* a subcommand *)
+        option(scope: []U8; letter: U8; long, value, help: []U8);
+    end;
+    Parser* = record
+        letter*: U8;    (* the option just read *)
+        value*: []U8;   (* its value; "" for a flag *)
+        long*: BOOL;    (* it was written by its long name *)
+        spelt*: []U8;   (* as it was written, no dashes: "b" or "bar"; to read only *)
+        ...
+    end;
+proc init*(var p: Parser; name: []U8; table: []Row);   (* the arguments from 1 on, by table *)
+proc next*(var p: Parser): BOOL;                      (* the next option; false when they end *)
+proc operand*(var p: Parser): ([]U8, BOOL);           (* the next operand; false when there are no more *)
+proc at*(var p: Parser): INT;                         (* the argument operand would give next *)
+proc scope*(var p: Parser; name: []U8);               (* subcommand name's options, from the word after it *)
+proc number*(const p: Parser; lo, hi: I64): I64;      (* the value just read, a number from lo to hi *)
+proc refuse*(const p: Parser; wants: []U8);           (* the value just read refused, as number refuses one *)
+proc fail*(const p: Parser; text: []U8);              (* the program's own mistake *)
+proc misuse*(const p: Parser; text: []U8);            (* the program's own mistake, with the synopsis *)
+

Opt reads a command line by the rules of the C library’s getopt, with GNU’s long options, so that a program’s options behave as every other Unix program’s. The program describes itself once, in a table of Rows: its synopsis lines, its subcommands and its options. The help and the messages for mistakes are made from the table, so they can’t drift from it; the program’s test of p.letter is the only other place an option appears. The parser is a record the program owns, and the table a slice it keeps as long as the parser: a literal written in the call to init lives as long as the procedure that makes it, and a constant, const Rows: []Opt.Row = [...], as long as the program.

+

A row’s scope is "" for the program itself, or a subcommand’s name: "start", or "remote.add" for a subcommand of remote. An option has a letter, a long name, or both. One with a long name only has a key of its own below '!' for a letter, so that the program can tell it from the others. With a value, the name the help and the messages give it, the option takes a value; with "" it is a flag. A value written in brackets, "[when]", may be left out, and is "" then: it is given only in the option’s own word, --color=always or -calways, never as the next, as getopt’s :: has it, and the help shows it as --color[=when].

+
const wait = 1;     (* the key of --wait, which has no letter *)
+...
+Opt.init(p, "keep", [
+    Opt.usage("", "keep [-v] [--wait secs] start ..."),
+    Opt.sub("", "start", "start a job"),
+    Opt.option("", 'v', "verbose", "", "say more"),
+    Opt.option("", wait, "wait", "secs", "give the job secs to start"),
+    Opt.usage("start", "keep start [-b label] name command [argument ...]"),
+    Opt.option("start", 'b', "bar", "label", "show the job in the bar as label")]);
+while Opt.next(p) do
+    if p.letter = 'v' then verbose := true;
+    elsif p.letter = wait then secs := Opt.number(p, 1, 600);
+    end;
+end;
+w, ok := Opt.operand(p);
+if not ok or (w # "start") then Opt.fail(p, "no command; see keep -h"); end;
+Opt.scope(p, "start");
+while Opt.next(p) do
+    if p.letter = 'b' then bar := p.value; end;
+end;
+job, ok := Opt.operand(p);
+

The rules are getopt’s:

+ +

number reads the value as Str.toInt does. operand reads what options are left first, and the program doesn’t see them. So does at, which says where the operands are: the arguments from operand’s next on are Files.arg(i) for i from at(p) to ARGC() - 1, so that an interpreter hands a script its arguments as they are:

+
script, ok := Opt.operand(p);       (* tery file arg ... *)
+first := Opt.at(p);                 (* file's own arguments, from here on *)
+

-h or --help among a scope’s options prints its help on standard output and ends the program with status 0. init and scope answer it, looking through the scope’s options before next gives one, so that the program has done nothing yet: keep -v -h -x prints the help, and the program never sees -v, nor the mistake. The help is the scope’s synopsis lines, a blank line, and its subcommands, its options and the help itself, each with its line of help:

+
usage: keep start [-b label] name command [argument ...]
+
+  -b, --bar label   show the job in the bar as label
+  -h, --help        print this and exit
+

A scope with several synopsis lines has the others indented under the first; one with none, usage: and its words, as usage: keep start. A scope may give -h to an option of its own, as grep’s “no file names”; help there is --help alone, and its row in the help has no letter.

+

A mistake on the command line is a sentence on standard error, the program’s name first, then the scope’s synopsis lines, as the help begins, and status 2:

+
keep: unknown option -x
+usage: keep start [-b label] name command [argument ...]
+

The sentences are unknown option -x (or --name, up to its =), -b needs a label, --follow takes no value and --wait wants a number from 1 to 600, not '0'; for a number with no top, given the largest I64 for hi, --jobs wants a number from 1 up, not '0'. refuse refuses a value the program reads itself, as number refuses one, naming the option as the user wrote it, -b or --bar: Opt.refuse(p, "a label with no spaces") writes keep: -b wants a label with no spaces, not 'a b', and the synopsis lines. p.spelt is that spelling, for the program’s own sentences. fail writes the program’s own mistakes the same way, but alone, so that the sentence can say where the help is: keep: no command; see keep -h. misuse writes one with the scope’s synopsis lines after it, for a mistake in the operands: Opt.misuse(p, "no tests named").

+

A mistake in the table is the program’s, not its user’s. init checks the table before it reads a word, and ends the program with status 1: keep: option table, row 3: the option is in the scope already. The others are an option with neither a letter nor a long name, a long name with = in it, a letter -, a value with one bracket but not the other, and --help in the table, since it is Opt’s.

+

Width says how many columns of a terminal text takes, for a program with a screen that wraps its lines and cuts them at the window’s edge.

+
module Width;
+proc width*(c: I32): INT;      (* the columns the character c takes: 0, 1 or 2 *)
+proc columns*(s: []U8): INT;   (* the columns the UTF-8 text s takes *)
+

A combining mark, a format character, a control and Hangul’s medial and final jamo take 0 columns; an ideograph, a kana, most emoji and the rest that Unicode calls East Asian Wide or Fullwidth take 2; every other character takes 1, the ambiguous ones among them, as most terminals draw them. These are the C library’s wcwidth’s answers, but for a control, which is -1 there. Width knows characters, not clusters: an emoji joined to another by a zero width joiner, or a flag, counts as its parts. Its tables, about 4 KB, come from Unicode’s data, made again by tools/Widths.raz for a new version of Unicode; a program that imports Width and calls neither procedure carries none of them.

+

Rand, Check and Prop are for testing a program, and are standard library, not core: a target may leave them out. raztest(1) builds and runs the tests that use them.

+

Rand is a seeded generator of numbers, splitmix64: one U64 of state. The same seed gives the same numbers on every machine, so a run can be replayed. It is not for secrets.

+
module Rand;
+type Rand* = record ... end;
+proc init*(var r: Rand; seed: U64);     (* starts r at seed; any seed, 0 too *)
+proc next*(var r: Rand): U64;           (* the next number, all 64 bits of it *)
+proc below*(var r: Rand; n: U64): U64;  (* 0 to n - 1, each as likely as another; n = 0 stops the program *)
+proc range*(var r: Rand; lo, hi: I64): I64;   (* lo to hi, both included; lo must not exceed hi *)
+proc seed*(): U64;                      (* a fresh seed from the kernel, to print and give back to init *)
+
module Dice;
+import Rand, Check;
+
+(* Five rolls of a die from seed, as the digits of a number. *)
+proc rolls(seed: U64): INT;
+var r: Rand.Rand; i, v: INT;
+begin
+    Rand.init(r, seed);
+    for i := 1 to 5 do v := v * 10 + INT(Rand.range(r, 1, 6)); end;
+    return v;
+end;
+
+proc main*;
+begin
+    Check.int("the same seed, the same rolls", rolls(7), rolls(7));
+    Check.ok(rolls(7) >= 11111, "every die shows 1 or more");
+    Check.ok(rolls(7) <= 66666, "every die shows 6 or less");
+end;
+
+end Dice.
+

Check says what a test expects. A check that fails writes FAIL and its words on standard error, with what it got and what it wanted where they differ; the program goes on. At its end, if any check failed, it says how many and exits with status 1, and a run with none failed says nothing and keeps its own status. No call is needed at the end: the first check asks Rt.atExit to make it. A program that stops after a check failed, by Rt.stop or a failed check of the language, ends with status 1 too. mute is for Prop, which searches with the checks silenced.

+
module Check;
+proc ok*(cond: BOOL; what: []U8);                 (* fails, saying what, when cond is false *)
+proc str*(what, got, want: []U8);                 (* fails when got is not want; shows both, escaped, and the byte where they differ *)
+proc int*(what: []U8; got, want: I64);            (* fails when got is not want; shows both *)
+proc mute*(on: BOOL);                             (* while on, checks say nothing and are not counted *)
+proc mutedFailures*(): INT;                       (* how many failed since mute was turned on *)
+
module Digits;
+import Check;
+
+(* How many decimal digits n, not negative, takes. *)
+proc count(n: INT): INT;
+var d: INT;
+begin
+    d := 1;
+    while n >= 10 do n := n div 10; INC(d); end;
+    return d;
+end;
+
+proc main*;
+begin
+    Check.int("0 is one digit", count(0), 1);
+    Check.int("9 is one digit", count(9), 1);
+    Check.int("10 is two digits", count(10), 2);
+    Check.ok(count(1000000) = 7, "a million is seven digits");
+end;
+
+end Digits.
+

Prop tests a property: a procedure that draws values and checks them with Check. A case is the bytes the property drew, and Source gives them as a number, a choice, a flag or a string of bytes; fewer and smaller bytes give simpler values. When a case fails, Prop shrinks it by changing its bytes and running the property again, so no type needs a shrinker of its own, and it saves the case. A property that draws only bytes is a fuzzer.

+
module Prop;
+type Source* = record ... end;
+type Property* = proc(var s: Source);              (* draws from s, checks with Check *)
+proc bits*(var s: Source): U64;                    (* 64 bits, from 8 bytes, the first the highest *)
+proc int*(var s: Source; lo, hi: I64): I64;        (* lo to hi, both included; zeros give lo *)
+proc pick*(var s: Source; n: INT): INT;            (* 0 to n - 1; n at least 1 *)
+proc bool*(var s: Source): BOOL;
+proc bytes*(var s: Source; max: INT; var b: Buf.Buf);   (* b, emptied, then given at most max bytes *)
+proc check*(name: []U8; p: Property);              (* runs p on the saved cases, then on fresh ones *)
+

check runs p on each case saved in the directory $PROP_DIR/name (test/seeds/name if PROP_DIR is unset), then on $PROP_CASES fresh cases (100 if unset), from the seed $PROP_SEED or a new one, or for as many seconds as $PROP_TIME says, if it is set. Each is a whole number. A property that holds says nothing and writes no file. The first case that fails is shrunk and saved in a file named by its hash; standard error says the seed and the file; the shrunk case runs once more with Check heard, and the program ends with status 1. A saved case is run first the next time, so a failure stays found until it is mended; keep the directory with the tests. A case that stops the program, by Rt.stop, a failed check of the language or a signal, can’t be shrunk; it is saved as it was, when the program ends. raztest --seed and --fuzz set PROP_SEED and PROP_TIME.

+
module Reverse;
+import Prop, Check, Buf, Heap;
+
+var
+    b, was: Buf.Buf;    (* the bytes drawn, and a copy of them *)
+
+(* Turns s round, in place. *)
+proc reverse(s: []U8);
+var i: INT; c: U8;
+begin
+    for i := 0 to LEN(s) div 2 - 1 do
+        c := s[i]; s[i] := s[LEN(s) - 1 - i]; s[LEN(s) - 1 - i] := c;
+    end;
+end;
+
+(* Reversing any string twice gives it back. *)
+proc twice(var s: Prop.Source);
+begin
+    Prop.bytes(s, 64, b);
+    Buf.reset(was);
+    Buf.str(was, Buf.bytes(b));
+    reverse(Buf.bytes(b));
+    reverse(Buf.bytes(b));
+    Check.str("reversed twice", Buf.bytes(b), Buf.bytes(was));
+end;
+
+proc main*;
+begin
+    Buf.init(b, Heap.heap);
+    Buf.init(was, Heap.heap);
+    Prop.check("reverse", twice);
+end;
+
+end Reverse.
+
+
+ + + diff --git a/site/public/tour/c.html b/site/public/tour/c.html new file mode 100644 index 0000000..333a844 --- /dev/null +++ b/site/public/tour/c.html @@ -0,0 +1,153 @@ + + + + + +Talking to C - Raz, Set, Go + + + + + + + + + + + + +
+
+

Go · lesson 14 of 15

Talking to C

+
Qsort.raz
module Qsort;
+import Out, Fmt, SYSTEM;
+
+link "libm.so.6";
+
+extern proc qsort(base: ^U8; n, size: UINT;
+    less: proc(a, b: ^U8): I32);
+extern proc cbrt(x: F64): F64;
+
+(* the order of two INTs, as C's qsort wants it *)
+proc order(a, b: ^U8): I32;
+var x, y: ^INT;
+begin
+    x := ^INT(a);
+    y := ^INT(b);
+    if x^ < y^ then return -1; elsif x^ > y^ then return 1; end;
+    return 0;
+end;
+
+proc main*;
+var a: [5]INT; i: INT;
+begin
+    a := [30, 10, 50, 20, 40];
+    qsort(^U8(SYSTEM.ADR(a)), LEN(a), SIZE(INT), order);
+    for i := 0 to 4 do Out.int(a[i]); Out.char(' '); end;
+    Out.ln;
+    Fmt.print("{}\n", [Fmt.real(cbrt(27.0), 3)]);
+end;
+
+end Qsort.
+
10 20 30 40 50 
+3.000
+
+

An extern procedure is found by its name in the C library, or in a library a link line names. Its parameters are integers, reals, pointers and procedures, as C declares them; a raz procedure of such types can be given to C to call back, as order is. A record goes to C by pointer, never by value.

+

What using C costs

+

A program that uses C is linked against it dynamically and starts through it, so that C's own set-up and clean-up run; one that doesn't is a static executable with nothing in it but its own code. A program uses C if any module it uses has an extern or a link of a library.

+

Varargs

+

... after an extern's parameters takes any number of further arguments, as printf wants. A string literal goes as a C string, an integer constant as an INT, a real constant as an F64. An F32 is an error there, since C promotes it; write F64(x).

+
Say.raz
module Say;
+import Out;
+
+extern proc printf(format: ^U8; ...): I32;
+extern proc fflush(f: ^U8): I32;
+extern proc puts(s: ^U8): I32;
+
+proc main*;
+var n: INT; x: F32;
+begin
+    n := 42;
+    x := 2.5;
+    Out.str("raz first\n");
+    Out.flush;                         (* Out has a buffer; so does C *)
+    _ := printf("C says %ld and %.2f and %s\n", n, F64(x), "hello");
+    _ := puts("and puts");
+    _ := fflush(nil);                  (* nil: every C stream *)
+    Out.str("raz again\n");
+end;
+
+end Say.
+
raz first
+C says 42 and 2.50 and hello
+and puts
+raz again
+
+

Out and C's printf keep two buffers, so a program that writes with both flushes one before it writes with the other, or the text comes out of order.

+

Libraries, and C's variables

+

link "libm.so.6"; names a shared library to load at run time. An extern var is C's variable itself: reading it reads C's, assigning it writes C's.

+
Env.raz
module Env;
+import Out;
+
+extern var environ: ^^U8;
+extern proc strlen(s: ^U8): UINT;
+extern proc getenv(name: ^U8): ^U8;
+
+proc main*;
+var p: ^U8; n: INT;
+begin
+    n := 0;
+    while environ[n] # nil do INC(n); end;
+    if n > 0 then Out.str("the environment is not empty\n"); end;
+    p := getenv("RAZ_NO_SUCH_VARIABLE");
+    if p = nil then Out.str("not set\n"); end;
+    Out.int(INT(strlen("six"))); Out.ln;
+end;
+
+end Env.
+
the environment is not empty
+not set
+3
+
+

Callbacks

+

Every raz procedure uses the System V calling convention, so any with parameters and a result of C's types may be given to C to call, as qsort is given order above. The procedure may not be a closure: it has only its arguments, so state travels through the pointer C hands back or a module variable.

+
Roots.raz
module Roots;
+import Fmt;
+
+link "libm.so.6";
+
+extern proc cbrt(x: F64): F64;
+extern proc hypot(x, y: F64): F64;
+
+proc main*;
+begin
+    Fmt.print("{} {}\n", [Fmt.real(cbrt(27.0), 3), Fmt.real(hypot(3.0, 4.0), 3)]);
+end;
+
+end Roots.
+
3.000 5.000
+

Save a program under its module’s name and run it with raz run Name.raz.

+
+ + + diff --git a/site/public/tour/checks.html b/site/public/tour/checks.html new file mode 100644 index 0000000..68ea27f --- /dev/null +++ b/site/public/tour/checks.html @@ -0,0 +1,187 @@ + + + + + +When it goes wrong - Raz, Set, Go + + + + + + + + + + + + +
+
+

Go · lesson 12 of 15

When it goes wrong

+
Fail.raz
module Fail;
+import Out;
+
+proc show(a: []INT; i: INT);
+begin
+    Out.int(a[i]);
+    Out.ln;
+end;
+
+proc main*;
+var a: [3]INT; i: INT;
+begin
+    for i := 0 to 3 do
+        show(a, i);
+    end;
+end;
+
+end Fail.
+
0
+0
+0
+Fail.raz:6:15: index 3 is out of range for a length of 3
+  in Fail.show at Fail.raz:6:15: i = 3
+  in Fail.main at Fail.raz:14:9: i = 3
+
+

Every index and slice is checked. A failed check says where it failed and with what values, then the calls under way with their variables, and ends the program with status 2. The three 0s are what it printed before the fourth pass went one past the end.

+

Reading the message

+

The first line is the place of the offending expression: file, line and column, then what failed and the numbers involved. Each in line after it is a call still under way, innermost first, with the basic-typed variables it held. That is usually enough to see the bug without a debugger.

+

Other failures

+

The same shape of message tells of a nil pointer, a division by zero, a bad slice and a stack overflow. Each of them stops the program with status 2, and never runs on with a wrong value.

+
Nilp.raz
module Nilp;
+import Out;
+
+type Node = record val: INT; next: ^Node; end;
+
+proc last(n: ^Node): INT;
+begin
+    while n^.next # nil do n := n^.next; end;
+    return n^.val;
+end;
+
+proc main*;
+var a, b: Node;
+begin
+    a.val := 1; b.val := 2;
+    a.next := ADR(b);
+    Out.int(last(ADR(a))); Out.ln;
+    Out.int(last(nil)); Out.ln;
+end;
+
+end Nilp.
+
2
+Nilp.raz:8:11: stopped by a nil pointer
+  in Nilp.last at Nilp.raz:8:11: n = nil
+  in Nilp.main at Nilp.raz:18:5
+
+
Zero.raz
module Zero;
+import Out;
+
+proc ratio(a, b: INT): INT;
+begin
+    return a div b;
+end;
+
+proc main*;
+var n: INT;
+begin
+    Out.int(ratio(10, 3)); Out.ln;
+    Out.int(ratio(10, n)); Out.ln;       (* n is zero: every variable starts at zero *)
+end;
+
+end Zero.
+
3
+Zero.raz:13:5: stopped by a division fault
+  in Zero.main at Zero.raz:13:5: n = 0
+
+
Slicing.raz
module Slicing;
+import Out;
+
+proc main*;
+var a: [5]INT; s: []INT; hi: INT;
+begin
+    hi := 7;
+    s := a[2..5];
+    Out.int(LEN(s)); Out.ln;
+    s := a[2..hi];                       (* past the end *)
+    Out.int(LEN(s)); Out.ln;
+end;
+
+end Slicing.
+
3
+Slicing.raz:10:12: slice 2..7 is out of range for a length of 5
+  in Slicing.main at Slicing.raz:10:12: hi = 7
+
+

In every case the output before the failure was written first. Out's buffer is flushed by the failure, so what the program printed is never lost to the crash.

+

A constant can fail at compile time

+

A division by a zero constant, or a constant index out of range, is not a run-time failure at all; the compiler says it at the line, so you never ship it.

+
Early.raz
module Early;
+import Out;
+
+proc main*;
+var a: [3]INT;
+begin
+    a[3] := 1;
+    Out.int(10 div 0); Out.ln;
+end;
+
+end Early.
+
$ raz Early.raz
+Early.raz:7:7: error: index 3 is out of range for a length of 3
+    7 |     a[3] := 1;
+      |       ^
+Early.raz:8:13: error: division by zero
+    8 |     Out.int(10 div 0); Out.ln;
+      |             ^^^^^^^^
+raz: 2 errors
+

Looking at where you are

+

Rt.trace prints the calls under way, as a failure does, whenever you ask. It writes to standard error and the program goes on. It is the cheapest debugging tool there is.

+
Where.raz
module Where;
+import Rt;
+
+proc inner(depth: INT);
+begin
+    if depth = 0 then Rt.trace; return; end;
+    inner(depth - 1);
+end;
+
+proc main*;
+begin
+    inner(2);
+end;
+
+end Where.
+
  in Where.inner at Where.raz:6:23: depth = 0
+  in Where.inner at Where.raz:7:5: depth = 1
+  and 1 more the same
+  in Where.main at Where.raz:12:5
+
+

Leaving the checks out

+

A module that is sure of its indexes may say check off; after its imports and links, for speed. The module's own indexing and slicing is then unchecked, so an index out of range reads or writes whatever it reaches. Every other check stays (nil and division), and callers of the module keep theirs. Use it for a measured inner loop, never as a first step.

+

For gdb and the profiler

+

The program carries names and line numbers, so gdb can break at Fail.raz:6 and show raz source. RAZ_PROFILE=1 in the environment makes a program sample itself every millisecond and say at the end where its time went, by procedure and by line.

Save a program under its module’s name and run it with raz run Name.raz.

+
+ + + diff --git a/site/public/tour/defer.html b/site/public/tour/defer.html new file mode 100644 index 0000000..2bcd642 --- /dev/null +++ b/site/public/tour/defer.html @@ -0,0 +1,187 @@ + + + + + +Defer - Raz, Set, Go + + + + + + + + + + + + +
+
+

Go · lesson 11 of 15

Defer

+
Defers.raz
module Defers;
+import Out, Sys;
+
+proc step(n: INT);
+begin
+    Out.str("in "); Out.int(n); Out.ln;
+    defer Out.str("out\n");
+    if n = 2 then return; end;
+    defer Out.str("done\n");
+    Out.str("working\n");
+end;
+
+(* the lines of the file at path, or -1 if it can't be read *)
+proc lines(path: []U8): INT;
+var fd, n, i, count: INT; buf: [4096]U8;
+begin
+    fd := Sys.openRead(path);
+    if fd < 0 then return -1; end;
+    defer Sys.close(fd);
+    count := 0;
+    n := Sys.read(fd, buf);
+    while n > 0 do
+        for i := 0 to n - 1 do
+            if buf[i] = '\n' then INC(count); end;
+        end;
+        n := Sys.read(fd, buf);
+    end;
+    return count;
+end;
+
+proc main*;
+begin
+    step(1);
+    step(2);
+    Out.int(lines("/dev/null")); Out.ln;
+    Out.int(lines("/no/such/file")); Out.ln;
+end;
+
+end Defers.
+
in 1
+working
+done
+out
+in 2
+out
+0
+-1
+
+

defer s; runs s when the program leaves the statements the defer stands in: at their end, or by a return, a break or a continue. Deferred statements run the last first, and only those whose defer was reached. So a file is closed beside the line that opens it, however the procedure ends.

+

The order, and a return value

+

A return e; evaluates e before the deferred statements run, so the value is what it was at the return.

+
Order.raz
module Order;
+import Out;
+
+var counter: INT;
+
+proc next(): INT;
+begin
+    defer INC(counter);
+    return counter;          (* the old value is returned; then counter grows *)
+end;
+
+proc nest;
+begin
+    defer Out.str("1 ");
+    defer Out.str("2 ");
+    defer Out.str("3 ");
+    Out.str("body: ");
+end;
+
+proc main*;
+var a, b: INT;
+begin
+    a := next();
+    b := next();
+    Out.int(a); Out.char(' '); Out.int(b); Out.char(' '); Out.int(counter); Out.ln;
+    nest;
+    Out.ln;
+end;
+
+end Order.
+
0 1 2
+body: 3 2 1 
+
+

In a loop

+

A defer stands in the statement list that holds it, so in a loop body it runs at the end of each pass, and on a break or a continue.

+
Passes.raz
module Passes;
+import Out;
+
+proc main*;
+var i: INT;
+begin
+    for i := 1 to 4 do
+        Out.str("pass "); Out.int(i);
+        defer Out.str(" done\n");
+        if i = 3 then break; end;
+        Out.str(" ...");
+    end;
+end;
+
+end Passes.
+
pass 1 ... done
+pass 2 ... done
+pass 3 done
+
+

Giving back what was taken

+

The point is that acquiring and releasing sit next to each other, so a new early return added later can't leak. Here an arena and a buffer are both released on every path.

+
Report.raz
module Report;
+import Out, Buf, Heap;
+
+(* a line, built in a buffer; false (nothing written) if n is negative *)
+proc line(n: INT): BOOL;
+var b: Buf.Buf;
+begin
+    if n < 0 then return false; end;
+    Buf.init(b, Heap.heap);
+    defer Buf.done(b);            (* freed on every way out below *)
+    Buf.str(b, "n is ");
+    if n > 9 then
+        Buf.str(b, "large");
+        Out.str(Buf.bytes(b)); Out.ln;
+        return true;
+    end;
+    Buf.str(b, "small");
+    Out.str(Buf.bytes(b)); Out.ln;
+    return true;
+end;
+
+proc main*;
+begin
+    _ := line(3);
+    _ := line(30);
+    if not line(-1) then Out.str("rejected\n"); end;
+end;
+
+end Report.
+
n is small
+n is large
+rejected
+
+

What defer does not do

+

A deferred statement can't contain a return, break or defer that would leave it. A failed check, Rt.exit and Sys.exit end the program without running the deferred statements still pending, so deferred cleanup is for the program's resources, not for what must happen at exit; that is what Rt.atExit is for.

Save a program under its module’s name and run it with raz run Name.raz.

+
+ + + diff --git a/site/public/tour/errors.html b/site/public/tour/errors.html new file mode 100644 index 0000000..6727a45 --- /dev/null +++ b/site/public/tour/errors.html @@ -0,0 +1,217 @@ + + + + + +Errors - Raz, Set, Go + + + + + + + + + + + + +
+
+

Go · lesson 10 of 15

Errors

+
Errors.raz
module Errors;
+import Out, Str;
+
+const
+    Empty*: ERROR = "nothing to read";
+    TooBig*: ERROR = "not a number up to 1000";
+
+(* the number s holds, up to 1000 *)
+proc number(s: []U8): (INT, ERROR);
+var n: I64; ok: BOOL;
+begin
+    if LEN(s) = 0 then return 0, Empty; end;
+    n, ok := Str.toInt(s);
+    if not ok or (n > 1000) then return 0, TooBig; end;
+    return INT(n), nil;
+end;
+
+(* the sum of the numbers in words: the first error ends it *)
+proc total(words: [][]U8): (INT, ERROR);
+var i, sum: INT;
+begin
+    for i := 0 to LEN(words) - 1 do
+        sum := sum + try number(words[i]);
+    end;
+    return sum, nil;
+end;
+
+proc main*;
+var words: [3][]U8; i, n: INT; err: ERROR;
+begin
+    words := ["42", "", "12345"];
+    for i := 0 to 2 do
+        n, err := number(words[i]);
+        if err = nil then Out.int(n);
+        elsif err = Empty then Out.str("empty");
+        else Out.str(MSG(err));
+        end;
+        Out.ln;
+    end;
+    n, err := total(["1", "2", "3"]);
+    Out.int(n); Out.ln;
+    n, err := total(words);
+    if err # nil then Out.str(MSG(err)); Out.ln; end;
+end;
+
+end Errors.
+
42
+empty
+not a number up to 1000
+6
+nothing to read
+
+

A procedure that can fail returns an ERROR beside its result, and nil when it didn't. Each ERROR constant is an error of its own, compared with = by which declaration made it, never by its message; MSG(err) is the message. An exported one, as Empty is here, lets the callers tell it from the others. raz has no exceptions, so every failure is visible in the signature and handled where the call is written.

+

Handling them by kind

+

Because an error is compared by identity, a caller can handle the cases it knows and pass on the rest.

+
Parse.raz
module Parse;
+import Out, Str;
+
+const
+    Empty*: ERROR = "nothing to read";
+    Bad*: ERROR = "not a number";
+    Range*: ERROR = "out of range";
+
+(* a percentage, 0 to 100 *)
+proc percent(s: []U8): (INT, ERROR);
+var n: I64; ok: BOOL;
+begin
+    if LEN(s) = 0 then return 0, Empty; end;
+    n, ok := Str.toInt(s);
+    if not ok then return 0, Bad; end;
+    if (n < 0) or (n > 100) then return 0, Range; end;
+    return INT(n), nil;
+end;
+
+proc main*;
+var inputs: [4][]U8; i, n: INT; err: ERROR;
+begin
+    inputs := ["42", "", "forty", "140"];
+    for i := 0 to 3 do
+        n, err := percent(inputs[i]);
+        if err = nil then
+            Out.int(n); Out.str("%");
+        elsif err = Empty then
+            Out.str("(skipped)");
+        else
+            Out.str("error: "); Out.str(MSG(err));
+        end;
+        Out.ln;
+    end;
+end;
+
+end Parse.
+
42%
+(skipped)
+error: not a number
+error: out of range
+
+

Passing errors up

+

When a procedure can't do anything useful with an error, it returns it, so the first caller that can decide gets it. Written out, that is a test and a return after each call:

+

``raz x, err := value(a); if err # nil then return 0, err; end; ``

+

try says the same in a word. x := try value(a) calls value and, if the error it returned isn't nil, returns that error from the procedure it stands in, with zero for that procedure's other results; otherwise it is value's number. There is no hidden unwinding and no handler: try is a return, written where the call is, and a procedure that uses it must end in an ERROR itself, so its signature says it can fail. main returns none, so it tests its errors and deals with them.

+
Layers.raz
module Layers;
+import Out, Str;
+
+const Missing*: ERROR = "key missing";
+
+(* the number after "n=" in a line like "n=17" *)
+proc value(line: []U8): (INT, ERROR);
+var n: I64; ok: BOOL;
+begin
+    if not Str.hasPrefix(line, "n=") then return 0, Missing; end;
+    n, ok := Str.toInt(line[2..LEN(line)]);
+    if not ok then return 0, Missing; end;
+    return INT(n), nil;
+end;
+
+(* the sum of the values of two lines: the first error ends it *)
+proc sum(a, b: []U8): (INT, ERROR);
+begin
+    return try value(a) + try value(b), nil;
+end;
+
+proc main*;
+var n: INT; err: ERROR;
+begin
+    n, err := sum("n=40", "n=2");
+    if err = nil then Out.int(n); Out.ln; end;
+    n, err := sum("n=40", "x=2");
+    if err # nil then Out.str("sum failed: "); Out.str(MSG(err)); Out.ln; end;
+end;
+
+end Layers.
+
42
+sum failed: key missing
+
+

When the library reports errors

+

Library procedures that can fail say so in the same way: Thread.spawn returns an ERROR; Sys calls return a negative errno as an INT, with 0 or a positive count for success; Files.read returns a BOOL. The first is the language's way; the others are the system's, left as they are.

+
Probe.raz
module Probe;
+import Out, Sys;
+
+proc main*;
+var fd: INT;
+begin
+    fd := Sys.openRead("/no/such/file");
+    if fd < 0 then
+        Out.str("open failed, errno "); Out.int(-fd); Out.ln;     (* 2: ENOENT *)
+    end;
+    fd := Sys.openRead("/dev/null");
+    if fd >= 0 then
+        Out.str("open worked\n");
+        Sys.close(fd);
+    end;
+end;
+
+end Probe.
+
open failed, errno 2
+open worked
+
+

When there is nothing to do but stop

+

A program that has found a state it can't carry on from, such as a broken invariant, says so and ends with Rt.stop: the message goes to standard error and the status is 2, the same as a failed check.

+
Giveup.raz
module Giveup;
+import Rt;
+
+proc main*;
+begin
+    Rt.stop("the table is corrupt");
+end;
+
+end Giveup.
+
$ raz run Giveup.raz; echo "status $?"
+the table is corrupt
+status 2

Save a program under its module’s name and run it with raz run Name.raz.

+
+ + + diff --git a/site/public/tour/generics.html b/site/public/tour/generics.html new file mode 100644 index 0000000..67dd9e1 --- /dev/null +++ b/site/public/tour/generics.html @@ -0,0 +1,174 @@ + + + + + +Generic modules - Raz, Set, Go + + + + + + + + + + + + +
+
+

Go · lesson 13 of 15

Generic modules

+

A module may take types, and the procedures it needs on them, as parameters. Biggest.raz:

+
Biggest.raz
module Biggest(T; less: proc(a, b: T): BOOL);
+
+(* the biggest of s, which mustn't be empty *)
+proc max*(s: []T): T;
+var i: INT; m: T;
+begin
+    m := s[0];
+    for i := 1 to LEN(s) - 1 do
+        if less(m, s[i]) then m := s[i]; end;
+    end;
+    return m;
+end;
+
+end Biggest.
+

and a program that uses it:

+
Generics.raz
module Generics;
+import Out, Ints := Biggest(INT, before),
+    Words := Biggest([]U8, shorter), Order := Sort(INT, before);
+
+proc before(a, b: INT): BOOL;
+begin
+    return a < b;
+end;
+
+proc shorter(a, b: []U8): BOOL;
+begin
+    return LEN(a) < LEN(b);
+end;
+
+proc main*;
+var a: [5]INT; i: INT;
+begin
+    a := [3, 1, 4, 1, 5];
+    Out.int(Ints.max(a)); Out.ln;
+    Out.str(Words.max(["a", "tree", "is"])); Out.ln;
+    Order.sort(a);
+    for i := 0 to 4 do Out.int(a[i]); Out.char(' '); end;
+    Out.ln;
+end;
+
+end Generics.
+
5
+tree
+1 1 3 4 5 
+
+

Each import with its own arguments makes an instance: the module compiled again, with T standing for the type given, and less calling the procedure given. The arguments may name what the importing module declares later, as before is here. There is no run-time cost for being generic, and no boxing: Ints.max is exactly the code you would write by hand for INT.

+

Writing your own

+

A generic module is an ordinary module with parameters in its header. Here is a stack of anything, which takes the allocator it grows from.

+
Stk.raz
module Stk(T);
+import Mem;
+
+type
+    Stack* = record
+        items: ^T;         (* an array of cap Ts *)
+        cap*, len*: INT;
+        a: ^Mem.Allocator;
+    end;
+
+proc init*(s: ^Stack; a: ^Mem.Allocator);
+begin
+    s^.a := a;
+    s^.items := nil;
+    s^.cap := 0;
+    s^.len := 0;
+end;
+
+(* v on top; false if the allocator has no room *)
+proc push*(s: ^Stack; v: T): BOOL;
+var bigger: ^T; i, cap: INT; src, dst: ^T;
+begin
+    if s^.len = s^.cap then
+        if s^.cap = 0 then cap := 4; else cap := s^.cap * 2; end;
+        bigger := ^T(Mem.alloc(s^.a, cap * SIZE(T), 8));
+        if bigger = nil then return false; end;
+        for i := 0 to s^.len - 1 do
+            src := ^T(INT(s^.items) + i * SIZE(T));
+            dst := ^T(INT(bigger) + i * SIZE(T));
+            dst^ := src^;
+        end;
+        if s^.items # nil then Mem.free(s^.a, ^U8(s^.items)); end;
+        s^.items := bigger;
+        s^.cap := cap;
+    end;
+    dst := ^T(INT(s^.items) + s^.len * SIZE(T));
+    dst^ := v;
+    INC(s^.len);
+    return true;
+end;
+
+(* the top value, taken off; false if empty *)
+proc pop*(s: ^Stack): (T, BOOL);
+var z: T; p: ^T;
+begin
+    if s^.len = 0 then return z, false; end;
+    DEC(s^.len);
+    p := ^T(INT(s^.items) + s^.len * SIZE(T));
+    return p^, true;
+end;
+
+end Stk.
+
Uses.raz
module Uses;
+import Out, Heap, Nums := Stk(INT), Pairs := Stk(Pair);
+
+type Pair = record a, b: INT; end;
+
+proc main*;
+var n: Nums.Stack; p: Pairs.Stack; i, v: INT; ok: BOOL; pr: Pair;
+begin
+    Nums.init(ADR(n), Heap.heap);
+    Pairs.init(ADR(p), Heap.heap);
+    for i := 1 to 10 do _ := Nums.push(ADR(n), i * i); end;
+    _ := Pairs.push(ADR(p), {a: 3, b: 4});
+    v, ok := Nums.pop(ADR(n));
+    Out.int(v); Out.str(" of "); Out.int(n.len + 1); Out.ln;
+    pr, ok := Pairs.pop(ADR(p));
+    Out.int(pr.a * pr.b); Out.ln;
+    _, ok := Pairs.pop(ADR(p));
+    if not ok then Out.str("empty\n"); end;
+end;
+
+end Uses.
+
100 of 10
+12
+empty
+
+

Two instances (Nums and Pairs) are two separate modules, compiled with their own T. Its pointer arithmetic is the one place where the program does what C does and leaves the checks behind; a library would keep that inside, as this does.

+

The library's generics

+

The library's List, Map and Sort are generic modules. A Map takes its key hash and equality as procedure arguments: import Count := Map([]U8, INT, Str.hash, Str.eq);. The advanced tour uses each of them in a real program.

Save a program under its module’s name and run it with raz run Name.raz.

+
+ + + diff --git a/site/public/tour/hello.html b/site/public/tour/hello.html index 14949a7..b32de64 100644 --- a/site/public/tour/hello.html +++ b/site/public/tour/hello.html @@ -70,7 +70,7 @@ $ raz run Quiet.raz hello, again $ ls -l Quiet | awk '{print $5, "bytes"}' -28608 bytes +28680 bytes

The program is a static executable with no run time besides the code it uses, so it is a few kilobytes, and runs without any library installed.

What Out can write

Out is the library's buffered output. It writes strings, single characters, numbers in decimal or hexadecimal, and a line feed. A string is written as it is, with \n for a line feed, \t for a tab, \" and \\; or between backquotes, as a raw string with no escapes at all, which may run over lines (lesson 6).

@@ -136,20 +136,9 @@ end Args.
$ raz run Args.raz one "two words"; echo "status $?"
-Args.raz:9:11: error: indexing through a pointer needs import SYSTEM
-    9 |     while s[n] # 0 do n := n + 1; end;
-      |           ^^^
-help: it reaches memory other than through a variable: say import SYSTEM after the module's imports
-Args.raz:17:14: error: ARGV is SYSTEM's, and written SYSTEM.ARGV
-   17 |         s := ARGV()[i];
-      |              ^^^^
-help: say import SYSTEM after the module's imports, and write the name after SYSTEM.
-Args.raz:18:17: error: a slice of a pointer needs import SYSTEM
-   18 |         Out.str(s[0..len(s)]);
-      |                 ^
-help: it reaches memory other than through a variable: say import SYSTEM after the module's imports
-raz: 3 errors
-status 1

Save a program under its module’s name and run it with raz run Name.raz.

Contents
+one +two words +status 2

Save a program under its module’s name and run it with raz run Name.raz.

Contents
diff --git a/site/public/tour/index.html b/site/public/tour/index.html new file mode 100644 index 0000000..2985c6b --- /dev/null +++ b/site/public/tour/index.html @@ -0,0 +1,54 @@ + + + + + +Raz, Set, Go + + + + + + + + + + + + +
+
+

Raz, Set, Go

+

A tour of raz, in the spirit of A Tour of Go. Each lesson is one +idea and a whole program, and the output shown is what the program printed +when this page was made.

+

It is in three parts, as one counts off: Raz (one), the +first steps; Set, how data is laid out; and +Go, making programs that run, fail and finish well. To follow +along, get raz and run any program with +raz run Name.raz. When you finish, More Raz goes down to the machine.

+

Raz

    +
  1. Hello, world A module, an import, a procedure; running, printing, exit status and arguments.
  2. +
  3. Modules Exports, renaming, the order bodies run in, and what the compiler refuses.
  4. +
  5. Integers The ten integer types, literals, wrapping, signed and unsigned, division, shifts and bits.
  6. +
  7. Values and conversions Nothing converts unasked; what converts to what; booleans and reals.
  8. +
  9. Procedures and several results Value and var parameters, several results, forward, and procedures as values.
  10. +
+

Set

    +
  1. Arrays, slices and strings Five in a row, a window onto them, bytes in UTF-8, raw strings over lines, and checks on every index.
  2. +
  3. Records and pointers Laid out as C lays out a struct, packed records, pointers and nil.
  4. +
  5. Enumerations, sets, variants and match Names in order, sets as bits, and cases the compiler makes you handle.
  6. +
  7. Memory and allocators No garbage collector; you choose where memory comes from, and what happens when it runs out.
  8. +
+

Go

    +
  1. Errors A second result, compared by identity; passing errors up; and no exceptions.
  2. +
  3. Defer Clean up beside the line that needs it, in the right order, on every way out.
  4. +
  5. When it goes wrong Every index is checked, a failure says where and with what values, and how to read it.
  6. +
  7. Generic modules A module that takes types and procedures; the library's List, Map and Sort.
  8. +
  9. Talking to C Call a C library, be called back, share variables, and mind the two buffers.
  10. +
  11. Threads Native threads without C, atomics, a mutex, and why the counter needs both.
  12. +
+
+ + + diff --git a/site/public/tour/integers.html b/site/public/tour/integers.html new file mode 100644 index 0000000..b5157ba --- /dev/null +++ b/site/public/tour/integers.html @@ -0,0 +1,286 @@ + + + + + +Integers - Raz, Set, Go + + + + + + + + + + + + +
+
+

Raz · lesson 3 of 15

Integers

+

raz has ten integer types, and a program that works with bytes, addresses, hashes and file offsets uses most of them. Each is a different type, so each has rules, and the rules are the same everywhere: that is the point of having them.

+
TypeSizeValues
I8 I16 I32 I641, 2, 4, 8 bytessigned, two's complement
U8 U16 U32 U641, 2, 4, 8 bytesunsigned
INTan address's: 8 on x86-64signed, as big as an address
UINTan address'sunsigned, as big as an address
+

SIZE(T) says how many bytes a type takes, and an unsigned type's largest value is what you get by taking one from zero. This program asks each type.

+
Family.raz
module Family;
+import Out;
+
+proc main*;
+var a: U8; b: U16; c: U32; d: U64;
+begin
+    a := 0; a := a - 1;
+    b := 0; b := b - 1;
+    c := 0; c := c - 1;
+    d := 0; d := d - 1;
+    Out.str("U8   "); Out.int(SIZE(U8));  Out.str(" byte,  largest "); Out.int(I64(a)); Out.ln;
+    Out.str("U16  "); Out.int(SIZE(U16)); Out.str(" bytes, largest "); Out.int(I64(b)); Out.ln;
+    Out.str("U32  "); Out.int(SIZE(U32)); Out.str(" bytes, largest "); Out.int(I64(c)); Out.ln;
+    Out.str("U64  "); Out.int(SIZE(U64)); Out.str(" bytes, largest 0x"); Out.hex(d, 16); Out.ln;
+    Out.str("INT  "); Out.int(SIZE(INT)); Out.str(" bytes, as big as an address\n");
+    Out.str("I8   "); Out.int(SIZE(I8));  Out.str(" byte,  from -128 to 127\n");
+end;
+
+end Family.
+
U8   1 byte,  largest 255
+U16  2 bytes, largest 65535
+U32  4 bytes, largest 4294967295
+U64  8 bytes, largest 0xFFFFFFFFFFFFFFFF
+INT  8 bytes, as big as an address
+I8   1 byte,  from -128 to 127
+
+

INT is the everyday one

+

Lengths, indexes, counts and sizes are INTs. LEN(s) of a slice is an INT, and so is the loop variable that walks it. It is as big as an address, so it is the integer a pointer converts to, and the word the atomics work on. Reach for INT unless you have a reason: a byte is a U8, a character an I32, a file's size an I64, a hash a U64.

+

INT and I64 are two types even where they have the same size. An INT goes silently into an I64 (and a UINT into a U64) wherever it meets one, in pos + LEN(s) as in a call, which is why Out.int(n) and Fmt.int(n) take an I64 and accept any INT. The other way is written, INT(pos), since an INT may be smaller on another machine. An INT holds every U8, I8 and I16 on any machine, so those go silently into an INT too (and a U8 or U16 into a UINT): n := s[i], and n * 10 + s[i] - '0' for a digit. Not what an operator made of them, which was computed in the small type and may have wrapped there: with a, b: U8, n := a + b is an error, and INT(a) + b the sum. And only one step: a U8 goes into an INT, not on into an I64, so Out.int(I64(b)) still says it. Nothing else converts unasked.

+

A number written in the program

+

A number in the program text is untyped until it meets a type, and then it must fit. 0FFH is hexadecimal (it starts with a digit and ends in H), a character in quotes is its code point, and '\u{E9}' is a code point written by number. A hexadecimal literal too big for an I64 is a U64.

+
Literals.raz
module Literals;
+import Out;
+
+proc main*;
+var b: U8; w: I16; big: U64;
+begin
+    b := 0FFH;                    (* fits a U8 *)
+    w := -300;
+    big := 0FFFFFFFFFFFFFFFFH;    (* above the largest I64: a U64 *)
+    Out.int(I64(b)); Out.char(' ');
+    Out.int(I64(w)); Out.char(' ');
+    Out.int(I64('a')); Out.char(' ');
+    Out.int(I64('\u{E9}')); Out.char(' ');
+    Out.hex(big, 16); Out.ln;
+end;
+
+end Literals.
+
255 -300 97 233 FFFFFFFFFFFFFFFF
+
+

A constant that doesn't fit is an error, not a quiet cut. A conversion of a constant, which says you mean it, is allowed: U8(300) is 44.

+
Fits.raz
module Fits;
+
+proc main*;
+var b: U8; c: U8;
+begin
+    b := 300;
+    c := U8(300);
+end;
+
+end Fits.
+
$ raz Fits.raz
+Fits.raz:6:10: error: 300 doesn't fit U8
+    6 |     b := 300;
+      |          ^^^
+raz: 1 error
+

Wrapping

+

Arithmetic wraps at the type's width and never stops the program. 250 + 10 in a U8 is 4; one more than the largest I8 is the smallest. A unary minus wraps too: for an unsigned x, -x is 0 - x. This is not undefined behaviour, as in C; it is what the report says, in every program, on every target, so a hash function can rely on it.

+
Wrap.raz
module Wrap;
+import Out;
+
+proc main*;
+var a: U8; b: I8; c: U32; d: U8;
+begin
+    a := 250;  a := a + 10;
+    Out.int(I64(a)); Out.ln;               (* 4 *)
+    b := 127;  b := b + 1;
+    Out.int(I64(b)); Out.ln;               (* -128 *)
+    c := 0;    c := c - 1;
+    Out.int(I64(c)); Out.ln;               (* 4294967295 *)
+    d := 1;    d := -d;
+    Out.int(I64(d)); Out.ln;               (* 255: 0 - 1 *)
+end;
+
+end Wrap.
+
4
+-128
+4294967295
+255
+
+

Because wrapping is defined, a hash that depends on it is portable. Here is the FNV-1a hash that Str.hash uses, written in a few lines; the multiplication overflows a U64 on every byte, on purpose.

+
Fnv.raz
module Fnv;
+import Out, Str;
+
+const Offset = 0CBF29CE484222325H;
+const Prime = 100000001B3H;
+
+(* FNV-1a: xor each byte in, then multiply, all modulo 2^64 *)
+proc fnv(s: []U8): U64;
+var h: U64; i: INT;
+begin
+    h := Offset;
+    for i := 0 to LEN(s) - 1 do
+        h := (h xor U64(s[i])) * Prime;
+    end;
+    return h;
+end;
+
+proc main*;
+begin
+    Out.hex(fnv("raz"), 16); Out.ln;
+    Out.hex(Str.hash("raz"), 16); Out.ln;
+    if fnv("raz") = Str.hash("raz") then Out.str("the same\n"); end;
+end;
+
+end Fnv.
+
89F6BC1960FF4912
+89F6BC1960FF4912
+the same
+
+

Widening, narrowing, and sign

+

A conversion to a narrower integer cuts the value to the new width. To a wider one it extends by the sign for a signed source and with zeros for an unsigned one. That difference is the whole story of "why did my byte come out negative".

+
Widths.raz
module Widths;
+import Out;
+
+proc main*;
+var s: I8; u: U8;
+begin
+    s := -1;
+    u := 255;                         (* the same eight bits *)
+    Out.int(I64(s)); Out.char(' ');   (* sign-extended: -1 *)
+    Out.int(I64(u)); Out.char(' ');   (* zero-extended: 255 *)
+    Out.int(I64(U8(s))); Out.char(' ');   (* the bits, read as unsigned: 255 *)
+    Out.int(I64(I8(u))); Out.char(' ');   (* and back: -1 *)
+    Out.int(I64(U8(300 + INT(u)))); Out.ln;   (* 555 cut to 8 bits: 43 *)
+end;
+
+end Widths.
+
-1 255 255 -1 43
+
+

Relations compare as signed or unsigned according to the type, so the same bits order differently:

+
Order.raz
module Order;
+import Out;
+
+proc main*;
+var s: I8; u: U8;
+begin
+    s := -1;
+    u := U8(s);                        (* 255 *)
+    if s < 0 then Out.str("s is below zero\n"); end;
+    if u > 100 then Out.str("u is above 100\n"); end;
+    if U8(s) = u then Out.str("but they are the same bits\n"); end;
+end;
+
+end Order.
+
s is below zero
+u is above 100
+but they are the same bits
+
+

Division

+

div rounds toward zero, and mod takes the sign of the dividend, as in C: -7 div 2 is -3 and -7 mod 2 is -1. Dividing by zero stops the program, and so does dividing the smallest value of a signed type by -1, whose result can't be represented. Neither is a silent wrong answer.

+
Divide.raz
module Divide;
+import Out;
+
+proc main*;
+var n, d: INT;
+begin
+    n := -7; d := 2;
+    Out.int(n div d); Out.char(' '); Out.int(n mod d); Out.char(' ');   (* -3 -1 *)
+    n := 7; d := -2;
+    Out.int(n div d); Out.char(' '); Out.int(n mod d); Out.ln;          (* -3 1 *)
+end;
+
+end Divide.
+
-3 -1 -3 1
+
+

Shifts and bits

+

& (and), | (or), xor and ~ (not) work on every bit. x shl n and x shr n shift by n modulo the width of x's type: for a U8, x shl 9 is x shl 1. shr brings in copies of the sign bit for signed types, so it divides by two keeping the sign, and zeros for unsigned ones. The result has x's type, cut to its width: in a U8, 0C0H shl 1 is 80H.

+
Shifts.raz
module Shifts;
+import Out;
+
+proc main*;
+var u: U8; s: I8;
+begin
+    u := 0C0H;
+    Out.hex(U64(u shl 1), 2); Out.char(' ');        (* 80: cut to 8 bits *)
+    Out.hex(U64(u shr 4), 2); Out.char(' ');        (* 0C: zeros come in *)
+    Out.hex(U64(u shl 9), 2); Out.ln;               (* 9 mod 8 = 1: 80 *)
+    s := -64;
+    Out.int(I64(s shr 2)); Out.char(' ');           (* -16: the sign comes in *)
+    Out.int(I64(s shr 7)); Out.ln;                  (* -1 *)
+end;
+
+end Shifts.
+
80 0C 80
+-16 -1
+
+

A packed value is the usual use of all this: several small numbers in one word. This puts a colour in the bytes of a U32 and takes it out again.

+
Colour.raz
module Colour;
+import Out;
+
+(* red, green and blue, each 0 to 255, in the low 24 bits *)
+proc pack(r, g, b: U8): U32;
+begin
+    return (U32(r) shl 16) | (U32(g) shl 8) | U32(b);
+end;
+
+proc red(c: U32): U8;
+begin
+    return U8(c shr 16);
+end;
+
+proc green(c: U32): U8;
+begin
+    return U8((c shr 8) & 0FFH);
+end;
+
+proc blue(c: U32): U8;
+begin
+    return U8(c & 0FFH);
+end;
+
+proc main*;
+var c: U32;
+begin
+    c := pack(0FFH, 80H, 10H);
+    Out.str("0x"); Out.hex(U64(c), 6); Out.ln;
+    Out.int(I64(red(c))); Out.char(' ');
+    Out.int(I64(green(c))); Out.char(' ');
+    Out.int(I64(blue(c))); Out.ln;
+end;
+
+end Colour.
+
0xFF8010
+255 128 16
+
+

Which one to use

+
  • INT for lengths, indexes, counts, loop variables, and anything you'd write int for in C.
  • U8 for bytes, and for a string's elements ([]U8). I32 for a character, a code point.
  • U32, U64 for hashes, bit sets, masks and addresses you do arithmetic on.
  • I64 for what must not shrink on a smaller target: a file's size or position, a time in nanoseconds, a number read from text.
  • I8, I16, U16 when a format or a layout says so, in a record or an array, to save space or match a protocol. Convert at the edge and compute in INT.
  • UINT rarely: for a count that must use the whole address range, or an address.

Save a program under its module’s name and run it with raz run Name.raz.

+
+ + + diff --git a/site/public/tour/memory.html b/site/public/tour/memory.html new file mode 100644 index 0000000..f4d8292 --- /dev/null +++ b/site/public/tour/memory.html @@ -0,0 +1,196 @@ + + + + + +Memory and allocators - Raz, Set, Go + + + + + + + + + + + + +
+
+

Set · lesson 9 of 15

Memory and allocators

+
Stack.raz
module Stack;
+import Out, Mem, Heap, Arena, SYSTEM;
+
+type Node = record next: ^Node; val: INT; end;
+
+(* a node holding v on top of top, from the allocator a;
+   nil if a has no room *)
+proc push(top: ^Node; v: INT; a: ^Mem.Allocator): ^Node;
+var n: ^Node;
+begin
+    NEW(n, a);
+    if n # nil then
+        n^.next := top;
+        n^.val := v;
+    end;
+    return n;
+end;
+
+proc main*;
+var top, n: ^Node; i: INT; ar: Arena.Arena;
+begin
+    for i := 1 to 3 do top := push(top, i, Heap.heap); end;
+    while top # nil do
+        Out.int(top^.val); Out.char(' ');
+        n := top;
+        top := top^.next;
+        Mem.free(Heap.heap, ^U8(n));
+    end;
+    Out.ln;
+    if not Arena.init(ar, 100000) then return; end;
+    for i := 1 to 1000 do top := push(top, i, SYSTEM.ADR(ar.base)); end;
+    Out.int(top^.val); Out.ln;
+    Arena.done(ar);            (* every node at once *)
+end;
+
+end Stack.
+
3 2 1 
+1000
+
+

raz has no garbage collector, and no allocator of its own: memory comes from an allocator, a Mem.Allocator, which the program chooses and passes. NEW(n, a) sets n to a fresh, zeroed Node from a, or to nil if a has no room. Heap.heap is the general one, which Mem.free gives memory back to. An Arena hands out memory from one block and frees it all at once, as the last lines above do.

+

Why an allocator is a parameter

+

A procedure that allocates takes the allocator it uses, so its caller decides where the memory comes from and when it goes: the heap for something that lives long, an arena for everything one request needs. Nothing in the library allocates behind your back.

+
Pool.raz
module Pool;
+import Out, Mem, Arena;
+
+type Item = record id: INT; next: ^Item; end;
+
+(* n items, linked; or nil if the allocator ran dry (what came is lost with it) *)
+proc make(n: INT; a: ^Mem.Allocator): ^Item;
+var head, it: ^Item; i: INT;
+begin
+    head := nil;
+    for i := 1 to n do
+        NEW(it, a);
+        if it = nil then return nil; end;
+        it^.id := i;
+        it^.next := head;
+        head := it;
+    end;
+    return head;
+end;
+
+proc count(it: ^Item): INT;
+var n: INT;
+begin
+    n := 0;
+    while it # nil do INC(n); it := it^.next; end;
+    return n;
+end;
+
+proc main*;
+var ar: Arena.Arena; small: Arena.Arena; list: ^Item;
+begin
+    if not Arena.init(ar, 1000000) then return; end;
+    list := make(1000, ADR(ar.base));
+    Out.int(count(list)); Out.str(" items from a big arena\n");
+    Arena.reset(ar);              (* every allocation forgotten *)
+    list := make(10, ADR(ar.base));
+    Out.int(count(list)); Out.str(" after a reset\n");
+    Arena.done(ar);
+
+    if not Arena.init(small, 4096) then return; end;
+    list := make(1000, ADR(small.base));
+    if list = nil then Out.str("a small arena ran out, and said so\n"); end;
+    Arena.done(small);
+end;
+
+end Pool.
+
1000 items from a big arena
+10 after a reset
+a small arena ran out, and said so
+
+

The run-out case is an ordinary nil to test, not an exception that unwinds past your code.

+

The heap

+

Heap.heap serves any size and takes memory back with Mem.free. Freeing a block twice, or one that was never given out, stops the program with a message instead of corrupting the heap. It is safe to call from several threads.

+
Free.raz
module Free;
+import Out, Mem, Heap;
+
+type Cell = record val: INT; end;
+
+proc main*;
+var a, b: ^Cell; i, total: INT;
+begin
+    for i := 1 to 5 do
+        NEW(a, Heap.heap);
+        a^.val := i * i;
+        total := total + a^.val;
+        Mem.free(Heap.heap, ^U8(a));     (* freed at once: its block is reused *)
+    end;
+    NEW(b, Heap.heap);
+    Out.int(total); Out.char(' '); Out.int(b^.val); Out.ln;   (* a new block is zeroed *)
+    Mem.free(Heap.heap, ^U8(b));
+end;
+
+end Free.
+
55 0
+
+

Buffers that grow

+

Buf is a growable byte buffer; like everything else it takes the allocator it grows from. It is what the program uses to build a string of unknown length.

+
Build.raz
module Build;
+import Out, Buf, Heap, Str;
+
+proc main*;
+var b: Buf.Buf; i: INT;
+begin
+    Buf.init(b, Heap.heap);
+    defer Buf.done(b);
+    for i := 1 to 5 do
+        Buf.str(b, "item ");
+        Buf.add(b, U8('0' + i));
+        Buf.add(b, ',');
+    end;
+    Out.str(Buf.bytes(b)); Out.ln;
+    Out.int(b.len); Out.str(" bytes\n");
+    Buf.reset(b);
+    Str.join(b, ["red", "green", "blue"], ", ");
+    Out.str(Buf.bytes(b)); Out.ln;
+    Buf.reset(b);
+    Str.replace(b, "a-b-c", "-", " and ");
+    Out.str(Buf.bytes(b)); Out.ln;
+end;
+
+end Build.
+
item 1,item 2,item 3,item 4,item 5,
+35 bytes
+red, green, blue
+a and b and c
+
+

Str.join and Str.replace build into a Buf too: the parts with a separator between them, or a string with one text replaced by another wherever it is.

+

Pages

+

Under the allocators are pages from the system: Mem.pages(size) gives zeroed memory in whole pages, or nil, and Mem.unmap gives it back. Most programs never need to call it directly.

Save a program under its module’s name and run it with raz run Name.raz.

+
+ + + diff --git a/site/public/tour/modules.html b/site/public/tour/modules.html index ceaf4c1..551fe06 100644 --- a/site/public/tour/modules.html +++ b/site/public/tour/modules.html @@ -45,7 +45,7 @@ var count*: INT; (* the greetings so far *) -proc hello*(name: []const U8); +proc hello*(name: []U8); begin Out.str("hello, "); Out.str(name); diff --git a/site/public/tour/procedures.html b/site/public/tour/procedures.html new file mode 100644 index 0000000..953d471 --- /dev/null +++ b/site/public/tour/procedures.html @@ -0,0 +1,237 @@ + + + + + +Procedures and several results - Raz, Set, Go + + + + + + + + + + + + +
+
+

Raz · lesson 5 of 15

Procedures and several results

+
Procs.raz
module Procs;
+import Out;
+
+proc divmod(a, b: INT): (INT, INT);
+begin
+    return a div b, a mod b;
+end;
+
+proc swap(var a, b: INT);
+var t: INT;
+begin
+    t := a;
+    a := b;
+    b := t;
+end;
+
+proc square(n: INT): INT;
+begin
+    return n * n;
+end;
+
+proc twice(f: proc(n: INT): INT; n: INT): INT;
+begin
+    return f(f(n));
+end;
+
+proc main*;
+var q, r, x, y: INT;
+begin
+    q, r := divmod(17, 5);
+    x := 1;
+    y := 2;
+    swap(x, y);
+    Out.int(q); Out.char(' '); Out.int(r); Out.ln;
+    Out.int(x); Out.char(' '); Out.int(y); Out.ln;
+    Out.int(twice(square, 3)); Out.ln;
+    _, r := divmod(-7, 2);
+    Out.int(r); Out.ln;
+end;
+
+end Procs.
+
3 2
+2 1
+81
+-1
+
+

A parameter is a copy, unless it is var, when it is the caller's variable itself. A procedure may return several results, which a multiple assignment takes apart; the blank, _, drops one.

+

Value and var parameters

+

A value parameter is the procedure's own: it may change it, and the caller's variable stays as it was. A var parameter is the caller's variable, and its argument must be a variable of exactly that type.

+
Params.raz
module Params;
+import Out;
+
+proc bump(n: INT);            (* changes its own copy *)
+begin
+    n := n + 1;
+end;
+
+proc bumpIn(var n: INT);      (* changes the caller's *)
+begin
+    n := n + 1;
+end;
+
+proc fill(var a: [4]INT; v: INT);   (* an array is copied unless var *)
+var i: INT;
+begin
+    for i := 0 to 3 do a[i] := v; end;
+end;
+
+proc main*;
+var x: INT; a: [4]INT;
+begin
+    x := 10;
+    bump(x);
+    Out.int(x); Out.ln;       (* 10 *)
+    bumpIn(x);
+    Out.int(x); Out.ln;       (* 11 *)
+    fill(a, 7);
+    Out.int(a[0] + a[3]); Out.ln;   (* 14 *)
+end;
+
+end Params.
+
10
+11
+14
+
+

Several results

+

Instead of an output parameter, a procedure says what it returns: (INT, INT), or any list of types. The caller takes them apart with a multiple assignment. A call that returns several values may stand on the right of one, alone as a statement, or alone after return, which passes them on as they are.

+
Several.raz
module Several;
+import Out;
+
+proc divmod(a, b: INT): (INT, INT);
+begin
+    return a div b, a mod b;
+end;
+
+proc minmax(a, b: INT): (INT, INT);
+begin
+    if a < b then return a, b; end;
+    return b, a;
+end;
+
+proc spread(a, b: INT): (INT, INT);
+begin
+    return minmax(a, b);        (* passes both results on *)
+end;
+
+proc main*;
+var q, r, lo, hi: INT;
+begin
+    q, r := divmod(100, 7);
+    Out.int(q); Out.str(" rest "); Out.int(r); Out.ln;
+    lo, hi := spread(9, 4);
+    Out.int(lo); Out.str(" .. "); Out.int(hi); Out.ln;
+    _, r := divmod(-7, 2);      (* drop the quotient *)
+    Out.int(r); Out.ln;
+end;
+
+end Several.
+
14 rest 2
+4 .. 9
+-1
+
+

Recursion, and forward

+

A name is declared before it is used, and procedures don't nest. When two procedures need each other, forward declares the first so that its body can come later.

+
Recur.raz
module Recur;
+import Out;
+
+proc gcd(a, b: INT): INT;
+begin
+    if b = 0 then return a; end;
+    return gcd(b, a mod b);
+end;
+
+proc isOdd(n: INT): BOOL; forward;
+
+proc isEven(n: INT): BOOL;
+begin
+    if n = 0 then return true; end;
+    return isOdd(n - 1);
+end;
+
+proc isOdd(n: INT): BOOL;
+begin
+    if n = 0 then return false; end;
+    return isEven(n - 1);
+end;
+
+proc main*;
+begin
+    Out.int(gcd(84, 36)); Out.ln;
+    if isEven(10) and isOdd(7) then Out.str("parity works\n"); end;
+end;
+
+end Recur.
+
12
+parity works
+
+

Procedures are values

+

A procedure used without parentheses is a procedure value, of a procedure type such as proc(a, b: INT): INT. It can be passed, stored in a variable or a record, and called. This is raz's only dynamic dispatch, and it is as plain as it looks.

+
Table.raz
module Table;
+import Out;
+
+type Op = proc(a, b: INT): INT;
+
+proc add(a, b: INT): INT; begin return a + b; end;
+proc sub(a, b: INT): INT; begin return a - b; end;
+proc mul(a, b: INT): INT; begin return a * b; end;
+
+proc apply(f: Op; a, b: INT): INT;
+begin
+    return f(a, b);
+end;
+
+proc main*;
+var ops: [3]Op; names: [3][]U8; i: INT;
+begin
+    ops := [add, sub, mul];
+    names := ["add", "sub", "mul"];
+    for i := 0 to 2 do
+        Out.str(names[i]); Out.str(": ");
+        Out.int(apply(ops[i], 12, 5)); Out.ln;
+    end;
+end;
+
+end Table.
+
add: 17
+sub: 7
+mul: 60
+
+

A procedure without parameters leaves out the parentheses where it is called, as Out.ln does. That means f alone is the procedure and f() would not be a call, so be careful when passing one around.

+

Dropped results

+

A call that drops a result, as Sys.write(fd, s); does, is warned of; _ := Sys.write(fd, s); says it is meant. The compiler also warns of a variable that is assigned and never read, and of a name declared and never used, unless it starts with _.

Save a program under its module’s name and run it with raz run Name.raz.

+
+ + + diff --git a/site/public/tour/records.html b/site/public/tour/records.html new file mode 100644 index 0000000..aa6bc89 --- /dev/null +++ b/site/public/tour/records.html @@ -0,0 +1,350 @@ + + + + + +Records and pointers - Raz, Set, Go + + + + + + + + + + + + +
+
+

Set · lesson 7 of 15

Records and pointers

+
Boxes.raz
module Boxes;
+import Fmt, SYSTEM;
+
+type
+    Point = record x, y: INT; end;
+    Box = record lo, hi: Point; end;
+
+proc area(b: Box): INT;
+begin
+    return (b.hi.x - b.lo.x) * (b.hi.y - b.lo.y);
+end;
+
+proc grow(b: ^Box; n: INT);
+begin
+    DEC(b^.lo.x, n);
+    DEC(b^.lo.y, n);
+    INC(b^.hi.x, n);
+    INC(b^.hi.y, n);
+end;
+
+proc main*;
+var b: Box; p: ^Point;
+begin
+    b := {lo: {x: 1, y: 1}, hi: {x: 4, y: 3}};
+    Fmt.print("{}\n", [Fmt.int(area(b))]);
+    grow(SYSTEM.ADR(b), 1);
+    p := SYSTEM.ADR(b.hi);
+    p^.x := 10;
+    Fmt.print("{} {}\n", [Fmt.int(area(b)), Fmt.int(b.hi.x)]);
+end;
+
+end Boxes.
+
6
+40 10
+
+

A record is laid out as C lays out a struct. {lo: ..., hi: ...} builds one, naming its fields; the ones it leaves out are zero. ^Box is a pointer to a Box, ADR(b) the address of b, and b^ what a pointer points at. A pointer is never the record: it is b^.lo, never b.lo, so you always see where the memory is reached through an address.

+

Copies and literals

+

Assigning a record copies it whole, as with an array. A record is compared field by field by writing the comparison, not by =.

+
Points.raz
module Points;
+import Out;
+
+type Point = record x, y: INT; end;
+
+proc show(p: Point);
+begin
+    Out.char('('); Out.int(p.x); Out.str(", "); Out.int(p.y); Out.char(')');
+end;
+
+proc mirror(p: Point): Point;
+begin
+    return {x: p.y, y: p.x};
+end;
+
+proc main*;
+var a, b: Point;
+begin
+    a := {x: 3, y: 4};
+    b := a;                  (* a copy *)
+    b.x := 30;
+    show(a); show(b); show(mirror(a)); Out.ln;
+    a := {y: 9};             (* x is zero *)
+    show(a); Out.ln;
+end;
+
+end Points.
+
(3, 4)(30, 4)(4, 3)
+(0, 9)
+
+

Tables of constants

+

A constant may be a record, or an array of them: a table the program reads but can't change. Its fields are integers, reals, BOOLs, strings, procedures and the like, and arrays and records of these.

+
Planets.raz
module Planets;
+import Fmt;
+
+type Planet = record name: []U8; moons: INT; water: BOOL; end;
+
+const Inner: []Planet = [
+    {name: "Mercury"},
+    {name: "Venus"},
+    {name: "Earth", moons: 1, water: true},
+    {name: "Mars", moons: 2}];
+
+proc main*;
+var i, total: INT;
+begin
+    for i := 0 to LEN(Inner) - 1 do
+        total := total + Inner[i].moons;
+        if Inner[i].moons = 0 then Fmt.print("{} has no moon\n", [Fmt.str(Inner[i].name)]); end;
+    end;
+    Fmt.print("{} moons in all\n", [Fmt.int(total)]);
+end;
+
+end Planets.
+
Mercury has no moon
+Venus has no moon
+3 moons in all
+
+

Fields left out are zero, as in any literal: Mercury's moons is 0 and its water is false. A constant typed []Planet takes its length from its literal, here 4, so a planet added to the list needs no count changed.

+

Layout

+

A record's layout is C's: each field at the next multiple of its own alignment, and the whole padded to a multiple of its largest alignment. SIZE(T) says how many bytes. A packed record has no padding, which is what a file format or a wire protocol wants.

+
Layout.raz
module Layout;
+import Out;
+
+type
+    Loose = record a: U8; b: U32; c: U8; end;
+    Tight = packed record a: U8; b: U32; c: U8; end;
+
+proc main*;
+begin
+    Out.str("loose: "); Out.int(SIZE(Loose)); Out.ln;     (* 12 *)
+    Out.str("tight: "); Out.int(SIZE(Tight)); Out.ln;     (* 6 *)
+    Out.str("INT:   "); Out.int(SIZE(INT)); Out.ln;
+    Out.str("[5]I16: "); Out.int(SIZE([5]I16)); Out.ln;
+end;
+
+end Layout.
+
loose: 12
+tight: 6
+INT:   8
+[5]I16: 10
+
+

A field of a packed record may sit at any address, and is read and written like any other; but it has no address of its own to take with ADR.

+

Bytes as numbers and records: views

+

A file, a socket or a device hands a program bytes. A view reads and writes them as another type: msg[3].(U32) is the U32 whose four bytes start at msg[3], and msg[0].(Head) the Head whose bytes start at msg[0].

+
Wire.raz
module Wire;
+import Out;
+
+type Head = packed record magic: U16; kind: U8; len: U32; end;   (* 7 bytes, as sent *)
+
+var msg: [32]U8;
+
+proc main*;
+var h: Head; i: INT; sum: I64;
+begin
+    (* what a socket might have handed us *)
+    msg[0] := 52H; msg[1] := 5AH;
+    msg[2] := 1;
+    msg[3].(U32) := 8;
+    msg[7].(I32) := 100;
+    msg[11].(I32) := 200;
+
+    h := msg[0].(Head);
+    Out.hex(U64(h.magic), 4); Out.char(' ');
+    Out.int(I64(h.kind)); Out.char(' ');
+    Out.int(I64(h.len)); Out.ln;
+    sum := 0;
+    i := 7;
+    while i < 7 + INT(h.len) do
+        sum := sum + I64(msg[i].(I32));
+        i := i + 4;
+    end;
+    Out.int(sum); Out.ln;
+end;
+
+end Wire.
+
5A52 1 8
+300
+
+

A view isn't a copy: it *is* those bytes, so msg[3].(U32) := 8 writes msg[3] to msg[6], and a view goes wherever a variable does, with a field after it, in INC, on the left of :=. Nor is it a conversion: I64(x) is a real's number, x.(U64) its bits. The magic number reads 5A52, its bytes backwards, because x86-64 keeps a number's low byte first; a format with an order of its own is read with Str.le or Str.be.

+

A view of an element must end inside the array, and the program checks it as it checks an index:

+
Short.raz
module Short;
+import Out;
+
+var msg: [10]U8;
+
+proc main*;
+var i: INT;
+begin
+    i := 0;
+    while i < LEN(msg) do
+        Out.int(I64(msg[i].(U32))); Out.char(' ');
+        i := i + 4;
+    end;
+end;
+
+end Short.
+
0 0 Short.raz:11:25: a view at index 8 runs past a length of 10
+  in Short.main at Short.raz:11:25: i = 8
+
+

The type of a view is an integer, a real or a pointer, or a record or array made of them: types any bytes are a value of, which a BOOL or an enumeration isn't. A view may start at any byte, so, as a packed record's field, it has no address of its own.

+

Pointers

+

ADR(x) takes the address of a variable, ^T is a pointer to a T, and p^ is what it points at. A pointer that points nowhere is nil, and following it stops the program with a message that names the place, so a forgotten check is found at once instead of corrupting memory.

+
Pointers.raz
module Pointers;
+import Out;
+
+type Counter = record hits: INT; name: []U8; end;
+
+proc hit(c: ^Counter);
+begin
+    if c = nil then return; end;
+    INC(c^.hits);
+end;
+
+proc swap(a, b: ^INT);
+var t: INT;
+begin
+    t := a^;
+    a^ := b^;
+    b^ := t;
+end;
+
+proc main*;
+var c: Counter; x, y: INT; p: ^INT;
+begin
+    c.name := "front door";
+    hit(ADR(c)); hit(ADR(c)); hit(nil);
+    Out.str(c.name); Out.str(": "); Out.int(c.hits); Out.ln;
+    x := 1; y := 2;
+    swap(ADR(x), ADR(y));
+    Out.int(x); Out.char(' '); Out.int(y); Out.ln;
+    p := ADR(x);
+    p^ := p^ + 40;
+    Out.int(x); Out.ln;
+end;
+
+end Pointers.
+
front door: 2
+2 1
+42
+
+

Pointers that link

+

A record may hold a pointer to its own type, which is how lists and trees are made. Memory for them comes from an allocator, which is the next lesson; here the nodes simply live in an array.

+
Chain.raz
module Chain;
+import Out;
+
+type Node = record next: ^Node; val: INT; end;
+
+proc main*;
+var nodes: [4]Node; head, n: ^Node; i: INT;
+begin
+    head := nil;
+    for i := 0 to 3 do
+        nodes[i].val := (i + 1) * 10;
+        nodes[i].next := head;       (* each new one in front *)
+        head := ADR(nodes[i]);
+    end;
+    n := head;
+    while n # nil do
+        Out.int(n^.val); Out.char(' ');
+        n := n^.next;
+    end;
+    Out.ln;
+end;
+
+end Chain.
+
40 30 20 10 
+
+

A slice's pointer

+

A slice is a pointer and a length, and a record can keep the two apart: an interpreter keeps a string so, and C takes one so. LEN(s) is the length. The pointer looks like ADR(s[0]), the address of the first element, and that works until the slice is empty: then there is no first element, s[0] is out of range, and the program stops.

+
Empty.raz
module Empty;
+import Out;
+
+type Span = record p: ^U8; n: INT; end;
+
+proc spanOf(s: []U8): Span;
+begin
+    return {p: ADR(s[0]), n: LEN(s)};
+end;
+
+proc main*;
+var a, b: Span;
+begin
+    a := spanOf("one");
+    Out.int(a.n); Out.ln;
+    b := spanOf("");
+    Out.int(b.n); Out.ln;
+end;
+
+end Empty.
+
3
+Empty.raz:8:22: index 0 is out of range for a length of 0
+  in Empty.spanOf at Empty.raz:8:22
+  in Empty.main at Empty.raz:16:5
+
+

PTR(s) is the pointer itself, a ^U8 for a []U8, with no check. For a slice that isn't empty it is ADR(s[0]); for an empty one it is what the slice holds, nil for one never set. So nothing needs testing first, and sp.p[0..sp.n] makes the slice again, empty when sp.n is 0, whatever sp.p is:

+
Spans.raz
module Spans;
+import Out, SYSTEM;
+
+type Span = record p: ^U8; n: INT; end;
+
+proc spanOf(s: []U8): Span;
+begin
+    return {p: SYSTEM.PTR(s), n: LEN(s)};
+end;
+
+proc text(sp: Span): []U8;
+begin
+    return sp.p[0..sp.n];
+end;
+
+proc main*;
+var words: [3]Span; i: INT;
+begin
+    words := [spanOf("one"), spanOf(""), spanOf("three")];
+    for i := 0 to 2 do
+        Out.int(words[i].n); Out.char(' ');
+        Out.str(text(words[i])); Out.ln;
+    end;
+end;
+
+end Spans.
+
3 one
+0 
+5 three
+
+

Of an array, PTR(a) is the address of its first element, a ^T where ADR(a) is a ^[n]T. Reading through the pointer is as unchecked as through any pointer: the length is yours to keep with it. The compiler says so when the two are mixed up: a slice given where a pointer is wanted is an error whose help says to write PTR(s) and LEN(s), and a pointer given where a slice is, p[0..n].

Save a program under its module’s name and run it with raz run Name.raz.

+
+ + + diff --git a/site/public/tour/slices.html b/site/public/tour/slices.html new file mode 100644 index 0000000..cedbd14 --- /dev/null +++ b/site/public/tour/slices.html @@ -0,0 +1,350 @@ + + + + + +Arrays, slices and strings - Raz, Set, Go + + + + + + + + + + + + +
+
+

Set · lesson 6 of 15

Arrays, slices and strings

+
Slices.raz
module Slices;
+import Out, Str;
+
+proc sum(s: []INT): INT;
+var i, t: INT;
+begin
+    t := 0;
+    for i := 0 to LEN(s) - 1 do t := t + s[i]; end;
+    return t;
+end;
+
+proc main*;
+var a: [5]INT; i: INT; s, val: []U8; name: [8]U8; ok: BOOL;
+begin
+    for i := 0 to 4 do a[i] := i * i; end;
+    Out.int(sum(a)); Out.ln;        (* the array, as a slice *)
+    Out.int(sum(a[1..3])); Out.ln;  (* a[1] and a[2] *)
+    s := "hello, world";
+    Out.str(s[7..LEN(s)]); Out.ln;
+    if s[0..5] = "hello" then Out.str("it says hello\n"); end;
+    Out.int(Str.find(s, "world")); Out.ln;
+    _, val, ok := Str.cut(" size = 42 ", "=");
+    if ok then Out.str(Str.trim(val)); Out.ln; end;
+    name := "raz";                  (* a copy, the program's own *)
+    name[0] := 'R';
+    Out.str(name[0..3]); Out.ln;
+    Out.str(`
+        C:\tmp\ "as it stands"
+          over lines
+        `);
+end;
+
+end Slices.
+
30
+5
+world
+it says hello
+7
+42
+Raz
+C:\tmp\ "as it stands"
+  over lines
+
+

Arrays

+

[5]INT is an array: five INTs in a row, copied when it is assigned or passed. Its length is part of its type, so [5]INT and [6]INT are different types, and LEN(a) of an array is a constant. Array literals are written in brackets, and need a type from the place they are used.

+
Arrays.raz
module Arrays;
+import Out;
+
+proc main*;
+var a, b: [4]INT; grid: [3][3]INT; i, j: INT;
+begin
+    a := [1, 2, 3, 4];
+    b := a;                         (* a copy *)
+    b[0] := 99;
+    Out.int(a[0]); Out.char(' '); Out.int(b[0]); Out.ln;
+    if a # b then Out.str("they differ now\n"); end;
+
+    for i := 0 to 2 do
+        for j := 0 to 2 do grid[i][j] := i * 3 + j; end;
+    end;
+    Out.int(grid[2][1]); Out.ln;    (* 7 *)
+    Out.int(LEN(grid)); Out.char('x'); Out.int(LEN(grid[0])); Out.ln;
+end;
+
+end Arrays.
+
1 99
+they differ now
+7
+3x3
+
+

Slices

+

[]INT is a slice: a pointer to elements that live elsewhere, and their number, LEN(s). a[lo..hi] is the slice of the elements from lo up to, but not including, hi, and an array goes silently where a slice is wanted. A slice doesn't copy anything: changing an element of it changes the array it looks at.

+
Windows.raz
module Windows;
+import Out;
+
+proc zero(s: []INT);
+var i: INT;
+begin
+    for i := 0 to LEN(s) - 1 do s[i] := 0; end;
+end;
+
+proc show(s: []INT);
+var i: INT;
+begin
+    for i := 0 to LEN(s) - 1 do Out.int(s[i]); Out.char(' '); end;
+    Out.ln;
+end;
+
+proc main*;
+var a: [8]INT; i: INT;
+begin
+    for i := 0 to 7 do a[i] := i + 1; end;
+    zero(a[2..5]);                  (* a window onto a *)
+    show(a);                        (* 1 2 0 0 0 6 7 8 *)
+    show(a[6..8]);
+    show(a[3..3]);                  (* empty: prints just a line feed *)
+end;
+
+end Windows.
+
1 2 0 0 0 6 7 8 
+7 8 
+
+
+

Every index and every slice bound is checked, so a slice can never reach past what it was made from; the lesson on failures shows what that looks like.

+

A slice of a local array is good only while its procedure runs: the array is gone once it returns. So returning one is an error, return a[0..n] or return a with a a local, a value parameter or an array literal. Take the array as a var parameter instead, and the slice is of the caller's array; or fill a buffer the caller gives.

+

COPY

+

COPY(d, s) copies the elements of s to the start of d, as one block, and is right when they overlap. LEN(s) must be at most LEN(d).

+
Moves.raz
module Moves;
+import Out;
+
+proc main*;
+var a: [6]INT; i: INT;
+begin
+    a := [1, 2, 3, 4, 5, 0];
+    COPY(a[1..6], a[0..5]);         (* shift everything one place up *)
+    for i := 0 to 5 do Out.int(a[i]); Out.char(' '); end;
+    Out.ln;
+end;
+
+end Moves.
+
1 1 2 3 4 5 
+
+

Strings

+

A string is a slice of bytes, []U8, in UTF-8, and a string constant's bytes are constant. A [8]U8 made from one is a copy you can change. Arrays and slices of integers compare with = and #, so strings do too. Str has the rest: ordering, finding, hashing, prefixes and suffixes, trimming, taking apart, ASCII case and kinds of character, UTF-8, and numbers to and from text.

+
Words.raz
module Words;
+import Out, Str;
+
+proc main*;
+var s: []U8; n: I64; ok: BOOL; name: [8]U8;
+begin
+    s := "hello, world";
+    Out.str(s[7..LEN(s)]); Out.ln;
+    if s[0..5] = "hello" then Out.str("it says hello\n"); end;
+    Out.int(Str.find(s, "world")); Out.ln;          (* 7 *)
+    Out.int(Str.find(s, "xyz")); Out.ln;            (* -1 *)
+    Out.int(Str.findLast("abcabc", "bc")); Out.ln;  (* 4 *)
+    Out.int(Str.findFrom(s, "o", 5)); Out.ln;       (* 8: the first o from 5 on *)
+    if Str.isDigit('7') and not Str.isLetter('7') then Out.str("a digit\n"); end;
+    if Str.hasPrefix(s, "hell") then Out.str("prefix\n"); end;
+    if Str.hasSuffix(s, "world") then Out.str("suffix\n"); end;
+    Out.int(Str.cmp("apple", "banana")); Out.ln;    (* -1 *)
+    if Str.eqFold("RAZ", "raz") then Out.str("the same, but for case\n"); end;
+    Out.str("["); Out.str(Str.trim("  padded \t\n")); Out.str("]\n");
+
+    n, ok := Str.toInt("-1234");
+    if ok then Out.int(n + 1); Out.ln; end;
+    n, ok := Str.toInt("12x");
+    if not ok then Out.str("not a number\n"); end;
+
+    name := "raz";                  (* a copy, the program's own *)
+    name[0] := 'R';
+    Out.str(name[0..3]); Out.ln;
+    Str.upper(name[0..3]);          (* in place: name is a variable *)
+    Out.str(name[0..3]); Out.ln;
+end;
+
+end Words.
+
world
+it says hello
+7
+-1
+4
+8
+a digit
+prefix
+suffix
+-1
+the same, but for case
+[padded]
+-1233
+not a number
+Raz
+RAZ
+
+

Taking a string apart

+

Str.cut splits a string at the first place a separator is: what comes before it, what comes after, and whether it was there at all. Str.field gives the first word, past any spaces, and the rest. Neither copies anything: every part is a slice of the string it came from, so taking a line or a file apart costs no memory.

+
Parts.raz
module Parts;
+import Out, Str;
+
+const Text = "name = raz\nkind = language\nyear = 2026\n";
+
+proc main*;
+var line, rest, key, val, w: []U8; more, ok: BOOL;
+begin
+    (* line by line, then each line at its = *)
+    line, rest, more := Str.cut(Text, "\n");
+    while more do
+        key, val, ok := Str.cut(line, "=");
+        if ok then
+            Out.str(Str.trim(key)); Out.str(" is "); Out.str(Str.trim(val)); Out.ln;
+        end;
+        line, rest, more := Str.cut(rest, "\n");
+    end;
+
+    (* word by word *)
+    w, rest := Str.field("  the quick   brown fox ");
+    while LEN(w) > 0 do
+        Out.str("<"); Out.str(w); Out.str(">");
+        w, rest := Str.field(rest);
+    end;
+    Out.ln;
+end;
+
+end Parts.
+
name is raz
+kind is language
+year is 2026
+<the><quick><brown><fox>
+
+

When Str.cut finds no separator it gives the whole string, an empty one and false, so the loop above ends after the last line that has a line feed. Building a string goes the other way, in a Buf: Str.join adds parts with a separator between them, and Str.replace adds a string with every match of one text replaced by another (lesson 9 shows Buf).

+

Raw strings

+

A string between backquotes is raw: its bytes are the text as it stands, with no escapes, so a backslash or a double quote is itself, and it may run over lines. When the opening backquote ends its line and the closing one has only spaces and tabs before it, those blanks come off the start of every line between, and the text keeps the indent of the code it sits in. Each line ends in a line feed, the last one too.

+
Raw.raz
module Raw;
+import Out;
+
+const Path = `C:\Users\raz\"notes".txt`;
+
+proc usage;
+begin
+    Out.str(`
+        usage: tool [-v] file ...
+          -v    say what is done
+          file  read this, not standard input
+        `);
+end;
+
+proc main*;
+begin
+    Out.str(Path); Out.ln;
+    usage;
+    Out.str(`a raw string on one line, \n and all`); Out.ln;
+end;
+
+end Raw.
+
C:\Users\raz\"notes".txt
+usage: tool [-v] file ...
+  -v    say what is done
+  file  read this, not standard input
+a raw string on one line, \n and all
+
+

A line of an indented raw string that doesn't start with the closing line's blanks is an error, so a slip in the indent is caught where it is made, not printed. A raw string can't hold a backquote; join one in with + and an ordinary string that holds it.

+

UTF-8

+

A character is an I32, its code point. A string stays bytes; UTF-8 is how Str reads them. Str.next walks a string a character at a time, giving each one and where the next starts, -1 at the end. Str.decode reads the first character of a string and says how many bytes it took, Str.decodeLast the last, and Str.encode goes the other way. Str.chars counts characters and Str.valid says whether a string is UTF-8 at all; a byte that doesn't start a character rightly reads as FFFDH, the character that stands for a wrong one. Byte length and character count are different things, and the program is the one that says which it wants. On a terminal there is a third: a character takes 0, 1 or 2 columns, a combining accent none and an ideograph two, and Width.columns counts those.

+
Runes.raz
module Runes;
+import Out, Str, Width;
+
+proc main*;
+var s: []U8; c: I32; i, size: INT; bytes: [4]U8; k: INT;
+begin
+    s := "caf\u{E9} \u{3BB}";
+    Out.int(LEN(s)); Out.str(" bytes, ");
+    Out.int(Str.chars(s)); Out.str(" characters, ");
+    Out.int(Width.columns("\u{4E2D}\u{6587}")); Out.str(" columns for two ideographs\n");
+
+    (* each character, as its code point *)
+    c, i := Str.next(s, 0);
+    while i >= 0 do
+        Out.int(I64(c)); Out.str(" ");
+        c, i := Str.next(s, i);
+    end;
+    Out.ln;
+
+    c, size := Str.decodeLast(s);
+    Out.int(I64(c)); Out.str(" is last, in "); Out.int(size); Out.str(" bytes\n");
+    bytes, k := Str.encode(955);
+    Out.str(bytes[0..k]); Out.ln;
+    if not Str.valid(s[0..4]) then Out.str("cut in the middle of a character\n"); end;
+end;
+
+end Runes.
+
8 bytes, 6 characters, 4 columns for two ideographs
+99 97 102 233 32 955 
+955 is last, in 2 bytes
+λ
+cut in the middle of a character
+
+

Str knows UTF-8 and no more of Unicode: its case is ASCII's, and it doesn't say how wide a character is on a terminal or which spellings of a text are the same. Those need tables bigger than the rest of the library.

+

Loops over lengths

+

A for loop takes its bounds once, and never steps past the last: with an empty slice, 0 to LEN(s) - 1 doesn't run at all, and the variable can't wrap. for takes a constant step with by, and while and repeat ... until do the rest. break leaves a loop, and continue ends its round: a for steps, a while or a repeat tests again. So a while moves on before any continue, or it never moves at all.

+
Loops.raz
module Loops;
+import Out;
+
+proc main*;
+var i: INT;
+begin
+    for i := 10 to 0 by -5 do Out.int(i); Out.char(' '); end;
+    Out.ln;
+    i := 1;
+    while i < 100 do i := i * 3; end;
+    Out.int(i); Out.ln;
+    repeat DEC(i, 30); until i < 0;
+    Out.int(i); Out.ln;
+    for i := 1 to 10 do
+        if i mod 3 = 0 then continue; end;     (* 3, 6 and 9 passed over *)
+        Out.int(i); Out.char(' ');
+    end;
+    Out.ln;
+end;
+
+end Loops.
+
10 5 0 
+243
+-27
+1 2 4 5 7 8 10 
+

Save a program under its module’s name and run it with raz run Name.raz.

+
+ + + diff --git a/site/public/tour/threads.html b/site/public/tour/threads.html new file mode 100644 index 0000000..9afd0f8 --- /dev/null +++ b/site/public/tour/threads.html @@ -0,0 +1,185 @@ + + + + + +Threads - Raz, Set, Go + + + + + + + + + + + + +
+
+

Go · lesson 15 of 15

Threads

+
Hits.raz
module Hits;
+import Out, Thread, SYSTEM;
+
+const Workers = 4;
+
+var
+    hits: INT;      (* added to by every thread at once, by XADD *)
+    m: Thread.Mutex;
+    total: INT;     (* added to under m *)
+
+proc work(arg: ^U8);
+var i, n, sum: INT;
+begin
+    n := INT(arg);
+    sum := 0;
+    for i := 1 to n do
+        sum := sum + i;
+        _ := XADD(hits, 1);
+    end;
+    Thread.lock(m);
+    total := total + sum;
+    Thread.unlock(m);
+end;
+
+proc main*;
+var t: [Workers]^Thread.Thread; i: INT; err: ERROR;
+begin
+    for i := 0 to Workers - 1 do
+        t[i], err := Thread.spawn(work, ^U8(1000 * (i + 1)));
+        if err # nil then Out.str(MSG(err)); Out.ln; return; end;
+    end;
+    for i := 0 to Workers - 1 do Thread.join(t[i]); end;
+    Out.int(hits); Out.char(' '); Out.int(total); Out.ln;
+end;
+
+end Hits.
+
10000 15005000
+
+

Thread.spawn runs a procedure in a thread of its own, with a stack of its own, and Thread.join waits for it to end. XADD, CAS and XCHG change a word atomically; a Thread.Mutex keeps a longer section to one thread at a time. Out and Heap lock themselves.

+

What goes wrong without them

+

Two threads that each read a variable, add one and write it back can lose one of the additions. A plain INC on a variable shared by threads has no particular value afterwards; the report says so. XADD is the atomic add: it returns the old value and adds in one indivisible step.

+
Race.raz
module Race;
+import Out, Thread;
+
+var
+    safe: INT;       (* added to by XADD *)
+    plain: INT;      (* added to by INC: unsafe, never printed *)
+
+proc work(_arg: ^U8);
+var i: INT;
+begin
+    for i := 1 to 100000 do
+        _ := XADD(ADR(safe), 1);
+        INC(plain);              (* unsafe: lost additions *)
+    end;
+end;
+
+proc main*;
+var t: [4]^Thread.Thread; i: INT; err: ERROR;
+begin
+    for i := 0 to 3 do
+        t[i], err := Thread.spawn(work, nil);
+        if err # nil then Out.str(MSG(err)); Out.ln; return; end;
+    end;
+    for i := 0 to 3 do Thread.join(t[i]); end;
+    Out.str("safe  "); Out.int(safe); Out.ln;
+end;
+
+end Race.
+
safe  400000
+
+

The atomic count is always 400000. The plain one is usually lower, and different from run to run, which is why this page doesn't print it.

+

A mutex for longer sections

+

An atomic is one word. When several variables must change together, take a Thread.Mutex; it sleeps while it waits, so it suits sections that take a while. Declare it as a module variable, since zero is free.

+
Bank.raz
module Bank;
+import Out, Thread;
+
+var
+    m: Thread.Mutex;
+    balance, deposits: INT;     (* kept in step, under m *)
+
+proc deposit(_arg: ^U8);
+var i: INT;
+begin
+    for i := 1 to 10000 do
+        Thread.lock(m);
+        balance := balance + 5;
+        INC(deposits);
+        Thread.unlock(m);
+    end;
+end;
+
+proc main*;
+var t: [3]^Thread.Thread; i: INT; err: ERROR;
+begin
+    for i := 0 to 2 do
+        t[i], err := Thread.spawn(deposit, nil);
+        if err # nil then Out.str(MSG(err)); Out.ln; return; end;
+    end;
+    for i := 0 to 2 do Thread.join(t[i]); end;
+    Out.int(deposits); Out.char(' '); Out.int(balance); Out.ln;
+end;
+
+end Bank.
+
30000 150000
+
+

Handing work out

+

A thread's procedure takes one pointer argument. Pass a record's address to give each thread its own job and its own place to put the answer; then no one shares anything.

+
Jobs.raz
module Jobs;
+import Out, Thread;
+
+type Job = record lo, hi: INT; sum: INT; end;
+
+proc work(arg: ^U8);
+var j: ^Job; i: INT;
+begin
+    j := ^Job(arg);
+    for i := j^.lo to j^.hi - 1 do j^.sum := j^.sum + i; end;
+end;
+
+proc main*;
+var jobs: [4]Job; t: [4]^Thread.Thread; i, total: INT; err: ERROR;
+begin
+    for i := 0 to 3 do
+        jobs[i].lo := i * 250000;
+        jobs[i].hi := (i + 1) * 250000;
+        t[i], err := Thread.spawn(work, ^U8(ADR(jobs[i])));
+        if err # nil then Out.str(MSG(err)); Out.ln; return; end;
+    end;
+    for i := 0 to 3 do
+        Thread.join(t[i]);
+        total := total + jobs[i].sum;
+    end;
+    Out.int(total); Out.ln;
+end;
+
+end Jobs.
+
499999500000
+
+

Thread makes its own threads, without C, so a program that uses it can't use C; one that does makes its threads with C's pthread_create instead. The advanced tour goes further into atomics, memory ordering and lock-free code.

Save a program under its module’s name and run it with raz run Name.raz.

+
+ + + diff --git a/site/public/tour/values.html b/site/public/tour/values.html new file mode 100644 index 0000000..4b40f62 --- /dev/null +++ b/site/public/tour/values.html @@ -0,0 +1,146 @@ + + + + + +Values and conversions - Raz, Set, Go + + + + + + + + + + + + +
+
+

Raz · lesson 4 of 15

Values and conversions

+

This program uses several of the basic types at once, with each conversion written where it happens.

+
Values.raz
module Values;
+import Fmt;
+
+const Max = 100;    (* untyped: it takes the type it meets *)
+
+proc main*;
+var n: INT; b: U8; big: I64; x: F64; c: I32; ok: BOOL;
+begin
+    n := Max * 3;
+    b := 250;
+    b := b + 10;          (* wraps, in a U8: 4 *)
+    big := n;             (* an INT goes into an I64 *)
+    x := F64(n) / 7.0;    (* nothing else converts unasked *)
+    c := '\u{E9}';        (* a character is its code point *)
+    ok := (n > Max) and (b # 0);
+    Fmt.print("{} {} {} {} {} {}\n", [Fmt.int(n), Fmt.int(I64(b)),
+        Fmt.int(big), Fmt.real(x, 3), Fmt.int(I64(c)),
+        Fmt.bool(ok)]);
+end;
+
+end Values.
+
300 4 300 42.857 233 true
+
+

Conversions are written

+

Two types never mix but where nothing can be lost: an INT goes into an I64 wherever it meets one, so with pos: I64, pos + LEN(s) is an I64; and a U8, I8 or I16 into an INT, unless an operator made it, so n := s[i] needs no conversion. With i: I32 and a slice s, i < LEN(s) is an error. A type's name converts: F64(n), I64(b), U8(x); an I64 becomes an INT only so, INT(pos), since an INT may be smaller on another machine. The lesson on integers says what each width conversion does.

+

A number written in the program is untyped until it meets a type, and 1.5 is a real, which an integer never becomes without a conversion.

+
Mix.raz
module Mix;
+import Out;
+
+proc main*;
+var i: I32; s: []U8;
+begin
+    s := "four";
+    i := 3;
+    if i < LEN(s) then Out.str("smaller\n"); end;
+end;
+
+end Mix.
+
$ raz Mix.raz
+Mix.raz:9:8: error: I32 and INT are different types
+    9 |     if i < LEN(s) then Out.str("smaller\n"); end;
+      |        ^^^^^^^^^^
+help: convert one to the other's type, as in INT(i)
+raz: 1 error
+

The fix is the conversion, written where it happens: if INT(i) < LEN(s). It costs nothing at run time and says what is meant.

+

What converts to what

+

Everything else that converts does so with the type's name, and the rules are short:

+
FromToResult
integerintegercut to the new width, or extended by the sign (signed) or zeros (unsigned)
integerF32, F64the nearest real
F32, F64integerrounded toward zero
F32F64the same value; the other way, the nearest F32
enumerationintegerits position; and back, if there is a name at that position
setintegerits bits; and back
INT, UINTpointerthe address; and back
+

There is no conversion between BOOL and an integer: say what you mean with if. A BOOL is true or false, and and, or and not are for BOOLs: they bind below the relations, so i < n and a[i] # 0 needs no parentheses, and and and or evaluate their right operand only when it decides the result. #, not <>, is "different".

+
Truth.raz
module Truth;
+import Out;
+
+proc positive(n: INT): BOOL;
+begin
+    return n > 0;
+end;
+
+proc main*;
+var a: [3]INT; i: INT; found: BOOL;
+begin
+    a := [4, 0, 9];
+    i := 0;
+    while (i < LEN(a)) and (a[i] # 0) do INC(i); end;   (* never reads a[3] *)
+    Out.int(i); Out.ln;
+    found := positive(i) or positive(-1);
+    if found and not positive(0) then Out.str("true and true\n"); end;
+end;
+
+end Truth.
+
1
+true and true
+
+

Reals

+

F32 and F64 are the reals. A real constant is written with a point, 1.5 or 2.0E-3. Fmt.real(x, places) writes one with that many digits after the point, and Math has the functions.

+
Reals.raz
module Reals;
+import Fmt, Math;
+
+proc main*;
+var n: INT; x: F64; y: F32;
+begin
+    n := 22;
+    x := F64(n) / 7.0;
+    y := F32(x);
+    Fmt.print("22/7 = {}\n", [Fmt.real(x, 6)]);
+    Fmt.print("as F32 = {}\n", [Fmt.real(F64(y), 6)]);
+    Fmt.print("sqrt 2 = {}, pi = {}\n", [Fmt.real(Math.sqrt(2.0), 5), Fmt.real(Math.pi, 5)]);
+    Fmt.print("2^10 = {}, log2 of that = {}\n", [Fmt.real(Math.pow(2.0, 10.0), 1), Fmt.real(Math.log2(1024.0), 1)]);
+    Fmt.print("rounded: {} {}\n", [Fmt.real(Math.round(2.5), 1), Fmt.real(Math.round(-2.5), 1)]);
+    Fmt.print("truncated: {} {}\n", [Fmt.int(I64(2.9)), Fmt.int(I64(-2.9))]);
+end;
+
+end Reals.
+
22/7 = 3.142857
+as F32 = 3.142857
+sqrt 2 = 1.41421, pi = 3.14159
+2^10 = 1024.0, log2 of that = 10.0
+rounded: 3.0 -3.0
+truncated: 2 -2
+
+

A real converts to an integer by rounding toward zero. Every variable starts at zero, a real's 0.0 and a BOOL's false included, so there is no uninitialised value to be surprised by.

Save a program under its module’s name and run it with raz run Name.raz.

+
+ + + diff --git a/site/public/tour/variants.html b/site/public/tour/variants.html new file mode 100644 index 0000000..83daac1 --- /dev/null +++ b/site/public/tour/variants.html @@ -0,0 +1,318 @@ + + + + + +Enumerations, sets, variants and match - Raz, Set, Go + + + + + + + + + + + + +
+
+

Set · lesson 8 of 15

Enumerations, sets, variants and match

+
Shapes.raz
module Shapes;
+import Out, Fmt, Math;
+
+type
+    Colour = (red, green, blue);
+    Colours = set of Colour;
+    Shape = variant
+        circle(r: F64);
+        rect(w, h: F64);
+        dot;
+    end;
+
+const Some: []Shape = [circle(1.0), rect(2.0, 3.5), dot];
+
+proc area(const s: Shape): F64;
+begin
+    match s of
+    | circle(r): return Math.pi * r * r;
+    | rect(w, h): return w * h;
+    | dot: return 0.0;
+    end;
+end;
+
+proc kind(c: I32): []U8;
+begin
+    match c of
+    | ' ', '\t', '\n': return "space";
+    | '0' .. '9': return "digit";
+    | 'a' .. 'z', 'A' .. 'Z': return "letter";
+    | else: return "other";
+    end;
+end;
+
+proc colour(name: []U8): Colour;
+begin
+    match name of
+    | "red", "rose": return red;
+    | "green": return green;
+    | else: return blue;
+    end;
+end;
+
+proc main*;
+var i: INT; warm: Colours; c: Colour;
+begin
+    for i := 0 to LEN(Some) - 1 do
+        Fmt.print("{}\n", [Fmt.real(area(Some[i]), 2)]);
+    end;
+    Fmt.print("{} {} {}\n", [Fmt.str(kind('7')), Fmt.str(kind('x')),
+        Fmt.str(kind('+'))]);
+    warm := {red, blue} - {blue} + {green};
+    for c := red to blue do
+        if c in warm then Out.int(I64(c)); Out.ln; end;
+    end;
+    Out.int(I64(colour("rose"))); Out.int(I64(colour("green"))); Out.ln;
+end;
+
+end Shapes.
+
3.14
+7.00
+0.00
+digit letter other
+0
+1
+01
+
+

Enumerations

+

An enumeration is a list of names, in order. They convert to their position and back, and a for loop can run over them. A name may be written with its type, Day.mon, and two enumerations of a module may share a name, Style.bold and Elem.bold, which is then always written so. An integer that has no name at its position is a failed check, never a silent wrong value.

+
Days.raz
module Days;
+import Out;
+
+type Day = (mon, tue, wed, thu, fri, sat, sun);
+
+proc name(d: Day): []U8;
+begin
+    match d of
+    | mon: return "Monday";
+    | tue: return "Tuesday";
+    | wed: return "Wednesday";
+    | thu: return "Thursday";
+    | fri: return "Friday";
+    | sat: return "Saturday";
+    | sun: return "Sunday";
+    end;
+end;
+
+proc main*;
+var d: Day;
+begin
+    for d := mon to sun do
+        Out.int(I64(d)); Out.str(" "); Out.str(name(d));
+        if d >= sat then Out.str(" (weekend)"); end;
+        Out.ln;
+    end;
+    d := Day(4);
+    Out.str(name(d)); Out.ln;
+end;
+
+end Days.
+
0 Monday
+1 Tuesday
+2 Wednesday
+3 Thursday
+4 Friday
+5 Saturday (weekend)
+6 Sunday (weekend)
+Friday
+
+

Sets

+

A set of an enumeration holds any choice of its names, in the bits of a word. in tests membership; + is union, * intersection and - difference; {} is the empty set. Sets are how Unix permissions, option flags and key modifiers are best written.

+
Perms.raz
module Perms;
+import Out;
+
+type
+    Perm = (x, w, r);               (* bits 0, 1, 2, as chmod has them *)
+    Perms = set of Perm;
+
+proc show(p: Perms);
+begin
+    if r in p then Out.char('r'); else Out.char('-'); end;
+    if w in p then Out.char('w'); else Out.char('-'); end;
+    if x in p then Out.char('x'); else Out.char('-'); end;
+end;
+
+proc main*;
+var user, group, mine: Perms;
+begin
+    user := {r, w, x};
+    group := {r, x};
+    show(user); Out.char(' '); show(group); Out.ln;
+    show(user * group); Out.char(' ');      (* both: r-x *)
+    show(user - group); Out.char(' ');      (* only user: -w- *)
+    show(user - {w}); Out.ln;        (* r-x *)
+    mine := group;
+    if mine = {r, x} then Out.str("same as group\n"); end;
+    Out.int(I64(U8(user))); Out.ln;         (* 7: a set is its bits *)
+end;
+
+end Perms.
+
rwx r-x
+r-x -w- r-x
+same as group
+7
+
+

Variants

+

A variant holds one of its cases, each with fields of its own, and match is the only way to read them: it runs the arm of the case the variant holds, naming its fields. Every case has an arm, unless an | else: comes last, so adding a case to the type makes every match that forgot it a compile error.

+
Tokens.raz
module Tokens;
+import Out;
+
+type
+    Token = variant
+        number(n: INT);
+        plus;
+        times;
+        word(s: []U8);
+    end;
+
+proc describe(t: Token);
+begin
+    match t of
+    | number(n): Out.str("number "); Out.int(n);
+    | plus: Out.str("plus");
+    | times: Out.str("times");
+    | word(s): Out.str("word '"); Out.str(s); Out.char('\'');
+    end;
+    Out.ln;
+end;
+
+(* evaluates tokens in reverse Polish; assumes the input is well formed *)
+proc eval(ts: []Token): INT;
+var stack: [16]INT; top, i, b: INT;
+begin
+    top := 0;
+    for i := 0 to LEN(ts) - 1 do
+        match ts[i] of
+        | number(n): stack[top] := n; INC(top);
+        | plus: b := stack[top - 1]; DEC(top); stack[top - 1] := stack[top - 1] + b;
+        | times: b := stack[top - 1]; DEC(top); stack[top - 1] := stack[top - 1] * b;
+        | else:
+        end;
+    end;
+    return stack[0];
+end;
+
+proc main*;
+var ts: [5]Token; i: INT;
+begin
+    ts := [number(3), number(4), plus, number(5), times];   (* (3 + 4) * 5 *)
+    for i := 0 to 4 do describe(ts[i]); end;
+    Out.int(eval(ts)); Out.ln;
+    describe(word("hello"));
+end;
+
+end Tokens.
+
number 3
+number 4
+plus
+number 5
+times
+35
+word 'hello'
+
+

Matching integers

+

On an integer, match takes constants and ranges, and must have an | else:. Characters are integers, so it is also how a scanner is written.

+
Classify.raz
module Classify;
+import Out;
+
+proc kind(c: I32): []U8;
+begin
+    match c of
+    | ' ', '\t', '\n': return "space";
+    | '0' .. '9': return "digit";
+    | 'a' .. 'z', 'A' .. 'Z', '_': return "letter";
+    | else: return "other";
+    end;
+end;
+
+proc main*;
+var s: []U8; i: INT;
+begin
+    s := "x1 + _y";
+    for i := 0 to LEN(s) - 1 do
+        Out.char(s[i]); Out.str(" is "); Out.str(kind(I32(s[i]))); Out.ln;
+    end;
+end;
+
+end Classify.
+
x is letter
+1 is digit
+  is space
++ is other
+  is space
+_ is letter
+y is letter
+
+

Matching strings

+

On a string, match takes string constants, several to an arm if need be, and compares them as = does. It too must have an | else:. It is how a program reads a command, an option or a keyword without a chain of elsifs.

+
Commands.raz
module Commands;
+import Out;
+
+type Op = (none, add, sub, show);
+
+proc op(word: []U8): Op;
+begin
+    match word of
+    | "add", "plus", "+": return add;
+    | "sub", "minus", "-": return sub;
+    | "show": return show;
+    | else: return none;
+    end;
+end;
+
+proc main*;
+var total: INT; words: [6][]U8; i: INT;
+begin
+    words := ["add", "plus", "sub", "show", "times", "-"];
+    for i := 0 to 5 do
+        match op(words[i]) of
+        | add: INC(total);
+        | sub: DEC(total);
+        | show: Out.int(total); Out.ln;
+        | none: Out.str(words[i]); Out.str("?\n");
+        end;
+    end;
+    Out.int(total); Out.ln;
+end;
+
+end Commands.
+
1
+times?
+0
+
+

Two labels that are the same string are an error, as two arms for one case are.

Save a program under its module’s name and run it with raz run Name.raz.

+
+ + +