From 311d3f661b13051426201c6829395bbeac37cbdc Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Mon, 26 Oct 2026 12:41:52 +0000 Subject: [PATCH] site: v0.22.0 and v0.23.0 --- diff --git a/site/public/_redirects b/site/public/_redirects index db5dd2e..22ac5bf 100644 --- a/site/public/_redirects +++ b/site/public/_redirects @@ -1 +1 @@ -/download/latest /download/raz-0.21.0-linux-x86_64.tar.gz 302 +/download/latest /download/raz-0.23.0-linux-x86_64.tar.gz 302 diff --git a/site/public/advanced/linkstatic.html b/site/public/advanced/linkstatic.html index f2095c4..0d7305e 100644 --- a/site/public/advanced/linkstatic.html +++ b/site/public/advanced/linkstatic.html @@ -64,9 +64,9 @@ stores C's exit in Rt.cExit; so this module uses no C itself, and serves both kinds of program. C's thread has a stack and a guard page of C's; the mapping here holds only the handlers' stack and - the Thread. *) + the Thread. Its test uses Check. *) module Thread; -import Sys, Rt; +import Sys, Rt, Check; const Failed*: ERROR = "can't start a thread"; diff --git a/site/public/advanced/listing.html b/site/public/advanced/listing.html index b7ec410..3f64dbb 100644 --- a/site/public/advanced/listing.html +++ b/site/public/advanced/listing.html @@ -61,32 +61,19 @@ end Add.
$ raz -S Add.raz
 
-Add.add:
-     3  proc add*(a, b: INT): INT;
-             0  push rbp
-             1  mov rbp, rsp
-             4  sub rsp, 16
-     5      return a + b;
-            11  mov r8, rdi
-            14  add r8, rsi
-            17  mov rax, r8
-     6  end;
-            20  leave
-            21  ret
-
 Add.main:
      8  proc main*;
              0  push rbp
              1  mov rbp, rsp
              4  sub rsp, 16
     10      _ := add(1, 2);
-            11  mov rdi, 1
-            16  mov rsi, 2
-            21  call Add.add
-            26  mov r8, rax
+            11  mov qword [rbp - 8], 2
+            19  mov qword [rbp - 16], 1
+            27  mov r8, [rbp - 16]
+            31  add r8, [rbp - 8]
     11  end;
-            29  leave
-            30  ret
+ 35 leave + 36 ret

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

A loop with its checks

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

@@ -258,18 +245,18 @@
$ raz -o Dot Dot.raz
 $ objdump -d -M intel --no-show-raw-insn Dot | sed -n '/<Dot.dot>:/,/ret/p' | head -12
-0000000000403b20 <Dot.dot>:
-  403b20:	push   rbp
-  403b21:	mov    rbp,rsp
-  403b24:	sub    rsp,0x40
-  403b2b:	mov    QWORD PTR [rbp-0x38],rbx
-  403b2f:	xor    ebx,ebx
-  403b31:	mov    QWORD PTR [rbp-0x30],r12
-  403b35:	xor    r12d,r12d
-  403b38:	mov    QWORD PTR [rbp-0x28],r13
-  403b3c:	xor    r13d,r13d
-  403b3f:	mov    QWORD PTR [rbp-0x20],rdx
-  403b43:	mov    QWORD PTR [rbp-0x18],rcx
+0000000000403c60 <Dot.dot>: + 403c60: push rbp + 403c61: mov rbp,rsp + 403c64: sub rsp,0x40 + 403c6b: mov QWORD PTR [rbp-0x38],rbx + 403c6f: xor ebx,ebx + 403c71: mov QWORD PTR [rbp-0x30],r12 + 403c75: xor r12d,r12d + 403c78: mov QWORD PTR [rbp-0x28],r13 + 403c7c: xor r13d,r13d + 403c7f: mov QWORD PTR [rbp-0x20],rdx + 403c83: mov QWORD PTR [rbp-0x18],rcx

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

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

← System callsContents
diff --git a/site/public/advanced/static.html b/site/public/advanced/static.html index 617006f..d87ed2a 100644 --- a/site/public/advanced/static.html +++ b/site/public/advanced/static.html @@ -65,7 +65,7 @@ $ ldd Bare not a dynamic executable $ ls -l Bare | awk '{print $5, "bytes"}' -26336 bytes +26488 bytes

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

What it does when it runs

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

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

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

Stripping

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

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

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

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

← Writing an allocatorContents
diff --git a/site/public/advanced/targets.html b/site/public/advanced/targets.html index 202f7e0..d474557 100644 --- a/site/public/advanced/targets.html +++ b/site/public/advanced/targets.html @@ -52,7 +52,7 @@ Sys.raz Thread.linux-x86_64.raz $ cd $RAZLIB && grep -c SYSCALL Sys.linux-x86_64.raz Sys.raz -Sys.linux-x86_64.raz:129 +Sys.linux-x86_64.raz:151 Sys.raz:0

A module of your own

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

diff --git a/site/public/download/raz-0.22.0-linux-x86_64.tar.gz b/site/public/download/raz-0.22.0-linux-x86_64.tar.gz new file mode 100644 index 0000000..5ffbdda Binary files /dev/null and b/site/public/download/raz-0.22.0-linux-x86_64.tar.gz differ diff --git a/site/public/download/raz-0.22.0-linux-x86_64.tar.gz.sha256 b/site/public/download/raz-0.22.0-linux-x86_64.tar.gz.sha256 new file mode 100644 index 0000000..b1d7267 --- /dev/null +++ b/site/public/download/raz-0.22.0-linux-x86_64.tar.gz.sha256 @@ -0,0 +1 @@ +451bca750e9222a08aaabe514a6db78e1f076ff12068a9a88d64ef6443fe1774 raz-0.22.0-linux-x86_64.tar.gz diff --git a/site/public/download/raz-0.23.0-linux-x86_64.tar.gz b/site/public/download/raz-0.23.0-linux-x86_64.tar.gz new file mode 100644 index 0000000..c9c52fa Binary files /dev/null and b/site/public/download/raz-0.23.0-linux-x86_64.tar.gz differ diff --git a/site/public/download/raz-0.23.0-linux-x86_64.tar.gz.sha256 b/site/public/download/raz-0.23.0-linux-x86_64.tar.gz.sha256 new file mode 100644 index 0000000..5c040fd --- /dev/null +++ b/site/public/download/raz-0.23.0-linux-x86_64.tar.gz.sha256 @@ -0,0 +1 @@ +103eb421a7fcca1c1495c1a9c699297d460ab72067fa04854da8f21edc07347c raz-0.23.0-linux-x86_64.tar.gz diff --git a/site/public/index.html b/site/public/index.html index e50cb59..10f8708 100644 --- a/site/public/index.html +++ b/site/public/index.html @@ -43,7 +43,7 @@
~10,700 lines of compiler ~500K lines compiled a second - 1 report, 32 pages + 1 report, 35 pages static executables, no run time to install
@@ -110,28 +110,28 @@

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

Download

-

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

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

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

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

-

SHA-256 a8e2e550e927050d36a7e9731e6de22b094189adea15a984cd921917cbd8d90f

+

SHA-256 103eb421a7fcca1c1495c1a9c699297d460ab72067fa04854da8f21edc07347c

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 e67a972..73e855a 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 7aea1e1..5cb5dce 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 223518e..0a57ffd 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.34 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.

+

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

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

1. A first look

module Hello;
@@ -92,8 +92,17 @@
 Link       = "link" ( string | "static" ) ";" .
 Check      = "check" "off" ";" .

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

-

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

+

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

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

+

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

+ +

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

Generic modules take types as parameters:

module List(T);
 type
@@ -111,9 +120,9 @@
 
