From a5145f647fc11d3fef1a57ba63f8b435f992a170 Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Mon, 26 Oct 2026 14:09:39 +0000 Subject: [PATCH] site: v0.24.0, and its examples held to report 2026-10.37 Strings only read are []const U8; ADR, PTR, SYSCALL and ARGV written SYSTEM., in pages whose modules import SYSTEM; atomics on the variable; the atomics, lockfree, syscalls, records, hello and slices pages say so. --- diff --git a/site/content/advanced/01-fmt.txt b/site/content/advanced/01-fmt.txt index cd55d49..0a87be1 100644 --- a/site/content/advanced/01-fmt.txt +++ b/site/content/advanced/01-fmt.txt @@ -67,7 +67,7 @@ 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); +proc describe(var b: Buf.Buf; name: []const U8; age: INT); begin Fmt.write(b, "{} (age {})", [Fmt.str(name), Fmt.int(age)]); end; @@ -96,7 +96,7 @@ import Out; (* s, then spaces up to width *) -proc left(s: []U8; width: INT); +proc left(s: []const U8; width: INT); var i: INT; begin Out.str(s); @@ -115,7 +115,7 @@ Out.int(n); end; -proc row(name: []U8; qty, price: INT); +proc row(name: []const U8; qty, price: INT); begin left(name, 10); right(qty, 5); @@ -144,7 +144,7 @@ module Dump; import Out; -proc dump(data: []U8); +proc dump(data: []const U8); var i: INT; begin for i := 0 to LEN(data) - 1 do diff --git a/site/content/advanced/02-bytes.txt b/site/content/advanced/02-bytes.txt index 1af4764..bbbef5b 100644 --- a/site/content/advanced/02-bytes.txt +++ b/site/content/advanced/02-bytes.txt @@ -13,7 +13,7 @@ import Out, Str, Fmt; proc main*; -var names: [4][]U8; i, j: INT; t: []U8; +var names: [4][]const U8; i, j: INT; t: []const U8; begin names := ["pear", "Apple", "fig", "apple"]; (* a small insertion sort, with Str.cmp *) @@ -44,13 +44,14 @@ ```raz Keep run module Keep; import Out, Str, Heap, Mem; +import SYSTEM; 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); +proc remember(slot: INT; name: []const U8); var copy: []U8; ok: BOOL; begin copy, ok := Str.copy(Heap.heap, name); @@ -68,7 +69,7 @@ end; for i := 0 to 2 do Out.str(entries[i].name); Out.char(' '); - Mem.free(Heap.heap, ^U8(ADR(entries[i].name[0]))); + Mem.free(Heap.heap, ^U8(SYSTEM.ADR(entries[i].name[0]))); end; Out.ln; end; @@ -85,13 +86,13 @@ import Out, Fmt, Bytes; (* the last part of a path: what follows its last slash *) -proc base(path: []U8): []U8; +proc base(path: []const U8): []const U8; begin return path[Bytes.last(path, '/') + 1..LEN(path)]; end; proc main*; -var text: []U8; at, n, line: INT; +var text: []const U8; at, n, line: INT; begin Out.str(base("/usr/local/lib/raz/Bytes.raz")); Out.char(' '); Out.str(base("Out.raz")); Out.ln; @@ -127,7 +128,7 @@ const HeaderSize = 10; (* the sum of the bytes of data, all mod 2^32 *) -proc checksum(data: []U8): U32; +proc checksum(data: []const U8): U32; var i: INT; sum: U32; begin for i := 0 to LEN(data) - 1 do sum := sum + U32(data[i]); end; @@ -135,7 +136,7 @@ end; (* writes a frame to out, which must have room; its length *) -proc pack(out: []U8; tag, data: []U8): INT; +proc pack(out: []U8; tag, data: []const U8): INT; begin COPY(out[0..4], tag); Str.putBE(out[4..6], U64(LEN(data))); @@ -178,8 +179,8 @@ 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; +proc total(s: []const U8): I64; +var part: []const U8; sum, n: I64; ok, more: BOOL; begin more := true; while more do diff --git a/site/content/advanced/03-collections.txt b/site/content/advanced/03-collections.txt index 8d32a9a..166e84d 100644 --- a/site/content/advanced/03-collections.txt +++ b/site/content/advanced/03-collections.txt @@ -59,7 +59,7 @@ ```raz Ages run module Ages; -import Out, Fmt, Str, Heap, Book := Map([]U8, INT, Str.hash, Str.eq); +import Out, Fmt, Str, Heap, Book := Map([]const U8, INT, Str.hash, Str.eq); proc main*; var m: Book.Map; age: INT; found, ok: BOOL; i: INT; v: INT; @@ -100,11 +100,11 @@ ```raz Freq run module Freq; import Fmt, Str, Heap, - Count := Map([]U8, INT, Str.hash, Str.eq), + Count := Map([]const U8, INT, Str.hash, Str.eq), Entries := Vec(Entry), Rank := Sort(Entry, before); -type Entry = record word: []U8; n: INT; end; +type Entry = record word: []const U8; n: INT; end; const Text = "the cat and the hat and the bat sat on the mat and the cat sat"; @@ -118,7 +118,7 @@ proc main*; var m: Count.Map; entries: Entries.Vec; i, k, found: INT; - w, rest: []U8; key: []U8; v: INT; all: []Entry; + w, rest: []const U8; key: []const U8; v: INT; all: []Entry; begin Count.init(m, Heap.heap); defer Count.done(m); diff --git a/site/content/advanced/04-files.txt b/site/content/advanced/04-files.txt index ace3acd..ea637cb 100644 --- a/site/content/advanced/04-files.txt +++ b/site/content/advanced/04-files.txt @@ -42,7 +42,7 @@ import Out, Sys; (* the lines of the file at path, or minus an errno *) -proc lines(path: []U8): INT; +proc lines(path: []const U8): INT; var fd, n, i, count: INT; buf: [4096]U8; begin fd := Sys.openRead(path); @@ -85,6 +85,7 @@ ```raz Tree run module Tree; import Out, Sys, Str, Heap, Mem, Buf, Order := Sort([]U8, before); +import SYSTEM; proc before(a, b: []U8): BOOL; begin @@ -92,7 +93,7 @@ end; (* a file made to hold text *) -proc put(path, text: []U8); +proc put(path, text: []const U8); var fd: INT; begin fd := Sys.create(path); @@ -102,7 +103,7 @@ proc main*; var - d: Sys.Dir; name, copy: []U8; more, ok: BOOL; i, n: INT; + d: Sys.Dir; name: []const U8; copy: []U8; more, ok: BOOL; i, n: INT; info: Sys.Info; err: INT; names: [16][]U8; path: Buf.Buf; begin _ := Sys.makeDir("proj"); @@ -131,7 +132,7 @@ else Out.str(", "); Out.int(info.size); Out.str(" bytes"); end; Out.ln; - Mem.free(Heap.heap, ^U8(ADR(names[i][0]))); + Mem.free(Heap.heap, ^U8(SYSTEM.ADR(names[i][0]))); end; Buf.done(path); end; @@ -188,7 +189,7 @@ 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; +var p: Opt.Parser; verbose: BOOL; n, i: INT; w: []const U8; ok: BOOL; begin n := 1; Opt.init(p, "tool", [ diff --git a/site/content/advanced/06-allocators.txt b/site/content/advanced/06-allocators.txt index ed55dfd..8140b1c 100644 --- a/site/content/advanced/06-allocators.txt +++ b/site/content/advanced/06-allocators.txt @@ -22,6 +22,7 @@ ```raz Bump module Bump; import Mem; +import SYSTEM; type Bump* = record @@ -65,6 +66,7 @@ ```raz Bumping run module Bumping; import Out, Bump; +import SYSTEM; type Point = record x, y: INT; end; @@ -73,19 +75,19 @@ 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)); + Bump.init(SYSTEM.ADR(b), SYSTEM.ADR(arena[0]), 256); + NEW(p, SYSTEM.ADR(b.base)); + NEW(q, SYSTEM.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)); + NEW(r, SYSTEM.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)); + Bump.reset(SYSTEM.ADR(b)); + NEW(r, SYSTEM.ADR(b.base)); if r # nil then Out.str("room again after a reset\n"); end; end; @@ -101,6 +103,7 @@ ```raz Counted module Counted; import Mem; +import SYSTEM; type Counted* = record @@ -141,26 +144,27 @@ ```raz Audit run module Audit; -import Fmt, Heap, Mem, Buf, Counted, Names := List([]U8); +import Fmt, Heap, Mem, Buf, Counted, Names := List([]const U8); +import SYSTEM; 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)); + Counted.init(SYSTEM.ADR(c), Heap.heap); + Buf.init(b, SYSTEM.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)); + Names.init(l, SYSTEM.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); + p := Mem.alloc(SYSTEM.ADR(c.base), 64, 8); + Mem.free(SYSTEM.ADR(c.base), p); end; end Audit. diff --git a/site/content/advanced/07-static.txt b/site/content/advanced/07-static.txt index ec66699..a387ff9 100644 --- a/site/content/advanced/07-static.txt +++ b/site/content/advanced/07-static.txt @@ -10,12 +10,13 @@ ```raz Bare module Bare; +import SYSTEM; const Msg = "hello from raw system calls\n"; proc main*; begin - _ := SYSCALL(1, 1, ADR(Msg[0]), LEN(Msg)); + _ := SYSTEM.SYSCALL(1, 1, SYSTEM.ADR(Msg[0]), LEN(Msg)); end; end Bare. diff --git a/site/content/advanced/08-linkstatic.txt b/site/content/advanced/08-linkstatic.txt index 831d8aa..df3782f 100644 --- a/site/content/advanced/08-linkstatic.txt +++ b/site/content/advanced/08-linkstatic.txt @@ -19,13 +19,14 @@ ```raz Hello module Hello; import Out, Thread; +import SYSTEM; var done: INT; proc greet(arg: ^U8); begin Out.str("hello from thread "); Out.int(INT(arg)); Out.ln; - _ := XADD(ADR(done), 1); + _ := XADD(done, 1); end; proc main*; diff --git a/site/content/advanced/09-lifecycle.txt b/site/content/advanced/09-lifecycle.txt index c6fbe03..a7d4739 100644 --- a/site/content/advanced/09-lifecycle.txt +++ b/site/content/advanced/09-lifecycle.txt @@ -19,7 +19,7 @@ var steps*: INT; -proc note(what: []U8); +proc note(what: []const U8); begin INC(steps); Out.int(steps); Out.str(". "); Out.str(what); Out.ln; diff --git a/site/content/advanced/11-asm.txt b/site/content/advanced/11-asm.txt index e4e55eb..15ba8cd 100644 --- a/site/content/advanced/11-asm.txt +++ b/site/content/advanced/11-asm.txt @@ -13,6 +13,7 @@ ```raz Cycles run module Cycles; import Out; +import SYSTEM; proc rdtsc*: U64; code @@ -50,6 +51,7 @@ ```raz Bits run module Bits; import Out; +import SYSTEM; (* the bytes of x in the opposite order: bswap rax, which the assembler doesn't know, written as its bytes *) @@ -87,6 +89,7 @@ ```raz Sum run module Sum; import Out; +import SYSTEM; (* the sum of the INTs of a *) proc sum(a: []INT): INT; @@ -131,9 +134,10 @@ ```raz Trim run module Trim; import Out; +import SYSTEM; (* s past its leading blanks *) -proc trim(s: []U8): []U8; +proc trim(s: []const U8): []const U8; code mov rax, rdi; mov rdx, rsi; @@ -168,6 +172,7 @@ ```raz Divmod run module Divmod; import Out, Fmt; +import SYSTEM; (* quotient and remainder, as idiv gives them: rax and rdx *) proc divmod(a, b: INT): (INT, INT); @@ -206,6 +211,7 @@ ```raz Vendor run module Vendor; import Out; +import SYSTEM; (* the 12 bytes of the processor vendor, in buf (rdi) *) proc vendor(buf: ^U8); @@ -224,7 +230,7 @@ proc main*; var buf: [12]U8; i: INT; ok: BOOL; begin - vendor(ADR(buf[0])); + vendor(SYSTEM.ADR(buf[0])); ok := true; for i := 0 to 11 do if (buf[i] < ' ') or (buf[i] > '~') then ok := false; end; diff --git a/site/content/advanced/12-syscalls.txt b/site/content/advanced/12-syscalls.txt index 1d11acb..13644d0 100644 --- a/site/content/advanced/12-syscalls.txt +++ b/site/content/advanced/12-syscalls.txt @@ -2,7 +2,7 @@ part: The machine summary: SYSCALL directly: the numbers, the arguments, negative errno, and a cat without a library. --- -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. +Under `Sys` there is one built-in, `SYSTEM.SYSCALL(n, x1, ..., x6)`, which a module reaches with `import SYSTEM;`. 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. @@ -12,14 +12,15 @@ ```raz Raw module Raw; +import SYSTEM; 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 *) + n := SYSTEM.SYSCALL(1, 1, SYSTEM.ADR(Msg[0]), LEN(Msg)); + if n # LEN(Msg) then _ := SYSTEM.SYSCALL(60, 1); end; (* exit(1), if it came up short *) end; end Raw. @@ -39,18 +40,19 @@ ```raz Open run module Open; import Out; +import SYSTEM; 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) *) + fd := SYSTEM.SYSCALL(2, SYSTEM.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); + fd := SYSTEM.SYSCALL(2, SYSTEM.ADR(path[0]), 0, 0); if fd >= 0 then Out.str("opened /dev/null\n"); - _ := SYSCALL(3, fd); (* close *) + _ := SYSTEM.SYSCALL(3, fd); (* close *) end; end; @@ -61,14 +63,15 @@ ## 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. +`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 its `SYSTEM.ADR` given to the kernel. ```raz Who run module Who; import Out; +import SYSTEM; (* the length of the zero-ended string at the start of s *) -proc cstr(s: []U8): INT; +proc cstr(s: []const U8): INT; var n: INT; begin n := 0; @@ -79,7 +82,7 @@ proc main*; var u: [390]U8; begin - if SYSCALL(63, ADR(u[0])) = 0 then + if SYSTEM.SYSCALL(63, SYSTEM.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; @@ -95,18 +98,19 @@ ```raz Pages run module Pages; import Out; +import SYSTEM; 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)); + p := ^U8(SYSTEM.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); + _ := SYSTEM.SYSCALL(11, p, 4096); end; end Pages. @@ -118,19 +122,20 @@ ```raz Cat module Cat; +import SYSTEM; proc main*: INT; var buf: [4096]U8; n, wrote, at: INT; begin - n := SYSCALL(0, 0, ADR(buf[0]), LEN(buf)); + n := SYSTEM.SYSCALL(0, 0, SYSTEM.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); + wrote := SYSTEM.SYSCALL(1, 1, SYSTEM.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)); + n := SYSTEM.SYSCALL(0, 0, SYSTEM.ADR(buf[0]), LEN(buf)); end; if n < 0 then return 1; end; return 0; @@ -155,6 +160,7 @@ ```raz Ppid run module Ppid; import Out; +import SYSTEM; (* getppid, call 110: no arguments *) proc getppid: INT; @@ -166,7 +172,7 @@ proc main*; begin - if (getppid() > 0) and (SYSCALL(110) = getppid()) then + if (getppid() > 0) and (SYSTEM.SYSCALL(110) = getppid()) then Out.str("two ways to ask, one answer\n"); end; end; diff --git a/site/content/advanced/14-volatile.txt b/site/content/advanced/14-volatile.txt index 5595f84..f3c94c2 100644 --- a/site/content/advanced/14-volatile.txt +++ b/site/content/advanced/14-volatile.txt @@ -13,6 +13,7 @@ ```raz Uart run module Uart; import Out; +import SYSTEM; type Regs = record @@ -26,7 +27,7 @@ proc main*; var dev: ^VOLATILE Regs; i: INT; begin - dev := ^VOLATILE Regs(ADR(page)); (* the conversion is written *) + dev := ^VOLATILE Regs(SYSTEM.ADR(page)); (* the conversion is written *) dev^.control := 1; dev^.status := 0FFH; for i := 0 to 2 do @@ -60,6 +61,7 @@ ```raz Poll run module Poll; import Out, Sys, Thread; +import SYSTEM; type Dev = record status: INT; data: INT; end; @@ -68,7 +70,7 @@ proc device(_arg: ^U8); var d: ^VOLATILE Dev; begin - d := ^VOLATILE Dev(ADR(dev)); + d := ^VOLATILE Dev(SYSTEM.ADR(dev)); Sys.sleep(20); d^.data := 42; FENCE; (* data before the flag that announces it *) @@ -78,7 +80,7 @@ proc main*; var t: ^Thread.Thread; err: ERROR; d: ^VOLATILE Dev; spins: INT; begin - d := ^VOLATILE Dev(ADR(dev)); + d := ^VOLATILE Dev(SYSTEM.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; @@ -103,6 +105,7 @@ ```raz Wrong module Wrong; +import SYSTEM; type Pair = record a, b: U32; end; @@ -111,7 +114,7 @@ proc main*; var v: ^VOLATILE Pair; p: ^Pair; copy: Pair; begin - v := ^VOLATILE Pair(ADR(cell)); + v := ^VOLATILE Pair(SYSTEM.ADR(cell)); p := v; copy := v^; end; diff --git a/site/content/advanced/15-atomics.txt b/site/content/advanced/15-atomics.txt index cb143e2..d0fad73 100644 --- a/site/content/advanced/15-atomics.txt +++ b/site/content/advanced/15-atomics.txt @@ -6,22 +6,23 @@ | Call | Does | |---|---| -| `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` | +| `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`: +`p` is a variable (or `q^` through a pointer `q`, even `^VOLATILE`) of type `INT`, `UINT` or a pointer type (`INT` or `UINT` for `XADD`); the atomic works on the variable itself, so no `ADR` is taken. A module that uses them says `import SYSTEM;`. They compile to single x86-64 instructions: `lock xadd`, `xchg` (which is always locked when it touches memory) and `lock cmpxchg`: ```raz Ops module Ops; +import SYSTEM; var counter: INT; proc main*; begin - _ := XADD(ADR(counter), 5); - _ := XCHG(ADR(counter), 100); - _ := CAS(ADR(counter), 100, 7); + _ := XADD(counter, 5); + _ := XCHG(counter, 100); + _ := CAS(counter, 100, 7); end; end Ops. @@ -38,6 +39,7 @@ ```raz Tickets run module Tickets; import Out, Thread; +import SYSTEM; var next: INT; (* the next ticket to give out *) @@ -47,7 +49,7 @@ var i, t: INT; begin for i := 1 to 1000 do - t := XADD(ADR(next), 1); (* a ticket no other thread gets *) + t := XADD(next, 1); (* a ticket no other thread gets *) seen[t] := 1; end; end; @@ -76,6 +78,7 @@ ```raz Peak run module Peak; import Out, Thread; +import SYSTEM; var peak: INT; @@ -85,7 +88,7 @@ begin seen := peak; while seen < v do - if CAS(ADR(peak), seen, v) then return; end; + if CAS(peak, seen, v) then return; end; seen := peak; (* someone changed it: look again *) end; end; diff --git a/site/content/advanced/16-ordering.txt b/site/content/advanced/16-ordering.txt index 7e8a57f..0087878 100644 --- a/site/content/advanced/16-ordering.txt +++ b/site/content/advanced/16-ordering.txt @@ -15,6 +15,7 @@ ```raz Publish run module Publish; import Out, Sys, Thread; +import SYSTEM; type Message = record id: INT; text: [32]U8; len: INT; end; @@ -28,7 +29,7 @@ msg.id := 7; msg.text := "built before the flag"; msg.len := 21; - _ := XCHG(ADR(ready), 1); (* publish *) + _ := XCHG(ready, 1); (* publish *) end; proc main*; @@ -36,7 +37,7 @@ 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 *) + while XADD(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; @@ -53,6 +54,7 @@ ```raz Fenced run module Fenced; import Out, Sys, Thread; +import SYSTEM; var data: INT; (* ordinary *) @@ -61,7 +63,7 @@ proc producer(_arg: ^U8); var f: ^VOLATILE INT; begin - f := ^VOLATILE INT(ADR(flag)); + f := ^VOLATILE INT(SYSTEM.ADR(flag)); Sys.sleep(10); data := 1234; FENCE; (* data is written before the flag is *) @@ -71,7 +73,7 @@ proc main*; var t: ^Thread.Thread; err: ERROR; f: ^VOLATILE INT; begin - f := ^VOLATILE INT(ADR(flag)); + f := ^VOLATILE INT(SYSTEM.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; diff --git a/site/content/advanced/17-lockfree.txt b/site/content/advanced/17-lockfree.txt index 9e70d40..cfe9997 100644 --- a/site/content/advanced/17-lockfree.txt +++ b/site/content/advanced/17-lockfree.txt @@ -11,6 +11,7 @@ ```raz Treiber run module Treiber; import Out, Thread; +import SYSTEM; type Node = record next: ^Node; val: INT; end; @@ -26,7 +27,7 @@ begin old := top; n^.next := old; - while not CAS(ADR(top), old, n) do + while not CAS(top, old, n) do old := top; (* lost the race: look again *) n^.next := old; end; @@ -38,7 +39,7 @@ first := INT(arg) * Each; for i := 0 to Each - 1 do nodes[first + i].val := first + i; - push(ADR(nodes[first + i])); + push(SYSTEM.ADR(nodes[first + i])); end; end; @@ -75,11 +76,12 @@ - **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. +- **Don't pop concurrently.** Many threads push and one thread, at the end, takes everything with a single `XCHG(top, nil)` and walks the list in peace. A stack used this way for work lists and logs needs no more. ```raz Drain run module Drain; import Out, Thread; +import SYSTEM; type Node = record next: ^Node; val: INT; end; @@ -94,7 +96,7 @@ begin old := top; n^.next := old; - while not CAS(ADR(top), old, n) do + while not CAS(top, old, n) do old := top; n^.next := old; end; @@ -106,7 +108,7 @@ first := INT(arg) * Each; for i := 0 to Each - 1 do nodes[first + i].val := 1; - push(ADR(nodes[first + i])); + push(SYSTEM.ADR(nodes[first + i])); end; end; @@ -118,7 +120,7 @@ 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 *) + all := XCHG(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, "); diff --git a/site/content/advanced/18-ring.txt b/site/content/advanced/18-ring.txt index 6f56f26..1485f9e 100644 --- a/site/content/advanced/18-ring.txt +++ b/site/content/advanced/18-ring.txt @@ -17,6 +17,7 @@ ```raz Ring module Ring; import Sys; +import SYSTEM; const Size* = 64; @@ -31,9 +32,9 @@ var t: INT; begin t := r^.tail; (* mine: an ordinary read *) - while t - XADD(ADR(r^.head), 0) = Size do Sys.yield; end; (* full *) + while t - XADD(r^.head, 0) = Size do Sys.yield; end; (* full *) r^.slots[t mod Size] := v; - _ := XCHG(ADR(r^.tail), t + 1); (* publish the slot *) + _ := XCHG(r^.tail, t + 1); (* publish the slot *) end; (* the next value, waiting while the ring is empty *) @@ -41,9 +42,9 @@ var h, v: INT; begin h := r^.head; (* mine *) - while XADD(ADR(r^.tail), 0) = h do Sys.yield; end; (* empty *) + while XADD(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 *) + _ := XCHG(r^.head, h + 1); (* give the slot back *) return v; end; @@ -57,6 +58,7 @@ ```raz Pipe run module Pipe; import Out, Fmt, Ring, Thread; +import SYSTEM; const Count = 100000; @@ -67,14 +69,14 @@ proc producer(_arg: ^U8); var i: INT; begin - for i := 1 to Count do Ring.put(ADR(ring), i); end; + for i := 1 to Count do Ring.put(SYSTEM.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)); + v := Ring.take(SYSTEM.ADR(ring)); if v # i then INC(outOfOrder); end; sum := sum + v; end; diff --git a/site/content/tour/01-hello.txt b/site/content/tour/01-hello.txt index 620e220..238f79f 100644 --- a/site/content/tour/01-hello.txt +++ b/site/content/tour/01-hello.txt @@ -80,11 +80,12 @@ ## Arguments -`ARGC()` is the number of command line arguments, with the program's own name first, and `ARGV()` the arguments, as C strings. Most programs read them through `Files.arg` and `Opt`, which the advanced tour shows; here is the raw form. +`ARGC()` is the number of command line arguments, with the program's own name first, and `SYSTEM.ARGV()` the arguments, as C strings. Most programs read them through `Files.arg` and `Opt`, which the advanced tour shows; here is the raw form. ```raz Args module Args; import Out; +import SYSTEM; (* The length of a C string. *) proc len(s: ^U8): INT; @@ -99,7 +100,7 @@ var i: INT; s: ^U8; begin for i := 1 to ARGC() - 1 do - s := ARGV()[i]; + s := SYSTEM.ARGV()[i]; Out.str(s[0..len(s)]); Out.ln; end; diff --git a/site/content/tour/03-integers.txt b/site/content/tour/03-integers.txt index 1cf6507..545d15d 100644 --- a/site/content/tour/03-integers.txt +++ b/site/content/tour/03-integers.txt @@ -118,7 +118,7 @@ const Prime = 100000001B3H; (* FNV-1a: xor each byte in, then multiply, all modulo 2^64 *) -proc fnv(s: []U8): U64; +proc fnv(s: []const U8): U64; var h: U64; i: INT; begin h := Offset; diff --git a/site/content/tour/04-values.txt b/site/content/tour/04-values.txt index 4217e15..596e1aa 100644 --- a/site/content/tour/04-values.txt +++ b/site/content/tour/04-values.txt @@ -18,7 +18,7 @@ import Out; proc main*; -var i: I32; s: []U8; +var i: I32; s: []const U8; begin s := "four"; i := 3; diff --git a/site/content/tour/05-procedures.txt b/site/content/tour/05-procedures.txt index 2ce342d..36da7a6 100644 --- a/site/content/tour/05-procedures.txt +++ b/site/content/tour/05-procedures.txt @@ -141,7 +141,7 @@ end; proc main*; -var ops: [3]Op; names: [3][]U8; i: INT; +var ops: [3]Op; names: [3][]const U8; i: INT; begin ops := [add, sub, mul]; names := ["add", "sub", "mul"]; diff --git a/site/content/tour/06-slices.txt b/site/content/tour/06-slices.txt index 56c81c3..9b42961 100644 --- a/site/content/tour/06-slices.txt +++ b/site/content/tour/06-slices.txt @@ -92,14 +92,14 @@ ## 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. +A string is a slice of bytes, `[]U8`, in UTF-8, and a string constant is a `[]const U8`: a procedure that only reads a string takes that, and one that writes takes `[]U8`. 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. ```raz Words run module Words; import Out, Str; proc main*; -var s: []U8; n: I64; ok: BOOL; name: [8]U8; +var s: []const U8; n: I64; ok: BOOL; name: [8]U8; begin s := "hello, world"; Out.str(s[7..LEN(s)]); Out.ln; @@ -141,7 +141,7 @@ const Text = "name = raz\nkind = language\nyear = 2026\n"; proc main*; -var line, rest, key, val, w: []U8; more, ok: BOOL; +var line, rest, key, val, w: []const U8; more, ok: BOOL; begin (* line by line, then each line at its = *) line, rest, more := Str.cut(Text, "\n"); @@ -207,7 +207,7 @@ import Out, Str, Width; proc main*; -var s: []U8; c: I32; i, size: INT; bytes: [4]U8; k: INT; +var s: []const 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, "); diff --git a/site/content/tour/07-records.txt b/site/content/tour/07-records.txt index a7dab0c..99ca8d2 100644 --- a/site/content/tour/07-records.txt +++ b/site/content/tour/07-records.txt @@ -5,7 +5,7 @@ ```raz Boxes run ``` -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. +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`, `SYSTEM.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 @@ -49,7 +49,7 @@ module Planets; import Fmt; -type Planet = record name: []U8; moons: INT; water: BOOL; end; +type Planet = record name: []const U8; moons: INT; water: BOOL; end; const Inner: []Planet = [ {name: "Mercury"}, @@ -95,7 +95,7 @@ end Layout. ``` -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`. +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 `SYSTEM.ADR`. ## Bytes as numbers and records: views @@ -162,13 +162,14 @@ ## 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. +`SYSTEM.ADR(x)` (a module that uses it says `import SYSTEM;`) 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. ```raz Pointers run module Pointers; import Out; +import SYSTEM; -type Counter = record hits: INT; name: []U8; end; +type Counter = record hits: INT; name: []const U8; end; proc hit(c: ^Counter); begin @@ -188,12 +189,12 @@ var c: Counter; x, y: INT; p: ^INT; begin c.name := "front door"; - hit(ADR(c)); hit(ADR(c)); hit(nil); + hit(SYSTEM.ADR(c)); hit(SYSTEM.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)); + swap(SYSTEM.ADR(x), SYSTEM.ADR(y)); Out.int(x); Out.char(' '); Out.int(y); Out.ln; - p := ADR(x); + p := SYSTEM.ADR(x); p^ := p^ + 40; Out.int(x); Out.ln; end; @@ -208,6 +209,7 @@ ```raz Chain run module Chain; import Out; +import SYSTEM; type Node = record next: ^Node; val: INT; end; @@ -218,7 +220,7 @@ 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]); + head := SYSTEM.ADR(nodes[i]); end; n := head; while n # nil do @@ -233,17 +235,18 @@ ## 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. +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 `SYSTEM.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. ```raz Empty fail module Empty; import Out; +import SYSTEM; type Span = record p: ^U8; n: INT; end; -proc spanOf(s: []U8): Span; +proc spanOf(s: []const U8): Span; begin - return {p: ADR(s[0]), n: LEN(s)}; + return {p: SYSTEM.ADR(s[0]), n: LEN(s)}; end; proc main*; @@ -258,9 +261,9 @@ end Empty. ``` -`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: +`SYSTEM.PTR(s)` is the pointer itself, a `^U8` for a `[]U8`, with no check. For a slice that isn't empty it is `SYSTEM.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: ```raz Spans run ``` -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]`. +Of an array, `SYSTEM.PTR(a)` is the address of its first element, a `^T` where `SYSTEM.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]`. diff --git a/site/content/tour/08-variants.txt b/site/content/tour/08-variants.txt index 8785292..650540f 100644 --- a/site/content/tour/08-variants.txt +++ b/site/content/tour/08-variants.txt @@ -15,7 +15,7 @@ type Day = (mon, tue, wed, thu, fri, sat, sun); -proc name(d: Day): []U8; +proc name(d: Day): []const U8; begin match d of | mon: return "Monday"; @@ -92,7 +92,7 @@ number(n: INT); plus; times; - word(s: []U8); + word(s: []const U8); end; proc describe(t: Token); @@ -142,7 +142,7 @@ module Classify; import Out; -proc kind(c: I32): []U8; +proc kind(c: I32): []const U8; begin match c of | ' ', '\t', '\n': return "space"; @@ -153,7 +153,7 @@ end; proc main*; -var s: []U8; i: INT; +var s: []const U8; i: INT; begin s := "x1 + _y"; for i := 0 to LEN(s) - 1 do @@ -174,7 +174,7 @@ type Op = (none, add, sub, show); -proc op(word: []U8): Op; +proc op(word: []const U8): Op; begin match word of | "add", "plus", "+": return add; @@ -185,7 +185,7 @@ end; proc main*; -var total: INT; words: [6][]U8; i: INT; +var total: INT; words: [6][]const U8; i: INT; begin words := ["add", "plus", "sub", "show", "times", "-"]; for i := 0 to 5 do diff --git a/site/content/tour/09-memory.txt b/site/content/tour/09-memory.txt index b89e727..ee62ee3 100644 --- a/site/content/tour/09-memory.txt +++ b/site/content/tour/09-memory.txt @@ -14,6 +14,7 @@ ```raz Pool run module Pool; import Out, Mem, Arena; +import SYSTEM; type Item = record id: INT; next: ^Item; end; @@ -44,15 +45,15 @@ 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)); + list := make(1000, SYSTEM.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)); + list := make(10, SYSTEM.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)); + list := make(1000, SYSTEM.ADR(small.base)); if list = nil then Out.str("a small arena ran out, and said so\n"); end; Arena.done(small); end; @@ -69,6 +70,7 @@ ```raz Free run module Free; import Out, Mem, Heap; +import SYSTEM; type Cell = record val: INT; end; diff --git a/site/content/tour/10-errors.txt b/site/content/tour/10-errors.txt index 31294ad..3f95ec0 100644 --- a/site/content/tour/10-errors.txt +++ b/site/content/tour/10-errors.txt @@ -21,7 +21,7 @@ Range*: ERROR = "out of range"; (* a percentage, 0 to 100 *) -proc percent(s: []U8): (INT, ERROR); +proc percent(s: []const U8): (INT, ERROR); var n: I64; ok: BOOL; begin if LEN(s) = 0 then return 0, Empty; end; @@ -32,7 +32,7 @@ end; proc main*; -var inputs: [4][]U8; i, n: INT; err: ERROR; +var inputs: [4][]const U8; i, n: INT; err: ERROR; begin inputs := ["42", "", "forty", "140"]; for i := 0 to 3 do @@ -69,7 +69,7 @@ const Missing*: ERROR = "key missing"; (* the number after "n=" in a line like "n=17" *) -proc value(line: []U8): (INT, ERROR); +proc value(line: []const U8): (INT, ERROR); var n: I64; ok: BOOL; begin if not Str.hasPrefix(line, "n=") then return 0, Missing; end; @@ -79,7 +79,7 @@ end; (* the sum of the values of two lines: the first error ends it *) -proc sum(a, b: []U8): (INT, ERROR); +proc sum(a, b: []const U8): (INT, ERROR); begin return try value(a) + try value(b), nil; end; diff --git a/site/content/tour/12-checks.txt b/site/content/tour/12-checks.txt index 9ebb5ca..6e4799d 100644 --- a/site/content/tour/12-checks.txt +++ b/site/content/tour/12-checks.txt @@ -18,6 +18,7 @@ ```raz Nilp fail module Nilp; import Out; +import SYSTEM; type Node = record val: INT; next: ^Node; end; @@ -31,8 +32,8 @@ var a, b: Node; begin a.val := 1; b.val := 2; - a.next := ADR(b); - Out.int(last(ADR(a))); Out.ln; + a.next := SYSTEM.ADR(b); + Out.int(last(SYSTEM.ADR(a))); Out.ln; Out.int(last(nil)); Out.ln; end; diff --git a/site/content/tour/13-generics.txt b/site/content/tour/13-generics.txt index a2f88af..0e33736 100644 --- a/site/content/tour/13-generics.txt +++ b/site/content/tour/13-generics.txt @@ -21,6 +21,7 @@ ```raz Stk module Stk(T); import Mem; +import SYSTEM; type Stack* = record @@ -76,21 +77,22 @@ ```raz Uses run module Uses; import Out, Heap, Nums := Stk(INT), Pairs := Stk(Pair); +import SYSTEM; 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)); + Nums.init(SYSTEM.ADR(n), Heap.heap); + Pairs.init(SYSTEM.ADR(p), Heap.heap); + for i := 1 to 10 do _ := Nums.push(SYSTEM.ADR(n), i * i); end; + _ := Pairs.push(SYSTEM.ADR(p), {a: 3, b: 4}); + v, ok := Nums.pop(SYSTEM.ADR(n)); Out.int(v); Out.str(" of "); Out.int(n.len + 1); Out.ln; - pr, ok := Pairs.pop(ADR(p)); + pr, ok := Pairs.pop(SYSTEM.ADR(p)); Out.int(pr.a * pr.b); Out.ln; - _, ok := Pairs.pop(ADR(p)); + _, ok := Pairs.pop(SYSTEM.ADR(p)); if not ok then Out.str("empty\n"); end; end; @@ -101,4 +103,4 @@ ## 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. +The library's `List`, `Map` and `Sort` are generic modules. A `Map` takes its key hash and equality as procedure arguments: `import Count := Map([]const U8, INT, Str.hash, Str.eq);`. The advanced tour uses each of them in a real program. diff --git a/site/content/tour/14-c.txt b/site/content/tour/14-c.txt index 833a565..74979f1 100644 --- a/site/content/tour/14-c.txt +++ b/site/content/tour/14-c.txt @@ -18,6 +18,7 @@ ```raz Say run module Say; import Out; +import SYSTEM; extern proc printf(format: ^U8; ...): I32; extern proc fflush(f: ^U8): I32; @@ -48,6 +49,7 @@ ```raz Env run module Env; import Out; +import SYSTEM; extern var environ: ^^U8; extern proc strlen(s: ^U8): UINT; @@ -74,6 +76,7 @@ ```raz Roots run module Roots; import Fmt; +import SYSTEM; link "libm.so.6"; diff --git a/site/content/tour/15-threads.txt b/site/content/tour/15-threads.txt index c73fa73..fb8a91a 100644 --- a/site/content/tour/15-threads.txt +++ b/site/content/tour/15-threads.txt @@ -14,6 +14,7 @@ ```raz Race run module Race; import Out, Thread; +import SYSTEM; var safe: INT; (* added to by XADD *) @@ -23,7 +24,7 @@ var i: INT; begin for i := 1 to 100000 do - _ := XADD(ADR(safe), 1); + _ := XADD(safe, 1); INC(plain); (* unsafe: lost additions *) end; end; @@ -88,6 +89,7 @@ ```raz Jobs run module Jobs; import Out, Thread; +import SYSTEM; type Job = record lo, hi: INT; sum: INT; end; @@ -104,7 +106,7 @@ 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]))); + t[i], err := Thread.spawn(work, ^U8(SYSTEM.ADR(jobs[i]))); if err # nil then Out.str(MSG(err)); Out.ln; return; end; end; for i := 0 to 3 do diff --git a/site/public/_redirects b/site/public/_redirects index 22ac5bf..6ccb2fc 100644 --- a/site/public/_redirects +++ b/site/public/_redirects @@ -1 +1 @@ -/download/latest /download/raz-0.23.0-linux-x86_64.tar.gz 302 +/download/latest /download/raz-0.24.0-linux-x86_64.tar.gz 302 diff --git a/site/public/advanced/allocators.html b/site/public/advanced/allocators.html index 42a1d92..2165b4f 100644 --- a/site/public/advanced/allocators.html +++ b/site/public/advanced/allocators.html @@ -55,6 +55,7 @@

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;
+import SYSTEM;
 
 type
     Bump* = record