module Map(K, V; hash: proc(k: K): U64; eq: proc(a, b: K): BOOL);
import Names := Map([]U8, I64, Str.hash, Str.eq);

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

-

Finding modules. The compiler looks for module Name in the main module’s directory, then in each directory given with -I, then in the lib directory beside the compiler. In each directory it 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.

+

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

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

-

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

+

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

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

  • a constant of the same type (its value may differ: a system call number, say);
  • @@ -123,8 +132,8 @@

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

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

-

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

-

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

+

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

+

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

4. Declarations

Declaration = "const" { IdentDef [ ":" Type ] "=" Expr ";" }
             | "type" { IdentDef "=" Type ";" }
@@ -133,20 +142,21 @@
             | ExternDeclaration ";" .
 IdentDef    = ident [ "*" ] .
 IdentList   = IdentDef { "," IdentDef } .
-

A name must be declared before it is used, with two exceptions: the base type of a pointer may name a type declared later in the same type section (so that two records can point at each other), and a procedure may be declared forward and defined later (section 8).

-

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

+

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

+

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

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

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

+

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

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

It is used as a variable of that type is, but can’t be changed: an array constant can be indexed and sliced and its LEN is n, a record constant’s fields can be read, and either can be assigned, compared as its type allows, and passed. Its parts are constant as a string’s bytes are (section 5.10). A part of it isn’t a constant, even at a constant index.

+

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

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

const Wide: [][2]I32 = [[1100H, 115FH], [2E80H, 303EH], [0AC00H, 0D7A3H]];
     Count = LEN(Wide);        (* 3, a constant *)
@@ -155,7 +165,7 @@
 

5. Types

Type      = QualIdent
           | "[" Expr "]" Type                 (* array *)
-          | "[" "]" Type                      (* slice *)
+          | "[" "]" [ "const" ] Type          (* slice *)
           | "^" [ "VOLATILE" ] Type           (* pointer *)
           | [ "packed" ] "record" { IdentList ":" Type ";" } "end"
           | "variant" { Case ";" } "end"
@@ -220,14 +230,17 @@
 

5.3 Slices

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

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

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

+

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

+

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

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

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

5.4 Pointers

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

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

5.5 Records

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

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

-

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

+

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

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

5.6 Variants

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

@@ -259,8 +272,8 @@

5.8 Errors

const NotFound*: ERROR = "not found";

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

-

ERROR is a basic type as big as an address. A value of it is made only by a constant declared as above, and each such declaration makes an error different from every other, whatever its message: two modules that both declare "not found" have two different errors. A generic module makes its errors once per instance. nil is no error.

-

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

+

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

+

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

proc find*(key: I64): (^Node, ERROR);
 ...
 n, err := Table.find(7);
@@ -268,21 +281,24 @@
 

5.9 Procedure types

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

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

+

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

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

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

5.10 Same and assignable

-

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

+

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

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

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

  • A is an integer constant whose value fits in the integer type B;
  • A is nil and B is a pointer, procedure or ERROR type;
  • A is ^T and B is ^VOLATILE T;
  • -
  • A is [n]T and B is []T;
  • -
  • A is a string literal and B is []U8, ^U8 (a pointer to the bytes followed by a zero byte, as C wants), or [n]U8 with n at least the string’s length (the rest is zero);
  • +
  • A is [n]T and B is []T or []const T, or A is []T and B is []const T;
  • +
  • A is a string literal and B is []const U8, [n]U8 with n at least the string’s length (the rest is zero), or, in a module that imports SYSTEM, ^U8 (a pointer to the bytes followed by a zero byte, as C wants);
  • A is a procedure and B a procedure type with the same signature;
  • A is INT and B is I64, or A is UINT and B is U64, which loses nothing on any target;
  • A is U8, I8 or I16 and B is INT, or A is U8 or U16 and B is UINT, which an INT or a UINT of 16 bits holds whole, so on every target; unless the value is what an operator gives (below).
-

A string’s bytes are constant. A []U8 or ^U8 made from a string literal, or a slice of a string constant, points at them, and writing through it isn’t defined: on a target with read-only memory, it may stop the program as a bad address (section 10). A [n]U8 made from a string is a copy, the program’s to change.

+

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

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

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

var s: []U8; n, d: INT;
@@ -315,9 +331,12 @@
 

6.1 Integers

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

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

-

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

+

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

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

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

+

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

+

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

+

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

Relations compare as signed or unsigned according to the type.

6.2 Booleans

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