@@ -95,6 +96,7 @@
 end Bump.
Bumping.raz
module Bumping;
 import Out, Bump;
+import SYSTEM;
 
 type Point = record x, y: INT; end;
 
@@ -103,19 +105,19 @@
 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));
+    Bump.init(SYSTEM.ADR(b), SYSTEM.ADR(arena[0]), 256);
+    NEW(p, SYSTEM.ADR(b.base));
+    NEW(q, SYSTEM.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));
+        NEW(r, SYSTEM.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));
+    Bump.reset(SYSTEM.ADR(b));
+    NEW(r, SYSTEM.ADR(b.base));
     if r # nil then Out.str("room again after a reset\n"); end;
 end;
 
@@ -129,6 +131,7 @@
 

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;
+import SYSTEM;
 
 type
     Counted* = record
@@ -166,26 +169,27 @@
 
 end Counted.
Audit.raz
module Audit;
-import Fmt, Heap, Mem, Buf, Counted, Names := List([]U8);
+import Fmt, Heap, Mem, Buf, Counted, Names := List([]const U8);
+import SYSTEM;
 
 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));
+    Counted.init(SYSTEM.ADR(c), Heap.heap);
+    Buf.init(b, SYSTEM.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));
+    Names.init(l, SYSTEM.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);
+    p := Mem.alloc(SYSTEM.ADR(c.base), 64, 8);
+    Mem.free(SYSTEM.ADR(c.base), p);
 end;
 
 end Audit.
diff --git a/site/public/advanced/asm.html b/site/public/advanced/asm.html index 04432aa..2db4b8f 100644 --- a/site/public/advanced/asm.html +++ b/site/public/advanced/asm.html @@ -50,6 +50,7 @@

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;
+import SYSTEM;
 
 proc rdtsc*: U64;
 code
@@ -77,6 +78,7 @@
 

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

Bits.raz
module Bits;
 import Out;
+import SYSTEM;
 
 (* the bytes of x in the opposite order: bswap rax, which the assembler
    doesn't know, written as its bytes *)
@@ -111,6 +113,7 @@
 

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;
+import SYSTEM;
 
 (* the sum of the INTs of a *)
 proc sum(a: []INT): INT;
@@ -152,9 +155,10 @@
 

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;
+import SYSTEM;
 
 (* s past its leading blanks *)
-proc trim(s: []U8): []U8;
+proc trim(s: []const U8): []const U8;
 code
     mov rax, rdi;
     mov rdx, rsi;
@@ -187,6 +191,7 @@
 

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;
+import SYSTEM;
 
 (* quotient and remainder, as idiv gives them: rax and rdx *)
 proc divmod(a, b: INT): (INT, INT);
@@ -222,6 +227,7 @@
 

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;
+import SYSTEM;
 
 (* the 12 bytes of the processor vendor, in buf (rdi) *)
 proc vendor(buf: ^U8);
@@ -240,7 +246,7 @@
 proc main*;
 var buf: [12]U8; i: INT; ok: BOOL;
 begin
-    vendor(ADR(buf[0]));
+    vendor(SYSTEM.ADR(buf[0]));
     ok := true;
     for i := 0 to 11 do
         if (buf[i] < ' ') or (buf[i] > '~') then ok := false; end;
diff --git a/site/public/advanced/atomics.html b/site/public/advanced/atomics.html
index 4268768..1426ced 100644
--- a/site/public/advanced/atomics.html
+++ b/site/public/advanced/atomics.html
@@ -45,29 +45,31 @@
 
  • A ring buffer between threads
  • 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:

    +
    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 variable (or q^ through a pointer q, even ^VOLATILE) of type INT, UINT or a pointer type (INT or UINT for XADD); the atomic works on the variable itself, so no ADR is taken. A module that uses them says import SYSTEM;. 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;
    +import SYSTEM;
     
     var counter: INT;
     
     proc main*;
     begin
    -    _ := XADD(ADR(counter), 5);
    -    _ := XCHG(ADR(counter), 100);
    -    _ := CAS(ADR(counter), 100, 7);
    +    _ := XADD(counter, 5);
    +    _ := XCHG(counter, 100);
    +    _ := CAS(counter, 100, 7);
     end;
     
     end Ops.
    $ raz -S Ops.raz | grep -i "lock\|xchg"
                 23  lock xadd [r8], rax
    -     8      _ := XCHG(ADR(counter), 100);
    +     9      _ := XCHG(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;
    +import SYSTEM;
     
     var
         next: INT;                  (* the next ticket to give out *)
    @@ -77,7 +79,7 @@
     var i, t: INT;
     begin
         for i := 1 to 1000 do
    -        t := XADD(ADR(next), 1);      (* a ticket no other thread gets *)
    +        t := XADD(next, 1);      (* a ticket no other thread gets *)
             seen[t] := 1;
         end;
     end;
    @@ -102,6 +104,7 @@
     

    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;
    +import SYSTEM;
     
     var peak: INT;
     
    @@ -111,7 +114,7 @@
     begin
         seen := peak;
         while seen < v do
    -        if CAS(ADR(peak), seen, v) then return; end;
    +        if CAS(peak, seen, v) then return; end;
             seen := peak;                  (* someone changed it: look again *)
         end;
     end;
    @@ -148,7 +151,7 @@
     var tries: INT;
     begin
         tries := 0;
    -    while not CAS(ADR(l.held), 0, 1) do
    +    while not CAS(l.held, 0, 1) do
             INC(tries);
             if tries = 64 then Sys.yield; tries := 0; end;
         end;
    @@ -157,7 +160,7 @@
     (* Gives up l, which the caller holds. *)
     proc give*(var l: Lock);
     begin
    -    _ := XCHG(ADR(l.held), 0);
    +    _ := XCHG(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;
    diff --git a/site/public/advanced/bytes.html b/site/public/advanced/bytes.html
    index ec23646..66a66d4 100644
    --- a/site/public/advanced/bytes.html
    +++ b/site/public/advanced/bytes.html
    @@ -51,7 +51,7 @@
     import Out, Str, Fmt;
     
     proc main*;
    -var names: [4][]U8; i, j: INT; t: []U8;
    +var names: [4][]const U8; i, j: INT; t: []const U8;
     begin
         names := ["pear", "Apple", "fig", "apple"];
         (* a small insertion sort, with Str.cmp *)
    @@ -80,13 +80,14 @@
     

    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;
    +import SYSTEM;
     
     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);
    +proc remember(slot: INT; name: []const U8);
     var copy: []U8; ok: BOOL;
     begin
         copy, ok := Str.copy(Heap.heap, name);
    @@ -104,7 +105,7 @@
         end;
         for i := 0 to 2 do
             Out.str(entries[i].name); Out.char(' ');
    -        Mem.free(Heap.heap, ^U8(ADR(entries[i].name[0])));
    +        Mem.free(Heap.heap, ^U8(SYSTEM.ADR(entries[i].name[0])));
         end;
         Out.ln;
     end;
    @@ -118,13 +119,13 @@
     import Out, Fmt, Bytes;
     
     (* the last part of a path: what follows its last slash *)
    -proc base(path: []U8): []U8;
    +proc base(path: []const U8): []const U8;
     begin
         return path[Bytes.last(path, '/') + 1..LEN(path)];
     end;
     
     proc main*;
    -var text: []U8; at, n, line: INT;
    +var text: []const U8; at, n, line: INT;
     begin
         Out.str(base("/usr/local/lib/raz/Bytes.raz")); Out.char(' ');
         Out.str(base("Out.raz")); Out.ln;
    @@ -158,7 +159,7 @@
     const HeaderSize = 10;
     
     (* the sum of the bytes of data, all mod 2^32 *)
    -proc checksum(data: []U8): U32;
    +proc checksum(data: []const U8): U32;
     var i: INT; sum: U32;
     begin
         for i := 0 to LEN(data) - 1 do sum := sum + U32(data[i]); end;
    @@ -166,7 +167,7 @@
     end;
     
     (* writes a frame to out, which must have room; its length *)
    -proc pack(out: []U8; tag, data: []U8): INT;
    +proc pack(out: []U8; tag, data: []const U8): INT;
     begin
         COPY(out[0..4], tag);
         Str.putBE(out[4..6], U64(LEN(data)));
    @@ -206,8 +207,8 @@
     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;
    +proc total(s: []const U8): I64;
    +var part: []const U8; sum, n: I64; ok, more: BOOL;
     begin
         more := true;
         while more do
    diff --git a/site/public/advanced/collections.html b/site/public/advanced/collections.html
    index c7c3d47..91daa0f 100644
    --- a/site/public/advanced/collections.html
    +++ b/site/public/advanced/collections.html
    @@ -93,7 +93,7 @@
     

    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);
    +import Out, Fmt, Str, Heap, Book := Map([]const U8, INT, Str.hash, Str.eq);
     
     proc main*;
     var m: Book.Map; age: INT; found, ok: BOOL; i: INT; v: INT;
    @@ -131,11 +131,11 @@
     

    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),
    +    Count := Map([]const U8, INT, Str.hash, Str.eq),
         Entries := Vec(Entry),
         Rank := Sort(Entry, before);
     
    -type Entry = record word: []U8; n: INT; end;
    +type Entry = record word: []const U8; n: INT; end;
     
     const Text = "the cat and the hat and the bat sat on the mat and the cat sat";
     
    @@ -149,7 +149,7 @@
     proc main*;
     var
         m: Count.Map; entries: Entries.Vec; i, k, found: INT;
    -    w, rest: []U8; key: []U8; v: INT; all: []Entry;
    +    w, rest: []const U8; key: []const U8; v: INT; all: []Entry;
     begin
         Count.init(m, Heap.heap);
         defer Count.done(m);
    diff --git a/site/public/advanced/files.html b/site/public/advanced/files.html
    index 30d7ee3..df78490 100644
    --- a/site/public/advanced/files.html
    +++ b/site/public/advanced/files.html
    @@ -79,7 +79,7 @@
     import Out, Sys;
     
     (* the lines of the file at path, or minus an errno *)
    -proc lines(path: []U8): INT;
    +proc lines(path: []const U8): INT;
     var fd, n, i, count: INT; buf: [4096]U8;
     begin
         fd := Sys.openRead(path);
    @@ -122,6 +122,7 @@
     

    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);
    +import SYSTEM;
     
     proc before(a, b: []U8): BOOL;
     begin
    @@ -129,7 +130,7 @@
     end;
     
     (* a file made to hold text *)
    -proc put(path, text: []U8);
    +proc put(path, text: []const U8);
     var fd: INT;
     begin
         fd := Sys.create(path);
    @@ -139,7 +140,7 @@
     
     proc main*;
     var
    -    d: Sys.Dir; name, copy: []U8; more, ok: BOOL; i, n: INT;
    +    d: Sys.Dir; name: []const U8; copy: []U8; more, ok: BOOL; i, n: INT;
         info: Sys.Info; err: INT; names: [16][]U8; path: Buf.Buf;
     begin
         _ := Sys.makeDir("proj");
    @@ -168,7 +169,7 @@
             else Out.str(", "); Out.int(info.size); Out.str(" bytes");
             end;
             Out.ln;
    -        Mem.free(Heap.heap, ^U8(ADR(names[i][0])));
    +        Mem.free(Heap.heap, ^U8(SYSTEM.ADR(names[i][0])));
         end;
         Buf.done(path);
     end;
    @@ -224,7 +225,7 @@
     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;
    +var p: Opt.Parser; verbose: BOOL; n, i: INT; w: []const U8; ok: BOOL;
     begin
         n := 1;
         Opt.init(p, "tool", [
    diff --git a/site/public/advanced/fmt.html b/site/public/advanced/fmt.html
    index fbe8d1b..54d16d7 100644
    --- a/site/public/advanced/fmt.html
    +++ b/site/public/advanced/fmt.html
    @@ -96,7 +96,7 @@
     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);
    +proc describe(var b: Buf.Buf; name: []const U8; age: INT);
     begin
         Fmt.write(b, "{} (age {})", [Fmt.str(name), Fmt.int(age)]);
     end;
    @@ -123,7 +123,7 @@
     import Out;
     
     (* s, then spaces up to width *)
    -proc left(s: []U8; width: INT);
    +proc left(s: []const U8; width: INT);
     var i: INT;
     begin
         Out.str(s);
    @@ -142,7 +142,7 @@
         Out.int(n);
     end;
     
    -proc row(name: []U8; qty, price: INT);
    +proc row(name: []const U8; qty, price: INT);
     begin
         left(name, 10);
         right(qty, 5);
    @@ -172,7 +172,7 @@
     
    Dump.raz
    module Dump;
     import Out;
     
    -proc dump(data: []U8);
    +proc dump(data: []const U8);
     var i: INT;
     begin
         for i := 0 to LEN(data) - 1 do
    diff --git a/site/public/advanced/lifecycle.html b/site/public/advanced/lifecycle.html
    index 1521f54..617f33c 100644
    --- a/site/public/advanced/lifecycle.html
    +++ b/site/public/advanced/lifecycle.html
    @@ -53,7 +53,7 @@
     
     var steps*: INT;
     
    -proc note(what: []U8);
    +proc note(what: []const U8);
     begin
         INC(steps);
         Out.int(steps); Out.str(". "); Out.str(what); Out.ln;
    diff --git a/site/public/advanced/linkstatic.html b/site/public/advanced/linkstatic.html
    index 0d7305e..9b87e83 100644
    --- a/site/public/advanced/linkstatic.html
    +++ b/site/public/advanced/linkstatic.html
    @@ -67,20 +67,21 @@
        the Thread. Its test uses Check. *)
     module Thread;
     import Sys, Rt, Check;
    +import SYSTEM;
     
     const
    -    Failed*: ERROR = "can't start a thread";
    -    Stack = 1 shl 20;
    + Failed*: ERROR = "can't start a thread";

    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;
    +import SYSTEM;
     
     var done: INT;
     
     proc greet(arg: ^U8);
     begin
         Out.str("hello from thread "); Out.int(INT(arg)); Out.ln;
    -    _ := XADD(ADR(done), 1);
    +    _ := XADD(done, 1);
     end;
     
     proc main*;
    @@ -112,7 +113,12 @@
     end;
     
     end Mixed.
    -
    $ raz Mixed.raz
    +
    $ raz Mixed.raz
    +Mixed.raz:7:19: error: a string as a ^U8 needs import SYSTEM
    +    7 |     _ := C.printf("%d\n", I32(1));
    +      |                   ^^^^^^
    +help: it reaches memory other than through a variable: say import SYSTEM after the module's imports
    +raz: 1 error

    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 index 3f64dbb..a83adb4 100644 --- a/site/public/advanced/listing.html +++ b/site/public/advanced/listing.html @@ -185,59 +185,20 @@ 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
    +Dot2.raz:2:1: error: check off needs import SYSTEM
    +    2 | check off;
    +      | ^^^^^
    +help: it reaches memory other than through a variable: say import SYSTEM after the module's imports
    +raz: 1 error
     $ raz -S Dot.raz | sed -n '/^Dot.dot:/,/^$/p' | wc -l
     61
     $ raz -S Dot2.raz | sed -n '/^Dot2.dot:/,/^$/p' | wc -l
    -50
    +Dot2.raz:2:1: error: check off needs import SYSTEM + 2 | check off; + | ^^^^^ +help: it reaches memory other than through a variable: say import SYSTEM after the module's imports +raz: 1 error +0

    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.

    @@ -245,18 +206,18 @@
    • 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
    +0000000000403c40 <Dot.dot>: + 403c40: push rbp + 403c41: mov rbp,rsp + 403c44: sub rsp,0x40 + 403c4b: mov QWORD PTR [rbp-0x38],rbx + 403c4f: xor ebx,ebx + 403c51: mov QWORD PTR [rbp-0x30],r12 + 403c55: xor r12d,r12d + 403c58: mov QWORD PTR [rbp-0x28],r13 + 403c5c: xor r13d,r13d + 403c5f: mov QWORD PTR [rbp-0x20],rdx + 403c63: 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.

    raz is under the ISC license. Source
    diff --git a/site/public/advanced/lockfree.html b/site/public/advanced/lockfree.html index 6ffff59..fb3dae0 100644 --- a/site/public/advanced/lockfree.html +++ b/site/public/advanced/lockfree.html @@ -49,6 +49,7 @@

    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;
    +import SYSTEM;
     
     type Node = record next: ^Node; val: INT; end;
     
    @@ -64,7 +65,7 @@
     begin
         old := top;
         n^.next := old;
    -    while not CAS(ADR(top), old, n) do
    +    while not CAS(top, old, n) do
             old := top;                      (* lost the race: look again *)
             n^.next := old;
         end;
    @@ -76,7 +77,7 @@
         first := INT(arg) * Each;
         for i := 0 to Each - 1 do
             nodes[first + i].val := first + i;
    -        push(ADR(nodes[first + i]));
    +        push(SYSTEM.ADR(nodes[first + i]));
         end;
     end;
     
    @@ -107,9 +108,10 @@
     

    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.
    +
    • 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(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;
    +import SYSTEM;
     
     type Node = record next: ^Node; val: INT; end;
     
    @@ -124,7 +126,7 @@
     begin
         old := top;
         n^.next := old;
    -    while not CAS(ADR(top), old, n) do
    +    while not CAS(top, old, n) do
             old := top;
             n^.next := old;
         end;
    @@ -136,7 +138,7 @@
         first := INT(arg) * Each;
         for i := 0 to Each - 1 do
             nodes[first + i].val := 1;
    -        push(ADR(nodes[first + i]));
    +        push(SYSTEM.ADR(nodes[first + i]));
         end;
     end;
     
    @@ -148,7 +150,7 @@
             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 *)
    +    all := XCHG(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, "); 
    diff --git a/site/public/advanced/ordering.html b/site/public/advanced/ordering.html
    index f0738cd..a512f9a 100644
    --- a/site/public/advanced/ordering.html
    +++ b/site/public/advanced/ordering.html
    @@ -51,6 +51,7 @@
     

    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;
    +import SYSTEM;
     
     type Message = record id: INT; text: [32]U8; len: INT; end;
     
    @@ -64,7 +65,7 @@
         msg.id := 7;
         msg.text := "built before the flag";
         msg.len := 21;
    -    _ := XCHG(ADR(ready), 1);               (* publish *)
    +    _ := XCHG(ready, 1);               (* publish *)
     end;
     
     proc main*;
    @@ -72,7 +73,7 @@
     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 *)
    +    while XADD(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;
    @@ -85,6 +86,7 @@
     

    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;
    +import SYSTEM;
     
     var
         data: INT;                   (* ordinary *)
    @@ -93,7 +95,7 @@
     proc producer(_arg: ^U8);
     var f: ^VOLATILE INT;
     begin
    -    f := ^VOLATILE INT(ADR(flag));
    +    f := ^VOLATILE INT(SYSTEM.ADR(flag));
         Sys.sleep(10);
         data := 1234;
         FENCE;                       (* data is written before the flag is *)
    @@ -103,7 +105,7 @@
     proc main*;
     var t: ^Thread.Thread; err: ERROR; f: ^VOLATILE INT;
     begin
    -    f := ^VOLATILE INT(ADR(flag));
    +    f := ^VOLATILE INT(SYSTEM.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;
    diff --git a/site/public/advanced/ring.html b/site/public/advanced/ring.html
    index dcef777..b36009a 100644
    --- a/site/public/advanced/ring.html
    +++ b/site/public/advanced/ring.html
    @@ -52,6 +52,7 @@
     

    The module

    Ring.raz
    module Ring;
     import Sys;
    +import SYSTEM;
     
     const Size* = 64;
     
    @@ -66,9 +67,9 @@
     var t: INT;
     begin
         t := r^.tail;                                    (* mine: an ordinary read *)
    -    while t - XADD(ADR(r^.head), 0) = Size do Sys.yield; end;   (* full *)
    +    while t - XADD(r^.head, 0) = Size do Sys.yield; end;   (* full *)
         r^.slots[t mod Size] := v;
    -    _ := XCHG(ADR(r^.tail), t + 1);                  (* publish the slot *)
    +    _ := XCHG(r^.tail, t + 1);                  (* publish the slot *)
     end;
     
     (* the next value, waiting while the ring is empty *)
    @@ -76,9 +77,9 @@
     var h, v: INT;
     begin
         h := r^.head;                                    (* mine *)
    -    while XADD(ADR(r^.tail), 0) = h do Sys.yield; end;          (* empty *)
    +    while XADD(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 *)
    +    _ := XCHG(r^.head, h + 1);                  (* give the slot back *)
         return v;
     end;
     
    @@ -87,6 +88,7 @@
     

    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;
    +import SYSTEM;
     
     const Count = 100000;
     
    @@ -97,14 +99,14 @@
     proc producer(_arg: ^U8);
     var i: INT;
     begin
    -    for i := 1 to Count do Ring.put(ADR(ring), i); end;
    +    for i := 1 to Count do Ring.put(SYSTEM.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));
    +        v := Ring.take(SYSTEM.ADR(ring));
             if v # i then INC(outOfOrder); end;
             sum := sum + v;
         end;
    diff --git a/site/public/advanced/static.html b/site/public/advanced/static.html
    index d87ed2a..2aa6416 100644
    --- a/site/public/advanced/static.html
    +++ b/site/public/advanced/static.html
    @@ -48,35 +48,35 @@
     

    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;
    +import SYSTEM;
     
     const Msg = "hello from raw system calls\n";
     
     proc main*;
     begin
    -    _ := SYSCALL(1, 1, ADR(Msg[0]), LEN(Msg));
    +    _ := SYSTEM.SYSCALL(1, 1, SYSTEM.ADR(Msg[0]), LEN(Msg));
     end;
     
     end Bare.
    $ raz Bare.raz
    +Bare.raz:8:42: error: Msg[0] is read through a []const slice, and can't be changed
    +    8 |     _ := SYSTEM.SYSCALL(1, 1, SYSTEM.ADR(Msg[0]), LEN(Msg));
    +      |                                          ^^^^^^
    +help: a []const slice's elements are only read: write them through a []T
    +raz: 1 error
     $ ./Bare
    -hello from raw system calls
    +/bin/sh: line 1: ./Bare: No such file or directory
     $ file Bare
    -Bare: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, with debug_info, not stripped
    +Bare: cannot open `Bare' (No such file or directory)
     $ ldd Bare
    -	not a dynamic executable
    +ldd: ./Bare: No such file or directory
     $ ls -l Bare | awk '{print $5, "bytes"}'
    -26488 bytes
    +ls: cannot access 'Bare': No such file or directory

    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 +++
    +strace: Cannot stat './Bare': No such file or directory

    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:

    @@ -91,14 +91,21 @@ end Cprint.
    $ raz Cprint.raz
    +Cprint.raz:3:1: error: extern needs import SYSTEM
    +    3 | extern proc puts(s: ^U8): I32;
    +      | ^^^^^^
    +help: it reaches memory other than through a variable: say import SYSTEM after the module's imports
    +Cprint.raz:7:15: error: a string as a ^U8 needs import SYSTEM
    +    7 |     _ := puts("hello from C");
    +      |               ^^^^^^^^^^^^^^
    +help: it reaches memory other than through a variable: say import SYSTEM after the module's imports
    +raz: 2 errors
     $ ./Cprint
    -hello from C
    +/bin/sh: line 1: ./Cprint: No such file or directory
     $ 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
    +Cprint: cannot open `Cprint' (No such file or directory)
     $ 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
    +ldd: ./Cprint: No such file or directory

    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.

    @@ -134,15 +141,15 @@
    $ raz Lean.raz
     $ raz Heavy.raz
     $ ls -l Lean Heavy | awk '{print $9, $5}'
    -Heavy 28680
    -Lean 28672
    +Heavy 28608 +Lean 28600

    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 28600
    +Lean-stripped 6856
     $ ./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 index c4474b7..9e98864 100644 --- a/site/public/advanced/syscalls.html +++ b/site/public/advanced/syscalls.html @@ -44,42 +44,49 @@
  • A lock-free stack
  • A ring buffer between threads
  • 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.

    +

    Under Sys there is one built-in, SYSTEM.SYSCALL(n, x1, ..., x6), which a module reaches with import SYSTEM;. 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;
    +import SYSTEM;
     
     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 *)
    +    n := SYSTEM.SYSCALL(1, 1, SYSTEM.ADR(Msg[0]), LEN(Msg));
    +    if n # LEN(Msg) then _ := SYSTEM.SYSCALL(60, 1); end;      (* exit(1), if it came up short *)
     end;
     
     end Raw.
    $ raz -Werror Raw.raz
    +Raw.raz:9:42: error: Msg[0] is read through a []const slice, and can't be changed
    +    9 |     n := SYSTEM.SYSCALL(1, 1, SYSTEM.ADR(Msg[0]), LEN(Msg));
    +      |                                          ^^^^^^
    +help: a []const slice's elements are only read: write them through a []T
    +raz: 1 error
     $ ./Raw
    -straight to the kernel
    +/bin/sh: line 1: ./Raw: No such file or directory

    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;
    +import SYSTEM;
     
     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) *)
    +    fd := SYSTEM.SYSCALL(2, SYSTEM.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);
    +    fd := SYSTEM.SYSCALL(2, SYSTEM.ADR(path[0]), 0, 0);
         if fd >= 0 then
             Out.str("opened /dev/null\n");
    -        _ := SYSCALL(3, fd);                      (* close *)
    +        _ := SYSTEM.SYSCALL(3, fd);                      (* close *)
         end;
     end;
     
    @@ -89,12 +96,13 @@
     

    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.

    +

    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 its SYSTEM.ADR given to the kernel.

    Who.raz
    module Who;
     import Out;
    +import SYSTEM;
     
     (* the length of the zero-ended string at the start of s *)
    -proc cstr(s: []U8): INT;
    +proc cstr(s: []const U8): INT;
     var n: INT;
     begin
         n := 0;
    @@ -105,7 +113,7 @@
     proc main*;
     var u: [390]U8;
     begin
    -    if SYSCALL(63, ADR(u[0])) = 0 then
    +    if SYSTEM.SYSCALL(63, SYSTEM.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;
    @@ -119,18 +127,19 @@
     

    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;
    +import SYSTEM;
     
     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));
    +    p := ^U8(SYSTEM.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);
    +    _ := SYSTEM.SYSCALL(11, p, 4096);
     end;
     
     end Pages.
    @@ -140,19 +149,20 @@

    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;
    +import SYSTEM;
     
     proc main*: INT;
     var buf: [4096]U8; n, wrote, at: INT;
     begin
    -    n := SYSCALL(0, 0, ADR(buf[0]), LEN(buf));
    +    n := SYSTEM.SYSCALL(0, 0, SYSTEM.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);
    +            wrote := SYSTEM.SYSCALL(1, 1, SYSTEM.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));
    +        n := SYSTEM.SYSCALL(0, 0, SYSTEM.ADR(buf[0]), LEN(buf));
         end;
         if n < 0 then return 1; end;
         return 0;
    @@ -173,6 +183,7 @@
     

    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;
    +import SYSTEM;
     
     (* getppid, call 110: no arguments *)
     proc getppid: INT;
    @@ -184,7 +195,7 @@
     
     proc main*;
     begin
    -    if (getppid() > 0) and (SYSCALL(110) = getppid()) then
    +    if (getppid() > 0) and (SYSTEM.SYSCALL(110) = getppid()) then
             Out.str("two ways to ask, one answer\n");
         end;
     end;
    diff --git a/site/public/advanced/volatile.html b/site/public/advanced/volatile.html
    index 9d9debf..04a52a9 100644
    --- a/site/public/advanced/volatile.html
    +++ b/site/public/advanced/volatile.html
    @@ -50,6 +50,7 @@
     

    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;
    +import SYSTEM;
     
     type
         Regs = record
    @@ -63,7 +64,7 @@
     proc main*;
     var dev: ^VOLATILE Regs; i: INT;
     begin
    -    dev := ^VOLATILE Regs(ADR(page));      (* the conversion is written *)
    +    dev := ^VOLATILE Regs(SYSTEM.ADR(page));      (* the conversion is written *)
         dev^.control := 1;
         dev^.status := 0FFH;
         for i := 0 to 2 do
    @@ -90,6 +91,7 @@
     

    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;
    +import SYSTEM;
     
     type Dev = record status: INT; data: INT; end;
     
    @@ -98,7 +100,7 @@
     proc device(_arg: ^U8);
     var d: ^VOLATILE Dev;
     begin
    -    d := ^VOLATILE Dev(ADR(dev));
    +    d := ^VOLATILE Dev(SYSTEM.ADR(dev));
         Sys.sleep(20);
         d^.data := 42;
         FENCE;                          (* data before the flag that announces it *)
    @@ -108,7 +110,7 @@
     proc main*;
     var t: ^Thread.Thread; err: ERROR; d: ^VOLATILE Dev; spins: INT;
     begin
    -    d := ^VOLATILE Dev(ADR(dev));
    +    d := ^VOLATILE Dev(SYSTEM.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;
    @@ -126,6 +128,7 @@
     
    • 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;
    +import SYSTEM;
     
     type Pair = record a, b: U32; end;
     
    @@ -134,18 +137,18 @@
     proc main*;
     var v: ^VOLATILE Pair; p: ^Pair; copy: Pair;
     begin
    -    v := ^VOLATILE Pair(ADR(cell));
    +    v := ^VOLATILE Pair(SYSTEM.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:10: error: can't use ^VOLATILE Pair as ^Pair
    +   12 |     p := v;
           |          ^
    -Wrong.raz:12:13: error: can't copy through a volatile pointer
    -   12 |     copy := v^;
    +Wrong.raz:13:13: error: can't copy through a volatile pointer
    +   13 |     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/download/raz-0.24.0-linux-x86_64.tar.gz b/site/public/download/raz-0.24.0-linux-x86_64.tar.gz new file mode 100644 index 0000000..463ff86 Binary files /dev/null and b/site/public/download/raz-0.24.0-linux-x86_64.tar.gz differ diff --git a/site/public/download/raz-0.24.0-linux-x86_64.tar.gz.sha256 b/site/public/download/raz-0.24.0-linux-x86_64.tar.gz.sha256 new file mode 100644 index 0000000..e0084ab --- /dev/null +++ b/site/public/download/raz-0.24.0-linux-x86_64.tar.gz.sha256 @@ -0,0 +1 @@ +3c6cac9b9ce8acc2a5284c426000440cb05a8d322cc693bfd552b9b520d935ec raz-0.24.0-linux-x86_64.tar.gz diff --git a/site/public/index.html b/site/public/index.html index 10f8708..3c58c12 100644 --- a/site/public/index.html +++ b/site/public/index.html @@ -114,24 +114,24 @@ the library.

    Download

    -

    raz 0.23.0 is a tarball for x86-64 Linux with the compiler, raz, +

    raz 0.24.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.

    -
    $ 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
    +
    $ tar xzf raz-0.24.0-linux-x86_64.tar.gz
    +$ ln -s $PWD/raz-0.24.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 +and download/raz-0.24.0-linux-x86_64.tar.gz to this one, for +good. Earlier releases: 0.23.0, 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

    +

    SHA-256 3c6cac9b9ce8acc2a5284c426000440cb05a8d322cc693bfd552b9b520d935ec

    Release pages give each version's commit, notes, compiler and source archives, with checksums. Browse the source and history, or clone: diff --git a/site/public/raz-lib.pdf b/site/public/raz-lib.pdf index 73e855a..b3ca764 100644 Binary files a/site/public/raz-lib.pdf and b/site/public/raz-lib.pdf differ diff --git a/site/public/raz.pdf b/site/public/raz.pdf index 5cb5dce..dce13f6 100644 Binary files a/site/public/raz.pdf and b/site/public/raz.pdf differ diff --git a/site/public/spec.html b/site/public/spec.html index 0a57ffd..a74aeb2 100644 --- a/site/public/spec.html +++ b/site/public/spec.html @@ -38,7 +38,7 @@

    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.

    +

    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 took them, as before; raz 0.24 doesn’t.

    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;
    @@ -111,14 +111,14 @@
     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);
    +
    import Table := Map([]const 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);
    +
    import Names := Map([]const 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.

    @@ -690,7 +690,7 @@ import Sys, Out; (* Prints the first line of the file at path. *) -proc head(path: []U8): BOOL; +proc head(path: []const U8): BOOL; var fd, n, i: INT; buf: [256]U8; begin fd := Sys.openRead(path); @@ -955,6 +955,7 @@

    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.

    +

    A procedure that only reads a slice takes a []const T, so that a string, a constant and any other slice fit it; what a procedure hands back from the environment, the arguments or a directory is a []const U8. A module that reaches memory, as the library’s lower modules do, says import SYSTEM (section 3 of the first volume).

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

    @@ -1010,7 +1011,7 @@ - + @@ -1077,7 +1078,7 @@ 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 stop*(msg: []const 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;
    @@ -1136,7 +1137,7 @@
     

    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 str*(s: []const U8);
     proc char*(c: U8);
     proc ln*;                        (* a line feed *)
     proc int*(n: I64);               (* n in decimal *)
    @@ -1145,7 +1146,7 @@
     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 *)
    +import Out, C, SYSTEM;  (* C: printf, fflush and C's FILE *stdout *)
     
     proc main*;
     begin
    @@ -1202,11 +1203,11 @@
         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 *)
    +        path*: []const U8;
    +        args*: [][]const U8;      (* the first is its name *)
    +        env*: [][]const 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 *)
    +        dir*: []const 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 *)
    @@ -1230,12 +1231,12 @@
             ready*: BOOL;         (* set by poll *)
         end;
     
    -proc write*(fd: INT; s: []U8): INT;     (* the bytes written *)
    +proc write*(fd: INT; s: []const 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 open*(path: []const U8; how: Accesses): INT;   (* its fd, closed on exec *)
    +proc openMode*(path: []const U8; how: Accesses; mode: INT): INT;   (* open, a file it makes given mode *)
    +proc openRead*(path: []const U8): INT;         (* open(path, {reading}) *)
    +proc create*(path: []const 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 *)
    @@ -1257,26 +1258,26 @@
     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 rename*(old, new: []const U8): INT;       (* replaces what new names *)
    +proc remove*(path: []const U8): INT;           (* a file, not a directory *)
    +proc removeDir*(path: []const U8): INT;        (* an empty directory *)
    +proc makeDir*(path: []const U8): INT;          (* readable by all, writable by its owner *)
    +proc makeDirMode*(path: []const U8; mode: INT): INT;   (* makeDir, given mode *)
    +proc chmod*(path: []const U8; mode: INT): INT;
    +proc chown*(path: []const U8; uid, gid: INT): INT;   (* its owner and group; -1 leaves one as it is *)
    +proc makeFifo*(path: []const U8; mode: INT): INT;    (* a named pipe, given mode *)
    +proc setTime*(path: []const U8; sec: I64; nsec: INT): INT;   (* its mtime, and the time it was read, made sec and nsec *)
    +proc access*(path: []const 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 symlink*(target, path: []const U8): INT;  (* path made a link to target *)
    +proc readLink*(path: []const U8): ([]const U8, INT); (* what the link names, good until the next call *)
    +proc info*(path: []const U8): (Info, INT);     (* following a symbolic link *)
    +proc linkInfo*(path: []const 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 space*(path: []const 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 openDir*(var d: Dir; path: []const U8): INT;
    +proc nextEntry*(var d: Dir): ([]const 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);
     
    @@ -1286,27 +1287,27 @@
     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 readyOf*(fds: []const INT; ms: INT): INT;   (* the first of fds with something to read within ms, or -1 *)
    +proc readyFor*(reads, writes: []const 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 errorText*(err: INT): []const 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 env*(name: []const U8): []const U8;       (* the environment variable's value; "" if unset *)
    +proc findEnv*(name: []const U8): ([]const U8, BOOL);   (* the value and true; "" and false if unset, "" and true if empty *)
    +proc envAt*(i: INT): ([]const U8, BOOL); (* the environment's ith NAME=value, from 0; false past the last *)
    +proc setEnv*(name, value: []const U8): INT;   (* name set to value, for env and the programs started *)
    +proc workDir*: ([]const U8, INT);        (* the working directory, good until the next call *)
    +proc setWorkDir*(path: []const 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 execve*(path: []const U8; args, env: [][]const 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 *)
    @@ -1319,13 +1320,13 @@
     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 hostName*: ([]const 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 catch*(sigs: []const 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 *)
    @@ -1337,23 +1338,23 @@
     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 connect*(path: []const U8): INT;    (* a stream socket, connected to the Unix socket at path: its fd *)
    +proc connectTcp*(addr: []const U8; port: INT): INT;   (* addr an IPv4 or IPv6 address, as numbers *)
    +proc connectUdp*(addr: []const U8; port: INT): INT;
    +proc listen*(path: []const U8): INT;     (* a Unix socket made at path, taking connections *)
    +proc listenTcp*(addr: []const 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 send*(fd: INT; s: []const U8): INT; (* write, to a socket: -32 (EPIPE), not a signal, if it is closed *)
    +proc sendNow*(fd: INT; s: []const U8): INT;   (* send, but -11 (EAGAIN) where it would wait *)
    +proc connectTcpWithin*(addr: []const U8; port, ms: INT): INT;   (* connectTcp, or -110 (ETIMEDOUT) after ms *)
    +proc listenUdp*(addr: []const 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 reply*(fd: INT; peer: Peer; s: []const 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 sendFds*(fd: INT; s: []const U8; fds: []const 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 *)
    @@ -1381,22 +1382,22 @@
     

    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 cmp*(a, b: []const U8): INT;           (* -1, 0 or 1 as a sorts before, with or after b, byte by byte *)
    +proc eq*(a, b: []const U8): BOOL;
    +proc eqFold*(a, b: []const U8): BOOL;       (* eq, an ASCII letter's capital and small the same *)
    +proc copy*(a: ^Mem.Allocator; s: []const 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 hash*(s: []const U8): U64;             (* FNV-1a, 64 bits *)
    +proc find*(s, sub: []const U8): INT;        (* where sub first starts in s, or -1 *)
    +proc findFrom*(s, sub: []const U8; from: INT): INT;   (* where sub first starts in s at or after from, or -1 *)
    +proc findLast*(s, sub: []const U8): INT;    (* where sub last starts in s, or -1 *)
    +proc hasPrefix*(s, p: []const U8): BOOL;
    +proc hasSuffix*(s, x: []const U8): BOOL;
    +proc trim*(s: []const U8): []const U8;            (* s without the spaces at either end *)
    +proc trimLeft*(s: []const U8): []const U8;        (* s without the spaces at its start *)
    +proc trimRight*(s: []const U8): []const U8;       (* s without the spaces at its end *)
    +proc cut*(s, sep: []const U8): ([]const U8, []const U8, BOOL);   (* what comes before the first sep, and after it *)
    +proc field*(s: []const U8): ([]const U8, []const 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 *)
    @@ -1404,28 +1405,28 @@
     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 join*(var b: Buf.Buf; parts: [][]const U8; sep: []const U8);   (* the parts added to b, sep between each two *)
    +proc replace*(var b: Buf.Buf; s, old, new: []const 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) *)
    +proc decode*(s: []const U8): (I32, INT);    (* the character s starts with, and its length in bytes *)
    +proc decodeLast*(s: []const U8): (I32, INT);   (* the character s ends with, and its length in bytes *)
    +proc next*(s: []const U8; i: INT): (I32, INT);  (* the character at i, and where the next starts; -1 at the end *)
    +proc valid*(s: []const U8): BOOL;           (* s is UTF-8, every character rightly spelled *)
    +proc chars*(s: []const U8): INT;            (* the characters in s, as decode reads them *)
    +proc toInt*(s: []const U8): (I64, BOOL);    (* s, in decimal; false if it isn't a number an I64 holds *)
    +proc toHex*(s: []const U8): (U64, BOOL);    (* s, in hexadecimal; false if it isn't a number a U64 holds *)
    +proc toU64*(s: []const U8): (U64, BOOL);    (* s, decimal digits only; false if it isn't one, or a U64 can't hold it *)
    +proc fromC*(p: ^U8): []const U8;            (* the bytes at p up to its zero byte, not copied; "" for nil *)
    +proc toC*(s: []const U8; 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 base64With*(s: []const U8; out: []U8; alphabet: []const 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: []const U8; out: []U8; alphabet: []const 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 base64*(s: []const U8; out: []U8): INT;      (* s in base64 into out, which holds base64Size(LEN(s)) bytes at least: the bytes written *)
    +proc unbase64*(s: []const U8; 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 le*(s: []const U8): U64;               (* s, at most 8 bytes, the first the lowest *)
    +proc be*(s: []const 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 *)
     
    @@ -1434,7 +1435,7 @@
     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 str*(var b: Buf; s: []const 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 *)
    @@ -1447,17 +1448,17 @@
         uint(u: U64);
         hex(h: U64);
         lowHex(h: U64);
    -    str(s: []U8);
    +    str(s: []const 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 *)
    +proc print*(f: []const U8; args: []const Arg);              (* to standard output *)
    +proc eprint*(f: []const U8; args: []const Arg);             (* to standard error, once Out is flushed *)
    +proc write*(var b: Buf.Buf; f: []const U8; args: []const Arg); (* added to b *)
    +proc into*(out: []U8; f: []const U8; args: []const Arg): (INT, BOOL); (* into out: the bytes, and false if cut short *)
     
     module List(T);
     type
    @@ -1521,8 +1522,8 @@
     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);.

    +proc toReal*(s: []const 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([]const 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
    @@ -1555,37 +1556,37 @@
     

    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 *)
    +proc arg*(i: INT): []const U8;                     (* argument i; 0 is the program's name; "" if there is none *)
    +proc read*(path: []const U8; var b: Buf.Buf): BOOL;   (* the whole file added to b *)
    +proc load*(path: []const U8; var b: Buf.Buf): INT;    (* as read: 0, or minus the errno that stopped it *)
    +proc write*(path, data: []const U8): BOOL;         (* the file made to hold data; false if it or its close failed *)
    +proc writeAll*(fd: INT; s: []const U8): INT;       (* all of s written to fd; 0, or minus the errno *)
    +proc realPath*(path: []const U8; var b: Buf.Buf): INT;   (* the absolute path of path, plain, added to b; 0, or minus an errno *)
    +proc removeTree*(path: []const 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);
    +        usage(scope, line: []const U8);           (* a synopsis line, without "usage: " *)
    +        sub(scope, name, help: []const U8);       (* a subcommand *)
    +        option(scope: []const U8; letter: U8; long, value, help: []const U8);
         end;
         Parser* = record
             letter*: U8;    (* the option just read *)
    -        value*: []U8;   (* its value; "" for a flag *)
    +        value*: []const 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 *)
    +        spelt*: []const 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 init*(var p: Parser; name: []const U8; table: []const 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 operand*(var p: Parser): ([]const 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 scope*(var p: Parser; name: []const 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 *)
    +proc refuse*(const p: Parser; wants: []const U8); (* the value just read refused, as number refuses one *) +proc fail*(const p: Parser; text: []const U8); (* the program's own mistake *) +proc misuse*(const p: Parser; text: []const 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 *)
    @@ -1634,7 +1635,7 @@
     

    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 *)
    +proc columns*(s: []const 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.

    @@ -1667,9 +1668,9 @@ 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 ok*(cond: BOOL; what: []const U8);                 (* fails, saying what, when cond is false *)
    +proc str*(what, got, want: []const U8);                 (* fails when got is not want; shows both, escaped, and the byte where they differ *)
    +proc int*(what: []const 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;
    @@ -1702,7 +1703,7 @@
     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 *)
    +proc check*(name: []const 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;
    diff --git a/site/public/tour/c.html b/site/public/tour/c.html
    index 333a844..0b5f128 100644
    --- a/site/public/tour/c.html
    +++ b/site/public/tour/c.html
    @@ -79,6 +79,7 @@
     

    ... 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;
    +import SYSTEM;
     
     extern proc printf(format: ^U8; ...): I32;
     extern proc fflush(f: ^U8): I32;
    @@ -108,6 +109,7 @@
     

    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;
    +import SYSTEM;
     
     extern var environ: ^^U8;
     extern proc strlen(s: ^U8): UINT;
    @@ -133,6 +135,7 @@
     

    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;
    +import SYSTEM;
     
     link "libm.so.6";
     
    diff --git a/site/public/tour/checks.html b/site/public/tour/checks.html
    index 68ea27f..a4bc4e8 100644
    --- a/site/public/tour/checks.html
    +++ b/site/public/tour/checks.html
    @@ -71,6 +71,7 @@
     

    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;
    +import SYSTEM;
     
     type Node = record val: INT; next: ^Node; end;
     
    @@ -84,16 +85,16 @@
     var a, b: Node;
     begin
         a.val := 1; b.val := 2;
    -    a.next := ADR(b);
    -    Out.int(last(ADR(a))); Out.ln;
    +    a.next := SYSTEM.ADR(b);
    +    Out.int(last(SYSTEM.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
    +Nilp.raz:9:11: stopped by a nil pointer
    +  in Nilp.last at Nilp.raz:9:11: n = nil
    +  in Nilp.main at Nilp.raz:19:5
     
    Zero.raz
    module Zero;
     import Out;
    diff --git a/site/public/tour/defer.html b/site/public/tour/defer.html
    index 2bcd642..8eeeb15 100644
    --- a/site/public/tour/defer.html
    +++ b/site/public/tour/defer.html
    @@ -52,7 +52,7 @@
     end;
     
     (* the lines of the file at path, or -1 if it can't be read *)
    -proc lines(path: []U8): INT;
    +proc lines(path: []const U8): INT;
     var fd, n, i, count: INT; buf: [4096]U8;
     begin
         fd := Sys.openRead(path);
    diff --git a/site/public/tour/errors.html b/site/public/tour/errors.html
    index 6727a45..6dec729 100644
    --- a/site/public/tour/errors.html
    +++ b/site/public/tour/errors.html
    @@ -47,7 +47,7 @@
         TooBig*: ERROR = "not a number up to 1000";
     
     (* the number s holds, up to 1000 *)
    -proc number(s: []U8): (INT, ERROR);
    +proc number(s: []const U8): (INT, ERROR);
     var n: I64; ok: BOOL;
     begin
         if LEN(s) = 0 then return 0, Empty; end;
    @@ -57,7 +57,7 @@
     end;
     
     (* the sum of the numbers in words: the first error ends it *)
    -proc total(words: [][]U8): (INT, ERROR);
    +proc total(words: [][]const U8): (INT, ERROR);
     var i, sum: INT;
     begin
         for i := 0 to LEN(words) - 1 do
    @@ -67,7 +67,7 @@
     end;
     
     proc main*;
    -var words: [3][]U8; i, n: INT; err: ERROR;
    +var words: [3][]const U8; i, n: INT; err: ERROR;
     begin
         words := ["42", "", "12345"];
         for i := 0 to 2 do
    @@ -103,7 +103,7 @@
         Range*: ERROR = "out of range";
     
     (* a percentage, 0 to 100 *)
    -proc percent(s: []U8): (INT, ERROR);
    +proc percent(s: []const U8): (INT, ERROR);
     var n: I64; ok: BOOL;
     begin
         if LEN(s) = 0 then return 0, Empty; end;
    @@ -114,7 +114,7 @@
     end;
     
     proc main*;
    -var inputs: [4][]U8; i, n: INT; err: ERROR;
    +var inputs: [4][]const U8; i, n: INT; err: ERROR;
     begin
         inputs := ["42", "", "forty", "140"];
         for i := 0 to 3 do
    @@ -146,7 +146,7 @@
     const Missing*: ERROR = "key missing";
     
     (* the number after "n=" in a line like "n=17" *)
    -proc value(line: []U8): (INT, ERROR);
    +proc value(line: []const U8): (INT, ERROR);
     var n: I64; ok: BOOL;
     begin
         if not Str.hasPrefix(line, "n=") then return 0, Missing; end;
    @@ -156,7 +156,7 @@
     end;
     
     (* the sum of the values of two lines: the first error ends it *)
    -proc sum(a, b: []U8): (INT, ERROR);
    +proc sum(a, b: []const U8): (INT, ERROR);
     begin
         return try value(a) + try value(b), nil;
     end;
    diff --git a/site/public/tour/generics.html b/site/public/tour/generics.html
    index 67dd9e1..eff6e49 100644
    --- a/site/public/tour/generics.html
    +++ b/site/public/tour/generics.html
    @@ -57,14 +57,14 @@
     

    and a program that uses it:

    Generics.raz
    module Generics;
     import Out, Ints := Biggest(INT, before),
    -    Words := Biggest([]U8, shorter), Order := Sort(INT, before);
    +    Words := Biggest([]const U8, shorter), Order := Sort(INT, before);
     
     proc before(a, b: INT): BOOL;
     begin
         return a < b;
     end;
     
    -proc shorter(a, b: []U8): BOOL;
    +proc shorter(a, b: []const U8): BOOL;
     begin
         return LEN(a) < LEN(b);
     end;
    @@ -90,6 +90,7 @@
     

    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;
    +import SYSTEM;
     
     type
         Stack* = record
    @@ -142,21 +143,22 @@
     end Stk.
    Uses.raz
    module Uses;
     import Out, Heap, Nums := Stk(INT), Pairs := Stk(Pair);
    +import SYSTEM;
     
     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));
    +    Nums.init(SYSTEM.ADR(n), Heap.heap);
    +    Pairs.init(SYSTEM.ADR(p), Heap.heap);
    +    for i := 1 to 10 do _ := Nums.push(SYSTEM.ADR(n), i * i); end;
    +    _ := Pairs.push(SYSTEM.ADR(p), {a: 3, b: 4});
    +    v, ok := Nums.pop(SYSTEM.ADR(n));
         Out.int(v); Out.str(" of "); Out.int(n.len + 1); Out.ln;
    -    pr, ok := Pairs.pop(ADR(p));
    +    pr, ok := Pairs.pop(SYSTEM.ADR(p));
         Out.int(pr.a * pr.b); Out.ln;
    -    _, ok := Pairs.pop(ADR(p));
    +    _, ok := Pairs.pop(SYSTEM.ADR(p));
         if not ok then Out.str("empty\n"); end;
     end;
     
    @@ -167,7 +169,7 @@
     

    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.

    +

    The library's List, Map and Sort are generic modules. A Map takes its key hash and equality as procedure arguments: import Count := Map([]const 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.

    raz is under the ISC license. Source
    diff --git a/site/public/tour/hello.html b/site/public/tour/hello.html index b32de64..c12291d 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"}' -28680 bytes
    +28608 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).

    @@ -110,9 +110,10 @@ exiting with 3 status 3

    Arguments

    -

    ARGC() is the number of command line arguments, with the program's own name first, and ARGV() the arguments, as C strings. Most programs read them through Files.arg and Opt, which the advanced tour shows; here is the raw form.

    +

    ARGC() is the number of command line arguments, with the program's own name first, and SYSTEM.ARGV() the arguments, as C strings. Most programs read them through Files.arg and Opt, which the advanced tour shows; here is the raw form.

    Args.raz
    module Args;
     import Out;
    +import SYSTEM;
     
     (* The length of a C string. *)
     proc len(s: ^U8): INT;
    @@ -127,7 +128,7 @@
     var i: INT; s: ^U8;
     begin
         for i := 1 to ARGC() - 1 do
    -        s := ARGV()[i];
    +        s := SYSTEM.ARGV()[i];
             Out.str(s[0..len(s)]);
             Out.ln;
         end;
    diff --git a/site/public/tour/integers.html b/site/public/tour/integers.html
    index b5157ba..98dd4fa 100644
    --- a/site/public/tour/integers.html
    +++ b/site/public/tour/integers.html
    @@ -140,7 +140,7 @@
     const Prime = 100000001B3H;
     
     (* FNV-1a: xor each byte in, then multiply, all modulo 2^64 *)
    -proc fnv(s: []U8): U64;
    +proc fnv(s: []const U8): U64;
     var h: U64; i: INT;
     begin
         h := Offset;
    diff --git a/site/public/tour/memory.html b/site/public/tour/memory.html
    index f4d8292..fa7778f 100644
    --- a/site/public/tour/memory.html
    +++ b/site/public/tour/memory.html
    @@ -83,6 +83,7 @@
     

    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;
    +import SYSTEM;
     
     type Item = record id: INT; next: ^Item; end;
     
    @@ -113,15 +114,15 @@
     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));
    +    list := make(1000, SYSTEM.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));
    +    list := make(10, SYSTEM.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));
    +    list := make(1000, SYSTEM.ADR(small.base));
         if list = nil then Out.str("a small arena ran out, and said so\n"); end;
         Arena.done(small);
     end;
    @@ -136,6 +137,7 @@
     

    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;
    +import SYSTEM;
     
     type Cell = record val: INT; end;
     
    diff --git a/site/public/tour/modules.html b/site/public/tour/modules.html
    index 551fe06..ceaf4c1 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: []U8);
    +proc hello*(name: []const U8);
     begin
         Out.str("hello, ");
         Out.str(name);
    diff --git a/site/public/tour/procedures.html b/site/public/tour/procedures.html
    index 953d471..bda2f3b 100644
    --- a/site/public/tour/procedures.html
    +++ b/site/public/tour/procedures.html
    @@ -213,7 +213,7 @@
     end;
     
     proc main*;
    -var ops: [3]Op; names: [3][]U8; i: INT;
    +var ops: [3]Op; names: [3][]const U8; i: INT;
     begin
         ops := [add, sub, mul];
         names := ["add", "sub", "mul"];
    diff --git a/site/public/tour/records.html b/site/public/tour/records.html
    index aa6bc89..e4d208e 100644
    --- a/site/public/tour/records.html
    +++ b/site/public/tour/records.html
    @@ -74,7 +74,7 @@
     
    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.

    +

    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, SYSTEM.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;
    @@ -112,7 +112,7 @@
     
    Planets.raz
    module Planets;
     import Fmt;
     
    -type Planet = record name: []U8; moons: INT; water: BOOL; end;
    +type Planet = record name: []const U8; moons: INT; water: BOOL; end;
     
     const Inner: []Planet = [
         {name: "Mercury"},
    @@ -159,7 +159,7 @@
     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.

    +

    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 SYSTEM.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;
    @@ -219,11 +219,12 @@
     

    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.

    +

    SYSTEM.ADR(x) (a module that uses it says import SYSTEM;) 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;
    +import SYSTEM;
     
    -type Counter = record hits: INT; name: []U8; end;
    +type Counter = record hits: INT; name: []const U8; end;
     
     proc hit(c: ^Counter);
     begin
    @@ -243,12 +244,12 @@
     var c: Counter; x, y: INT; p: ^INT;
     begin
         c.name := "front door";
    -    hit(ADR(c)); hit(ADR(c)); hit(nil);
    +    hit(SYSTEM.ADR(c)); hit(SYSTEM.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));
    +    swap(SYSTEM.ADR(x), SYSTEM.ADR(y));
         Out.int(x); Out.char(' '); Out.int(y); Out.ln;
    -    p := ADR(x);
    +    p := SYSTEM.ADR(x);
         p^ := p^ + 40;
         Out.int(x); Out.ln;
     end;
    @@ -262,6 +263,7 @@
     

    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;
    +import SYSTEM;
     
     type Node = record next: ^Node; val: INT; end;
     
    @@ -272,7 +274,7 @@
         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]);
    +        head := SYSTEM.ADR(nodes[i]);
         end;
         n := head;
         while n # nil do
    @@ -286,15 +288,16 @@
     
    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.

    +

    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 SYSTEM.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;
    +import SYSTEM;
     
     type Span = record p: ^U8; n: INT; end;
     
    -proc spanOf(s: []U8): Span;
    +proc spanOf(s: []const U8): Span;
     begin
    -    return {p: ADR(s[0]), n: LEN(s)};
    +    return {p: SYSTEM.ADR(s[0]), n: LEN(s)};
     end;
     
     proc main*;
    @@ -307,18 +310,19 @@
     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
    +
    Empty.raz:9:27: error: s[0] is read through a []const slice, and can't be changed
    +    9 |     return {p: SYSTEM.ADR(s[0]), n: LEN(s)};
    +      |                           ^^^^
    +help: a []const slice's elements are only read: write them through a []T
    +raz: 1 error
     
    -

    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:

    +

    SYSTEM.PTR(s) is the pointer itself, a ^U8 for a []U8, with no check. For a slice that isn't empty it is SYSTEM.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;
    +proc spanOf(s: []const U8): Span;
     begin
         return {p: SYSTEM.PTR(s), n: LEN(s)};
     end;
    @@ -343,7 +347,7 @@
     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.

    +

    Of an array, SYSTEM.PTR(a) is the address of its first element, a ^T where SYSTEM.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.

    raz is under the ISC license. Source
    diff --git a/site/public/tour/slices.html b/site/public/tour/slices.html index cedbd14..459c30d 100644 --- a/site/public/tour/slices.html +++ b/site/public/tour/slices.html @@ -51,7 +51,7 @@ end; proc main*; -var a: [5]INT; i: INT; s, val: []U8; name: [8]U8; ok: BOOL; +var a: [5]INT; i: INT; s, val: []const 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 *) @@ -162,12 +162,12 @@
    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.

    +

    A string is a slice of bytes, []U8, in UTF-8, and a string constant is a []const U8: a procedure that only reads a string takes that, and one that writes takes []U8. 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;
    +var s: []const U8; n: I64; ok: BOOL; name: [8]U8;
     begin
         s := "hello, world";
         Out.str(s[7..LEN(s)]); Out.ln;
    @@ -221,7 +221,7 @@
     const Text = "name = raz\nkind = language\nyear = 2026\n";
     
     proc main*;
    -var line, rest, key, val, w: []U8; more, ok: BOOL;
    +var line, rest, key, val, w: []const U8; more, ok: BOOL;
     begin
         (* line by line, then each line at its = *)
         line, rest, more := Str.cut(Text, "\n");
    @@ -286,7 +286,7 @@
     import Out, Str, Width;
     
     proc main*;
    -var s: []U8; c: I32; i, size: INT; bytes: [4]U8; k: INT;
    +var s: []const 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, ");
    diff --git a/site/public/tour/threads.html b/site/public/tour/threads.html
    index 9afd0f8..7704e12 100644
    --- a/site/public/tour/threads.html
    +++ b/site/public/tour/threads.html
    @@ -82,6 +82,7 @@
     

    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;
    +import SYSTEM;
     
     var
         safe: INT;       (* added to by XADD *)
    @@ -91,7 +92,7 @@
     var i: INT;
     begin
         for i := 1 to 100000 do
    -        _ := XADD(ADR(safe), 1);
    +        _ := XADD(safe, 1);
             INC(plain);              (* unsafe: lost additions *)
         end;
     end;
    @@ -149,6 +150,7 @@
     

    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;
    +import SYSTEM;
     
     type Job = record lo, hi: INT; sum: INT; end;
     
    @@ -165,7 +167,7 @@
         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])));
    +        t[i], err := Thread.spawn(work, ^U8(SYSTEM.ADR(jobs[i])));
             if err # nil then Out.str(MSG(err)); Out.ln; return; end;
         end;
         for i := 0 to 3 do
    diff --git a/site/public/tour/values.html b/site/public/tour/values.html
    index 4b40f62..99ae194 100644
    --- a/site/public/tour/values.html
    +++ b/site/public/tour/values.html
    @@ -70,7 +70,7 @@
     import Out;
     
     proc main*;
    -var i: I32; s: []U8;
    +var i: I32; s: []const U8;
     begin
         s := "four";
         i := 3;
    diff --git a/site/public/tour/variants.html b/site/public/tour/variants.html
    index 83daac1..2c76540 100644
    --- a/site/public/tour/variants.html
    +++ b/site/public/tour/variants.html
    @@ -62,7 +62,7 @@
         end;
     end;
     
    -proc kind(c: I32): []U8;
    +proc kind(c: I32): []const U8;
     begin
         match c of
         | ' ', '\t', '\n': return "space";
    @@ -72,7 +72,7 @@
         end;
     end;
     
    -proc colour(name: []U8): Colour;
    +proc colour(name: []const U8): Colour;
     begin
         match name of
         | "red", "rose": return red;
    @@ -112,7 +112,7 @@
     
     type Day = (mon, tue, wed, thu, fri, sat, sun);
     
    -proc name(d: Day): []U8;
    +proc name(d: Day): []const U8;
     begin
         match d of
         | mon: return "Monday";
    @@ -193,7 +193,7 @@
             number(n: INT);
             plus;
             times;
    -        word(s: []U8);
    +        word(s: []const U8);
         end;
     
     proc describe(t: Token);
    @@ -246,7 +246,7 @@
     
    Classify.raz
    module Classify;
     import Out;
     
    -proc kind(c: I32): []U8;
    +proc kind(c: I32): []const U8;
     begin
         match c of
         | ' ', '\t', '\n': return "space";
    @@ -257,7 +257,7 @@
     end;
     
     proc main*;
    -var s: []U8; i: INT;
    +var s: []const U8; i: INT;
     begin
         s := "x1 + _y";
         for i := 0 to LEN(s) - 1 do
    @@ -281,7 +281,7 @@
     
     type Op = (none, add, sub, show);
     
    -proc op(word: []U8): Op;
    +proc op(word: []const U8): Op;
     begin
         match word of
         | "add", "plus", "+": return add;
    @@ -292,7 +292,7 @@
     end;
     
     proc main*;
    -var total: INT; words: [6][]U8; i: INT;
    +var total: INT; words: [6][]const U8; i: INT;
     begin
         words := ["add", "plus", "sub", "show", "times", "-"];
         for i := 0 to 5 do
    
    Stroperations on []U8 strings: comparing, hashing, finding, trimming and cutting, case, joining and replacing, UTF-8, numbers to and from textoperations on strings, []const U8: comparing, hashing, finding, trimming and cutting, case, joining and replacing, UTF-8, numbers to and from text
    Bytes