@@ -332,12 +351,13 @@
  • p[i] is (p + i)^. p[lo..hi] is the slice of the hi - lo elements from p + lo. Neither is checked against a length, which a pointer doesn’t have, but a slice of a pointer that runs backwards, hi < lo, is a failed check (section 6.5). A pointer to an array isn’t indexed this way, since a step would be a whole array: its elements are p^[i].
  • Pointers compare with = # < <= > >= as unsigned addresses. Procedure values compare with = and # only.
  • +

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

    6.5 Arrays and slices

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

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

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

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

    +

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

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

    6.6 Enumerations and sets

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

    @@ -389,6 +409,11 @@ the name at that position; a position out of range is a failed check (6.5), and in a constant an error +BOOL +integer +0 for false, 1 for true + + set integer its bits @@ -415,7 +440,7 @@ -

    There are no others: no conversion between BOOL and integers, none between pointers and integers other than INT and UINT, and none to or from records, arrays, slices, variants or ERROR. An untyped integer constant converts to a pointer as an INT does, as in ^VOLATILE U32(0FEE00000H); it isn’t assigned to a pointer without the conversion. A conversion of a constant is made by the compiler, by the same rules: U8(300) is 44.

    +

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

    6.8 Built-in procedures

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

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

    +

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

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

    -

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

    +

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

    +

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

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

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

    +

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

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

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

    +

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

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

    +

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

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

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

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

    -

    For CAS, XCHG and XADD, p is a ^T or ^VOLATILE T where T is INT, UINT or a pointer type (INT or UINT for XADD), on every target. They are sequentially consistent, on every target; how a machine without atomic instructions makes them so is the implementation’s choice (appendix A). ### 6.9 Views

    +

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

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

    var mem: [4096]U8; n: I64; x: F64; bits: U64;
     
    @@ -519,18 +589,19 @@
     INC(mem[a].(I64), 8);

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

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

    +

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

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

    • for an element of an array or a slice, a[i].(T), from that element to the end of a: mem[4088].(I64) is the last 8 bytes of mem, and mem[4090].(I64) would run 2 bytes past its end;
    • for anything else, within v itself: x.(U64) is allowed only if x has at least 8 bytes.

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

    -

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

    +

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

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

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

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

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

    +

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

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

    7. Statements

    Statements = { Statement ";" } .
    @@ -548,7 +619,7 @@
                | "continue"
                | "defer" Statement
                | "try" Designator .
    -Arm        = ( ident [ "(" ident { "," ident } ")" ]
    +Arm        = ( ident { "." ident } [ "(" ident { "," ident } ")" ]
                  | Label { "," Label } | "else" ) ":" Statements .
     Label      = Expr [ ".." Expr ] .
     Target     = Designator | "_" .
    @@ -571,19 +642,19 @@ end;

    7.3 Return

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

    -

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

    +

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

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

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

    +

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

    7.4 Match

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

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

    +

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

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

    match op of
     | sPlus, sMinus: kind := additive;
    @@ -591,6 +662,7 @@
     | else:
     end;

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

    +

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

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

    match ch of
     | ' ', '\t':      skip := true;
    @@ -598,7 +670,7 @@
     | else:
     end;

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

    -

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

    +

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

    match word of
     | "add", "plus": op := add;
     | "sub":         op := sub;
    @@ -611,7 +683,7 @@
     

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

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

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

    -

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

    +

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

    7.7 Defer

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

    module Head;
    @@ -687,7 +759,7 @@
     Results           = Type | "(" Type { "," Type } ")" .

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

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

    -

    A const parameter is the caller’s variable too, read in place, whatever its size, with nothing copied; the procedure may only read it. It may not assign it or a part of it (a field, an element of an array in it), give it or a part of it to a var parameter, take the ADR of either, write it through a view (section 6.9), or assign the names a match arm gives its fields. What a slice or a pointer in it points at isn’t part of it: the procedure may write through them, as it may through a value parameter’s; and a slice it makes of an array in it, to read, is a slice like any other, which writes the caller’s array if written through. const keeps the procedure from changing the variable by its name, not every path to its bytes. Its argument is any expression of the parameter’s type: a variable or a constant is passed in place, anything else as a temporary of the statement, as an array a call returns is (below). If the variable changes while the procedure runs, through a var parameter, a pointer or another thread, the procedure sees the change.

    +

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

    type Parser = record args: [][]U8; at: INT; (* ... *) end;
     
     proc current(const p: Parser): []U8;     (* reads p, many words, in place *)
    @@ -701,9 +773,9 @@
     end;

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

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

    -

    An array a call returns lives to the end of the statement the call is in. A slice of it may be used there, indexed, passed or compared; one kept past the statement, in a variable or anywhere else, points at what is gone, and is the exception of section 10:

    -
    s := f('a')[0..4];     (* f returns a [8]U8: s is undefined after this *)
    -Out.str(f('a')[0..4]);   (* used in its statement: defined *)
    +

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

    +
    s := f('a')[0..4];     (* f returns a [8]U8: s is good to the end of the procedure *)
    +t := f('b')[0..4];     (* a hidden variable of its own: s is unchanged *)
    module Divide;
     import Out;
     
    @@ -723,7 +795,7 @@
     

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

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

    Procedures don’t nest.

    -

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

    +

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

    proc rdtsc*: U64;
     code
         rdtsc;
    @@ -740,15 +812,15 @@
     extern proc XOpenDisplay(name: ^U8): ^U8;
     extern proc printf(format: ^U8; ...): I32;
     extern var environ: ^^U8;
    -

    An extern procedure or variable is found by its name in the C libraries the program links: the C library always, and each library named by link.

    +

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

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

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

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

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

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

    @@ -759,7 +831,7 @@ proc exit*(status: INT); proc trace*; (* the calls under way, on standard error *)

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

    -

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

    +

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

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

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

    11. Versions

    @@ -772,15 +844,16 @@
  • Separate compilation. Whether modules are compiled on their own, and if so into what: the object file, its format, the form of the code in it, when one is out of date, and how an instance is named so that the program keeps one (section 10). This compiler compiles every module of a program together, and writes no object files.
  • Atomics. How CAS, XCHG and XADD are made sequentially consistent on a machine without atomic instructions (section 6.8): on one with a single processor, by holding off interrupts while they run, for one.
  • The calling convention. On x86-64 Linux it is System V (sections 8 and 9); elsewhere it is the C library’s own, so that extern procedures and callbacks work. How a procedure returns several results, and how its frame is laid out, are the implementation’s.
  • -
  • What is the target’s. Code procedures (section 8) hold the target’s machine code, written in its assembly language, and exist only where the implementation says so; SYSCALL exists only on Linux targets (section 6.8). A record’s layout is the target’s C layout (section 5.5), and the order of a value’s bytes is the target’s (little-endian on x86-64).
  • +
  • What is the target’s. Code procedures (section 8) hold the target’s machine code, written in its assembly language, and exist only where the implementation says so; SYSTEM.SYSCALL exists only on Linux targets (section 6.8). A record’s layout is the target’s C layout (section 5.5), and the order of a value’s bytes is the target’s (little-endian on x86-64).
  • The assembly language. How a code procedure’s instructions are written (section 8). On x86-64 it is Intel’s syntax, as NASM writes it, destination first. Which instructions it knows is the implementation’s; db gives any others.
  • Sizes in the library. How many bytes Out keeps before it writes them, Sys.outSize (the library volume): 4 KB on Linux, fewer on a small machine.
  • The executable. Its format, and the names and line numbers it carries for a debugger (section 10).
  • How a failure is caught. A nil pointer, a division by zero or a stack overflow may be caught by the machine or by checks in the compiled code; either way the program stops with its message (section 10).
  • Messages and warnings. The text of the compiler’s messages, how many errors it reports before it stops, and which warnings it gives, -Werror included (section 10). That a program that is an error in this report is rejected isn’t free; the words that say so are. So is what a program that fails says on standard error: conformance is judged by a program’s standard output and exit status, never by its standard error.
  • +
  • Copies. A procedure’s frame may hold copies of its variables that the program can’t name: registers saved to it, temporaries of its statements, its value parameters, and arrays its calls return. An implementation may leave them where they are when the procedure returns, until the stack is used again. A wipe (section 7.6) reaches only the variables it is given. A secret is best kept in one variable, passed by var or const or by pointer, never by value, and wiped there.
  • The command line. How the compiler is run, its options, and where its library lives (sections 1 and 3).
  • -

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

    +

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

    Appendix B. The grammar

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

    ident      = letter { letter | digit } .
    @@ -816,7 +889,7 @@
     
     Type      = QualIdent
               | "[" Expr "]" Type
    -          | "[" "]" Type
    +          | "[" "]" [ "const" ] Type
               | "^" [ "VOLATILE" ] Type
               | [ "packed" ] "record" { IdentList ":" Type ";" } "end"
               | "variant" { Case ";" } "end"
    @@ -861,7 +934,7 @@
                | "continue"
                | "defer" Statement
                | "try" Designator .
    -Arm        = ( ident [ "(" ident { "," ident } ")" ]
    +Arm        = ( ident { "." ident } [ "(" ident { "," ident } ")" ]
                  | Label { "," Label } | "else" ) ":" Statements .
     Label      = Expr [ ".." Expr ] .
     Target     = Designator | "_" .
    @@ -880,7 +953,8 @@
                                  | "var" IdentDef ":" Type ) .

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

    The library, volume 2

    -

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

    +

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

    +

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

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

    @@ -892,11 +966,11 @@ - + - + @@ -913,6 +987,14 @@ + + + + + + + + @@ -920,7 +1002,7 @@ - + @@ -973,6 +1055,18 @@ + + + + + + + + + + + +
    Rtending the program, exit and atExit; stop, which ends it with a message; trace, the calls under way; what the compiler’s checks call when they failending the program, exit, exitStatus and atExit; stop, which ends it with a message; trace, the calls under way; what the compiler’s checks call when they fail
    Syssystem calls: open, openMode, openRead, create, read, write, seek, position, truncate, sync, syncAll, lock, close, dup, dupTo, dupAbove, keepOnExec, mmap, munmap, isTerminal, yield, exit; files and directories, rename, remove, removeDir, makeDir, chmod, access, umask, symlink, readLink, info, linkInfo, infoOf, openDir, nextEntry, entryKind, closeDir; the terminal, rawMode, restoreMode, getMode, setMode, termSize, ready; the environment, env, envAt, setEnv, workDir, setWorkDir; programs, spawn, exec and execve, pipes and signals; the user, the machine, time used and limits; time, clock, now, sleep; random; errors, by name, and what one means, errorText; sockets, among them datagrams served and files passed; and memory shared through a file. One file per target, and Sys.raz over the C library for the others, which takes what each C library fixes from CAbisystem calls: open, openMode, openRead, create, read, write, seek, position, truncate, sync, syncAll, lock, lockShared, close, closeChecked, dup, dupTo, dupAbove, keepOnExec, mmap, munmap, mapRead, protect, isTerminal, yield, exit; files and directories, rename, remove, removeDir, makeDir, makeDirMode, chmod, setTime, access, umask, symlink, readLink, info, linkInfo, infoOf, openDir, nextEntry, entryKind, closeDir; the terminal, rawMode, restoreMode, getMode, setMode, termSize, ready; the environment, env, findEnv, envAt, setEnv, workDir, setWorkDir; programs, spawn, exec and execve, pipes and signals; the user, the machine, time used and limits; time, clock, now, sleep; random; errors, by name, and what one means, errorText; sockets, among them datagrams served and files passed; and memory shared through a file. One file per target, and Sys.raz over the C library for the others, which takes what each C library fixes from CAbi
    Out
    Thread threads, spawn, join and signal, and Mutex, in any program; in one that uses C, made by C’s pthread_create
    Taska thread given a value of its own, Task(T): spawn copies it, with no cast
    Guardeda value with its lock, Guarded(T): reached only through with
    Mem
    Heapa general allocator, Heap.heap, safe to call from several threads; freeing a block twice, or one it never gave out, stops the programa general allocator, Heap.heap, safe to call from several threads; freeing a block twice, or one it never gave out, stops the program; RAZ_HEAP=debug finds writes past a block’s end and after free
    Arena
    Width how many columns of a terminal a character, or a string, takes: 0, 1 or 2, as wcwidth says
    Randa seeded random number generator, splitmix64: the same seed, the same numbers; for tests and simulations, not secrets
    Checkchecks for a test: ok, str and int say what failed on standard error, and the program ends with status 1 if any did
    Propproperty tests and fuzzing: a property draws values, a failing case is shrunk and saved, and run first next time
    @@ -982,9 +1076,10 @@ const Full*: ERROR = "too many procedures to run at exit"; proc atExit*(p: proc): ERROR; (* p run when the program ends by exit *) proc exit*(status: INT); (* the atExit procedures, the last first, then the end *) +proc exitStatus*: INT; (* the status exit was given, in an atExit procedure; 0 before *) proc stop*(msg: []U8); (* msg, and a line feed, on standard error, then exit with status 2 *) proc trace*; (* the calls under way, and their variables, on standard error *)
    -

    Rt also holds what the compiler’s checks call when they fail, and the handlers of the signals that stop a program (section 10). exit takes each procedure off the list before it runs it, so it runs once even if it fails or calls exit itself; in a program that uses C, it ends through C’s exit, so that C flushes its buffers too.

    +

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

    module Mem;
     type
         Allocator* = record
    @@ -998,7 +1093,9 @@
     proc free*(a: ^Allocator; p: ^U8);   (* a^.free(a, p) *)
     
     module Heap;
    +proc debug*(on: BOOL);       (* debug mode on or off, for the blocks given from now on *)
     var heap*: ^Mem.Allocator;
    +var sure*: ^Mem.Allocator;   (* heap, but running out of memory stops the program *)
     
     module Arena;
     type Arena* = record
    @@ -1006,9 +1103,12 @@
         ...
     end;
     proc init*(var ar: Arena; size: INT): BOOL;   (* an arena of size bytes; false if the system has none *)
    +proc mark*(const ar: Arena): INT;             (* where ar stands now, for release *)
    +proc release*(var ar: Arena; m: INT);         (* all allocated since mark m freed; a mark past where it stands stops the program *)
     proc reset*(var ar: Arena);                   (* every allocation forgotten; the memory used again *)
     proc done*(var ar: Arena);                    (* its memory given back *)
    -

    NEW(p, a) calls a^.alloc. Heap is the general allocator. An arena hands out memory from one block: its free does nothing, and reset forgets everything.

    +

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

    +

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

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

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

    +

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

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

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

    module Out;
    @@ -1068,16 +1177,17 @@
         errNotDir* = -20; errIsDir* = -21; errInvalid* = -22;
         errNotTerminal* = -25; errNoSpace* = -28; errPipe* = -32;
         errNameTooLong* = -36; errNotEmpty* = -39; errLoop* = -40;
    -    errAddrInUse* = -98; errNetUnreach* = -101; errConnReset* = -104;
    +    errAddrInUse* = -98; errNetUnreach* = -101; errConnAborted* = -103; errConnReset* = -104;
         errTimedOut* = -110; errRefused* = -111; errHostUnreach* = -113;
         errInProgress* = -115;
     
     type
    -    Access* = (reading, writing, creating, exclusive, truncating, appending, executing);
    +    Access* = (reading, writing, creating, exclusive, truncating, appending, executing, nonblocking);
         Accesses* = set of Access;
         Info* = record
             size*: I64;      (* in bytes *)
             mtime*: I64;     (* when its contents last changed, in nanoseconds since 1970 *)
    +        seconds*: I64;   (* mtime in whole seconds, rounded down: exact past 2262 and before 1677, where mtime wraps *)
             mode*: INT;      (* its permission bits, as chmod takes them: 1EDH is rwxr-xr-x *)
             dir*: BOOL;      (* a directory *)
             file*: BOOL;     (* a regular file: not a directory, device, pipe or socket *)
    @@ -1085,6 +1195,9 @@
             ino*: U64;       (* its inode, which a rename keeps and a new file doesn't *)
             dev*: U64;       (* the file system it is on; with ino, it names the file *)
             links*: U64;     (* how many names it has: 1 for a file no hard link shares *)
    +        special*: INT;   (* its set-user-id, set-group-id and sticky bits, as chmod takes them: 800H, 400H, 200H *)
    +        uid*: INT;       (* its owner's user number *)
    +        gid*: INT;       (* its group's number *)
         end;
         Kind* = (unknown, isFile, isDir, isLink, isOther);   (* what a directory says a name in it is *)
         Dir* = record ... end;   (* an open directory; its fields are the target's *)
    @@ -1099,14 +1212,27 @@
             foreground*: BOOL;  (* its group takes the terminal on standard input *)
             tty*: INT;          (* a pseudo-terminal's fd, to start a session on; 0 for none *)
             more*: []INT;       (* fds above 2 passed on to it, at the same numbers *)
    +        keepIgnored*: BOOL; (* signals this program ignores stay ignored in it *)
         end;
         Status* = (running, exited, killed, stopped);
         Mode* = record ... end;   (* a terminal's modes; its fields are the target's *)
         Peer* = record ... end;   (* whom a datagram came from *)
    +    Remote* = record          (* who is at the other end of a connected socket *)
    +        unix*: BOOL;          (* a Unix socket: uid and pid say who *)
    +        ipv6*: BOOL;          (* addr is 16 bytes of IPv6, else 4 bytes of IPv4 then zeros *)
    +        addr*: [16]U8;
    +        port*: INT;
    +        uid*, pid*: INT;
    +    end;
    +    Poll* = record            (* a descriptor for poll to wait on *)
    +        fd*: INT;
    +        read*, write*: BOOL;  (* wait until it may be read, written *)
    +        ready*: BOOL;         (* set by poll *)
    +    end;
     
     proc write*(fd: INT; s: []U8): INT;     (* the bytes written *)
     proc read*(fd: INT; buf: []U8): INT;    (* the bytes read; 0 at the end *)
    -proc open*(path: []U8; how: Accesses): INT;   (* its fd *)
    +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}) *)
    @@ -1116,12 +1242,16 @@
     proc sync*(fd: INT): INT;                (* what was written to it, on the disk *)
     proc syncAll*(fd: INT): INT;             (* all that was written to its file system, on the disk *)
     proc lock*(fd: INT; wait: BOOL): INT;    (* the file's lock, held until fd is closed *)
    +proc lockShared*(fd: INT; wait: BOOL): INT;   (* lock, shared with others that ask it so *)
     proc close*(fd: INT);
    +proc closeChecked*(fd: INT): INT;        (* close, and 0 or minus the errno it failed with *)
     proc dup*(fd: INT): INT;                 (* a new fd for the same file, the lowest free *)
     proc dupTo*(fd, into: INT): INT;         (* into made the same file as fd, closing what it was *)
     proc dupAbove*(fd, least: INT): INT;     (* a new fd for the same file, the lowest free from least on, closed on exec *)
    -proc keepOnExec*(fd: INT; yes: BOOL): INT;   (* fd left open, or not, in the program exec runs *)
    +proc keepOnExec*(fd: INT; yes: BOOL): INT;   (* fd left open, or not (as at first for a file made by open or pipe), in the program exec runs *)
     proc isTerminal*(fd: INT): BOOL;
    +proc mapRead*(fd, size: INT): ^U8;     (* the first size bytes of fd, which may be open only to read, mapped read only; or nil *)
    +proc protect*(p: ^U8; size: INT; read, write: BOOL): INT;   (* the pages at p readable and writable as asked; neither, and touching them stops the program *)
     proc mmap*(size: INT): ^U8;              (* size bytes of zeroed memory, in whole pages; or nil *)
     proc munmap*(p: ^U8; size: INT);
     proc yield*;                             (* the processor given to another thread *)
    @@ -1131,7 +1261,11 @@
     proc remove*(path: []U8): INT;           (* a file, not a directory *)
     proc removeDir*(path: []U8): INT;        (* an empty directory *)
     proc makeDir*(path: []U8): INT;          (* readable by all, writable by its owner *)
    +proc makeDirMode*(path: []U8; mode: INT): INT;   (* makeDir, given mode *)
     proc chmod*(path: []U8; mode: INT): INT;
    +proc chown*(path: []U8; uid, gid: INT): INT;   (* its owner and group; -1 leaves one as it is *)
    +proc makeFifo*(path: []U8; mode: INT): INT;    (* a named pipe, given mode *)
    +proc setTime*(path: []U8; sec: I64; nsec: INT): INT;   (* its mtime, and the time it was read, made sec and nsec *)
     proc access*(path: []U8; how: Accesses): INT;   (* 0 if this user may read, write or execute it *)
     proc umask*(mask: INT): INT;             (* the bits taken from every file made; the mask it was *)
     proc symlink*(target, path: []U8): INT;  (* path made a link to target *)
    @@ -1154,11 +1288,14 @@
     proc ready*(fd, ms: INT): BOOL;          (* something to read within ms, or ever if ms < 0 *)
     proc readyOf*(fds: []INT; ms: INT): INT;   (* the first of fds with something to read within ms, or -1 *)
     proc readyFor*(reads, writes: []INT; ms: INT): INT;   (* readyOf, and the first of writes with room to write *)
    +proc poll*(var fds: []Poll; ms: INT): INT;   (* sets each fd's ready, as each read and write say; the number ready, 0 on a timeout, or minus an errno *)
     proc setBlocking*(fd: INT; yes: BOOL): INT;   (* if not yes, a read or write that would wait is -11 at once *)
    +proc blocking*(fd: INT): INT;            (* 1 if reads and writes wait, 0 if they are -11 at once, or minus an errno *)
     
     proc errorText*(err: INT): []U8;   (* what errno err, or minus it, means, as C's strerror says *)
     
     proc env*(name: []U8): []U8;       (* the environment variable's value; "" if unset *)
    +proc findEnv*(name: []U8): ([]U8, BOOL);   (* the value and true; "" and false if unset, "" and true if empty *)
     proc envAt*(i: INT): ([]U8, BOOL); (* the environment's ith NAME=value, from 0; false past the last *)
     proc setEnv*(name, value: []U8): INT;   (* name set to value, for env and the programs started *)
     proc workDir*: ([]U8, INT);        (* the working directory, good until the next call *)
    @@ -1171,7 +1308,9 @@
     proc exec*(p: Program): INT;       (* p run in this program's place; returns only if it can't *)
     proc execve*(path: []U8; args, env: [][]U8): INT;   (* as the kernel's execve: no search *)
     proc fork*: INT;                   (* this program copied: 0 in the copy, its process id in this one *)
    +proc setsid*: INT;                 (* a session of its own, led by this program: its process id, or minus an errno *)
     proc wait*(pid: INT; block: BOOL): (INT, Status, INT);   (* which program, how, and its code *)
    +proc waitExit*(pid: INT): (INT, Status, INT);   (* as wait, but only for a program to end *)
     proc kill*(pid, signal: INT): INT;
     proc pid*: INT;                    (* this program's process id *)
     proc group*: INT;                  (* the process group this program is in *)
    @@ -1181,6 +1320,7 @@
     proc uid*: INT;                    (* the user this program runs as *)
     proc euid*: INT;                   (* the user whose rights it has: 0 is root *)
     proc hostName*: ([]U8, INT);       (* this machine's name, good until the next call *)
    +proc processors*: INT;             (* the processors this program may run on, at least 1 *)
     proc cpuTime*(children: BOOL): (I64, I64);   (* ns used in the program and in the system; or by its children *)
     proc limit*(which: INT): (I64, I64, INT);    (* the soft limit and the hard; -1 for none *)
     proc setLimit*(which: INT; soft, hard: I64): INT;
    @@ -1188,13 +1328,14 @@
     proc catch*(sigs: []INT): INT;     (* sigs caught: an fd to wait on *)
     proc caught*(fd: INT): INT;        (* the next signal caught, or 0 if none is waiting *)
     proc ignore*(sig: INT; yes: BOOL): INT;  (* sig ignored; or, if not yes, back to what it does at first *)
    +proc ignored*(sig: INT): BOOL;     (* whether sig does nothing now *)
     proc handle*(sig: INT): INT;       (* sig noted, for came; a system call it comes during is -4 *)
     proc came*(sig: INT): BOOL;        (* whether sig came since the last time it was asked *)
     
     proc clock*: I64;                  (* nanoseconds, on a clock that only goes forward *)
     proc now*: I64;                    (* nanoseconds since 1970-01-01, UTC *)
     proc sleep*(ms: INT);
    -proc random*(b: []U8);             (* b filled with random bytes *)
    +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 *)
    @@ -1203,11 +1344,15 @@
     proc listenTcp*(addr: []U8; port: INT): INT;
     proc accept*(fd: INT): INT;        (* the next connection, waiting for one *)
     proc send*(fd: INT; s: []U8): INT; (* write, to a socket: -32 (EPIPE), not a signal, if it is closed *)
    +proc sendNow*(fd: INT; s: []U8): INT;   (* send, but -11 (EAGAIN) where it would wait *)
     proc connectTcpWithin*(addr: []U8; port, ms: INT): INT;   (* connectTcp, or -110 (ETIMEDOUT) after ms *)
     proc listenUdp*(addr: []U8; port: INT): INT;   (* a socket of datagrams on port at addr *)
     proc receive*(fd: INT; buf: []U8): (INT, Peer);   (* the next datagram, in buf, and who sent it *)
     proc reply*(fd: INT; peer: Peer; s: []U8): INT;   (* s, as one datagram, to peer *)
     proc localPort*(fd: INT): INT;     (* the port the socket fd is bound to *)
    +proc closeWrite*(fd: INT): INT;    (* no more writing to the socket fd; the other end reads an end *)
    +proc peer*(fd: INT): (Remote, INT);   (* who is at the other end of the connected socket fd *)
    +proc socketPair*: (INT, INT, INT); (* two connected stream sockets, and 0 *)
     proc sendFds*(fd: INT; s: []U8; fds: []INT): INT;   (* send, and with it fds, to a Unix socket *)
     proc receiveFds*(fd: INT; buf: []U8; fds: []INT): (INT, INT);   (* read, and the fds that came with it *)
     
    @@ -1215,21 +1360,24 @@
     proc mapFile*(fd, size: INT): ^U8; (* the first size bytes of fd, shared; munmap gives them back; or nil *)

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

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

    -

    Files. open gives a file for what how asks: reading, writing or both; creating it if it is missing, readable by all and writable by its owner; with exclusive, failing with -17 (EEXIST) if it is there, as a program does that makes a lock or a file of its own; truncating it to nothing; appending, each write going to its end, however other programs write it too. openMode is open that gives a file it makes the bits mode, less those the umask takes away: 1EDH (755) for a program, 124H (444) for a file never to be written; open gives 1A4H (644). seek moves to pos from the start of the file, or from its end if fromEnd, where a negative pos reads back from the end; position says where the file is, without moving. truncate makes the file size bytes long, cutting it or adding zeros, and leaves the position where it was. sync returns once what was written to the file is on the disk, as a program needs before it says a file is saved; syncAll returns once everything written to the file system that holds the file is on the disk, at once rather than a file at a time, and may flush other file systems too. lock takes the file’s lock, which one open file holds at a time: another that asks for it waits if wait, and otherwise fails with -11 (EAGAIN). The lock goes when the file is closed or the program ends, however it ends, so it never goes stale as a file made with exclusive does. infoOf is info of an open file: its size is what it holds now, however it was written; linkInfo is info of a symbolic link itself, not what it names, so that symlink is true, dir and file false, and size the length of what it names, which need not be there. Info.mtime is what a program checks to see whether a file changed under it, and Info.ino whether it is still the same file, not one renamed over it; 0 on a target whose files have none. Info.dev is the file system the file is on: two files are one only if both dev and ino agree, which is how a program following links finds that one has led it back into a directory it is already in. Info.links is how many names the file has: more than 1 if a hard link shares it, so that writing to it writes to a file named elsewhere too; 0 on a target that doesn’t say. Info.mode holds the nine bits of rwxrwxrwx, and chmod sets them, 1EDH (755) for a program, 1A4H (644) for data.

    +

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

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

    -

    spawn starts the program at p.path, with p.args as its arguments, the first being its name. A p.path without a / is looked for as a shell looks for a command, and as C’s execvp does: in each directory of this program’s PATH in turn, an empty one being the working directory, or of /bin:/usr/bin if PATH is unset or empty; the first that runs is the program. Its environment is this program’s with each NAME=value of p.env added or put in place of the old value, or, if p.onlyEnv, p.env alone. It starts in p.dir. Its standard input, output and error are p.fds; a 0 gives it this program’s own, so {path: "ls", args: ["ls"]} runs ls as a shell runs it, with every other field zero. It gets no other open file but those of p.more, each at its own number, as a shell passes 3<file on, every signal does what it does at first, and none is blocked. If p.tty is a pseudo-terminal’s fd, the program starts a session on that terminal: it is its controlling terminal, and its standard input, output and error, and p.fds and p.group are not used.

    +

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

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

    -

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

    +

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

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

    -

    A shell moves its own files with dup and dupTo, for 2>&1 and exec >log and around a builtin: dupTo(fd, into) makes into the same open file as fd, closing what into was, and dup gives a new fd for it, the lowest free, as a shell saves a file to give it back. dupAbove(fd, 10) gives one at 10 or above, closed on exec, out of the way of the fds a script names (3>log), as a shell keeps its own. fork copies this program, which goes on from there in both: it is 0 in the copy and the copy’s process id in this one, as a shell runs a builtin or a procedure as a stage of a pipe. Only the thread that calls it is copied, so a program with threads mustn’t; and what Out keeps is copied too, to be written twice, so Out.flush comes first. group is the process group this program is in: a shell starting on a terminal waits until it is foregroundOf(0) before it takes it. access says whether this user, by its real ids, may read, write or execute a file, as test -r, -w and -x ask, which Info.mode alone can’t say; an empty how asks only whether it is there. open refuses executing, with -22 (EINVAL). umask sets the bits taken away from the mode of every file this program, and those it starts, make, and says what they were. envAt gives the environment one variable at a time, from 0, for a shell to list it and to pass it on whole with onlyEnv. setEnv refuses a name that is empty or holds an =, and a 0 in either, with -22; as C’s setenv, it isn’t safe while another thread reads the environment, and what env gave for a variable may be gone once it sets that variable again. getMode reads a terminal’s modes, and setMode sets them again once what was written is sent, so that a shell keeps them for each job: a program stopped by Ctrl-Z with its terminal raw gets it back raw, and the shell its own between. cpuTime says how long the processor ran this program, in its own code and in the system for it, or, if children, the programs it started and has waited for, as time and times say. limit gives a limit, limitFiles say, soft and hard, and setLimit sets them, as ulimit does: a program may raise its soft limit up to the hard one, and lower either. uid is the user this program runs as, euid the one whose rights it has, 0 for root, as a prompt shows #; hostName is the machine’s name.

    -

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

    -

    Signals. catch takes the signals sigs away from what they would do, ending the program most of them, and gives an fd that is ready to read when one comes, so that a program waits for signals with ready and readyOf as it waits for keys or a server. caught gives each signal that came, in turn. A later catch adds to the signals caught and gives the same fd. Catching sigKill or sigStop, or the signals Rt reports, SIGSEGV and SIGFPE, is -22 (EINVAL). ignore makes a signal do nothing, as a shell ignores sigTtou so that it can take its terminal back, and ignore(sig, false) gives it back what it does at first. A program that spawn starts begins with neither.

    +

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

    +

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

    +

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

    +

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

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

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

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

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

    -

    Passing files and sharing memory. A program can give another an open file over a Unix socket: sendFds sends s, at least one byte, and with it fds, at most 16, each a file the other program then has open too; receiveFds reads into buf as read does, puts the fds that came with it in fds, as many as there is room for, closing the rest, and says how many bytes and how many fds. Each is closed in a program exec starts. memFile makes a file that lives in memory, of size zeroed bytes, and mapFile maps it, or any file, so that what one program writes there another sees at once: so a program hands an X server or a Wayland compositor its pixels, by sendFds of a memFile both map, rather than by copying them down a socket.

    -

    readyOf waits on several file descriptors at once, as a program does that listens to a server and a terminal both; a descriptor at its end, or failed, counts as ready, since a read of it won’t wait. It looks at the first 64 of fds, and connect and listen take a path of at most 107 bytes, as struct sockaddr_un holds; a longer one is -36 (ENAMETOOLONG).

    +

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

    +

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

    +

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

    +

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

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

    Strings, buffers and collections.

    module Str;
    @@ -1266,6 +1414,15 @@
     proc chars*(s: []U8): INT;            (* the characters in s, as decode reads them *)
     proc toInt*(s: []U8): (I64, BOOL);    (* s, in decimal; false if it isn't a number an I64 holds *)
     proc toHex*(s: []U8): (U64, BOOL);    (* s, in hexadecimal; false if it isn't a number a U64 holds *)
    +proc toU64*(s: []U8): (U64, BOOL);    (* s, decimal digits only; false if it isn't one, or a U64 can't hold it *)
    +proc fromC*(p: ^U8): []U8;            (* the bytes at p up to its zero byte, not copied; "" for nil *)
    +proc toC*(s, out: []U8): ^U8;         (* s copied into out with a zero byte after it, which holds LEN(s) + 1 bytes at least: PTR(out) *)
    +const Base64*, Base64Url*;            (* the digits of RFC 4648, sections 4 and 5 *)
    +proc base64With*(s, out, alphabet: []U8; pad: BOOL): INT;   (* s in base64 with alphabet's 64 digits into out, which holds base64Size(LEN(s)) bytes at least, padded with = if pad: the bytes written *)
    +proc unbase64With*(s, out, alphabet: []U8; pad: BOOL): (INT, BOOL);   (* s, base64 as base64With wrote it, into out, which holds (LEN(s) + 3) div 4 * 3 bytes at least: the bytes written; false if s is not that *)
    +proc base64Size*(n: INT): INT;        (* the bytes base64 makes of n bytes: 4 for each 3, or part of 3 *)
    +proc base64*(s, out: []U8): INT;      (* s in base64 into out, which holds base64Size(LEN(s)) bytes at least: the bytes written *)
    +proc unbase64*(s, out: []U8): (INT, BOOL);   (* s, base64, into out, which holds LEN(s) div 4 * 3 bytes at least: the bytes written; false if s is not base64 *)
     proc fromInt*(n: I64): ([20]U8, INT); (* n in decimal: its bytes, and how many *)
     proc le*(s: []U8): U64;               (* s, at most 8 bytes, the first the lowest *)
     proc be*(s: []U8): U64;               (* s, at most 8 bytes, the first the highest *)
    @@ -1289,14 +1446,18 @@
         int(i: I64);
         uint(u: U64);
         hex(h: U64);
    +    lowHex(h: U64);
         str(s: []U8);
         char(c: U8);
         bool(b: BOOL);
         real(r: F64; places: INT);
     end;
    +const ShortMost* = 24;                      (* the longest Fmt.short *)
    +proc short*(x: F64; var out: [ShortMost]U8): []U8; (* x in the fewest digits that read back, in out *)
     proc print*(f: []U8; args: []Arg);              (* to standard output *)
     proc eprint*(f: []U8; args: []Arg);             (* to standard error, once Out is flushed *)
     proc write*(var b: Buf.Buf; f: []U8; args: []Arg); (* added to b *)
    +proc into*(out: []U8; f: []U8; args: []Arg): (INT, BOOL); (* into out: the bytes, and false if cut short *)
     
     module List(T);
     type
    @@ -1327,6 +1488,8 @@
     proc tryPush*(var v: Vec; x: T): BOOL;   (* push; false, and v as it was, if there is no room *)
     proc tryAdd*(var v: Vec): (^T, BOOL);    (* add; nil and false, and v as it was, if there is no room *)
     proc resize*(var v: Vec; n: INT);        (* n elements: cut short, or the new ones zero *)
    +proc insert*(var v: Vec; i, n: INT);     (* n zero elements opened at i; stops the program if there is no room *)
    +proc remove*(var v: Vec; i, n: INT);     (* the n elements from i taken out, those after moved down *)
     proc all*(const v: Vec): []T;            (* the elements, until it next grows *)
     proc reset*(var v: Vec);                 (* emptied, its memory kept *)
     proc done*(var v: Vec);                  (* its memory given back *)
    @@ -1341,6 +1504,7 @@
     proc floor*(x: F64): F64;
     proc ceil*(x: F64): F64;
     proc round*(x: F64): F64;             (* to the nearest whole number; a half away from 0 *)
    +proc roundEven*(x: F64): F64;         (* to the nearest whole number; a half to the even one *)
     proc exp*(x: F64): F64;
     proc ln*(x: F64): F64;
     proc log2*(x: F64): F64;
    @@ -1348,6 +1512,7 @@
     proc sin*(x: F64): F64;
     proc cos*(x: F64): F64;
     proc tan*(x: F64): F64;
    +proc tanh*(x: F64): F64;              (* from -1 to 1 *)
     proc asin*(x: F64): F64;              (* from -pi/2 to pi/2 *)
     proc acos*(x: F64): F64;              (* from 0 to pi *)
     proc atan*(x: F64): F64;              (* from -pi/2 to pi/2 *)
    @@ -1355,6 +1520,7 @@
     proc bits*(x: F64): U64;              (* the bits of x, as IEEE 754 lays them out *)
     proc fromBits*(u: U64): F64;          (* the F64 whose bits are u *)
     proc mul*(a, b: U64): (U64, U64);     (* a times b: the low 64 bits of the product, and the high *)
    +proc divMod*(hi, lo, d: U64): (U64, U64); (* hi, lo divided by d: the quotient and the remainder; hi < d *)
     proc toReal*(s: []U8): (F64, BOOL);   (* s as a real, the F64 nearest it; false if it isn't one *)

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

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

    @@ -1373,7 +1539,9 @@ w, rest := Str.field(rest); end;

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

    -

    toInt reads a decimal number, with a - or + before it if any, and nothing else. toHex reads hexadecimal digits, capitals or not, and nothing else: no sign, 0x or H. fromInt writes a number as Out.int does, with a - if it is negative, its bytes the first of the 20 it gives.

    +

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

    +

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

    +

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

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

    len := U32(Str.le(header[4..8]));
     Str.putBE(packet[0..2], U64(port));
    @@ -1384,13 +1552,16 @@ Fmt.print("{} is {}\n", [Fmt.str(k), Fmt.int(v)]); i, k, v := Names.next(names, i); end;
    -

    Sort.sort puts s in the order less gives, in place, without memory of its own, in time n log n at most; two elements equal by less may change places. Math’s procedures are as C’s math.h has them, to within the last bit or so. 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.

    -

    Files and Opt are what most programs need of their command line.

    +

    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 *)
    +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 *)
    +proc write*(path, data: []U8): BOOL;         (* the file made to hold data; false if it or its close failed *)
    +proc writeAll*(fd: INT; s: []U8): INT;       (* all of s written to fd; 0, or minus the errno *)
    +proc realPath*(path: []U8; var b: Buf.Buf): INT;   (* the absolute path of path, plain, added to b; 0, or minus an errno *)
    +proc removeTree*(path: []U8): INT;           (* the file, or the directory and all in it, removed; 0, or minus the first errno *)
     
     module Opt;
     type
    @@ -1413,7 +1584,8 @@
     proc scope*(var p: Parser; name: []U8);               (* subcommand name's options, from the word after it *)
     proc number*(const p: Parser; lo, hi: I64): I64;      (* the value just read, a number from lo to hi *)
     proc refuse*(const p: Parser; wants: []U8);           (* the value just read refused, as number refuses one *)
    -proc fail*(const p: Parser; text: []U8);              (* the program's own mistake *)
    +proc fail*(const p: Parser; text: []U8); (* the program's own mistake *) +proc misuse*(const p: Parser; text: []U8); (* the program's own mistake, with the synopsis *)

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

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

    const wait = 1;     (* the key of --wait, which has no letter *)
    @@ -1442,6 +1614,7 @@
     
  • Flags may share a dash: -lw is -l -w. A letter’s value is the rest of its word, -bdev, or the whole next word, -b dev, even one that starts with a dash or is empty; in a group, the first letter that takes a value takes the rest, -qn12.
  • A long option is written in full, with its value after a = or in the next word: --bar=dev, --bar dev. An abbreviation is unknown, not guessed, so that adding an option never breaks a script. A value given to a flag, --follow=x, is a mistake.
  • -- ends the options, and isn’t an operand; - alone is one. The options end at the first operand, so in keep start site python -m http.server the -m is python’s.
  • +
  • In a scope with no option whose letter is a digit, a word of - and a digit, such as -33.87, is an operand, and so ends the options. A scope that gives a digit a letter, as head -5 has, reads it as an option.
  • Each scope has its own options. An option given twice is read twice.
  • number reads the value as Str.toInt does. operand reads what options are left first, and the program doesn’t see them. So does at, which says where the operands are: the arguments from operand’s next on are Files.arg(i) for i from at(p) to ARGC() - 1, so that an interpreter hands a script its arguments as they are:

    @@ -1456,13 +1629,115 @@

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

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

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

    +

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

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

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

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

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

    +

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

    +

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

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

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

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

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

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

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

    +
    module Reverse;
    +import Prop, Check, Buf, Heap;
    +
    +var
    +    b, was: Buf.Buf;    (* the bytes drawn, and a copy of them *)
    +
    +(* Turns s round, in place. *)
    +proc reverse(s: []U8);
    +var i: INT; c: U8;
    +begin
    +    for i := 0 to LEN(s) div 2 - 1 do
    +        c := s[i]; s[i] := s[LEN(s) - 1 - i]; s[LEN(s) - 1 - i] := c;
    +    end;
    +end;
    +
    +(* Reversing any string twice gives it back. *)
    +proc twice(var s: Prop.Source);
    +begin
    +    Prop.bytes(s, 64, b);
    +    Buf.reset(was);
    +    Buf.str(was, Buf.bytes(b));
    +    reverse(Buf.bytes(b));
    +    reverse(Buf.bytes(b));
    +    Check.str("reversed twice", Buf.bytes(b), Buf.bytes(was));
    +end;
    +
    +proc main*;
    +begin
    +    Buf.init(b, Heap.heap);
    +    Buf.init(was, Heap.heap);
    +    Prop.check("reverse", twice);
    +end;
    +
    +end Reverse.
    raz is under the ISC license. Source
    diff --git a/site/public/tour/c.html b/site/public/tour/c.html index e175cb4..333a844 100644 --- a/site/public/tour/c.html +++ b/site/public/tour/c.html @@ -40,7 +40,7 @@
  • Threads
  • Go · lesson 14 of 15

    Talking to C

    Qsort.raz
    module Qsort;
    -import Out, Fmt;
    +import Out, Fmt, SYSTEM;
     
     link "libm.so.6";
     
    @@ -62,7 +62,7 @@
     var a: [5]INT; i: INT;
     begin
         a := [30, 10, 50, 20, 40];
    -    qsort(^U8(ADR(a)), LEN(a), SIZE(INT), order);
    +    qsort(^U8(SYSTEM.ADR(a)), LEN(a), SIZE(INT), order);
         for i := 0 to 4 do Out.int(a[i]); Out.char(' '); end;
         Out.ln;
         Fmt.print("{}\n", [Fmt.real(cbrt(27.0), 3)]);
    diff --git a/site/public/tour/checks.html b/site/public/tour/checks.html
    index bce3716..68ea27f 100644
    --- a/site/public/tour/checks.html
    +++ b/site/public/tour/checks.html
    @@ -42,17 +42,17 @@
     
    Fail.raz
    module Fail;
     import Out;
     
    -proc get(a: []INT; i: INT): INT;
    +proc show(a: []INT; i: INT);
     begin
    -    return a[i];
    +    Out.int(a[i]);
    +    Out.ln;
     end;
     
     proc main*;
     var a: [3]INT; i: INT;
     begin
         for i := 0 to 3 do
    -        Out.int(get(a, i));
    -        Out.ln;
    +        show(a, i);
         end;
     end;
     
    @@ -60,9 +60,9 @@
     
    0
     0
     0
    -Fail.raz:6:14: index 3 is out of range for a length of 3
    -  in Fail.get at Fail.raz:6:14: i = 3
    -  in Fail.main at Fail.raz:13:9: i = 3
    +Fail.raz:6:15: index 3 is out of range for a length of 3
    +  in Fail.show at Fail.raz:6:15: i = 3
    +  in Fail.main at Fail.raz:14:9: i = 3
     

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

    Reading the message

    @@ -112,8 +112,7 @@ end Zero.
    3
    -Zero.raz:6:5: stopped by a division fault
    -  in Zero.ratio at Zero.raz:6:5: a = 10, b = 0
    +Zero.raz:13:5: stopped by a division fault
       in Zero.main at Zero.raz:13:5: n = 0
     
    Slicing.raz
    module Slicing;
    diff --git a/site/public/tour/hello.html b/site/public/tour/hello.html
    index 86c2774..b32de64 100644
    --- a/site/public/tour/hello.html
    +++ b/site/public/tour/hello.html
    @@ -70,7 +70,7 @@
     $ raz run Quiet.raz
     hello, again
     $ ls -l Quiet | awk '{print $5, "bytes"}'
    -28480 bytes
    +28680 bytes

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

    What Out can write

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

    diff --git a/site/public/tour/memory.html b/site/public/tour/memory.html index ef809f0..f4d8292 100644 --- a/site/public/tour/memory.html +++ b/site/public/tour/memory.html @@ -40,7 +40,7 @@
  • Threads
  • Set · lesson 9 of 15

    Memory and allocators

    Stack.raz
    module Stack;
    -import Out, Mem, Heap, Arena;
    +import Out, Mem, Heap, Arena, SYSTEM;
     
     type Node = record next: ^Node; val: INT; end;
     
    @@ -69,7 +69,7 @@
         end;
         Out.ln;
         if not Arena.init(ar, 100000) then return; end;
    -    for i := 1 to 1000 do top := push(top, i, ADR(ar.base)); end;
    +    for i := 1 to 1000 do top := push(top, i, SYSTEM.ADR(ar.base)); end;
         Out.int(top^.val); Out.ln;
         Arena.done(ar);            (* every node at once *)
     end;
    diff --git a/site/public/tour/records.html b/site/public/tour/records.html
    index a580507..aa6bc89 100644
    --- a/site/public/tour/records.html
    +++ b/site/public/tour/records.html
    @@ -40,7 +40,7 @@
     
  • Threads
  • Set · lesson 7 of 15

    Records and pointers

    Boxes.raz
    module Boxes;
    -import Fmt;
    +import Fmt, SYSTEM;
     
     type
         Point = record x, y: INT; end;
    @@ -64,8 +64,8 @@
     begin
         b := {lo: {x: 1, y: 1}, hi: {x: 4, y: 3}};
         Fmt.print("{}\n", [Fmt.int(area(b))]);
    -    grow(ADR(b), 1);
    -    p := ADR(b.hi);
    +    grow(SYSTEM.ADR(b), 1);
    +    p := SYSTEM.ADR(b.hi);
         p^.x := 10;
         Fmt.print("{} {}\n", [Fmt.int(area(b)), Fmt.int(b.hi.x)]);
     end;
    @@ -314,13 +314,13 @@
     

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

    Spans.raz
    module Spans;
    -import Out;
    +import Out, SYSTEM;
     
     type Span = record p: ^U8; n: INT; end;
     
     proc spanOf(s: []U8): Span;
     begin
    -    return {p: PTR(s), n: LEN(s)};
    +    return {p: SYSTEM.PTR(s), n: LEN(s)};
     end;
     
     proc text(sp: Span): []U8;
    diff --git a/site/public/tour/threads.html b/site/public/tour/threads.html
    index f0daf89..9afd0f8 100644
    --- a/site/public/tour/threads.html
    +++ b/site/public/tour/threads.html
    @@ -40,7 +40,7 @@
     
  • Threads
  • Go · lesson 15 of 15

    Threads

    Hits.raz
    module Hits;
    -import Out, Thread;
    +import Out, Thread, SYSTEM;
     
     const Workers = 4;
     
    @@ -56,7 +56,7 @@
         sum := 0;
         for i := 1 to n do
             sum := sum + i;
    -        _ := XADD(ADR(hits), 1);
    +        _ := XADD(hits, 1);
         end;
         Thread.lock(m);
         total := total + sum;