raz / site / public / spec.html

1749 lines · 220.7 KiB · raw · history · last change de634aad

1<!doctype html>
2<html lang="en">
3<head>
4<meta charset="utf-8">
5<meta name="viewport" content="width=device-width, initial-scale=1">
6<title>The raz report</title>
7<meta name="description" content="raz: a small systems language in Wirth's tradition, for x86-64 Linux.">
8<meta name="theme-color" content="#E07A5F">
9<meta property="og:title" content="The raz report">
10<meta property="og:description" content="A small systems language for x86-64 Linux. No run time, no GC, one report.">
11<meta property="og:image" content="https://raz.lucela.org/social.png">
12<meta name="twitter:card" content="summary_large_image">
13<link rel="icon" href="favicon.svg" type="image/svg+xml">
14<link rel="icon" href="favicon-32.png" type="image/png" sizes="32x32">
15<link rel="apple-touch-icon" href="apple-touch-icon.png">
16<link rel="stylesheet" href="style.css">
17</head>
18<body>
19<header><nav><a class="mark" href="index.html"><img src="logo.svg" width="26" height="26" alt="">raz</a><a href="tour/index.html">Raz, Set, Go</a><a href="advanced/index.html">More Raz</a><a href="spec.html" aria-current="page">Report</a><a href="source/index.html">Source</a><a href="index.html#download">Download</a></nav></header>
20<main>
21<div class="spec"><p><a href="raz.pdf">Volume 1 as a PDF</a> &middot; <a href="raz-lib.pdf">Volume 2 as a PDF</a></p>
22<ul>
23<li><a href="#a-first-look" id="toc-a-first-look">1. A first look</a></li>
24<li><a href="#words-and-symbols" id="toc-words-and-symbols">2. Words and symbols</a></li>
25<li><a href="#modules" id="toc-modules">3. Modules</a></li>
26<li><a href="#declarations" id="toc-declarations">4. Declarations</a></li>
27<li><a href="#types" id="toc-types">5. Types</a></li>
28<li><a href="#expressions" id="toc-expressions">6. Expressions</a></li>
29<li><a href="#statements" id="toc-statements">7. Statements</a></li>
30<li><a href="#procedures" id="toc-procedures">8. Procedures</a></li>
31<li><a href="#calling-c" id="toc-calling-c">9. Calling C</a></li>
32<li><a href="#programs" id="toc-programs">10. Programs</a></li>
33<li><a href="#versions" id="toc-versions">11. Versions</a></li>
34<li><a href="#appendix-a.-what-an-implementation-chooses" id="toc-appendix-a.-what-an-implementation-chooses">Appendix A. What an implementation chooses</a></li>
35<li><a href="#appendix-b.-the-grammar" id="toc-appendix-b.-the-grammar">Appendix B. The grammar</a></li>
36<li><a href="#the-library-volume-2" id="toc-the-library-volume-2">The library, volume 2</a></li>
37</ul>
38<p>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.</p>
39<p>This is the first volume of the report: the language, what an implementation chooses, and the grammar. The second, <code>doc/raz-lib.md</code>, is the library, which sections 3 and 10 and appendix A name.</p>
40<p>This report defines the language. It is short on purpose. Whatever it doesn’t allow, raz doesn’t have.</p>
41<p>This is version 2026-10.38 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 <code>try</code> (section 7.8); it breaks a program that has a name <code>try</code>. 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 <code>match</code> on a string (section 7.4); it breaks no program. 2026-10.26 is a fifth: an <code>INT</code> widens to an <code>I64</code> wherever it goes to one, in an expression too (sections 5.10 and 6.1); and a view, <code>v.(T)</code>, reads and writes the bytes of a variable as a <code>T</code> (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 <code>[]T</code> takes its length from its literal (section 4); it breaks no program. 2026-10.30 mends a defect: <code>[]</code> 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: <code>INT</code> is at least 16 bits, and <code>U8</code>, <code>I8</code> and <code>I16</code> 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 <code>continue</code> (section 7.2), which breaks a program that has a name <code>continue</code>. 2026-10.32 is an eighth thaw: a constant typed <code>[]T</code> may be <code>[]</code>, the empty slice (section 4); it breaks no program. 2026-10.33 is a ninth: a <code>const</code> 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 <code>var</code> parameter, a <code>const</code> one or a value instead (the library volume), which breaks a program that calls them with <code>ADR</code>. 2026-10.34 is a tenth: <code>PTR(s)</code>, the address a slice starts at, even an empty one (section 6.8); it breaks no program. 2026-10.35 is an eleventh: <code>ROL(x, n)</code> and <code>ROR(x, n)</code>, a word rotated (sections 6.1 and 6.8); it breaks no program. 2026-10.36 is a twelfth: <code>MIN(T)</code> and <code>MAX(T)</code>, the limits of an integer type, and <code>CLZ</code>, <code>CTZ</code> and <code>POPCOUNT</code>, which count bits (sections 6.1 and 6.8); <code>ABS(x)</code>, a number without its sign (sections 6.1 and 6.8); <code>INT(b)</code>, a <code>BOOL</code> as an integer (section 6.7); <code>OFFSET(T, f)</code> and <code>SIZE(T.f)</code>, where a field lies and how big it is; <code>BYTES(x)</code>, the bytes of a variable or a slice (sections 4 and 6.8); <code>FILL(d, x)</code>, an array or a slice set to one value (section 6.8); a qualified case in a <code>match</code> arm (section 7.4); a slice part written as a literal, and an <code>ERROR</code> constant named by another (sections 4 and 5.8); and a <code>const</code> parameter’s slice returned (section 7.3); and a procedure type’s parameter or result may name a type declared later in its <code>type</code> 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). <code>CAS</code>, <code>XCHG</code> and <code>XADD</code> take the variable they work on (section 6.8). <code>[]const T</code> is a slice whose elements can’t be written through it, which a string literal, a slice of a constant, <code>MSG</code> and a slice of a <code>const</code> parameter’s array are (sections 4, 5.3, 5.10, 6.8 and 8). And <code>import SYSTEM</code> is what a module says to reach memory other than through its variables: <code>SYSTEM.ADR</code>, <code>SYSTEM.PTR</code>, <code>SYSTEM.SYSCALL</code> and <code>SYSTEM.ARGV</code>, a pointer’s arithmetic and conversions, C, code procedures and <code>check off;</code> (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 <code>SYSTEM</code> holds without importing it; raz 0.23 still took them, as before; raz 0.24 doesn’t. 2026-10.38, the last change before the language is frozen for good, is for a program on the bare machine: a code procedure names a procedure or a global variable in three operands (section 8), and section 10 gives the least an implementation accepts, and what it does past its own limits; it breaks no program.</p>
42<p>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.</p>
43<h1 id="a-first-look">1. A first look</h1>
44<pre><code>module Hello;
45import Out;
46
47proc main*;
48begin
49 Out.str(&quot;hello, world\n&quot;);
50end;
51
52end Hello.</code></pre>
53<p>A program is a set of modules. The one named on the command line is the main module, and it exports a procedure <code>main</code>; the program starts there, once every module’s body has run (section 3). Saved as <code>Hello.raz</code>, it is compiled with <code>raz Hello.raz</code>, which writes the executable <code>Hello</code>.</p>
54<h1 id="words-and-symbols">2. Words and symbols</h1>
55<p>A program is written in UTF-8. The compiler rejects a file that isn’t valid UTF-8: a malformed or overlong sequence, a surrogate, or a code point beyond 10FFFFH, and a file with a NUL byte. Everything outside strings, characters and comments is ASCII. Spaces, tabs and line breaks separate symbols and are otherwise ignored.</p>
56<p><strong>Identifiers</strong> are an ASCII letter or <code>_</code> followed by letters, digits and <code>_</code>, up to 63 characters. Case matters: <code>count</code> and <code>Count</code> are different names. <code>_</code> alone isn’t a name: it is the blank, which stands only to the left of <code>:=</code> (section 7.1).</p>
57<p><strong>Reserved words</strong> are lowercase, except <code>VOLATILE</code>:</p>
58<pre><code>and begin break by code const continue defer div do else elsif end
59extern for forward if import in link match mod module not of or packed
60proc record repeat return set shl shr then to try type until var
61variant VOLATILE while xor</code></pre>
62<p><code>static</code>, in <code>link static;</code> (section 3), and <code>check</code> and <code>off</code>, in <code>check off;</code> (section 3), aren’t reserved.</p>
63<p><strong>Predeclared names</strong> are the basic types (section 5.1), <code>ERROR</code>, <code>true</code>, <code>false</code>, <code>nil</code> and the built-in procedures (section 6.8). They belong to a scope around every module, so a module or a procedure may declare the same name for something else, which hides them there.</p>
64<p><strong>Numbers.</strong> <code>123</code> is decimal. <code>0FFH</code> is hexadecimal: it starts with a digit, its digits are <code>0</code> to <code>9</code> and <code>A</code> to <code>F</code>, and it ends in <code>H</code>, all in capitals. <code>1.5</code> and <code>2.0E-3</code> are reals; a real always has a digit on both sides of its point, and its exponent, if it has one, is <code>E</code>, a sign if wanted, and digits. A decimal number above the largest <code>I64</code>, or a hexadecimal one above the largest <code>U64</code>, is an error; so is a real above the largest <code>F64</code>. A real below the least <code>F64</code> is 0.</p>
65<p>An integer is an untyped constant, which takes the type it is used as, up to the largest <code>I64</code>. A hexadecimal number above that, such as <code>0FFFFFFFFFFFFFFFFH</code>, has type <code>U64</code>: so <code>-1</code> never fits a <code>U64</code>, and the big number goes nowhere else without a conversion. Arithmetic on untyped constants doesn’t wrap: a result beyond the <code>I64</code>s, such as <code>9223372036854775807 + 1</code>, is an error.</p>
66<p>A real is an untyped constant too. It is read as the nearest <code>F64</code> (a tie goes to the even one), and takes <code>F32</code> or <code>F64</code>, whichever it is used as: an <code>F32</code> is the nearest to that <code>F64</code>. Where nothing says which, it is an <code>F64</code>. A real never becomes an integer, nor an integer a real, without a conversion: <code>x := 1;</code> is an error for <code>x: F64</code>, and <code>x := 1.0;</code> is right.</p>
67<p><strong>Characters.</strong> <code>'a'</code> is the code point of one character, an integer: <code>'a'</code> is 97 and <code>'é'</code> is 233.</p>
68<p><strong>Strings.</strong> <code>"héllo\n"</code> is a sequence of bytes, the UTF-8 of its text: <code>"é"</code> is the two bytes 0C3H, 0A9H. Both characters and strings take the escapes <code>\n</code> (line feed), <code>\t</code> (tab), <code>\r</code> (carriage return), <code>\0</code> (zero), <code>\\</code>, <code>\'</code>, <code>\"</code>, <code>\u{H...}</code> (the code point with hexadecimal value H…, up to 10FFFFH, in a string its UTF-8) and, in strings only, <code>\xHH</code> (the byte with hexadecimal value HH, which needn’t make valid UTF-8). In an escape, the hexadecimal digits may be capitals or not. A character, or a string in double quotes, ends on the line it starts on.</p>
69<p><strong>Raw strings.</strong> <code>`C:\tmp\"a b"`</code> is a string written between backquotes: its bytes are the text between them as it stands, with no escapes, so <code>\</code> and <code>"</code> are themselves. A raw string may run over lines, and each line break in it is a line feed, part of the string; a carriage return in it is left out.</p>
70<p>A raw string whose opening backquote ends its line, and whose closing backquote has only blanks (spaces and tabs) before it on its line, is indented: the text is its lines between those two, each without the closing line’s blanks at its start, and each ending in a line feed. So a long text may stand at the indentation of the code around it:</p>
71<pre><code>proc usage;
72begin
73 Out.str(`
74 usage: tool [-v] file ...
75 -v say what is done
76 `);
77end;</code></pre>
78<p>writes <code>"usage: tool [-v] file ...\n -v say what is done\n"</code>. Each line of an indented raw string must start with the closing line’s blanks, the same spaces and tabs in the same order, or it is an error; a line holding only blanks is an empty line of the text. A raw string that isn’t indented is the text between its backquotes as it stands.</p>
79<p>A raw string can’t hold a backquote; a text that needs one joins it with <code>+</code>, as <code>"`"</code>. Everywhere else a raw string is a string, as one in double quotes is.</p>
80<p>Messages give the line and the column, counted in characters (section 10).</p>
81<p><strong>Comments</strong> are <code>(*</code> … <code>*)</code> and nest. A comment ends at the <code>*)</code> that closes it, wherever that stands, so one that quotes <code>*)</code>, as in <code>x*)</code> of a pattern, writes it apart: <code>x* )</code>. By convention, the comment just before an exported declaration is its documentation, and the one before <code>module</code> is the module’s.</p>
82<p><strong>Operators and delimiters:</strong></p>
83<pre><code>+ - * / &amp; | ~ = # &lt; &lt;= &gt; &gt;= := : ; , . .. ... ( ) [ ] { } ^</code></pre>
84<p><code>|</code> is also what starts an arm of <code>match</code> (section 7.4); an arm comes where a statement could, never after an operand, so the two don’t mix.</p>
85<h1 id="modules">3. Modules</h1>
86<pre><code>Module = &quot;module&quot; ident [ &quot;(&quot; ModParams &quot;)&quot; ] &quot;;&quot;
87 { Import } { Link } [ Check ] { Declaration }
88 [ &quot;begin&quot; Statements ] &quot;end&quot; ident &quot;.&quot; .
89ModParams = ident { &quot;,&quot; ident } { &quot;;&quot; ident &quot;:&quot; &quot;proc&quot; Signature } .
90Import = &quot;import&quot; ImportItem { &quot;,&quot; ImportItem } &quot;;&quot; .
91ImportItem = ident [ &quot;:=&quot; ident [ &quot;(&quot; Type { &quot;,&quot; Type } &quot;)&quot; ] ] .
92Link = &quot;link&quot; ( string | &quot;static&quot; ) &quot;;&quot; .
93Check = &quot;check&quot; &quot;off&quot; &quot;;&quot; .</code></pre>
94<p>A module lives in a file of its own name: module <code>Out</code> is <code>Out.raz</code>. The name after <code>end</code> repeats the module’s name.</p>
95<p><strong>Exports.</strong> A name declared at the top of a module with <code>*</code> after it is exported: other modules can use it as <code>Module.name</code>. 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 <code>var</code> argument, changed by <code>INC</code>, <code>DEC</code> or <code>NEW</code>, or given to <code>SYSTEM.ADR</code>; 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 <code>[]const T</code>, 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 <code>match</code>, 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 <code>s: []U8</code> exported, <code>M.s[0] := 0</code> writes what <code>M.s</code> points at, not <code>M</code>. 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.</p>
96<p><strong>Imports.</strong> <code>import Out;</code> makes <code>Out</code>’s exports available as <code>Out.x</code>. <code>import O := Out;</code> uses the name <code>O</code> instead. A module can’t import itself, directly or through others.</p>
97<p><strong><code>import SYSTEM</code>.</strong> <code>SYSTEM</code> 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 <code>import SYSTEM;</code>, and it is an error to do them in one that doesn’t:</p>
98<ul>
99<li><code>SYSTEM.ADR</code>, <code>SYSTEM.PTR</code>, <code>SYSTEM.SYSCALL</code> and <code>SYSTEM.ARGV</code> (section 6.8), which are written so, by that name;</li>
100<li><code>p + i</code>, <code>p - i</code>, <code>p[i]</code> and <code>p[lo..hi]</code> on a pointer (section 6.4);</li>
101<li>a conversion to a pointer or a procedure type from an integer or from another pointer or procedure type, or from a pointer or a procedure to an integer (section 6.7), and a string literal given where a <code>^U8</code> is wanted (section 5.10);</li>
102<li>a view whose type holds a pointer, a view written over a variable whose type holds anything but integers and reals, and <code>BYTES</code> of such a variable (sections 6.8 and 6.9);</li>
103<li><code>extern</code> and <code>link</code> of a library (section 9), code procedures (section 8) and <code>check off;</code> (below).</li>
104</ul>
105<p><code>SYSTEM</code> 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 <code>import SYSTEM</code> needn’t say it itself; it trusts that module as it trusts the library, whose <code>Rt</code>, <code>Mem</code>, <code>Heap</code>, <code>Sys</code>, <code>Thread</code> and others say it.</p>
106<p><strong>Generic modules</strong> take types as parameters:</p>
107<pre><code>module List(T);
108type
109 Node* = record next*: ^Node; val*: T; end;
110...
111end List.</code></pre>
112<p>An import gives the arguments: <code>import Ints := List(I64);</code>. Each distinct list of arguments makes one <em>instance</em>: the module compiled with <code>T</code> standing for <code>I64</code>. Two imports of <code>List(I64)</code>, in any modules, share one instance, its variables and its <code>ERROR</code>s with it: two lists of arguments are the same when their types are the same (section 5.10), an alias as what it stands for, and their procedures are the same procedures. Since every instance is checked on its own, an operation the argument type doesn’t support (adding two records, say) is reported as an error in that instance.</p>
113<p>An instance is made where its module is first used, not at the import: so the arguments may name types the importing module declares after its imports, as long as they are declared before that first use. The instance is made before the code of the procedure, or the module body, that first uses it, and its arguments are read in the scope there.</p>
114<pre><code>import Table := Map([]const U8, Colour, Str.hash, Str.eq);
115
116type Colour = (red, green, blue);
117
118var names: Table.Map; (* the instance is made here *)</code></pre>
119<p>What a generic module needs to do with its types, beyond moving them about, it is given as procedures, after the types:</p>
120<pre><code>module Map(K, V; hash: proc(k: K): U64; eq: proc(a, b: K): BOOL);</code></pre>
121<pre><code>import Names := Map([]const U8, I64, Str.hash, Str.eq);</code></pre>
122<p>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, <code>hash(k)</code> calls it directly. Two imports make the same instance only if their types and their procedures are the same.</p>
123<p><strong>Finding modules.</strong> The compiler looks for module <code>Name</code> in the main module’s directory, then in each directory given with <code>-I</code>, then in the user library directories, then in the <code>lib</code> directory beside the compiler. User libraries live in <code>$HOME/.raz/lib</code> by default. <code>RAZ_PATH</code>, 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 <code>HOME</code>, there is no default. Paths are not searched recursively; relative paths are relative to the compiler’s working directory, and <code>~</code> 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 <code>Name.OS-ARCH.raz</code>, <code>Name.OS.raz</code>, <code>Name.ARCH.raz</code> and <code>Name.raz</code> that exists, where <code>OS-ARCH</code> is the target, for now only <code>linux-x86_64</code>. 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.</p>
124<p><strong>One module to a name.</strong> 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 <code>Buf.raz</code> beside a program would otherwise stand in for the library’s <code>Buf</code> 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 <code>lib/Sys.raz</code> builds a program over the C library’s <code>Sys</code> on Linux too.</p>
125<p><strong>Names are flat.</strong> 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, <code>doc/raz-lib.md</code>) are kept for it: a program or another library doesn’t name a module of its own <code>Arena</code>, <code>Buf</code>, <code>C</code>, <code>Files</code>, <code>Fmt</code>, <code>Guarded</code>, <code>Heap</code>, <code>List</code>, <code>Lock</code>, <code>Map</code>, <code>Math</code>, <code>Mem</code>, <code>Opt</code>, <code>Out</code>, <code>Rt</code>, <code>Sort</code>, <code>Str</code>, <code>Sys</code>, <code>SYSTEM</code>, <code>Task</code> or <code>Thread</code>, nor any name the library takes later. The modules of any other library share a prefix of their own, as an X11 library’s <code>Xauth</code> and <code>Xkeys</code> do, and a program that wants a shorter name imports one: <code>import Auth := Xauth;</code>.</p>
126<p>The compiler holds every file of such a module to the same interface. When it takes one of <code>Name.*.raz</code>, it also reads the declarations of the others beside it, and of <code>Name.raz</code> if there is one, and reports an error unless they all export the same names, each the same kind of thing:</p>
127<ul>
128<li>a constant of the same type (its value may differ: a system call number, say);</li>
129<li>a type of the same kind, and for a record or variant the same exported fields and cases, with the same types (unexported fields, and so the size and layout, may differ);</li>
130<li>a variable of the same type;</li>
131<li>a procedure of the same signature.</li>
132</ul>
133<p>Two types here are the same if they are built alike, a name in one file standing for the same name in another.</p>
134<p><strong>Module bodies.</strong> A module may end with <code>begin</code> and statements, its body. Every module’s body runs once, before the main module’s <code>main</code>: a module’s body runs after the bodies of the modules it imports, in the order of its <code>import</code>s, 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. <code>return;</code> ends a body early.</p>
135<p><strong><code>link "libX11.so.6";</code></strong> names a shared library to load at run time, for the <code>extern</code> declarations of section 9, in a module that imports <code>SYSTEM</code>. <strong><code>link static;</code></strong> 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.</p>
136<p><strong><code>check off;</code></strong>, after the links, in a module that imports <code>SYSTEM</code>, 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 <code>check</code> line, not that of the module that made it.</p>
137<h1 id="declarations">4. Declarations</h1>
138<pre><code>Declaration = &quot;const&quot; { IdentDef [ &quot;:&quot; Type ] &quot;=&quot; Expr &quot;;&quot; }
139 | &quot;type&quot; { IdentDef &quot;=&quot; Type &quot;;&quot; }
140 | &quot;var&quot; { IdentList &quot;:&quot; Type &quot;;&quot; }
141 | ProcDeclaration &quot;;&quot;
142 | ExternDeclaration &quot;;&quot; .
143IdentDef = ident [ &quot;*&quot; ] .
144IdentList = IdentDef { &quot;,&quot; IdentDef } .</code></pre>
145<p>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 <code>type</code> 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 <code>forward</code> and defined later (section 8).</p>
146<p><strong>Constants</strong> are evaluated by the compiler. Their expressions use only literals, other constants, operators, conversions, <code>SIZE</code>, <code>OFFSET</code>, the <code>LEN</code> of arrays and strings, <code>MIN</code>, <code>MAX</code>, <code>ABS</code>, <code>ROL</code>, <code>ROR</code>, <code>CLZ</code>, <code>CTZ</code>, <code>POPCOUNT</code>, and a variant’s cases. A constant is an integer, a real, a <code>BOOL</code>, a name of an enumeration, a set, a string, an array, a record, a variant or an <code>ERROR</code>. A constant of an integer type wraps as the program would: <code>U8(250) + 10</code> 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 <code>div</code> or <code>mod</code>, which stops a program (section 6.1). A string constant can be indexed and sliced as an array of <code>U8</code> is, and its <code>LEN</code> is its length in bytes. <code>+</code> joins two string constants into one:</p>
147<pre><code>const Text = &quot;the cat&quot;;
148 Line = Text + &quot;\n&quot;;
149...
150w := Text[4..7]; (* &quot;cat&quot; *)</code></pre>
151<p>A constant with a type is an <code>ERROR</code> (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, <code>BOOL</code>s, enumerations, sets, <code>ERROR</code>s, procedures, <code>nil</code>, a string for a <code>[]const U8</code>, an array constant, an array literal or the empty slice for a <code>[]const T</code> 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: <code>const D = dot;</code> is an error, <code>const D: Shape = dot;</code> isn’t.</p>
152<pre><code>const Primes: [5]I64 = [2, 3, 5, 7, 11];
153type Rule = record class: []const U8; tag: INT; float: BOOL; end;
154const Rules: [2]Rule = [{class: &quot;firefox&quot;, tag: 2}, {class: &quot;mpv&quot;, float: true}];
155const Shapes: []Shape = [circle(1.0), rect(2.0, 3.0), dot]; (* Shape of section 5.6 *)
156const Rows: [][]const INT = [[1, 2], [3]]; (* each row an array constant of its own *)
157...
158p := Primes[i];</code></pre>
159<p>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 <code>LEN</code> is <code>n</code>, 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 <code>[]const T</code> (section 5.3), as a string’s is. A part of it isn’t a constant, even at a constant index.</p>
160<p>An array constant may be typed <code>[]T</code>, 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, <code>[n]T</code>, in all else. If its literal is <code>[]</code>, it is no array but the empty slice, as a slice variable starts: a value of type <code>[]T</code>, used as a slice is, and <code>LEN</code> of it is 0 but not a constant.</p>
161<pre><code>const Wide: [][2]I32 = [[1100H, 115FH], [2E80H, 303EH], [0AC00H, 0D7A3H]];
162 Count = LEN(Wide); (* 3, a constant *)
163 Narrow: [][2]I32 = []; (* the empty slice *)</code></pre>
164<p><strong>Variables</strong> of a module live as long as the program; variables of a procedure live as long as its call. Both start at zero: every byte of them is zero. So a number starts as <code>0</code> (<code>0.0</code> for <code>F32</code> and <code>F64</code>), a <code>BOOL</code> as <code>false</code>, a pointer, procedure or <code>ERROR</code> as <code>nil</code>, a slice as the empty slice (<code>ptr</code> is <code>nil</code>, <code>len</code> is 0), a variant as its first case with its fields zero, a set as the empty set, and an enumeration as its first name. No variable is ever read before it has a value.</p>
165<h1 id="types">5. Types</h1>
166<pre><code>Type = QualIdent
167 | &quot;[&quot; Expr &quot;]&quot; Type (* array *)
168 | &quot;[&quot; &quot;]&quot; [ &quot;const&quot; ] Type (* slice *)
169 | &quot;^&quot; [ &quot;VOLATILE&quot; ] Type (* pointer *)
170 | [ &quot;packed&quot; ] &quot;record&quot; { IdentList &quot;:&quot; Type &quot;;&quot; } &quot;end&quot;
171 | &quot;variant&quot; { Case &quot;;&quot; } &quot;end&quot;
172 | &quot;(&quot; ident { &quot;,&quot; ident } &quot;)&quot; (* enumeration *)
173 | &quot;set&quot; &quot;of&quot; QualIdent
174 | &quot;proc&quot; Signature .
175Case = ident [ &quot;(&quot; FieldList { &quot;;&quot; FieldList } &quot;)&quot; ] .
176FieldList = ident { &quot;,&quot; ident } &quot;:&quot; Type .
177QualIdent = [ ident &quot;.&quot; ] ident .</code></pre>
178<h2 id="basic-types">5.1 Basic types</h2>
179<table>
180<thead>
181<tr>
182<th>Type</th>
183<th>Size</th>
184<th>Values</th>
185</tr>
186</thead>
187<tbody>
188<tr>
189<td><code>I8</code> <code>I16</code> <code>I32</code> <code>I64</code></td>
190<td>1, 2, 4, 8</td>
191<td>signed integers, two’s complement</td>
192</tr>
193<tr>
194<td><code>INT</code></td>
195<td>an address’s: 8 on x86-64</td>
196<td>signed, as big as an address</td>
197</tr>
198<tr>
199<td><code>UINT</code></td>
200<td>an address’s</td>
201<td>unsigned, as big as an address</td>
202</tr>
203<tr>
204<td><code>U8</code> <code>U16</code> <code>U32</code> <code>U64</code></td>
205<td>1, 2, 4, 8</td>
206<td>unsigned integers</td>
207</tr>
208<tr>
209<td><code>BOOL</code></td>
210<td>1</td>
211<td><code>false</code> (0), <code>true</code> (1)</td>
212</tr>
213<tr>
214<td><code>F32</code></td>
215<td>4</td>
216<td>IEEE 754 single precision</td>
217</tr>
218<tr>
219<td><code>F64</code></td>
220<td>8</td>
221<td>IEEE 754 double precision</td>
222</tr>
223</tbody>
224</table>
225<p><code>INT</code> is the everyday integer: lengths, indexes and sizes are <code>INT</code>s. It is as big as an address, and at least 16 bits, as <code>UINT</code> is, on every target; so it is the integer a pointer converts to (section 6.7), and a word the atomic built-ins work on (section 6.8). <code>INT</code> and <code>I64</code> are two types, even where they have the same size: an <code>INT</code> goes silently into an <code>I64</code> wherever it meets one, in an expression too (sections 5.10 and 6.1), and an <code>I64</code> becomes an <code>INT</code> only by <code>INT(x)</code>, which may drop bits on a smaller target. A type bigger than the largest <code>INT</code> in bytes is an error.</p>
226<p><code>F32</code> and <code>F64</code> exist only on a target that has reals (appendix A). On one that hasn’t, a real literal, and a use of <code>F32</code>, <code>F64</code> or of a name whose type is made of them, is an error; a declaration that no used code names isn’t, so a module like <code>Fmt</code> keeps one interface on every target.</p>
227<p>Each is aligned as the target’s C aligns it: to its size on x86-64. So are <code>ERROR</code> (section 5.8), pointers and procedures, each as big as an address; a slice is aligned as an address is.</p>
228<h2 id="arrays">5.2 Arrays</h2>
229<p><code>[n]T</code> is <code>n</code> elements of type <code>T</code>, one after another. <code>n</code> is a constant greater than zero. Arrays are values: assigning one copies it.</p>
230<h2 id="slices">5.3 Slices</h2>
231<p><code>[]T</code> is a view of elements that live elsewhere: a pointer to the first and a count, two addresses’ worth, 16 bytes on x86-64.</p>
232<pre><code>Slice = record ptr: ^T; len: INT; end; (* its layout *)</code></pre>
233<p>A slice is made from an array (<code>a[2..5]</code>, or an array used where a slice is wanted), from another slice, or from a pointer (<code>p[0..n]</code>). It doesn’t own what it points at. <code>LEN(s)</code> is its count, and <code>SYSTEM.PTR(s)</code> its pointer (section 6.8).</p>
234<p><code>[]const T</code> is a slice whose elements can’t be written through it. It is laid out as <code>[]T</code> is. Its elements are read, and it is sliced, and a slice of it is a <code>[]const T</code> too; but an element of it isn’t assigned, given to <code>COPY</code> or <code>FILL</code> as the destination, changed by <code>INC</code> or <code>DEC</code>, passed as a <code>var</code> argument, or written through a view, and <code>SYSTEM.ADR</code> of one is an error. A <code>[]T</code> and an array of <code>T</code> go silently where a <code>[]const T</code> is wanted, never the other way (section 5.10). So a procedure that only reads a slice takes a <code>[]const T</code>, and every caller’s slice or array fits it:</p>
235<pre><code>proc count(s: []const U8; c: U8): INT; (* reads s, and says so *)</code></pre>
236<p>A string literal and a slice of a constant are <code>[]const T</code> (sections 4 and 5.10). Another slice may still point at the same elements and write them: <code>const</code> says what this slice may do, not what the elements are.</p>
237<h2 id="pointers">5.4 Pointers</h2>
238<p><code>^T</code> is the address of a <code>T</code>, as big as an <code>INT</code>. <code>nil</code> is the pointer to nothing.</p>
239<p><code>^VOLATILE T</code> is the address of a <code>T</code> that something besides the program may read or change: a device register, memory shared with another process. Section 7.6 says what that promises.</p>
240<h2 id="records">5.5 Records</h2>
241<pre><code>type Cell = record ch: U8; attr: U8; end;</code></pre>
242<p>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.</p>
243<p>A <code>packed record</code> 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: <code>SYSTEM.ADR</code> of it, a <code>var</code> parameter of it and a slice of it are errors. Nor can it be reached through a <code>^VOLATILE</code> pointer, since a misaligned access can’t be promised as one access (section 7.6). Its value can be copied out and back in.</p>
244<p>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 <code>Str.le</code>, <code>Str.be</code>, <code>Str.putLE</code> and <code>Str.putBE</code> do (the library, <code>doc/raz-lib.md</code>).</p>
245<h2 id="variants">5.6 Variants</h2>
246<p>A variant holds one of several cases, each with its own fields:</p>
247<pre><code>type
248 Shape* = variant
249 circle(r: F64);
250 rect(w, h: F64);
251 dot;
252 end;</code></pre>
253<p>The case names are declared in the scope around the type, so <code>circle</code> can be used directly, and as <code>Shapes.circle</code> from another module if <code>Shape</code> is exported. A case with fields is built by calling it like a procedure, <code>circle(2.0)</code>; a case without fields is just <code>dot</code>. The only way to read the fields is <code>match</code> (section 7.4).</p>
254<p>Layout: an <code>INT</code> tag (0 for the first case, 1 for the second, and so on), then the space for the fields. Each case’s fields are laid out in that space as a record’s would be, after the tag, and the cases share it, so the variant is as big as its largest case needs, padded to its alignment, the largest of an <code>INT</code>‘s and its fields’. <code>variant a(x: U8); b(y: I64; z: U8); end</code> is 24 bytes on x86-64. A variant that starts at zero therefore holds its first case.</p>
255<h2 id="enumerations-and-sets">5.7 Enumerations and sets</h2>
256<pre><code>type
257 Color* = (red, green, blue);
258 Colors* = set of Color;</code></pre>
259<p>An enumeration is a list of names, in order. Like the cases of a variant, the names are declared in the scope around the type. An enumeration has at most 256 names and takes 1 byte; the first name is 0, the next 1, and so on.</p>
260<p>A name of an enumeration may also be written with its type, <code>Color.red</code>, and one imported with the type’s module, <code>M.Color.red</code>. Two enumerations of a scope may share a name, and an enumeration may have a name that something else of its scope has, a constant, a variable or a procedure: such a name is written with its type, <code>Elem.bold</code>. Written alone, it names the one declaration of it that isn’t an enumeration’s, if there is one, and is an error if there isn’t:</p>
261<pre><code>type
262 Style = (bold, italic);
263 Elem = (para, bold, rule);
264proc rule; (* a procedure, beside Elem&#39;s rule *)
265...
266s := Style.bold; e := Elem.bold; e := Elem.rule;
267e := para; (* para is Elem&#39;s alone *)
268rule; (* the procedure *)
269s := bold; (* an error: write Style.bold or Elem.bold *)</code></pre>
270<p>The type is never taken from where the name stands: <code>s := bold</code> is an error though <code>s</code> is a <code>Style</code>.</p>
271<p><code>set of E</code>, for an enumeration <code>E</code> of at most 64 names, holds any choice of <code>E</code>’s names: bit <code>i</code> stands for the name at position <code>i</code>. It takes the smallest of 1, 2, 4 and 8 bytes that has a bit for each name, so a set can stand for a C flags word.</p>
272<h2 id="errors">5.8 Errors</h2>
273<pre><code>const NotFound*: ERROR = &quot;not found&quot;;</code></pre>
274<p>An <code>ERROR</code> is how a procedure says it failed: by convention the last of its results, and <code>nil</code> when nothing failed. A caller that can’t deal with a failure itself passes it on with <code>try</code> (section 7.8).</p>
275<p><code>ERROR</code> 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 <code>"not found"</code> have two different errors. A generic module makes its errors once per instance. <code>nil</code> is no error. Only a string makes a new error: an <code>ERROR</code> constant whose value is another <code>ERROR</code> constant is that same error, so <code>const Short*: ERROR = PictBase.Short;</code> passes on an error of another module, and <code>Short = PictBase.Short</code> holds.</p>
276<p>Errors compare with <code>=</code> and <code>#</code> only, by which declaration made them, never by their message. <code>MSG(e)</code> is the message, a <code>[]const U8</code>; <code>MSG(nil)</code> is <code>""</code>.</p>
277<pre><code>proc find*(key: I64): (^Node, ERROR);
278...
279n, err := Table.find(7);
280if err = Table.NotFound then ... end;</code></pre>
281<h2 id="procedure-types">5.9 Procedure types</h2>
282<pre><code>type Compare = proc(a, b: I64): BOOL;</code></pre>
283<p>A value of a procedure type is the address of a procedure with that signature, as big as an address, or <code>nil</code>. Two signatures are alike when their parameters have the same types, each <code>var</code>, <code>const</code> or neither alike, in order, and their results are the same types; the parameters’ names don’t matter.</p>
284<p>A parameter or a result of a procedure type in a <code>type</code> section may name a type declared later in it, a record that is being declared too:</p>
285<pre><code>type Lines = record each: proc(var r: Lines; s: []U8); n: INT; end;</code></pre>
286<p>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.</p>
287<h2 id="same-and-assignable">5.10 Same and assignable</h2>
288<p>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: <code>^I64</code> is <code>^I64</code> wherever it is written. A record, variant or enumeration, though, is a type of its own wherever it is written, named or not: two <code>record x: I64; end</code> are two types. A named and an anonymous type are the same if the named one is built like the anonymous one, so that <code>p := SYSTEM.ADR(n)</code> works for <code>p: NodePtr</code> with <code>type NodePtr = ^Node</code>. Sameness doesn’t pass through the anonymous type: with <code>type P1 = ^Node; P2 = ^Node;</code>, each of <code>P1</code> and <code>P2</code> is the same as <code>^Node</code>, but they are two declarations, so not the same as each other.</p>
289<p>A type declared with only a name on the right, <code>type Count = I64;</code>, is another name for that type, not a new one.</p>
290<p>A value of type <code>A</code> can be assigned to a variable of type <code>B</code> (and passed to a parameter of type <code>B</code>, and returned as a <code>B</code>) if they are the same type, or if:</p>
291<ul>
292<li><code>A</code> is an integer constant whose value fits in the integer type <code>B</code>;</li>
293<li><code>A</code> is <code>nil</code> and <code>B</code> is a pointer, procedure or <code>ERROR</code> type;</li>
294<li><code>A</code> is <code>^T</code> and <code>B</code> is <code>^VOLATILE T</code>;</li>
295<li><code>A</code> is <code>[n]T</code> and <code>B</code> is <code>[]T</code> or <code>[]const T</code>, or <code>A</code> is <code>[]T</code> and <code>B</code> is <code>[]const T</code>;</li>
296<li><code>A</code> is a string literal and <code>B</code> is <code>[]const U8</code>, <code>[n]U8</code> with <code>n</code> at least the string’s length (the rest is zero), or, in a module that imports <code>SYSTEM</code>, <code>^U8</code> (a pointer to the bytes followed by a zero byte, as C wants);</li>
297<li><code>A</code> is a procedure and <code>B</code> a procedure type with the same signature;</li>
298<li><code>A</code> is <code>INT</code> and <code>B</code> is <code>I64</code>, or <code>A</code> is <code>UINT</code> and <code>B</code> is <code>U64</code>, which loses nothing on any target;</li>
299<li><code>A</code> is <code>U8</code>, <code>I8</code> or <code>I16</code> and <code>B</code> is <code>INT</code>, or <code>A</code> is <code>U8</code> or <code>U16</code> and <code>B</code> is <code>UINT</code>, which an <code>INT</code> or a <code>UINT</code> of 16 bits holds whole, so on every target; unless the value is what an operator gives (below).</li>
300</ul>
301<p>A string’s bytes are constant. A string literal, or a slice of a string constant, is a <code>[]const U8</code>, so writing them is an error. A <code>[n]U8</code> made from a string is a copy, the program’s to change. A <code>^U8</code> made from one, for C, points at the constant bytes, and writing through it isn’t defined (section 10).</p>
302<p>Nothing else converts silently. In particular, there is no other conversion between integer types, between integers and reals, or between <code>F32</code> and <code>F64</code>, without a written conversion (section 6.7). An <code>INT</code> widens to <code>I64</code>, and a <code>UINT</code> to <code>U64</code>, wherever its value goes where an <code>I64</code> is wanted: in <code>a, b := f(x)</code> and <code>return f(x)</code> as in any other assignment, to the bounds of a <code>for</code> and the step of <code>INC</code> and <code>DEC</code> whose variable is an <code>I64</code>, and in an expression, where it meets an <code>I64</code> (section 6.1). The types themselves stay two: a <code>^INT</code> isn’t a <code>^I64</code>, an <code>INT</code> variable isn’t passed to a <code>var</code> parameter of type <code>I64</code>, and a procedure returning an <code>INT</code> isn’t of a procedure type returning an <code>I64</code>.</p>
303<p>A <code>U8</code>, <code>I8</code> or <code>I16</code> widens to <code>INT</code>, and a <code>U8</code> or <code>U16</code> to <code>UINT</code>, in the same places, as an <code>INT</code> to <code>I64</code>: assigned, passed, returned, in <code>a, b := f(x)</code>, to a <code>for</code>’s bounds and <code>INC</code> and <code>DEC</code>’s step, and in an expression, where it meets an <code>INT</code> or a <code>UINT</code> (section 6.1); not in <code>return f(x)</code>, which passes <code>f</code>’s results on as they are. They widen only that far: a <code>U8</code> meets an <code>I64</code> only as <code>INT(b)</code> or <code>I64(b)</code>. 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 <code>a, b: U8</code> holding 200 and 100, <code>a + b</code> is 44, so <code>n := a + b</code>, for an <code>INT</code> <code>n</code>, is an error; <code>n := INT(a) + b</code> is 300, and says where the sum is made.</p>
304<pre><code>var s: []U8; n, d: INT;
305n := s[i]; (* an element: widens *)
306n := n * 10 + s[i] - &#39;0&#39;; (* n * 10 + s[i] is an INT, and so the rest *)
307d := s[i] - &#39;0&#39;; (* an error: a U8, which may have wrapped *)
308d := INT(s[i]) - &#39;0&#39;; (* below &#39;0&#39; too, it is negative *)</code></pre>
309<h1 id="expressions">6. Expressions</h1>
310<pre><code>Expr = Conjunct { &quot;or&quot; Conjunct } .
311Conjunct = Relation { &quot;and&quot; Relation } .
312Relation = SimpleExpr [ RelOp SimpleExpr ] .
313RelOp = &quot;=&quot; | &quot;#&quot; | &quot;&lt;&quot; | &quot;&lt;=&quot; | &quot;&gt;&quot; | &quot;&gt;=&quot; | &quot;in&quot; .
314SimpleExpr = [ &quot;-&quot; ] Term { AddOp Term } .
315AddOp = &quot;+&quot; | &quot;-&quot; | &quot;|&quot; | &quot;xor&quot; .
316Term = Factor { MulOp Factor } .
317MulOp = &quot;*&quot; | &quot;/&quot; | &quot;div&quot; | &quot;mod&quot; | &quot;&amp;&quot; | &quot;shl&quot; | &quot;shr&quot; .
318Factor = number | char | string | Designator | &quot;(&quot; Expr &quot;)&quot;
319 | &quot;not&quot; Factor | &quot;~&quot; Factor
320 | &quot;[&quot; [ Expr { &quot;,&quot; Expr } ] &quot;]&quot;
321 | &quot;{&quot; [ Element { &quot;,&quot; Element } ] &quot;}&quot;
322 | &quot;^&quot; [ &quot;VOLATILE&quot; ] Type &quot;(&quot; Expr &quot;)&quot;
323 | &quot;try&quot; Designator .
324Element = Expr | ident &quot;:&quot; Expr .
325Designator = QualIdent { Selector } .
326Selector = &quot;.&quot; ident | &quot;^&quot; | &quot;[&quot; Expr [ &quot;..&quot; Expr ] &quot;]&quot;
327 | &quot;(&quot; [ Expr { &quot;,&quot; Expr } ] &quot;)&quot; | &quot;.&quot; &quot;(&quot; Type &quot;)&quot; .</code></pre>
328<p>The operators bind in the order of the grammar: <code>not</code>, <code>~</code> and <code>try</code> (section 7.8) most tightly, then the multiplying operators, then the adding ones, then the relations, then <code>and</code>, then <code>or</code>. So <code>a + b * c = d</code> is <code>(a + (b * c)) = d</code>, <code>x &amp; 0FH = 0</code> is <code>(x &amp; 0FH) = 0</code>, and <code>i &lt; n and a[i] # 0 or done</code> is <code>((i &lt; n) and (a[i] # 0)) or done</code>. A unary minus applies to the first term: <code>-a * b</code> is <code>-(a * b)</code>.</p>
329<p><code>and</code>, <code>or</code> and <code>not</code> are for <code>BOOL</code>s only; <code>&amp;</code>, <code>|</code>, <code>xor</code> and <code>~</code> are for integers only.</p>
330<p>A pointer to a record isn’t the record: its fields are <code>p^.f</code>, never <code>p.f</code>, and the elements of a pointer to an array are <code>p^[i]</code>. A statement starts with a name or <code>try</code>, so <code>^T(x)^ := v</code> isn’t one; a view, <code>mem[a].(I64) := v</code> (section 6.9), says it without a pointer.</p>
331<h2 id="integers">6.1 Integers</h2>
332<p>Both operands of <code>+ - * div mod &amp; | xor</code>, 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 <code>INT</code> and the other an <code>I64</code> (a <code>UINT</code> and a <code>U64</code>), and the <code>INT</code> widens to <code>I64</code>, or one is an <code>INT</code> and the other a <code>U8</code>, <code>I8</code> or <code>I16</code> (a <code>UINT</code> and a <code>U8</code> or <code>U16</code>) that no operator gave, and it widens to <code>INT</code> (section 5.10). So do <code>v</code> and <code>k</code> in <code>INC(v, k)</code> and <code>DEC(v, k)</code>, where only <code>k</code> widens: an <code>I64</code> <code>k</code> isn’t added to an <code>INT</code> <code>v</code>. The result has that type and wraps around at its width: in <code>U8</code>, <code>200 + 100</code> is <code>44</code>. A unary minus wraps too: for <code>x</code> of an unsigned type, <code>-x</code> is <code>0 - x</code>. Other integer types are never mixed, whatever their sizes: with <code>i: I32</code>, <code>i &lt; LEN(s)</code> is an error, and <code>i</code> should be an <code>INT</code>; with <code>c: U8</code>, <code>c &lt; LEN(s)</code> is an <code>INT</code> comparison. With <code>pos: I64</code>, <code>pos + LEN(s)</code> is an <code>I64</code>.</p>
333<p>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 <code>i</code> in <code>p + i</code>, or a conversion’s operand, any integer type will do, and its value is taken. On a target whose <code>INT</code> is narrower, a pointer’s offset is cut to an <code>INT</code>.</p>
334<p><code>SIZE(T)</code>, <code>SIZE(T.f)</code>, <code>OFFSET(T, f)</code>, and <code>LEN</code> of an array or a string constant, are untyped constants, like a literal.</p>
335<p><code>div</code> rounds toward zero and <code>mod</code> takes the sign of the dividend, as in C: <code>-7 div 2</code> is <code>-3</code>, <code>-7 mod 2</code> is <code>-1</code>. Dividing by zero, and dividing the smallest value of a signed type by <code>-1</code>, stop the program (section 10), whatever the type and the target.</p>
336<p><code>&amp;</code> (and), <code>|</code> (or), <code>xor</code> and <code>~</code> (not) work on every bit. <code>x shl n</code> and <code>x shr n</code> shift by <code>n</code> modulo the width of <code>x</code>’s type, in bits: for <code>x: U8</code>, <code>x shl 9</code> is <code>x shl 1</code>. <code>shr</code> brings in copies of the sign bit for signed types and zeros for unsigned ones. <code>n</code> may be of any integer type. The result has <code>x</code>’s type, cut to its width: in <code>U8</code>, <code>0C0H shl 1</code> is <code>80H</code>. If <code>x</code> is an untyped constant, so is the result, and it doesn’t wrap: <code>1 shl 9</code> is 512, which doesn’t fit a <code>U8</code>.</p>
337<p><code>ROL(x, n)</code> and <code>ROR(x, n)</code> (section 6.8) rotate <code>x</code> left and right by <code>n</code> bits modulo its width: the bits shifted out at one end come back in at the other. For <code>x: U8</code> holding <code>81H</code>, <code>ROL(x, 1)</code> is <code>03H</code> and <code>ROR(x, 1)</code> is <code>0C0H</code>. <code>x</code> is of an unsigned integer type, <code>U8</code>, <code>U16</code>, <code>U32</code>, <code>U64</code> or <code>UINT</code>, and the result has its type; <code>n</code> may be of any integer type. An untyped constant has no width, so <code>ROL(1, 3)</code> is an error, and <code>ROL(U32(1), 3)</code> is 8. Hashes and ciphers are written with rotations, which machines do in one instruction, and which two shifts and an <code>or</code> say only at more length: <code>ROR(x, 7)</code> is <code>x shr 7 | x shl 25</code> for a <code>U32</code> <code>x</code>.</p>
338<p><code>CLZ(x)</code> and <code>CTZ(x)</code> (section 6.8) count the zero bits above the highest one in <code>x</code> and below the lowest one, and <code>POPCOUNT(x)</code> counts its one bits. <code>x</code> is of an unsigned integer type, and the result is an <code>INT</code>; for <code>x: U8</code>, <code>CLZ(x)</code> is 7 when <code>x</code> is 1, and <code>CLZ(x)</code> and <code>CTZ(x)</code> are 8 when <code>x</code> is 0. The width is the type’s, as for <code>ROL</code>; an untyped constant has none, so <code>CLZ(1)</code> is an error, and <code>CLZ(U64(1))</code> is 63. <code>POPCOUNT(x)</code> may also take a set, and counts its members. <code>MIN(T)</code> and <code>MAX(T)</code> are the smallest and the largest value of the integer type <code>T</code>, untyped constants: <code>MAX(U8)</code> is 255 and <code>MIN(I16)</code> is -32768; <code>MAX(U64)</code> and <code>MAX(UINT)</code>, above the largest <code>I64</code>, have their own type, as a hexadecimal number above it has (section 2). Each of the five, given constants, is a constant (section 4).</p>
339<p><code>ABS(x)</code> (section 6.8) is <code>x</code> without its sign, of <code>x</code>’s type, for an integer or a real. For a signed integer it is <code>-x</code> if <code>x &lt; 0</code>, so the smallest value of the type gives itself, as <code>-x</code> does; for an unsigned type it is <code>x</code>. For a real it clears the sign bit: <code>ABS(-0.0)</code> is 0.0, <code>ABS</code> 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, <code>ABS(-5)</code> is 5, and a result beyond the <code>I64</code>s, <code>ABS(MIN(I64))</code>, is an error, as for any arithmetic on untyped constants (section 2).</p>
340<p>Relations compare as signed or unsigned according to the type.</p>
341<h2 id="booleans">6.2 Booleans</h2>
342<p><code>and</code> and <code>or</code> evaluate their right operand only when it decides the result. <code>not</code> negates, and <code>=</code> and <code>#</code> compare; <code>#</code> is “different”.</p>
343<h2 id="reals">6.3 Reals</h2>
344<p><code>+ - * /</code> and the relations work on <code>F32</code> and on <code>F64</code>. Both operands have the same type, or one is a real constant, which takes the other’s type (section 2). The result has that type: <code>F32</code> arithmetic is done in single precision, rounded at each step as C rounds <code>float</code>. A constant expression of reals is evaluated in double precision, then rounded once to the type it takes.</p>
345<p>Relations are IEEE 754’s: a NaN is equal to nothing, itself included, so for a NaN <code>x</code>, <code>x # x</code> is true and every other relation with it is false. Dividing by zero gives an infinity or a NaN; arithmetic on reals never stops the program.</p>
346<h2 id="pointers-1">6.4 Pointers</h2>
347<ul>
348<li><code>p^</code> is the variable <code>p</code> points at.</li>
349<li><code>p + i</code> and <code>p - i</code>, with <code>i</code> an integer, move <code>p</code> by <code>i</code> elements: by <code>i * SIZE(T)</code> bytes for <code>p: ^T</code>.</li>
350<li><code>p - q</code>, with both of the same pointer type, is the number of elements between them, an <code>INT</code>.</li>
351<li><code>p[i]</code> is <code>(p + i)^</code>. <code>p[lo..hi]</code> is the slice of the <code>hi - lo</code> elements from <code>p + lo</code>. Neither is checked against a length, which a pointer doesn’t have, but a slice of a pointer that runs backwards, <code>hi &lt; lo</code>, 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 <code>p^[i]</code>.</li>
352<li>Pointers compare with <code>= # &lt; &lt;= &gt; &gt;=</code> as unsigned addresses. Procedure values compare with <code>=</code> and <code>#</code> only.</li>
353</ul>
354<p><code>p + i</code>, <code>p - i</code>, <code>p[i]</code> and <code>p[lo..hi]</code> reach memory no variable of the program names, and are allowed only in a module that imports <code>SYSTEM</code> (section 3). <code>p^</code>, <code>p - q</code> and comparing are allowed in any.</p>
355<h2 id="arrays-and-slices">6.5 Arrays and slices</h2>
356<p><code>a[i]</code> is an element of an array or slice, and <code>a[lo..hi]</code> is the slice of the elements from <code>lo</code> up to but not including <code>hi</code>. Both are checked: <code>i</code> must be below the length, and <code>0 &lt;= lo &lt;= hi &lt;= length</code>. A check that fails prints to standard error where it is, as file, line and column, and what failed, with the values involved (<code>index 7 is out of range for a length of 5</code>), 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 <code>I8</code>, or a <code>U64</code> past the length, fails like any other. A module that says <code>check off;</code> (section 3) leaves these checks out of its code.</p>
357<p><strong>Literals.</strong> <code>[e1, e2, ...]</code> builds an array, and <code>{f: e, g: e, ...}</code> 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 <code>[n]T</code> has exactly <code>n</code> of them. A record literal names its fields, in any order, each at most once; the fields it leaves out are zero, so <code>{}</code> 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, <code>[]</code>, is the empty slice, as a slice variable starts (section 4), and no variable at all.</p>
358<pre><code>c := {ch: &#39;A&#39;, attr: 7};
359Fmt.print(&quot;{} of {}\n&quot;, [Fmt.int(n), Fmt.int(m)]);</code></pre>
360<p><strong>Arrays and strings compare.</strong> Two operands that are each a <code>[]T</code> or a <code>[n]T</code>, of the same element type <code>T</code>, are <code>=</code> when they have the same length and the same elements, and <code>#</code> otherwise, where <code>T</code> is an integer type, <code>BOOL</code>, an enumeration, a set or a pointer type. A string literal compares as a <code>[]const U8</code>. The comparison is code of its own where it stands, a check of the lengths and then of the bytes, not a call.</p>
361<p>Arrays of reals don’t compare this way, since <code>-0.0 = 0.0</code> 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 <code>Str.cmp</code>.</p>
362<h2 id="enumerations-and-sets-1">6.6 Enumerations and sets</h2>
363<p>Enumerations compare with all six relations, by position, and an enumeration can be the variable of a <code>for</code> loop and the expression of a <code>match</code> (section 7.4).</p>
364<p><code>{red, blue}</code> is a set, of the set type of its names’ enumeration; <code>{}</code> is the empty set, where the type it must have is known. On two sets of the same type, <code>+</code> is union, <code>*</code> intersection and <code>-</code> difference; <code>=</code> and <code>#</code> compare, and <code>&lt;=</code> and <code>&gt;=</code> are “is a subset of” and “is a superset of”. <code>x in s</code> is <code>true</code> if <code>x</code>, a value of the enumeration, is in the set <code>s</code>.</p>
365<h2 id="conversions">6.7 Conversions</h2>
366<p>A type name applied like a procedure converts: <code>I32(x)</code>, <code>F64(n)</code>, <code>^Cell(addr)</code>. A pointer type written out uses the <code>^</code> form of the grammar: <code>^VOLATILE U32(0FEE00000H)</code>.</p>
367<table>
368<thead>
369<tr>
370<th>From</th>
371<th>To</th>
372<th>Result</th>
373</tr>
374</thead>
375<tbody>
376<tr>
377<td>integer</td>
378<td>integer</td>
379<td>the value cut to the new width, or extended by its sign (signed) or zeros (unsigned)</td>
380</tr>
381<tr>
382<td>integer</td>
383<td><code>F32</code>, <code>F64</code></td>
384<td>the nearest real</td>
385</tr>
386<tr>
387<td><code>F32</code>, <code>F64</code></td>
388<td>integer</td>
389<td>rounded toward zero; a NaN, or a real out of the range of <code>I64</code>, gives the smallest <code>I64</code>, then cut</td>
390</tr>
391<tr>
392<td><code>F32</code></td>
393<td><code>F64</code></td>
394<td>the same value</td>
395</tr>
396<tr>
397<td><code>F64</code></td>
398<td><code>F32</code></td>
399<td>the nearest <code>F32</code>; too big a value gives an infinity</td>
400</tr>
401<tr>
402<td>enumeration</td>
403<td>integer</td>
404<td>its position</td>
405</tr>
406<tr>
407<td>integer</td>
408<td>enumeration</td>
409<td>the name at that position; a position out of range is a failed check (6.5), and in a constant an error</td>
410</tr>
411<tr>
412<td><code>BOOL</code></td>
413<td>integer</td>
414<td>0 for <code>false</code>, 1 for <code>true</code></td>
415</tr>
416<tr>
417<td>set</td>
418<td>integer</td>
419<td>its bits</td>
420</tr>
421<tr>
422<td>integer</td>
423<td>set</td>
424<td>the low bits, as many as the set has</td>
425</tr>
426<tr>
427<td><code>INT</code>, <code>UINT</code></td>
428<td>pointer, procedure</td>
429<td>the address</td>
430</tr>
431<tr>
432<td>pointer, procedure</td>
433<td><code>INT</code>, <code>UINT</code></td>
434<td>the address</td>
435</tr>
436<tr>
437<td>pointer, procedure</td>
438<td>pointer, procedure</td>
439<td>the same address, seen as the new type</td>
440</tr>
441</tbody>
442</table>
443<p>There are no others: none from an integer to <code>BOOL</code> (<code>x # 0</code> says it), none between pointers and integers other than <code>INT</code> and <code>UINT</code>, and none to or from records, arrays, slices, variants or <code>ERROR</code>. 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 <code>SYSTEM</code> (section 3). An untyped integer constant converts to a pointer as an <code>INT</code> does, as in <code>^VOLATILE U32(0FEE00000H)</code>; it isn’t assigned to a pointer without the conversion. A conversion of a constant is made by the compiler, by the same rules: <code>U8(300)</code> is 44. <code>U64(a = b)</code> is 0 or 1, and <code>0 - U64(a = b)</code> is a mask; this is how a comparison is used with no <code>if</code>.</p>
444<h2 id="built-in-procedures">6.8 Built-in procedures</h2>
445<table>
446<thead>
447<tr>
448<th>Call</th>
449<th>Result</th>
450</tr>
451</thead>
452<tbody>
453<tr>
454<td><code>SIZE(T)</code></td>
455<td>the size of type <code>T</code> in bytes, an untyped constant; <code>T</code> is a type, not a variable</td>
456</tr>
457<tr>
458<td><code>SIZE(T.f)</code></td>
459<td>the size of field <code>f</code> of the record type <code>T</code>, an untyped constant</td>
460</tr>
461<tr>
462<td><code>OFFSET(T, f)</code></td>
463<td>the byte offset of field <code>f</code> in the record type <code>T</code>, an untyped constant</td>
464</tr>
465<tr>
466<td><code>SYSTEM.ADR(x)</code></td>
467<td>the address of variable <code>x</code>, a <code>^T</code></td>
468</tr>
469<tr>
470<td><code>LEN(a)</code></td>
471<td>the number of elements of an array or a string constant (an untyped constant) or of a slice (an <code>INT</code>)</td>
472</tr>
473<tr>
474<td><code>SYSTEM.PTR(s)</code></td>
475<td>the address the slice <code>s</code> starts at, a <code>^T</code> for <code>s: []T</code> or <code>[]const T</code>, unchecked; for an array <code>a</code>, that of <code>a[0..LEN(a)]</code></td>
476</tr>
477<tr>
478<td><code>BYTES(x)</code></td>
479<td>the bytes of <code>x</code> as a <code>[]U8</code>: for a slice <code>s: []T</code>, its <code>LEN(s) * SIZE(T)</code> bytes, a <code>[]const U8</code> for a <code>[]const T</code>; for a variable of any other type <code>T</code>, its <code>SIZE(T)</code> bytes</td>
480</tr>
481<tr>
482<td><code>NEW(p, a)</code></td>
483<td>sets <code>p: ^T</code> to a fresh, zeroed <code>T</code> from the allocator <code>a: ^Mem.Allocator</code>, or to <code>nil</code> if <code>a</code> has no room</td>
484</tr>
485<tr>
486<td><code>MSG(e)</code></td>
487<td>the message of the error <code>e</code>, a <code>[]const U8</code></td>
488</tr>
489<tr>
490<td><code>COPY(d, s)</code></td>
491<td>copies the elements of <code>s</code> to the start of <code>d</code>, both arrays or slices of one type <code>T</code>; <code>LEN(s)</code> must be at most <code>LEN(d)</code></td>
492</tr>
493<tr>
494<td><code>FILL(d, x)</code></td>
495<td>sets every element of <code>d</code>, an array or a slice of elements of type <code>T</code>, to <code>x</code>, a value of <code>T</code></td>
496</tr>
497<tr>
498<td><code>SYSTEM.SYSCALL(n, x1, ..., x6)</code></td>
499<td>Linux system call <code>n</code> with up to six arguments, each a pointer or an integer no wider than <code>INT</code>; the raw result, an <code>INT</code> (a negative number is <code>-errno</code>)</td>
500</tr>
501<tr>
502<td><code>INC(v)</code>, <code>INC(v, k)</code></td>
503<td>adds 1, or <code>k</code>, to the integer variable <code>v</code>; it wraps, like <code>+</code></td>
504</tr>
505<tr>
506<td><code>DEC(v)</code>, <code>DEC(v, k)</code></td>
507<td>subtracts 1, or <code>k</code>, from <code>v</code></td>
508</tr>
509<tr>
510<td><code>FENCE</code></td>
511<td>a full memory barrier</td>
512</tr>
513<tr>
514<td><code>CAS(v, old, new)</code></td>
515<td>if <code>v = old</code>, sets <code>v := new</code> and returns <code>true</code>; atomically</td>
516</tr>
517<tr>
518<td><code>XCHG(v, x)</code></td>
519<td>sets <code>v := x</code> and returns the value before, atomically</td>
520</tr>
521<tr>
522<td><code>XADD(v, x)</code></td>
523<td>adds <code>x</code> to <code>v</code> and returns the value before, atomically</td>
524</tr>
525<tr>
526<td><code>ABS(x)</code></td>
527<td><code>x</code> without its sign, of <code>x</code>’s type; for an integer, <code>-x</code> if <code>x &lt; 0</code>, so the smallest <code>I64</code> gives itself, as <code>-x</code> does; for a real, the sign cleared; <code>x</code> of a numeric type (section 6.1)</td>
528</tr>
529<tr>
530<td><code>ROL(x, n)</code>, <code>ROR(x, n)</code></td>
531<td><code>x</code> rotated left, or right, by <code>n</code> bits modulo its width; <code>x</code> of an unsigned integer type (section 6.1)</td>
532</tr>
533<tr>
534<td><code>CLZ(x)</code>, <code>CTZ(x)</code></td>
535<td>the number of zero bits above the highest one in <code>x</code>, or below the lowest one, an <code>INT</code>; the width of <code>x</code>’s type if <code>x</code> is 0; <code>x</code> of an unsigned integer type</td>
536</tr>
537<tr>
538<td><code>POPCOUNT(x)</code></td>
539<td>the number of one bits in <code>x</code>, or of members of the set <code>x</code>, an <code>INT</code>; <code>x</code> of an unsigned integer type or a set</td>
540</tr>
541<tr>
542<td><code>MIN(T)</code>, <code>MAX(T)</code></td>
543<td>the smallest, or the largest, value of the integer type <code>T</code>, an untyped constant; any other type is an error</td>
544</tr>
545<tr>
546<td><code>ARGC()</code></td>
547<td>the number of command line arguments, an <code>INT</code></td>
548</tr>
549<tr>
550<td><code>SYSTEM.ARGV()</code></td>
551<td>the arguments, a <code>^^U8</code> (C strings)</td>
552</tr>
553</tbody>
554</table>
555<p><code>SYSTEM.SYSCALL</code> exists only on Linux targets. Other systems have no stable system call interface, and their modules call the C library instead (section 9).</p>
556<p><code>NEW(p, a)</code> calls <code>a^.alloc(a, SIZE(T), A)</code>, where <code>A</code> is the alignment of <code>T</code>, and zeroes the bytes it gets if they aren’t <code>nil</code>. <code>Mem.Allocator</code> (the library, <code>doc/raz-lib.md</code>) is the one type of the library the language names.</p>
557<p><code>SIZE(T.f)</code> and <code>OFFSET(T, f)</code> ask about a type’s field, not about storage, so <code>SIZE</code> still takes no variable. <code>f</code> is one field name: not a path, <code>a.b</code>, 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 <code>offsetof</code> and <code>sizeof</code>.</p>
558<p><code>BYTES(x)</code> is the bytes of <code>x</code>, as a <code>[]U8</code> that can be read and written: for a slice <code>s: []T</code>, the <code>LEN(s) * SIZE(T)</code> bytes it holds; for a variable of any other type <code>T</code>, its <code>SIZE(T)</code> bytes.</p>
559<pre><code>n := Sys.write(fd, BYTES(samples)); (* samples: []I32 *)
560n := Sys.read(fd, BYTES(h)); (* fills h: Header, a record *)</code></pre>
561<p><code>T</code> must be a type a view may take (section 6.9), since writing through the slice must not make a value mean nothing: a <code>BOOL</code>, a set, an enumeration, a slice, a variant, a procedure type, <code>ERROR</code>, or a record or array holding one, is an error; and, outside a module that imports <code>SYSTEM</code>, 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 <code>SYSTEM.PTR(s)</code> gives them, whatever holds the slice, and can be written only if the slice can. Of any other variable they are its own, as <code>SYSTEM.ADR</code> gives them: a <code>const</code> parameter, another module’s variable, a view and a field of a packed record are errors, as they are for <code>SYSTEM.ADR</code>, and so is a volatile variable. <code>x</code> must be a variable: a constant, a string constant too, is an error. The bytes are in the target’s order (appendix A).</p>
562<p><code>SYSTEM.PTR(s)</code> is the first of the two words of <code>s</code> (section 5.3), and is not checked. For a slice that isn’t empty it is <code>SYSTEM.ADR(s[0])</code>; for an empty one, where <code>s[0]</code> would stop the program, it is what the slice holds: <code>nil</code> for a slice variable as it starts (section 4) and for <code>[]</code>, and for one cut empty from another, <code>t[3..3]</code>, 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:</p>
563<pre><code>type Value = record n: INT; p: ^U8; end;
564
565proc valueOf(s: []const U8): Value;
566begin
567 return {n: LEN(s), p: SYSTEM.PTR(s)}; (* &quot;&quot; too *)
568end;</code></pre>
569<p>and <code>v.p[0..v.n]</code> is the slice again (section 6.4), empty when <code>v.n</code> is 0, whatever <code>v.p</code> is. Reading through the pointer is as unchecked as through any pointer. <code>SYSTEM.PTR(a)</code> of an array may be taken wherever the slice <code>a[0..LEN(a)]</code> may be made, and is an error wherever it may not.</p>
570<p><code>COPY</code> is a statement, as <code>INC</code> is. It copies the bytes of <code>LEN(s)</code> elements as one block, as an assignment of an array does, and is right when <code>d</code> and <code>s</code> overlap, as in <code>COPY(a[1..n], a[0..n - 1])</code>. It is checked as a slice is: past <code>LEN(d)</code>, it stops the program, unless the module says <code>check off;</code>.</p>
571<p><code>FILL</code> is a statement too. <code>d</code> is written as <code>COPY</code>’s destination is, and <code>x</code> is assigned to each element as by <code>:=</code>:</p>
572<pre><code>FILL(row[a..b], U32(bg)); (* a row of pixels *)
573FILL(window, 0.0); (* window: [576]F32 *)</code></pre>
574<p>It is no wipe: it may be left out when nothing reads what it wrote, as any write may (section 7.6).</p>
575<p><code>INC</code> and <code>DEC</code> evaluate <code>v</code> once, so <code>INC(a[f(i)])</code> calls <code>f</code> once. They read <code>v</code> and then write it: two accesses, even through a <code>^VOLATILE</code> pointer, and not atomic; <code>XADD</code> is the atomic one.</p>
576<p>For <code>CAS</code>, <code>XCHG</code> and <code>XADD</code>, <code>v</code> is a variable, as for <code>INC</code>, of type <code>INT</code>, <code>UINT</code> or a pointer type (<code>INT</code> or <code>UINT</code> for <code>XADD</code>), on every target, and may be volatile: a counter shared between threads is <code>XADD(count, 1)</code>, one reached through a pointer <code>XADD(p^, 1)</code>. 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 <code>SYSTEM.ADR</code>. 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</p>
577<p>A view reads and writes the bytes of a variable as a value of another type. <code>v.(T)</code>, with <code>v</code> a variable, is the <code>T</code> whose bytes start where <code>v</code> starts:</p>
578<pre><code>var mem: [4096]U8; n: I64; x: F64; bits: U64;
579
580mem[16].(I64) := -1; (* the 8 bytes mem[16] to mem[23] now hold -1 *)
581n := mem[16].(I64); (* and are read back as an I64: n is -1 *)
582bits := x.(U64); (* the 8 bytes of x, as a U64 *)</code></pre>
583<p>A view is a variable, not a value: <code>mem[16].(I64)</code> is made of the 8 bytes <code>mem[16]</code> to <code>mem[23]</code>, as <code>p^</code> is the variable <code>p</code> points at. Reading it reads those bytes; assigning it writes them, and so changes <code>mem</code>. Nothing is copied to make it. It stands wherever a variable may: on the left of <code>:=</code>, as the variable of <code>INC</code>, and with selectors after it:</p>
584<pre><code>type Header = record magic: U32; count: U32; end;
585var buf: [512]U8; k: U32;
586
587k := buf[0].(Header).count; (* bytes 4 to 7 of buf, as a U32 *)
588buf[0].(Header).count := 0;
589INC(mem[a].(I64), 8);</code></pre>
590<p><strong>A view isn’t a conversion.</strong> A conversion works on a value, a view on bytes. With <code>x: F64</code> holding 1.5, <code>I64(x)</code> is 1, the number rounded toward zero, while <code>x.(I64)</code> is 3FF8000000000000H, the bits that hold 1.5. With <code>n: I64</code> holding 258, <code>U8(n)</code> is 2, the number cut to its low byte, while <code>n.(U8)</code> is the first byte of <code>n</code> 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.</p>
591<p><strong>The types.</strong> <code>T</code> 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. <code>BOOL</code>, an enumeration, a set, a slice, a variant, a procedure type and <code>ERROR</code> 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: <code>Colour(mem[a])</code>. <code>v</code> 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.</p>
592<p>A view makes values from bytes, so where those bytes could be made into an address the module must import <code>SYSTEM</code> (section 3): a view whose <code>T</code> holds a pointer, and a view written over a variable <code>v</code> whose type holds anything but integers and reals, which would change a pointer, a <code>BOOL</code> or a slice behind its type. Reading any variable through a view of integers and reals is allowed in any module.</p>
593<p><strong>Where its bytes lie.</strong> The <code>T</code> lies within the variable <code>v</code> is part of:</p>
594<ul>
595<li>for an element of an array or a slice, <code>a[i].(T)</code>, from that element to the end of <code>a</code>: <code>mem[4088].(I64)</code> is the last 8 bytes of <code>mem</code>, and <code>mem[4090].(I64)</code> would run 2 bytes past its end;</li>
596<li>for anything else, within <code>v</code> itself: <code>x.(U64)</code> is allowed only if <code>x</code> has at least 8 bytes.</li>
597</ul>
598<p>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 <code>check off;</code>. An element reached through a pointer, <code>p[i].(T)</code>, is checked no more than <code>p[i]</code> is, since a pointer has no length.</p>
599<p><strong>Any address.</strong> The <code>T</code> may start at any byte: <code>mem[3].(I64)</code> is an <code>I64</code> whose first byte is <code>mem[3]</code>. 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: <code>SYSTEM.ADR</code> of it, a <code>var</code> 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 <code>^VOLATILE</code> pointer to a record of them.</p>
600<p><strong>Byte order.</strong> 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 <code>Str.le</code>, <code>Str.be</code> and the like (section 5.5), if the program is to read it right on every target.</p>
601<p><strong>Before views.</strong> A program used to make a pointer for each access, and may still: <code>mem[a].(I64) := n</code> does what</p>
602<pre><code>p := ^I64(SYSTEM.ADR(mem[a]));
603p^ := n;</code></pre>
604<p>does, but with <code>a</code> checked against the length of <code>mem</code>, no pointer variable, and no address of a word that may be misaligned, and no <code>import SYSTEM</code>.</p>
605<p><code>v</code> is evaluated once, and its check made, before the bytes are read or written.</p>
606<h1 id="statements">7. Statements</h1>
607<pre><code>Statements = { Statement &quot;;&quot; } .
608Statement = Designator [ &quot;:=&quot; Expr ]
609 | &quot;_&quot; &quot;:=&quot; Expr
610 | Target &quot;,&quot; Target { &quot;,&quot; Target } &quot;:=&quot; Expr
611 | &quot;if&quot; Expr &quot;then&quot; Statements
612 { &quot;elsif&quot; Expr &quot;then&quot; Statements } [ &quot;else&quot; Statements ] &quot;end&quot;
613 | &quot;while&quot; Expr &quot;do&quot; Statements &quot;end&quot;
614 | &quot;repeat&quot; Statements &quot;until&quot; Expr
615 | &quot;for&quot; ident &quot;:=&quot; Expr &quot;to&quot; Expr [ &quot;by&quot; Expr ] &quot;do&quot; Statements &quot;end&quot;
616 | &quot;match&quot; Expr &quot;of&quot; { &quot;|&quot; Arm } &quot;end&quot;
617 | &quot;return&quot; [ Expr { &quot;,&quot; Expr } ]
618 | &quot;break&quot;
619 | &quot;continue&quot;
620 | &quot;defer&quot; Statement
621 | &quot;try&quot; Designator .
622Arm = ( ident { &quot;.&quot; ident } [ &quot;(&quot; ident { &quot;,&quot; ident } &quot;)&quot; ]
623 | Label { &quot;,&quot; Label } | &quot;else&quot; ) &quot;:&quot; Statements .
624Label = Expr [ &quot;..&quot; Expr ] .
625Target = Designator | &quot;_&quot; .</code></pre>
626<p>Every statement ends in <code>;</code>, including the ones that end in <code>end</code> or <code>until</code>.</p>
627<h2 id="assignment-and-calls">7.1 Assignment and calls</h2>
628<p><code>x := e</code> evaluates <code>e</code> and stores it in <code>x</code>; arrays, records, slices and variants are copied. A designator on its own is a call, and any result it returns is dropped: <code>Out.ln;</code>, <code>write(fd, buf);</code>.</p>
629<p><code>a, b := f(x);</code> assigns the results of a procedure that returns several (section 8), in order.</p>
630<p>The blank, <code>_</code>, drops what would be assigned to it: <code>_ := e;</code> evaluates <code>e</code> and drops it, and <code>n, _ := f(x);</code> keeps the first result and drops the second. What is dropped is still evaluated as any expression is: its calls are made, and a volatile variable in it is read (section 7.6). A result dropped by a call standing on its own is a lint an implementation may warn of (section 10); one dropped through <code>_</code> says it is meant.</p>
631<h2 id="conditions-and-loops">7.2 Conditions and loops</h2>
632<p><code>if</code>, <code>while</code> and <code>repeat</code> take <code>BOOL</code> expressions. <code>repeat</code> runs its body at least once and stops when the condition is true.</p>
633<p><code>for i := a to b by s do ... end;</code> sets <code>i</code> to <code>a</code>, <code>a + s</code>, … while <code>i &lt;= b</code> (or <code>i &gt;= b</code> if <code>s</code> is negative). <code>i</code> is a variable of an integer or enumeration type, named by its name alone; <code>a</code> and then <code>b</code> are evaluated once, before the first round; <code>s</code> is a constant other than zero, and 1 if left out. <code>a</code> and <code>b</code> have <code>i</code>’s type, or are untyped constants that take it, or are <code>INT</code>s that widen to an <code>I64</code> <code>i</code>, as with <code>+</code> (section 6.1): so in <code>for i := 0 to LEN(s) - 1</code>, <code>i</code> is an <code>INT</code> or an <code>I64</code>.</p>
634<p>The loop never steps past <code>b</code>, so <code>i</code> can’t wrap: afterwards <code>i</code> holds the last value it took, or <code>a</code> if the body never ran. The body may assign <code>i</code>. Precisely, for a positive <code>s</code>: at the end of a round, if <code>i &lt;= b</code> and <code>b - i &lt; s</code>, the loop ends with <code>i</code> as it is; otherwise <code>i</code> becomes <code>i + s</code>, wrapping, and the loop goes on while <code>i &lt;= b</code>. A negative <code>s</code> is the same, the other way round.</p>
635<p><code>break</code> ends the innermost <code>while</code>, <code>repeat</code> or <code>for</code> it stands in, and the program goes on after it. <code>continue</code> ends the round of the innermost one, as reaching the end of its body would: a <code>while</code> tests its condition again, a <code>repeat</code> tests its <code>until</code>, and a <code>for</code> steps its variable, or ends. There is no <code>goto</code>.</p>
636<p>A <code>continue</code> passes over the rest of the body, the step of a <code>while</code> or a <code>repeat</code> included, if it stands there: so the step comes first.</p>
637<pre><code>while i &lt; LEN(t) do
638 ch, n := Str.decode(t[i..LEN(t)]);
639 i := i + n; (* before any continue *)
640 if ch = 0ADH then continue; end; (* a soft hyphen, passed over *)
641 ...
642end;</code></pre>
643<h2 id="return">7.3 Return</h2>
644<p><code>return e;</code> ends the procedure with the result <code>e</code>; <code>return a, b;</code> with several results; <code>return f(x);</code> with the several results of <code>f</code>, if they are the procedure’s own (section 8); <code>return;</code> 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).</p>
645<p>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 <code>[]</code>, or an array a call returns, or a slice of one, or the <code>BYTES</code> of a local variable, a field or an element of one included:</p>
646<pre><code>proc short(h: Hex): []U8; (* Hex = [64]U8 *)
647begin
648 return h[0..8]; (* an error: h is the procedure&#39;s copy *)
649end;</code></pre>
650<p>A slice of a <code>var</code> or <code>const</code> 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 <code>const</code> 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 <code>var</code> parameter does to the caller whose local it is.</p>
651<h2 id="match">7.4 Match</h2>
652<pre><code>match s of
653| circle(r): area := 3.14159 * r * r;
654| rect(w, h): area := w * h;
655| dot: area := 0.0;
656end;</code></pre>
657<p><code>match</code> takes a variant, an enumeration, an integer type (a <code>U8</code> included) or a string, a <code>[]U8</code> or a <code>[]const U8</code>; other types are an error. It runs the arm of the case <code>s</code> holds. An arm may name the case’s fields, in order, all of them; the names stand for those fields of <code>s</code> itself, so assigning to one changes <code>s</code>; if <code>s</code> is a constant or a <code>const</code> parameter, they can’t be assigned; if <code>s</code> 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 <code>| else:</code> arm, which must come last.</p>
658<p><code>match</code> 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:</p>
659<pre><code>match op of
660| sPlus, sMinus: kind := additive;
661| sTimes: kind := multiplicative;
662| else:
663end;</code></pre>
664<p>Every name must have an arm, and only one, unless there is an <code>| else:</code> arm. A variant’s arm names one case: the fields it may name belong to that case alone.</p>
665<p>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 (<code>done</code>, <code>Kind.done</code>, <code>Xml.done</code>, <code>Xml.Kind.done</code>), and a qualified name must be a case of the matched type.</p>
666<p><code>match</code> on an integer runs the arm whose labels hold its value:</p>
667<pre><code>match ch of
668| &#39; &#39;, &#39;\t&#39;: skip := true;
669| &#39;0&#39; .. &#39;9&#39;: digit := true;
670| else:
671end;</code></pre>
672<p>A label is a constant, or <code>lo .. hi</code>, the constants from <code>lo</code> to <code>hi</code>, both included (unlike a slice, which leaves <code>hi</code> out; <code>lo</code> may not be above <code>hi</code>). Each must fit the integer’s type, and no value may be in two labels. An integer <code>match</code> must have an <code>| else:</code> arm, which may be empty.</p>
673<p><code>match</code> on a string, a <code>[]U8</code>, a <code>[]const U8</code> or what converts to one (section 5.10), runs the arm one of whose labels it equals, as <code>=</code> compares strings (section 6.5):</p>
674<pre><code>match word of
675| &quot;add&quot;, &quot;plus&quot;: op := add;
676| &quot;sub&quot;: op := sub;
677| else: op := none;
678end;</code></pre>
679<p>A label is a string constant, and no two labels may be equal; there are no ranges. A <code>match</code> on a string must have an <code>| else:</code> arm, which may be empty. Whether an arm names a case or gives labels is set by the type matched: <code>| Max:</code> is a case of a variant or an enumeration, and a constant for an integer or a string.</p>
680<h2 id="order-of-evaluation">7.5 Order of evaluation</h2>
681<p>Operands, arguments and the designators of an assignment are evaluated from left to right, and the designators of an assignment before its right side: <code>a[i()] := g()</code> calls <code>i</code> and then <code>g</code>.</p>
682<h2 id="volatile">7.6 Volatile</h2>
683<p>A variable reached through a <code>^VOLATILE T</code> 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.</p>
684<p>A <code>^VOLATILE T</code> doesn’t convert to <code>^T</code> without a written conversion, and a volatile variable isn’t passed as a <code>var</code> argument, which would lose its volatility.</p>
685<p><code>FENCE</code> also orders the program’s ordinary accesses against those of other processors and devices.</p>
686<p><strong>Ordinary variables.</strong> Only volatile accesses, <code>CAS</code>, <code>XCHG</code>, <code>XADD</code> and <code>FENCE</code> 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 <code>FENCE</code> 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 <code>ERROR</code> 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.</p>
687<h2 id="defer">7.7 Defer</h2>
688<p><code>defer s;</code> runs the statement <code>s</code> when the program leaves the statement list the <code>defer</code> stands in: at its end, or by a <code>return</code>, or by a <code>break</code> or <code>continue</code> out of it. Statements deferred in the same list run in the opposite order to their <code>defer</code>s, and only those whose <code>defer</code> has been reached run.</p>
689<pre><code>module Head;
690import Sys, Out;
691
692(* Prints the first line of the file at path. *)
693proc head(path: []const U8): BOOL;
694var fd, n, i: INT; buf: [256]U8;
695begin
696 fd := Sys.openRead(path);
697 if fd &lt; 0 then return false; end;
698 defer Sys.close(fd);
699 n := Sys.read(fd, buf);
700 if n &lt; 0 then return false; end;
701 for i := 0 to n - 1 do
702 if buf[i] = 10 then n := i; break; end;
703 end;
704 Out.str(buf[0..n]);
705 Out.ln;
706 return true;
707end;
708
709proc main*;
710begin
711 if not head(&quot;/etc/hostname&quot;) then Out.str(&quot;no hostname\n&quot;); end;
712end;
713
714end Head.</code></pre>
715<p><code>return e;</code> evaluates <code>e</code> before the deferred statements run. A deferred statement can’t contain <code>defer</code>, nor a <code>return</code>, <code>break</code>, <code>continue</code> or <code>try</code> that would leave it. A failed check, <code>Rt.exit</code> and <code>Sys.exit</code> end the program without running the deferred statements still pending.</p>
716<h2 id="try">7.8 Try</h2>
717<p>A procedure that can fail returns an <code>ERROR</code> as its last result (section 5.8), <code>nil</code> when it didn’t. A caller that can’t deal with the failure passes it on to its own caller, which <code>try</code> does in a word:</p>
718<pre><code>proc total(words: [][]U8): (INT, ERROR);
719var i, sum: INT;
720begin
721 for i := 0 to LEN(words) - 1 do
722 sum := sum + try number(words[i]);
723 end;
724 return sum, nil;
725end;</code></pre>
726<p><code>try c</code>, where <code>c</code> is a call (below) of a procedure whose last result is an <code>ERROR</code>, makes the call and looks at that error. If it is <code>nil</code>, the program goes on, and <code>try c</code> is what <code>c</code> returned without the error. If it isn’t, the procedure <code>try</code> stands in returns at once, as <code>return</code> does (section 7.3): its last result is that error, and every other result is zero, as a variable of its type starts (section 4). Nothing more of the statement <code>try</code> stands in is done; in the example, <code>sum</code> isn’t assigned. So</p>
727<pre><code>x := try f(a);</code></pre>
728<p>is, with <code>e</code> a variable the program can’t name, and <code>0</code> standing for a zero of each of the procedure’s other results:</p>
729<pre><code>x, e := f(a);
730if e # nil then return 0, e; end;</code></pre>
731<p>The error is the one <code>c</code> returned, and compares with <code>=</code> as it did there. <code>try</code> has no handler and keeps no state: it is a <code>return</code>, written where the call is, so that every place a procedure can leave is in its text. A program that means to deal with an error tests it, as section 5.8 shows.</p>
732<p><strong>What <code>try</code> is applied to.</strong> <code>c</code> is a designator that ends in a call: <code>f(x)</code>, <code>Mod.f(x)</code>, <code>p^.next(x)</code>, or a call through a variable of procedure type. Where the procedure has no parameters its parentheses may be left out, as in a statement (section 7.1), and <code>try</code> calls it: <code>try setup;</code>. A conversion, a built-in procedure (section 6.8) and the case of a variant are written like calls and aren’t procedures’; <code>try</code> can’t be applied to them.</p>
733<p><strong>What <code>try c</code> is.</strong> <code>c</code>’s results but the last.</p>
734<ul>
735<li>With none, <code>try c</code> isn’t a value and stands only as a statement: <code>try flush;</code>.</li>
736<li>With one, it is a value of that type, an operand wherever <code>c</code> would be: <code>n := try number(s);</code>, <code>sum + try number(s)</code>, <code>if try ready(fd) then</code>. Like <code>not</code>, it applies to the factor after it: <code>try f(x) + 1</code> is <code>(try f(x)) + 1</code>.</li>
737<li>With several, it stands only on the right of a multiple assignment, as <code>c</code> itself would, with a target for each: <code>a, b := try f(x);</code>.</li>
738</ul>
739<p>As a statement, <code>try c;</code> drops the values of <code>c</code> that it has, and a dropped value is a lint, as a call that drops a result is (section 10); <code>_ := try c;</code> and <code>a, _ := try c;</code> say it is meant (section 7.1). The error is never dropped: <code>try</code> is the way of passing it on.</p>
740<p><strong>Where <code>try</code> may stand.</strong> Every use of <code>try</code> is an error unless:</p>
741<ul>
742<li>the procedure it stands in has an <code>ERROR</code> as its last result. A module’s body, and a procedure with no results, such as <code>proc main*;</code>, have none: there an error is dealt with where it is found, by a test;</li>
743<li>the last result of the procedure <code>c</code> calls is an <code>ERROR</code>;</li>
744<li>it is not inside a deferred statement, which <code>try</code> would leave (section 7.7).</li>
745</ul>
746<p>A generic module is checked in each instance (section 3), so a procedure of an instance whose last result, by its type arguments, is no <code>ERROR</code> and uses <code>try</code> is an error in that instance.</p>
747<p><strong>Order.</strong> The arguments of <code>c</code> are evaluated from left to right, then <code>c</code> is called, and then its error is looked at (section 7.5). The designators on the left of an assignment are evaluated before its right side as always, so in <code>a[i()] := try g()</code>, <code>i</code> is called, then <code>g</code>; if <code>g</code> fails, nothing is assigned. A <code>try</code> in the right operand of <code>and</code> or <code>or</code> is reached only when that operand is evaluated (section 6.2).</p>
748<p><strong>Deferred statements.</strong> When <code>try</code> returns, the statements deferred in the procedure and not yet run are run, the last first, as for a <code>return</code> (section 7.7), after the error and the zero results have been chosen; no deferred statement can change them.</p>
749<h1 id="procedures">8. Procedures</h1>
750<pre><code>ProcDeclaration = &quot;proc&quot; IdentDef Signature &quot;;&quot;
751 ( &quot;forward&quot; | { LocalDeclaration } &quot;begin&quot; Statements &quot;end&quot; [ ident ]
752 | &quot;code&quot; { [ ident &quot;:&quot; ] [ Instruction ] &quot;;&quot; } &quot;end&quot; [ ident ] ) .
753LocalDeclaration = &quot;const&quot; { ident [ &quot;:&quot; Type ] &quot;=&quot; Expr &quot;;&quot; }
754 | &quot;type&quot; { ident &quot;=&quot; Type &quot;;&quot; }
755 | &quot;var&quot; { ident { &quot;,&quot; ident } &quot;:&quot; Type &quot;;&quot; } .
756Signature = &quot;(&quot; [ Params { &quot;;&quot; Params } [ &quot;;&quot; &quot;...&quot; ] ] &quot;)&quot; [ &quot;:&quot; Results ]
757 | [ &quot;:&quot; Results ] .
758Params = [ &quot;var&quot; | &quot;const&quot; ] ident { &quot;,&quot; ident } &quot;:&quot; Type .
759Results = Type | &quot;(&quot; Type { &quot;,&quot; Type } &quot;)&quot; .</code></pre>
760<p>A procedure without parameters may leave out the parentheses, both where it is declared (<code>proc main*;</code>) and where it is called (<code>Out.ln</code>). Used without parentheses in an expression, a procedure is a procedure value, not a call.</p>
761<p><strong>Parameters.</strong> A value parameter is a copy: the procedure may change it, and the caller’s variable stays as it was. A <code>var</code> parameter is the caller’s variable itself; its argument must be a variable of exactly the parameter’s type.</p>
762<p>A <code>const</code> 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 <code>var</code> parameter, take the <code>SYSTEM.ADR</code> of either, write it through a view (section 6.9), or assign the names a <code>match</code> 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 <code>[]const T</code> (section 5.3), so it can’t write the caller’s array through it. <code>const</code> 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 <code>var</code> parameter, a pointer or another thread, the procedure sees the change.</p>
763<pre><code>type Parser = record args: [][]U8; at: INT; (* ... *) end;
764
765proc current(const p: Parser): []U8; (* reads p, many words, in place *)
766begin
767 return p.args[p.at];
768end;
769
770proc advance(var p: Parser); (* changes p *)
771begin
772 INC(p.at);
773end;</code></pre>
774<p>A procedure takes what it reads as a value when it is a single value or a slice, and as <code>const</code> when it is a record or an array; what it changes, as <code>var</code>; and a pointer only for what it keeps past the call, what may be <code>nil</code>, an allocator, or what C or the system takes.</p>
775<p><strong>Results.</strong> 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 <code>return</code> in a procedure whose results are of the same types, in the same order, which then returns them as they are: <code>return divmod(n, 2);</code>. A procedure that can fail has an <code>ERROR</code> as its last result (section 5.8), which <code>try</code> passes on (section 7.8).</p>
776<p>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):</p>
777<pre><code>s := f(&#39;a&#39;)[0..4]; (* f returns a [8]U8: s is good to the end of the procedure *)
778t := f(&#39;b&#39;)[0..4]; (* a hidden variable of its own: s is unchanged *)</code></pre>
779<pre><code>module Divide;
780import Out;
781
782proc divmod(a, b: I64): (I64, I64);
783begin
784 return a div b, a mod b;
785end;
786
787proc main*;
788var q, r: I64;
789begin
790 q, r := divmod(17, 5);
791 Out.int(q); Out.str(&quot; rest &quot;); Out.int(r); Out.ln;
792end;
793
794end Divide.</code></pre>
795<p><strong>forward.</strong> <code>proc f(x: I64): I64; forward;</code> declares <code>f</code> 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 <code>forward</code> with no body is an error.</p>
796<p>A name after a procedure’s <code>end</code>, if written, is the procedure’s own.</p>
797<p>Procedures don’t nest.</p>
798<p><strong>Code procedures.</strong> A procedure whose body is <code>code</code> is machine code, written by hand in the target’s assembly language (appendix A), in a module that imports <code>SYSTEM</code>: one instruction to each <code>;</code>, and labels for jumps, up to <code>end</code>:</p>
799<pre><code>proc rdtsc*: U64;
800code
801 rdtsc;
802 shl rdx, 32;
803 or rax, rdx;
804 ret;
805end rdtsc;</code></pre>
806<p>A label, <code>name:</code>, names the place of the instruction after it, within the procedure. A constant of the module may stand wherever a number does. A procedure or a global variable of the module, or one an imported module exports, by its qualified name, stands for its address in three places only: <code>call p;</code> and <code>jmp p;</code>, which reach it from where they are, and <code>lea r, [v];</code>, which puts its address in a register. A label of the procedure is found first. Nothing of its type is checked, and no other operand takes one. What is named is part of the program, as a procedure that is called is. Any bytes may be written with <code>db</code>, as in <code>db 0FH, 31H;</code>, for an instruction the assembler doesn’t know.</p>
807<p>It is called like any procedure, with the System V convention: integer and pointer arguments, and the addresses of <code>var</code> and <code>const</code> ones, arrive in <code>rdi</code>, <code>rsi</code>, <code>rdx</code>, <code>rcx</code>, <code>r8</code> and <code>r9</code>, <code>F32</code> and <code>F64</code> ones in <code>xmm0</code> to <code>xmm7</code>, and the result goes in <code>rax</code> (and <code>rdx</code> for a second) or <code>xmm0</code>. Its parameters and results are therefore of the types C can take (section 9), or slices, at most six integer and eight real parameters, and at most two results. A slice is two integers, as System V passes a struct of them: as a parameter its address arrives in one register and its length in the next, the two counting among the six; as the result its address goes in <code>rax</code> and its length in <code>rdx</code>, and it is the only result. The instructions are the whole procedure, <code>ret</code> included; they must keep <code>rbx</code>, <code>rbp</code>, <code>rsp</code> and <code>r12</code> to <code>r15</code> as they found them. The compiler doesn’t look past what they say.</p>
808<h1 id="calling-c">9. Calling C</h1>
809<pre><code>ExternDeclaration = &quot;extern&quot; ( &quot;proc&quot; IdentDef Signature
810 | &quot;var&quot; IdentDef &quot;:&quot; Type ) .</code></pre>
811<pre><code>link &quot;libX11.so.6&quot;;
812extern proc XOpenDisplay(name: ^U8): ^U8;
813extern proc printf(format: ^U8; ...): I32;
814extern var environ: ^^U8;</code></pre>
815<p>An <code>extern</code> procedure or variable is found by its name in the C libraries the program links, and is declared only in a module that imports <code>SYSTEM</code> (section 3), since C can reach any memory: the C library always, and each library named by <code>link</code>.</p>
816<p>An <code>extern</code> procedure’s parameters and result are integers, <code>BOOL</code>, <code>F32</code>, <code>F64</code>, pointers or procedures; a record goes to C by pointer, never by value. <code>...</code> accepts any number of further arguments of those types, and is allowed only in an <code>extern</code>. C takes no <code>float</code> there, so an <code>F32</code> given to <code>...</code> is an error: the program writes <code>F64(x)</code>. Past the parameters, a real constant goes as an <code>F64</code>, an integer constant as an <code>INT</code>, and a string literal as a pointer to its bytes followed by a zero byte.</p>
817<p>An <code>extern</code> 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 <code>errno</code>, can’t be reached this way; the C library has a procedure for it (<code>__errno_location</code>).</p>
818<p>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:</p>
819<pre><code>var ev: [24]I64; (* XEvent: 192 bytes *)
820...
821XNextEvent(dpy, SYSTEM.ADR(ev));
822if I32(ev[0]) = KeyPress then
823 key := ^XKeyEvent(SYSTEM.ADR(ev));
824 ...
825end;</code></pre>
826<p>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.</p>
827<h1 id="programs">10. Programs</h1>
828<p>Any module may export a procedure <code>main</code>, declared <code>proc main*;</code> or <code>proc main*: INT;</code>. The program runs the bodies of all its modules (section 3), then the main module’s <code>main</code>, if it has one, and ends with status 0, or with the status <code>main</code> returns, by calling <code>Rt.exit</code>. The <code>main</code> of an imported module is an ordinary procedure, which runs only if something calls it; so a library module can carry a <code>main</code> that tests it. A program uses C if any of its modules has an <code>extern</code> declaration or a <code>link</code> of a library; a module’s other files, read only to check its interface (section 3), don’t count. A program that doesn’t is a static executable with no run time besides the code it uses. One that does is linked dynamically and starts through the C library, so that C’s own set-up and clean-up run. A program with a module that says <code>link static;</code> must not use C, and the compiler reports an error if it does.</p>
829<p><strong>Ending.</strong> <code>Rt.exit(status)</code> ends the program. First it runs the procedures registered with <code>Rt.atExit</code>, the last registered first, each at most once; then it ends the program with <code>status</code>, through C’s <code>exit</code> in a program that uses C, so that C flushes its own buffers. A program that stops (below), a failed check (section 6.5) included, runs them too, after its message, so that <code>Out</code>’s buffer is written out, and ends with status 2. <code>Sys.exit</code> ends the program at once, and a program killed by a signal from outside runs none of them.</p>
830<pre><code>proc atExit*(p: proc): ERROR; (* Rt.Full if 32 are registered *)
831proc exit*(status: INT);
832proc trace*; (* the calls under way, on standard error *)</code></pre>
833<p><code>Rt.trace</code> 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.</p>
834<p><strong>Defined behaviour.</strong> 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 <code>Heap</code>’s <code>free</code> 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 <code>SYSTEM</code>, so does what that module does there (section 3): a made-up pointer, indexing through a pointer, an index out of range under <code>check off;</code>, writing a string’s bytes through a <code>^U8</code>, a code procedure that breaks its rules, and C code. Each can read or write any memory, and what follows isn’t defined. Dereferencing <code>nil</code>, dividing by zero, calling a <code>nil</code> 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 <code>nil</code> pointer, a <code>nil</code> 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.</p>
835<p><strong>Separate compilation.</strong> 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).</p>
836<p><strong>Errors.</strong> 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 <code>forward</code> 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 (<code>Sys.write(fd, s);</code>, where <code>_ := Sys.write(fd, s);</code> 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).</p>
837<p><strong>Limits.</strong> An implementation accepts at least: 63 levels of parentheses and calls nested in one expression; 63 levels of statements nested in one procedure; a chain of 15 modules, each importing the next; 31 names declared together (<code>a, b: INT</code>) and 15 variables assigned together (<code>a, b := f()</code>); 1023 elements in one array literal; 255 labels in one <code>match</code>; 31 deferred statements in force in one procedure; and 8 type arguments to a generic module. It may accept more, and its own limits are its own (appendix A); past one, it rejects the program with an error that names the limit, as for any other error, and never fails in another way.</p>
838<h1 id="versions">11. Versions</h1>
839<p>A version of this report is named by the month it was made in and a count: <code>2026-10.0</code>, then <code>2026-10.1</code> for the next change that month. <code>raz --version</code> says which version the compiler follows.</p>
840<p>The history of the versions, what each changed, is in <code>doc/report-history.md</code>.</p>
841<h1 id="appendix-a.-what-an-implementation-chooses">Appendix A. What an implementation chooses</h1>
842<p>Everything in this report binds every implementation of raz, except what follows, which each chooses for itself and documents. This compiler’s choices are in <code>doc/compiler.md</code>, under “This compiler’s choices”. The programs in <code>conform/</code> are how an implementation shows that it follows this report: it passes them all, its reals aside where its target has none; <code>conform/check.sh</code> runs them.</p>
843<ul>
844<li><strong>The target.</strong> Which machines and systems it compiles for, and the names of their files (<code>linux-x86_64</code>, section 3); for each, the size of an address, and so of <code>INT</code>, whether it has reals, and which C library a program that uses C is linked against.</li>
845<li><strong>Separate compilation.</strong> 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.</li>
846<li><strong>Atomics.</strong> How <code>CAS</code>, <code>XCHG</code> and <code>XADD</code> 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.</li>
847<li><strong>The calling convention.</strong> On x86-64 Linux it is System V (sections 8 and 9); elsewhere it is the C library’s own, so that <code>extern</code> procedures and callbacks work. How a procedure returns several results, and how its frame is laid out, are the implementation’s.</li>
848<li><strong>What is the target’s.</strong> Code procedures (section 8) hold the target’s machine code, written in its assembly language, and exist only where the implementation says so; <code>SYSTEM.SYSCALL</code> 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).</li>
849<li><strong>The assembly language.</strong> 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; <code>db</code> gives any others.</li>
850<li><strong>Sizes in the library.</strong> How many bytes <code>Out</code> keeps before it writes them, <code>Sys.outSize</code> (the library volume): 4 KB on Linux, fewer on a small machine.</li>
851<li><strong>The executable.</strong> Its format, and the names and line numbers it carries for a debugger (section 10).</li>
852<li><strong>How a failure is caught.</strong> A <code>nil</code> 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).</li>
853<li><strong>Limits.</strong> How far past the least of section 10 it goes, and how much stack and memory a compile of a given program needs.</li>
854<li><strong>Messages and warnings.</strong> The text of the compiler’s messages, how many errors it reports before it stops, and which warnings it gives, <code>-Werror</code> 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.</li>
855<li><strong>Copies.</strong> 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 <code>var</code> or <code>const</code> or by pointer, never by value, and wiped there.</li>
856<li><strong>The command line.</strong> How the compiler is run, its options, and where its library lives (sections 1 and 3).</li>
857</ul>
858<p><strong>The core.</strong> A target may leave out what the system under it can’t give: <code>Sys</code> past writing, ending the program and getting memory, <code>Thread</code>, <code>link</code> and <code>extern</code>. What it must have, besides the whole language, reals aside, is the core of the library: <code>Rt</code>, <code>Out</code>, <code>Mem</code>, <code>Arena</code>, <code>Lock</code>, <code>Str</code> and <code>Buf</code>, and of <code>Sys</code> what they need. A program that keeps to the core runs on every target. The rest of the library (<code>Heap</code>, <code>Fmt</code>, <code>List</code>, <code>Map</code>, <code>Vec</code>, <code>Sort</code>, <code>Math</code>, <code>Files</code>, <code>Opt</code>, <code>Width</code>, <code>Rand</code>, <code>Check</code>, <code>Prop</code> and the rest of <code>Sys</code>) is the standard library: a target may leave a module out, and one that has it gives what <code>doc/raz-lib.md</code> says. <code>conform/</code> tests the core only.</p>
859<h1 id="appendix-b.-the-grammar">Appendix B. The grammar</h1>
860<p>The whole syntax of raz, gathered from the sections above, with the symbols of section 2. <code>{ x }</code> is any number of <code>x</code>, <code>[ x ]</code> is <code>x</code> or nothing, and <code>( x | y )</code> is one of them.</p>
861<pre><code>ident = letter { letter | digit } .
862letter = &quot;A&quot; .. &quot;Z&quot; | &quot;a&quot; .. &quot;z&quot; | &quot;_&quot; .
863digit = &quot;0&quot; .. &quot;9&quot; .
864hexDigit = digit | &quot;A&quot; .. &quot;F&quot; .
865number = digit { digit }
866 | digit { hexDigit } &quot;H&quot;
867 | digit { digit } &quot;.&quot; digit { digit } [ &quot;E&quot; [ &quot;+&quot; | &quot;-&quot; ] digit { digit } ] .
868char = &quot;&#39;&quot; ( character | escape ) &quot;&#39;&quot; .
869string = &#39;&quot;&#39; { character | escape | &quot;\x&quot; anyHex anyHex } &#39;&quot;&#39;
870 | &quot;`&quot; { rawChar } &quot;`&quot; .
871escape = &quot;\n&quot; | &quot;\t&quot; | &quot;\r&quot; | &quot;\0&quot; | &quot;\\&quot; | &quot;\&#39;&quot; | &#39;\&quot;&#39;
872 | &quot;\u{&quot; anyHex { anyHex } &quot;}&quot; .
873anyHex = hexDigit | &quot;a&quot; .. &quot;f&quot; .
874
875Module = &quot;module&quot; ident [ &quot;(&quot; ModParams &quot;)&quot; ] &quot;;&quot;
876 { Import } { Link } [ Check ] { Declaration }
877 [ &quot;begin&quot; Statements ] &quot;end&quot; ident &quot;.&quot; .
878ModParams = ident { &quot;,&quot; ident } { &quot;;&quot; ident &quot;:&quot; &quot;proc&quot; Signature } .
879Import = &quot;import&quot; ImportItem { &quot;,&quot; ImportItem } &quot;;&quot; .
880ImportItem = ident [ &quot;:=&quot; ident [ &quot;(&quot; Type { &quot;,&quot; Type } &quot;)&quot; ] ] .
881Link = &quot;link&quot; ( string | &quot;static&quot; ) &quot;;&quot; .
882Check = &quot;check&quot; &quot;off&quot; &quot;;&quot; .
883
884Declaration = &quot;const&quot; { IdentDef [ &quot;:&quot; Type ] &quot;=&quot; Expr &quot;;&quot; }
885 | &quot;type&quot; { IdentDef &quot;=&quot; Type &quot;;&quot; }
886 | &quot;var&quot; { IdentList &quot;:&quot; Type &quot;;&quot; }
887 | ProcDeclaration &quot;;&quot;
888 | ExternDeclaration &quot;;&quot; .
889IdentDef = ident [ &quot;*&quot; ] .
890IdentList = IdentDef { &quot;,&quot; IdentDef } .
891
892Type = QualIdent
893 | &quot;[&quot; Expr &quot;]&quot; Type
894 | &quot;[&quot; &quot;]&quot; [ &quot;const&quot; ] Type
895 | &quot;^&quot; [ &quot;VOLATILE&quot; ] Type
896 | [ &quot;packed&quot; ] &quot;record&quot; { IdentList &quot;:&quot; Type &quot;;&quot; } &quot;end&quot;
897 | &quot;variant&quot; { Case &quot;;&quot; } &quot;end&quot;
898 | &quot;(&quot; ident { &quot;,&quot; ident } &quot;)&quot;
899 | &quot;set&quot; &quot;of&quot; QualIdent
900 | &quot;proc&quot; Signature .
901Case = ident [ &quot;(&quot; FieldList { &quot;;&quot; FieldList } &quot;)&quot; ] .
902FieldList = ident { &quot;,&quot; ident } &quot;:&quot; Type .
903QualIdent = [ ident &quot;.&quot; ] ident .
904
905Expr = Conjunct { &quot;or&quot; Conjunct } .
906Conjunct = Relation { &quot;and&quot; Relation } .
907Relation = SimpleExpr [ RelOp SimpleExpr ] .
908RelOp = &quot;=&quot; | &quot;#&quot; | &quot;&lt;&quot; | &quot;&lt;=&quot; | &quot;&gt;&quot; | &quot;&gt;=&quot; | &quot;in&quot; .
909SimpleExpr = [ &quot;-&quot; ] Term { AddOp Term } .
910AddOp = &quot;+&quot; | &quot;-&quot; | &quot;|&quot; | &quot;xor&quot; .
911Term = Factor { MulOp Factor } .
912MulOp = &quot;*&quot; | &quot;/&quot; | &quot;div&quot; | &quot;mod&quot; | &quot;&amp;&quot; | &quot;shl&quot; | &quot;shr&quot; .
913Factor = number | char | string | Designator | &quot;(&quot; Expr &quot;)&quot;
914 | &quot;not&quot; Factor | &quot;~&quot; Factor
915 | &quot;[&quot; [ Expr { &quot;,&quot; Expr } ] &quot;]&quot;
916 | &quot;{&quot; [ Element { &quot;,&quot; Element } ] &quot;}&quot;
917 | &quot;^&quot; [ &quot;VOLATILE&quot; ] Type &quot;(&quot; Expr &quot;)&quot;
918 | &quot;try&quot; Designator .
919Element = Expr | ident &quot;:&quot; Expr .
920Designator = QualIdent { Selector } .
921Selector = &quot;.&quot; ident | &quot;^&quot; | &quot;[&quot; Expr [ &quot;..&quot; Expr ] &quot;]&quot;
922 | &quot;(&quot; [ Expr { &quot;,&quot; Expr } ] &quot;)&quot; | &quot;.&quot; &quot;(&quot; Type &quot;)&quot; .
923
924Statements = { Statement &quot;;&quot; } .
925Statement = Designator [ &quot;:=&quot; Expr ]
926 | &quot;_&quot; &quot;:=&quot; Expr
927 | Target &quot;,&quot; Target { &quot;,&quot; Target } &quot;:=&quot; Expr
928 | &quot;if&quot; Expr &quot;then&quot; Statements
929 { &quot;elsif&quot; Expr &quot;then&quot; Statements } [ &quot;else&quot; Statements ] &quot;end&quot;
930 | &quot;while&quot; Expr &quot;do&quot; Statements &quot;end&quot;
931 | &quot;repeat&quot; Statements &quot;until&quot; Expr
932 | &quot;for&quot; ident &quot;:=&quot; Expr &quot;to&quot; Expr [ &quot;by&quot; Expr ] &quot;do&quot; Statements &quot;end&quot;
933 | &quot;match&quot; Expr &quot;of&quot; { &quot;|&quot; Arm } &quot;end&quot;
934 | &quot;return&quot; [ Expr { &quot;,&quot; Expr } ]
935 | &quot;break&quot;
936 | &quot;continue&quot;
937 | &quot;defer&quot; Statement
938 | &quot;try&quot; Designator .
939Arm = ( ident { &quot;.&quot; ident } [ &quot;(&quot; ident { &quot;,&quot; ident } &quot;)&quot; ]
940 | Label { &quot;,&quot; Label } | &quot;else&quot; ) &quot;:&quot; Statements .
941Label = Expr [ &quot;..&quot; Expr ] .
942Target = Designator | &quot;_&quot; .
943
944ProcDeclaration = &quot;proc&quot; IdentDef Signature &quot;;&quot;
945 ( &quot;forward&quot; | { LocalDeclaration } &quot;begin&quot; Statements &quot;end&quot; [ ident ]
946 | &quot;code&quot; { [ ident &quot;:&quot; ] [ Instruction ] &quot;;&quot; } &quot;end&quot; [ ident ] ) .
947LocalDeclaration = &quot;const&quot; { ident [ &quot;:&quot; Type ] &quot;=&quot; Expr &quot;;&quot; }
948 | &quot;type&quot; { ident &quot;=&quot; Type &quot;;&quot; }
949 | &quot;var&quot; { ident { &quot;,&quot; ident } &quot;:&quot; Type &quot;;&quot; } .
950Signature = &quot;(&quot; [ Params { &quot;;&quot; Params } [ &quot;;&quot; &quot;...&quot; ] ] &quot;)&quot; [ &quot;:&quot; Results ]
951 | [ &quot;:&quot; Results ] .
952Params = [ &quot;var&quot; | &quot;const&quot; ] ident { &quot;,&quot; ident } &quot;:&quot; Type .
953Results = Type | &quot;(&quot; Type { &quot;,&quot; Type } &quot;)&quot; .
954ExternDeclaration = &quot;extern&quot; ( &quot;proc&quot; IdentDef Signature
955 | &quot;var&quot; IdentDef &quot;:&quot; Type ) .</code></pre>
956<p><code>character</code> is any character but a line break, and in a string any but <code>"</code> and <code>\</code>, in a character any but <code>'</code> and <code>\</code>. <code>rawChar</code> is any character but <code>`</code>, line breaks included. A procedure argument of a generic module (section 3) is written as a <code>QualIdent</code>, which is a <code>Type</code> here. <code>...</code> comes last in a <code>Signature</code>, and only in an <code>extern</code>. An <code>Instruction</code> is written in the target’s assembly language (appendix A).</p>
957<h1 id="the-library-volume-2">The library, volume 2</h1>
958<p>The second volume of the report on raz. The first, <code>doc/raz.md</code>, 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, <code>Rand</code>, <code>Check</code> and <code>Prop</code> among it.</p>
959<p>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.</p>
960<p>A procedure that only reads a slice takes a <code>[]const T</code>, so that a string, a constant and any other slice fit it; what a procedure hands back from the environment, the arguments or a directory is a <code>[]const U8</code>. A module that reaches memory, as the library’s lower modules do, says <code>import SYSTEM</code> (section 3 of the first volume).</p>
961<p>Modules written in raz, in the compiler’s <code>lib</code> directory:</p>
962<table>
963<thead>
964<tr>
965<th>Module</th>
966<th>What</th>
967</tr>
968</thead>
969<tbody>
970<tr>
971<td><code>Rt</code></td>
972<td>ending the program, <code>exit</code>, <code>exitStatus</code> and <code>atExit</code>; <code>stop</code>, which ends it with a message; <code>trace</code>, the calls under way; what the compiler’s checks call when they fail</td>
973</tr>
974<tr>
975<td><code>Sys</code></td>
976<td>system calls: <code>open</code>, <code>openMode</code>, <code>openRead</code>, <code>create</code>, <code>read</code>, <code>write</code>, <code>seek</code>, <code>position</code>, <code>truncate</code>, <code>sync</code>, <code>syncAll</code>, <code>lock</code>, <code>lockShared</code>, <code>close</code>, <code>closeChecked</code>, <code>dup</code>, <code>dupTo</code>, <code>dupAbove</code>, <code>keepOnExec</code>, <code>mmap</code>, <code>munmap</code>, <code>mapRead</code>, <code>protect</code>, <code>isTerminal</code>, <code>yield</code>, <code>exit</code>; files and directories, <code>rename</code>, <code>remove</code>, <code>removeDir</code>, <code>makeDir</code>, <code>makeDirMode</code>, <code>chmod</code>, <code>setTime</code>, <code>access</code>, <code>umask</code>, <code>symlink</code>, <code>readLink</code>, <code>info</code>, <code>linkInfo</code>, <code>infoOf</code>, <code>openDir</code>, <code>nextEntry</code>, <code>entryKind</code>, <code>closeDir</code>; the terminal, <code>rawMode</code>, <code>restoreMode</code>, <code>getMode</code>, <code>setMode</code>, <code>termSize</code>, <code>ready</code>; the environment, <code>env</code>, <code>findEnv</code>, <code>envAt</code>, <code>setEnv</code>, <code>workDir</code>, <code>setWorkDir</code>; programs, <code>spawn</code>, <code>exec</code> and <code>execve</code>, pipes and signals; the user, the machine, time used and limits; time, <code>clock</code>, <code>now</code>, <code>sleep</code>; <code>random</code>; errors, by name, and what one means, <code>errorText</code>; sockets, among them datagrams served and files passed; and memory shared through a file. One file per target, and <code>Sys.raz</code> over the C library for the others, which takes what each C library fixes from <code>CAbi</code></td>
977</tr>
978<tr>
979<td><code>Out</code></td>
980<td>writing text and numbers to standard output, buffered; safe to call from several threads</td>
981</tr>
982<tr>
983<td><code>C</code></td>
984<td>the parts of the C library the others use, and <code>printf</code>, <code>fflush</code>, <code>stdout</code>, <code>pthread_create</code>; a program that imports it uses C</td>
985</tr>
986<tr>
987<td><code>Lock</code></td>
988<td>a lock for short sections, for C’s threads and <code>Thread</code>’s alike</td>
989</tr>
990<tr>
991<td><code>Thread</code></td>
992<td>threads, <code>spawn</code>, <code>join</code> and <code>signal</code>, and <code>Mutex</code>, in any program; in one that uses C, made by C’s <code>pthread_create</code></td>
993</tr>
994<tr>
995<td><code>Task</code></td>
996<td>a thread given a value of its own, <code>Task(T)</code>: <code>spawn</code> copies it, with no cast</td>
997</tr>
998<tr>
999<td><code>Guarded</code></td>
1000<td>a value with its lock, <code>Guarded(T)</code>: reached only through <code>with</code></td>
1001</tr>
1002<tr>
1003<td><code>Mem</code></td>
1004<td><code>Allocator</code>, the interface of every allocator, and pages from the system</td>
1005</tr>
1006<tr>
1007<td><code>Heap</code></td>
1008<td>a general allocator, <code>Heap.heap</code>, safe to call from several threads; freeing a block twice, or one it never gave out, stops the program; <code>RAZ_HEAP=debug</code> finds writes past a block’s end and after free</td>
1009</tr>
1010<tr>
1011<td><code>Arena</code></td>
1012<td>an allocator that frees everything at once; <code>ADR(arena.base)</code> is its allocator</td>
1013</tr>
1014<tr>
1015<td><code>Str</code></td>
1016<td>operations on strings, <code>[]const U8</code>: comparing, hashing, finding, trimming and cutting, case, joining and replacing, UTF-8, numbers to and from text</td>
1017</tr>
1018<tr>
1019<td><code>Bytes</code></td>
1020<td>searches of bytes, many at a time: <code>index</code>, <code>last</code>, <code>count</code> and <code>find</code> in a <code>[]U8</code>; one file per target where the target has instructions for it</td>
1021</tr>
1022<tr>
1023<td><code>Buf</code></td>
1024<td>a growable byte buffer</td>
1025</tr>
1026<tr>
1027<td><code>Fmt</code></td>
1028<td>formatted output: <code>Fmt.print("{} of {}\n", [Fmt.int(n), Fmt.real(x, 2)])</code>, into a <code>Buf</code> with <code>Fmt.write</code>, or to standard error with <code>Fmt.eprint</code></td>
1029</tr>
1030<tr>
1031<td><code>List</code></td>
1032<td>a generic singly linked list, <code>List(T)</code></td>
1033</tr>
1034<tr>
1035<td><code>Map</code></td>
1036<td>a generic hash map, <code>Map(K, V; hash, eq)</code></td>
1037</tr>
1038<tr>
1039<td><code>Vec</code></td>
1040<td>a generic growable array, <code>Vec(T)</code>, indexed as a slice</td>
1041</tr>
1042<tr>
1043<td><code>Sort</code></td>
1044<td>sorting a slice in place, <code>Sort(T; less)</code></td>
1045</tr>
1046<tr>
1047<td><code>Math</code></td>
1048<td>roots, powers, logarithms, rounding and trigonometry, and <code>pi</code>, for <code>F64</code></td>
1049</tr>
1050<tr>
1051<td><code>Files</code></td>
1052<td>an argument as a string, and a whole file read or written</td>
1053</tr>
1054<tr>
1055<td><code>Opt</code></td>
1056<td>a command line read through one table, by <code>getopt</code>’s rules with long options; its help and its mistakes</td>
1057</tr>
1058<tr>
1059<td><code>Width</code></td>
1060<td>how many columns of a terminal a character, or a string, takes: 0, 1 or 2, as <code>wcwidth</code> says</td>
1061</tr>
1062<tr>
1063<td><code>Rand</code></td>
1064<td>a seeded random number generator, splitmix64: the same seed, the same numbers; for tests and simulations, not secrets</td>
1065</tr>
1066<tr>
1067<td><code>Check</code></td>
1068<td>checks for a test: <code>ok</code>, <code>str</code> and <code>int</code> say what failed on standard error, and the program ends with status 1 if any did</td>
1069</tr>
1070<tr>
1071<td><code>Prop</code></td>
1072<td>property tests and fuzzing: a property draws values, a failing case is shrunk and saved, and run first next time</td>
1073</tr>
1074</tbody>
1075</table>
1076<p>Lengths, counts, file descriptors, process ids and statuses are <code>INT</code>s, and a character is an <code>I32</code>. What may pass an <code>INT</code> on a small target is an <code>I64</code>: a file’s size and position, a time in nanoseconds, and a number read from text.</p>
1077<p>What follows is each module’s interface, as <code>tools/Doc.raz</code> prints it from the module’s file; <code>...</code> stands for fields that are the module’s own. A module’s <code>main</code>, where it has one, is its test, and is left out here.</p>
1078<pre><code>module Rt;
1079const Full*: ERROR = &quot;too many procedures to run at exit&quot;;
1080proc atExit*(p: proc): ERROR; (* p run when the program ends by exit *)
1081proc exit*(status: INT); (* the atExit procedures, the last first, then the end *)
1082proc exitStatus*: INT; (* the status exit was given, in an atExit procedure; 0 before *)
1083proc stop*(msg: []const U8); (* msg, and a line feed, on standard error, then exit with status 2 *)
1084proc trace*; (* the calls under way, and their variables, on standard error *)</code></pre>
1085<p><code>Rt</code> also holds what the compiler’s checks call when they fail, and the handlers of the signals that stop a program (section 10). <code>exit</code> takes each procedure off the list before it runs it, so it runs once even if it fails or calls <code>exit</code> itself; in a program that uses C, it ends through C’s <code>exit</code>, so that C flushes its buffers too. <code>exitStatus</code> is the status <code>exit</code> was given, which a procedure <code>atExit</code> registered can read, to note a crash: a failed check and <code>stop</code> both end with 2. It is 0 before <code>exit</code> is called.</p>
1086<pre><code>module Mem;
1087type
1088 Allocator* = record
1089 alloc*: proc(a: ^Allocator; size, align: INT): ^U8; (* nil if out of room *)
1090 free*: proc(a: ^Allocator; p: ^U8);
1091 end;
1092const Page* = 4096;
1093proc pages*(size: INT): ^U8; (* size bytes, in whole pages, zeroed; or nil *)
1094proc unmap*(p: ^U8; size: INT); (* pages given back *)
1095proc alloc*(a: ^Allocator; size, align: INT): ^U8; (* a^.alloc(a, size, align) *)
1096proc free*(a: ^Allocator; p: ^U8); (* a^.free(a, p) *)
1097
1098module Heap;
1099proc debug*(on: BOOL); (* debug mode on or off, for the blocks given from now on *)
1100var heap*: ^Mem.Allocator;
1101var sure*: ^Mem.Allocator; (* heap, but running out of memory stops the program *)
1102
1103module Arena;
1104type Arena* = record
1105 base*: Mem.Allocator; (* first, so that ^Arena(a) finds the rest *)
1106 ...
1107end;
1108proc init*(var ar: Arena; size: INT): BOOL; (* an arena of size bytes; false if the system has none *)
1109proc mark*(const ar: Arena): INT; (* where ar stands now, for release *)
1110proc release*(var ar: Arena; m: INT); (* all allocated since mark m freed; a mark past where it stands stops the program *)
1111proc reset*(var ar: Arena); (* every allocation forgotten; the memory used again *)
1112proc done*(var ar: Arena); (* its memory given back *)</code></pre>
1113<p><code>NEW(p, a)</code> calls <code>a^.alloc</code>. <code>Heap</code> is the general allocator; <code>Heap.heap</code> gives <code>nil</code> when memory runs out, and <code>Heap.sure</code> stops the program instead, as <code>Buf</code> does, so that <code>NEW(p, Heap.sure)</code> needs no check.</p>
1114<p><code>Heap</code> has a debug mode, a light AddressSanitizer, chosen by <code>RAZ_HEAP=debug</code> in the environment or by <code>Heap.debug(true)</code>. 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 <code>0DEH</code> 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 <code>0DEH</code>, 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. <code>debug</code> 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 <code>free</code> does nothing, and <code>reset</code> forgets everything.</p>
1115<pre><code>module Lock;
1116type Lock* = record ... end;
1117proc take*(var l: Lock);
1118proc give*(var l: Lock);
1119
1120module Thread;
1121const Failed*: ERROR = &quot;can&#39;t start a thread&quot;;
1122type
1123 Thread* = record ... end;
1124 Mutex* = record ... end; (* zero is free *)
1125proc spawn*(p: proc(arg: ^U8); arg: ^U8): (^Thread, ERROR); (* p(arg) in a new thread *)
1126proc join*(t: ^Thread); (* waits for t to end, then frees its stack *)
1127proc signal*(t: ^Thread; sig: INT): INT; (* sig sent to t alone: 0, or minus an errno *)
1128proc lock*(var m: Mutex);
1129proc unlock*(var m: Mutex);
1130
1131module Task(T);
1132proc spawn*(p: proc(var x: T); x: T): (^Thread.Thread, ERROR); (* p run on a copy of x in a new thread *)
1133
1134module Guarded(T);
1135type Guarded* = record ... end; (* a value and its Thread.Mutex; zero is ready *)
1136proc with*(var g: Guarded; p: proc(var x: T)); (* p run on the value, under the lock *)</code></pre>
1137<p><code>Task(T)</code> starts a thread without a cast: <code>import Jobs := Task(Job); t, e := Jobs.spawn(work, job);</code> is the safe form of <code>Thread.spawn(work, ^U8(ADR(job)))</code>. <code>spawn</code> copies <code>x</code> into a block from <code>Heap</code> before it returns, so the caller may change or drop its <code>x</code> at once. The thread owns the copy: <code>work</code> changes it freely, and the thread frees it when <code>work</code> returns. The thread is joined with <code>Thread.join</code>; <code>Thread.Failed</code> comes back if there is no memory for the copy or the thread. A result goes back through a pointer in <code>x</code>, read after <code>join</code>.</p>
1138<p><code>Guarded(T)</code> is a <code>T</code> with its <code>Thread.Mutex</code>, for sharing a container between threads: the value is reached only through <code>with</code>, which holds the lock while <code>p</code> runs. A zeroed <code>Guarded</code> is ready. <code>p</code> must not call <code>with</code> on the same <code>Guarded</code>, nor keep a pointer into its <code>x</code>.</p>
1139<p>A <code>Lock</code> is for short sections: a thread that finds it taken tries again, giving up the processor now and then. A <code>Mutex</code> sleeps. Each of <code>Thread</code>’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, <code>Thread</code> makes its threads with C’s <code>pthread_create</code>, 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.</p>
1140<p><code>Sys.kill</code> signals a program, and the system gives the signal to any of its threads; <code>signal</code> gives it to <code>t</code> alone, until <code>t</code> is joined, and is -3 (ESRCH) once <code>t</code> has ended. With <code>Sys.handle(sig)</code>, a call <code>t</code> waits in, a <code>read</code> or a <code>ready</code>, fails with -4, so that one thread can break into another’s wait, as <code>^C</code> breaks into the main thread’s. A signal sent before <code>t</code> begins its wait is only noted, so a program sends it again until <code>t</code> says it has stopped.</p>
1141<pre><code>module Out;
1142proc str*(s: []const U8);
1143proc char*(c: U8);
1144proc ln*; (* a line feed *)
1145proc int*(n: I64); (* n in decimal *)
1146proc hex*(n: U64; digits: INT); (* n in hexadecimal, digits digits at least *)
1147proc flush*;
1148proc lines*(on: BOOL); (* written at each line feed, or only when full *)</code></pre>
1149<p><strong>Out and C’s stdio.</strong> <code>Out</code> keeps a buffer of <code>Sys.outSize</code> bytes, 4 KB on Linux. It writes it out when it is full, at each line feed when standard output is a terminal, at <code>Out.flush</code>, and when the program ends by <code>Rt.exit</code>. <code>lines(true)</code> has it written at each line feed whatever standard output is, as a filter of a stream that comes slowly wants through a pipe, as grep’s <code>--line-buffered</code>; <code>lines(false)</code>, only when full, at a terminal too. A lock keeps what each call writes together when threads write at once. C’s <code>stdio</code> keeps a buffer of its own for the same standard output. A program that writes with both flushes one before writing with the other, or the text comes out of order:</p>
1150<pre><code>module Both;
1151import Out, C, SYSTEM; (* C: printf, fflush and C&#39;s FILE *stdout *)
1152
1153proc main*;
1154begin
1155 Out.str(&quot;from raz\n&quot;);
1156 Out.flush;
1157 C.printf(&quot;from C\n&quot;);
1158 C.fflush(C.stdout);
1159 Out.str(&quot;from raz again\n&quot;);
1160end;
1161
1162end Both.</code></pre>
1163<p><strong>Sys</strong> gives every target the same procedures, so that a program that needs only these runs wherever raz does: through system calls on Linux, through the C library elsewhere. A result that can fail is a number, minus an errno, as on Linux; 0 is success. The number is Linux’s on every target: <code>Sys</code> over another system’s C library gives the Linux errno of the same name, and a program tests it by the names below; one with no Linux twin keeps its own number. <code>Sys.raz</code>, the <code>Sys</code> over C, keeps to POSIX’s names; what a C library fixes for its target, the layouts of its structs, its numbers and the names that differ, it takes from <code>CAbi</code>, one file per target, which <code>tools/cabi.c</code>, compiled there, writes.</p>
1164<pre><code>module Sys;
1165const
1166 stdin* = 0; stdout* = 1; stderr* = 2;
1167 outSize* = 4096; (* the bytes Out keeps; each target has its own *)
1168 (* signals, by their numbers on Linux; each target has its own *)
1169 sigHup* = 1; sigInt* = 2; sigQuit* = 3; sigKill* = 9; sigPipe* = 13;
1170 sigTerm* = 15; sigChld* = 17; sigCont* = 18; sigStop* = 19;
1171 sigTstp* = 20; sigTtin* = 21; sigTtou* = 22; sigWinch* = 28;
1172 sigUsr1* = 10; sigUsr2* = 12; sigAlrm* = 14;
1173 (* the limits limit and setLimit take, by their numbers on Linux; each target has its own *)
1174 limitCpu* = 0; limitFileSize* = 1; limitData* = 2; limitStack* = 3;
1175 limitCore* = 4; limitProcs* = 6; limitFiles* = 7; limitMemory* = 9;
1176 (* errors, minus Linux&#39;s errnos on every target *)
1177 errPerm* = -1; errNoEntry* = -2; errNoProcess* = -3; errIntr* = -4;
1178 errIo* = -5; errBadFd* = -9; errChild* = -10; errAgain* = -11;
1179 errNoMemory* = -12; errDenied* = -13; errExists* = -17;
1180 errNotDir* = -20; errIsDir* = -21; errInvalid* = -22;
1181 errNotTerminal* = -25; errNoSpace* = -28; errReadOnly* = -30; errPipe* = -32;
1182 errNameTooLong* = -36; errNotEmpty* = -39; errLoop* = -40;
1183 errAddrInUse* = -98; errNetUnreach* = -101; errConnAborted* = -103; errConnReset* = -104;
1184 errTimedOut* = -110; errRefused* = -111; errHostUnreach* = -113;
1185 errInProgress* = -115;
1186
1187type
1188 Access* = (reading, writing, creating, exclusive, truncating, appending, executing, nonblocking);
1189 Accesses* = set of Access;
1190 Info* = record
1191 size*: I64; (* in bytes *)
1192 mtime*: I64; (* when its contents last changed, in nanoseconds since 1970 *)
1193 seconds*: I64; (* mtime in whole seconds, rounded down: exact past 2262 and before 1677, where mtime wraps *)
1194 mode*: INT; (* its permission bits, as chmod takes them: 1EDH is rwxr-xr-x *)
1195 dir*: BOOL; (* a directory *)
1196 file*: BOOL; (* a regular file: not a directory, device, pipe or socket *)
1197 symlink*: BOOL; (* the path itself is a symbolic link *)
1198 ino*: U64; (* its inode, which a rename keeps and a new file doesn&#39;t *)
1199 dev*: U64; (* the file system it is on; with ino, it names the file *)
1200 links*: U64; (* how many names it has: 1 for a file no hard link shares *)
1201 special*: INT; (* its set-user-id, set-group-id and sticky bits, as chmod takes them: 800H, 400H, 200H *)
1202 uid*: INT; (* its owner&#39;s user number *)
1203 gid*: INT; (* its group&#39;s number *)
1204 end;
1205 Kind* = (unknown, isFile, isDir, isLink, isOther); (* what a directory says a name in it is *)
1206 Dir* = record ... end; (* an open directory; its fields are the target&#39;s *)
1207 Program* = record
1208 path*: []const U8;
1209 args*: [][]const U8; (* the first is its name *)
1210 env*: [][]const U8; (* NAME=value, each added to this program&#39;s environment *)
1211 onlyEnv*: BOOL; (* env is its whole environment *)
1212 dir*: []const U8; (* its working directory; &quot;&quot; for this program&#39;s *)
1213 fds*: [3]INT; (* its standard input, output and error; 0 for this program&#39;s own *)
1214 group*: INT; (* the process group it joins: 0 for this program&#39;s, -1 a new one it leads *)
1215 foreground*: BOOL; (* its group takes the terminal on standard input *)
1216 tty*: INT; (* a pseudo-terminal&#39;s fd, to start a session on; 0 for none *)
1217 more*: []INT; (* fds above 2 passed on to it, at the same numbers *)
1218 keepIgnored*: BOOL; (* signals this program ignores stay ignored in it *)
1219 end;
1220 Status* = (running, exited, killed, stopped);
1221 Mode* = record ... end; (* a terminal&#39;s modes; its fields are the target&#39;s *)
1222 Peer* = record ... end; (* whom a datagram came from *)
1223 Remote* = record (* who is at the other end of a connected socket *)
1224 unix*: BOOL; (* a Unix socket: uid and pid say who *)
1225 ipv6*: BOOL; (* addr is 16 bytes of IPv6, else 4 bytes of IPv4 then zeros *)
1226 addr*: [16]U8;
1227 port*: INT;
1228 uid*, pid*: INT;
1229 end;
1230 Poll* = record (* a descriptor for poll to wait on *)
1231 fd*: INT;
1232 read*, write*: BOOL; (* wait until it may be read, written *)
1233 ready*: BOOL; (* set by poll *)
1234 end;
1235
1236proc write*(fd: INT; s: []const U8): INT; (* the bytes written *)
1237proc read*(fd: INT; buf: []U8): INT; (* the bytes read; 0 at the end *)
1238proc open*(path: []const U8; how: Accesses): INT; (* its fd, closed on exec *)
1239proc openMode*(path: []const U8; how: Accesses; mode: INT): INT; (* open, a file it makes given mode *)
1240proc openRead*(path: []const U8): INT; (* open(path, {reading}) *)
1241proc create*(path: []const U8): INT; (* open(path, {writing, creating, truncating}) *)
1242proc seek*(fd: INT; pos: I64; fromEnd: BOOL): I64; (* the new position *)
1243proc position*(fd: INT): I64; (* where the next read or write is *)
1244proc truncate*(fd: INT; size: I64): INT; (* the file made size bytes long *)
1245proc sync*(fd: INT): INT; (* what was written to it, on the disk *)
1246proc syncAll*(fd: INT): INT; (* all that was written to its file system, on the disk *)
1247proc lock*(fd: INT; wait: BOOL): INT; (* the file&#39;s lock, held until fd is closed *)
1248proc lockShared*(fd: INT; wait: BOOL): INT; (* lock, shared with others that ask it so *)
1249proc close*(fd: INT);
1250proc closeChecked*(fd: INT): INT; (* close, and 0 or minus the errno it failed with *)
1251proc dup*(fd: INT): INT; (* a new fd for the same file, the lowest free *)
1252proc dupTo*(fd, into: INT): INT; (* into made the same file as fd, closing what it was *)
1253proc dupAbove*(fd, least: INT): INT; (* a new fd for the same file, the lowest free from least on, closed on exec *)
1254proc 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 *)
1255proc isTerminal*(fd: INT): BOOL;
1256proc mapRead*(fd, size: INT): ^U8; (* the first size bytes of fd, which may be open only to read, mapped read only; or nil *)
1257proc 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 *)
1258proc mmap*(size: INT): ^U8; (* size bytes of zeroed memory, in whole pages; or nil *)
1259proc munmap*(p: ^U8; size: INT);
1260proc yield*; (* the processor given to another thread *)
1261proc exit*(status: INT); (* the program ended at once, without Rt&#39;s atExit *)
1262
1263proc rename*(old, new: []const U8): INT; (* replaces what new names *)
1264proc remove*(path: []const U8): INT; (* a file, not a directory *)
1265proc removeDir*(path: []const U8): INT; (* an empty directory *)
1266proc makeDir*(path: []const U8): INT; (* readable by all, writable by its owner *)
1267proc makeDirMode*(path: []const U8; mode: INT): INT; (* makeDir, given mode *)
1268proc chmod*(path: []const U8; mode: INT): INT;
1269proc chown*(path: []const U8; uid, gid: INT): INT; (* its owner and group; -1 leaves one as it is *)
1270proc makeFifo*(path: []const U8; mode: INT): INT; (* a named pipe, given mode *)
1271proc setTime*(path: []const U8; sec: I64; nsec: INT): INT; (* its mtime, and the time it was read, made sec and nsec *)
1272proc access*(path: []const U8; how: Accesses): INT; (* 0 if this user may read, write or execute it *)
1273proc umask*(mask: INT): INT; (* the bits taken from every file made; the mask it was *)
1274proc symlink*(target, path: []const U8): INT; (* path made a link to target *)
1275proc readLink*(path: []const U8): ([]const U8, INT); (* what the link names, good until the next call *)
1276proc info*(path: []const U8): (Info, INT); (* following a symbolic link *)
1277proc linkInfo*(path: []const U8): (Info, INT); (* the link itself *)
1278proc infoOf*(fd: INT): (Info, INT); (* the open file&#39;s *)
1279proc space*(path: []const U8): (I64, I64, INT); (* the bytes free and in all on path&#39;s file system *)
1280
1281proc openDir*(var d: Dir; path: []const U8): INT;
1282proc nextEntry*(var d: Dir): ([]const U8, BOOL); (* a name, good until the next call; false at the end *)
1283proc entryKind*(const d: Dir): Kind; (* what the name nextEntry gave last is *)
1284proc closeDir*(var d: Dir);
1285
1286proc rawMode*(fd: INT): BOOL; (* the terminal on fd: no echo, no lines, no signals *)
1287proc restoreMode*(fd: INT); (* as rawMode found it *)
1288proc getMode*(fd: INT): (Mode, INT); (* the terminal&#39;s modes, to set again *)
1289proc setMode*(fd: INT; m: Mode): INT; (* once what was written to it is sent *)
1290proc termSize*(fd: INT): (INT, INT); (* columns and rows; 80 and 24 if unknown *)
1291proc ready*(fd, ms: INT): BOOL; (* something to read within ms, or ever if ms &lt; 0 *)
1292proc readyOf*(fds: []const INT; ms: INT): INT; (* the first of fds with something to read within ms, or -1 *)
1293proc readyFor*(reads, writes: []const INT; ms: INT): INT; (* readyOf, and the first of writes with room to write *)
1294proc poll*(var fds: []Poll; ms: INT): INT; (* sets each fd&#39;s ready, as each read and write say; the number ready, 0 on a timeout, or minus an errno *)
1295proc setBlocking*(fd: INT; yes: BOOL): INT; (* if not yes, a read or write that would wait is -11 at once *)
1296proc blocking*(fd: INT): INT; (* 1 if reads and writes wait, 0 if they are -11 at once, or minus an errno *)
1297
1298proc errorText*(err: INT): []const U8; (* what errno err, or minus it, means, as C&#39;s strerror says *)
1299
1300proc env*(name: []const U8): []const U8; (* the environment variable&#39;s value; &quot;&quot; if unset *)
1301proc findEnv*(name: []const U8): ([]const U8, BOOL); (* the value and true; &quot;&quot; and false if unset, &quot;&quot; and true if empty *)
1302proc envAt*(i: INT): ([]const U8, BOOL); (* the environment&#39;s ith NAME=value, from 0; false past the last *)
1303proc setEnv*(name, value: []const U8): INT; (* name set to value, for env and the programs started *)
1304proc workDir*: ([]const U8, INT); (* the working directory, good until the next call *)
1305proc setWorkDir*(path: []const U8): INT;
1306
1307proc pipe*: (INT, INT); (* the fd to read and the fd to write; or minus an errno and -1 *)
1308proc openPty*: INT; (* a pseudo-terminal: the fd of its controlling side *)
1309proc setTermSize*(fd, cols, rows: INT): INT; (* the size its programs are told of *)
1310proc spawn*(p: Program): INT; (* a program started: its process id *)
1311proc exec*(p: Program): INT; (* p run in this program&#39;s place; returns only if it can&#39;t *)
1312proc execve*(path: []const U8; args, env: [][]const U8): INT; (* as the kernel&#39;s execve: no search *)
1313proc fork*: INT; (* this program copied: 0 in the copy, its process id in this one *)
1314proc setsid*: INT; (* a session of its own, led by this program: its process id, or minus an errno *)
1315proc wait*(pid: INT; block: BOOL): (INT, Status, INT); (* which program, how, and its code *)
1316proc waitExit*(pid: INT): (INT, Status, INT); (* as wait, but only for a program to end *)
1317proc kill*(pid, signal: INT): INT;
1318proc pid*: INT; (* this program&#39;s process id *)
1319proc group*: INT; (* the process group this program is in *)
1320proc setGroup*(pid, group: INT): INT; (* pid 0 is this program; group 0 a new one pid leads *)
1321proc foreground*(fd, group: INT): INT; (* the terminal on fd gives its keys to group *)
1322proc foregroundOf*(fd: INT): INT; (* the group the terminal on fd gives its keys to *)
1323proc uid*: INT; (* the user this program runs as *)
1324proc euid*: INT; (* the user whose rights it has: 0 is root *)
1325proc hostName*: ([]const U8, INT); (* this machine&#39;s name, good until the next call *)
1326proc processors*: INT; (* the processors this program may run on, at least 1 *)
1327proc cpuTime*(children: BOOL): (I64, I64); (* ns used in the program and in the system; or by its children *)
1328proc limit*(which: INT): (I64, I64, INT); (* the soft limit and the hard; -1 for none *)
1329proc setLimit*(which: INT; soft, hard: I64): INT;
1330
1331proc catch*(sigs: []const INT): INT; (* sigs caught: an fd to wait on *)
1332proc caught*(fd: INT): INT; (* the next signal caught, or 0 if none is waiting *)
1333proc ignore*(sig: INT; yes: BOOL): INT; (* sig ignored; or, if not yes, back to what it does at first *)
1334proc ignored*(sig: INT): BOOL; (* whether sig does nothing now *)
1335proc handle*(sig: INT): INT; (* sig noted, for came; a system call it comes during is -4 *)
1336proc came*(sig: INT): BOOL; (* whether sig came since the last time it was asked *)
1337
1338proc clock*: I64; (* nanoseconds, on a clock that only goes forward *)
1339proc now*: I64; (* nanoseconds since 1970-01-01, UTC *)
1340proc sleep*(ms: INT);
1341proc random*(b: []U8); (* b filled with random bytes; stops the program if it can&#39;t be *)
1342
1343proc connect*(path: []const U8): INT; (* a stream socket, connected to the Unix socket at path: its fd *)
1344proc connectTcp*(addr: []const U8; port: INT): INT; (* addr an IPv4 or IPv6 address, as numbers *)
1345proc connectUdp*(addr: []const U8; port: INT): INT;
1346proc listen*(path: []const U8): INT; (* a Unix socket made at path, taking connections *)
1347proc listenTcp*(addr: []const U8; port: INT): INT;
1348proc accept*(fd: INT): INT; (* the next connection, waiting for one *)
1349proc send*(fd: INT; s: []const U8): INT; (* write, to a socket: -32 (EPIPE), not a signal, if it is closed *)
1350proc sendNow*(fd: INT; s: []const U8): INT; (* send, but -11 (EAGAIN) where it would wait *)
1351proc connectTcpWithin*(addr: []const U8; port, ms: INT): INT; (* connectTcp, or -110 (ETIMEDOUT) after ms *)
1352proc listenUdp*(addr: []const U8; port: INT): INT; (* a socket of datagrams on port at addr *)
1353proc receive*(fd: INT; buf: []U8): (INT, Peer); (* the next datagram, in buf, and who sent it *)
1354proc reply*(fd: INT; peer: Peer; s: []const U8): INT; (* s, as one datagram, to peer *)
1355proc localPort*(fd: INT): INT; (* the port the socket fd is bound to *)
1356proc closeWrite*(fd: INT): INT; (* no more writing to the socket fd; the other end reads an end *)
1357proc peer*(fd: INT): (Remote, INT); (* who is at the other end of the connected socket fd *)
1358proc socketPair*: (INT, INT, INT); (* two connected stream sockets, and 0 *)
1359proc sendFds*(fd: INT; s: []const U8; fds: []const INT): INT; (* send, and with it fds, to a Unix socket *)
1360proc receiveFds*(fd: INT; buf: []U8; fds: []INT): (INT, INT); (* read, and the fds that came with it *)
1361
1362proc memFile*(size: INT): INT; (* a file of size zero bytes, in memory, with no name: its fd *)
1363proc mapFile*(fd, size: INT): ^U8; (* the first size bytes of fd, shared; munmap gives them back; or nil *)</code></pre>
1364<p><code>info</code> follows a symbolic link: <code>size</code>, <code>dir</code> and <code>file</code> are those of what it names, and <code>symlink</code> 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 <code>-ENOENT</code>, as a missing file is. <code>file</code> lets a walk open only what holds data: opening a pipe would wait for a program to write to it.</p>
1365<p><code>nextEntry</code> gives every name in the directory except <code>.</code> and <code>..</code>, in no particular order. <code>entryKind</code> 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 <code>linkInfo</code> of every name, a system call each; where the file system doesn’t record it, it is <code>unknown</code>, and <code>linkInfo</code> must be asked. <code>rawMode</code> 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: <code>Rt.atExit</code> is the place.</p>
1366<p><strong>Files.</strong> <code>open</code> gives a file for what <code>how</code> asks: <code>reading</code>, <code>writing</code> or both; <code>creating</code> it if it is missing, readable by all and writable by its owner; with <code>exclusive</code>, failing with -17 (EEXIST) if it is there, as a program does that makes a lock or a file of its own; <code>truncating</code> it to nothing; <code>appending</code>, each write going to its end, however other programs write it too. <code>openMode</code> is <code>open</code> that gives a file it makes the bits <code>mode</code>, less those the umask takes away: 1EDH (755) for a program, 124H (444) for a file never to be written; <code>open</code> gives 1A4H (644). <code>seek</code> moves to <code>pos</code> from the start of the file, or from its end if <code>fromEnd</code>, where a negative <code>pos</code> reads back from the end; <code>position</code> says where the file is, without moving. <code>truncate</code> makes the file <code>size</code> bytes long, cutting it or adding zeros, and leaves the position where it was. <code>sync</code> returns once what was written to the file is on the disk, as a program needs before it says a file is saved; <code>syncAll</code> 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. <code>lock</code> takes the file’s lock for one open file alone: another that asks for it waits if <code>wait</code>, 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 <code>exclusive</code> does. <code>lockShared</code> takes it shared, as a program that only reads asks it: any number may hold it so at once, and <code>lock</code> waits, or fails, until the last has let it go, as a shared one waits for the one that <code>lock</code> took. Both are <code>flock</code>’s, so they agree with any other program that takes the file’s lock so. <code>closeChecked</code> closes as <code>close</code> 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 <code>closeChecked</code>, -4 (EINTR) too, is never tried again. <code>infoOf</code> is <code>info</code> of an open file: its size is what it holds now, however it was written; <code>linkInfo</code> is <code>info</code> of a symbolic link itself, not what it names, so that <code>symlink</code> is true, <code>dir</code> and <code>file</code> false, and <code>size</code> the length of what it names, which need not be there. <code>Info.mtime</code> is what a program checks to see whether a file changed under it, and <code>Info.ino</code> whether it is still the same file, not one renamed over it; 0 on a target whose files have none. <code>Info.dev</code> is the file system the file is on: two files are one only if both <code>dev</code> and <code>ino</code> agree, which is how a program following links finds that one has led it back into a directory it is already in. <code>Info.links</code> 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. <code>Info.mode</code> holds the nine bits of <code>rwxrwxrwx</code>, and <code>chmod</code> sets them, 1EDH (755) for a program, 1A4H (644) for data; <code>Info.special</code> holds the three above them, set-user-id 800H, set-group-id 400H and sticky 200H, which <code>chmod</code> sets too, with <code>mode | special</code>, as a program that copies a file keeps them. <code>Info.uid</code> and <code>Info.gid</code> are the owner’s and the group’s numbers; <code>chown</code> 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). <code>makeFifo</code> makes a named pipe, given the bits <code>mode</code> as <code>makeDirMode</code> is; <code>Info</code> of one has <code>file</code> and <code>dir</code> false, and <code>open</code> with <code>nonblocking</code> doesn’t wait for its other end. <code>makeDirMode</code> is <code>makeDir</code> that gives the directory the bits <code>mode</code>, less those the umask takes away, as <code>openMode</code> 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. <code>setTime</code> 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: <code>sec</code> seconds and <code>nsec</code>, from 0 to 999999999, nanoseconds since 1970. <code>Info.mtime</code> holds the time in nanoseconds, which an <code>I64</code> holds from 1677 to 2262 only; <code>Info.seconds</code> holds it in whole seconds, rounded down, whatever it is, so a program that copies times exactly takes <code>Info.seconds</code>, and the nanoseconds as <code>mtime - seconds * 1000000000</code>, which is right in any year, since the wrapping cancels out (section 6.1).</p>
1367<p><strong>Programs.</strong> <code>openPty</code> 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.</p>
1368<p><code>spawn</code> starts the program at <code>p.path</code>, with <code>p.args</code> as its arguments, the first being its name. A <code>p.path</code> without a <code>/</code> is looked for as a shell looks for a command, and as C’s <code>execvp</code> does: in each directory of this program’s <code>PATH</code> in turn, an empty one being the working directory, or of <code>/bin:/usr/bin</code> if <code>PATH</code> is unset or empty; the first that runs is the program. If there is none, <code>spawn</code> 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 <code>p.path</code> with a <code>/</code> 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 <code>NAME=value</code> of <code>p.env</code> added or put in place of the old value, or, if <code>p.onlyEnv</code>, <code>p.env</code> alone. It starts in <code>p.dir</code>. Its standard input, output and error are <code>p.fds</code>; a 0 gives it this program’s own, so <code>{path: "ls", args: ["ls"]}</code> runs <code>ls</code> as a shell runs it, with every other field zero. It gets no other open file but those of <code>p.more</code>, each at its own number, as a shell passes <code>3&lt;file</code> on, every signal does what it does at first, and none is blocked; with <code>p.keepIgnored</code>, a signal this program ignores stays ignored in it, as the kernel’s <code>execve</code> leaves it, which is what a program run under <code>nohup</code> wants of the programs it starts. If <code>p.tty</code> 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 <code>p.fds[i]</code> that is not 0 is that file instead, as for a job that reads <code>/dev/null</code>; <code>p.group</code> is not used.</p>
1369<p><code>p.group</code> 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: <code>p.foreground</code> puts the program’s group there before it starts, and <code>foreground</code> puts any group there, as a shell does to take the terminal back. <code>setGroup</code> 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, <code>setGroup(0, 0)</code>.</p>
1370<p><code>exec</code> runs the program <code>p</code> describes in this program’s place, as a shell’s <code>exec cmd</code> does, found and started as <code>spawn</code> would start it, <code>p.tty</code>, <code>p.group</code>, <code>p.foreground</code>, <code>p.fds</code> and <code>p.dir</code> 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 <code>open</code>, <code>pipe</code>, a socket or <code>memFile</code> gives are, unless <code>keepOnExec(fd, true)</code> was said of them; <code>dup</code> and <code>dupTo</code> give files that stay open; and those of <code>p.more</code> 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 <code>p</code> asks of the terminal, the group, the files and the directory done, and this program’s signals as they were.</p>
1371<p><code>execve(path, args, env)</code> is the kernel’s execve, for a shell, which has looked for the program along its own <code>PATH</code> and set up the child already: the program at <code>path</code> is run with <code>args</code> and with <code>env</code>, <code>NAME=value</code>, 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 <code>trap '' HUP</code> wants of the command it comes before. It returns only if it can’t: minus an errno, with nothing changed.</p>
1372<p>A shell moves its own files with <code>dup</code> and <code>dupTo</code>, for <code>2&gt;&amp;1</code> and <code>exec &gt;log</code> and around a builtin: <code>dupTo(fd, into)</code> makes <code>into</code> the same open file as <code>fd</code>, closing what <code>into</code> was, and <code>dup</code> gives a new fd for it, the lowest free, as a shell saves a file to give it back. <code>dupAbove(fd, 10)</code> gives one at 10 or above, closed on exec, out of the way of the fds a script names (<code>3&gt;log</code>), as a shell keeps its own. <code>fork</code> 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 <code>Out</code> keeps is copied too, to be written twice, so <code>Out.flush</code> comes first. <code>setsid</code> 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. <code>group</code> is the process group this program is in: a shell starting on a terminal waits until it is <code>foregroundOf(0)</code> before it takes it. <code>access</code> says whether this user, by its real ids, may read, write or execute a file, as <code>test -r</code>, <code>-w</code> and <code>-x</code> ask, which <code>Info.mode</code> alone can’t say; an empty <code>how</code> asks only whether it is there. <code>open</code> refuses <code>executing</code>, with -22 (EINVAL). <code>nonblocking</code> 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 <code>nonblocking</code> 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 <code>setBlocking(fd, false)</code> makes it, and <code>blocking(fd)</code> says which: 1 if they wait, 0 if not. A file <code>open</code>, <code>openMode</code>, <code>openRead</code> or <code>create</code> gives is closed in a program <code>exec</code> or <code>execve</code> starts, as <code>pipe</code>’s are, so that a fifo or a log one program holds doesn’t reach every program it runs; <code>keepOnExec(fd, true)</code> keeps one open, and <code>spawn</code> is unchanged, since it passes its <code>fds</code> and <code>more</code> as before. <code>umask</code> sets the bits taken away from the mode of every file this program, and those it starts, make, and says what they were. <code>envAt</code> gives the environment one variable at a time, from 0, for a shell to list it and to pass it on whole with <code>onlyEnv</code>. <code>env</code> gives “” for a variable that is unset and for one set to nothing; <code>findEnv</code> tells them apart, as <code>TZ</code> needs, unset meaning the local time and empty meaning UTC. <code>setEnv</code> refuses a name that is empty or holds an <code>=</code>, and a 0 in either, with -22; as C’s <code>setenv</code>, it isn’t safe while another thread reads the environment, and what <code>env</code> gave for a variable may be gone once it sets that variable again. <code>getMode</code> reads a terminal’s modes, and <code>setMode</code> 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. <code>cpuTime</code> says how long the processor ran this program, in its own code and in the system for it, or, if <code>children</code>, the programs it started and has waited for, as <code>time</code> and <code>times</code> say. <code>limit</code> gives a limit, <code>limitFiles</code> say, soft and hard, and <code>setLimit</code> sets them, as <code>ulimit</code> does: a program may raise its soft limit up to the hard one, and lower either. <code>uid</code> is the user this program runs as, <code>euid</code> the one whose rights it has, 0 for root, as a prompt shows <code>#</code>; <code>hostName</code> is the machine’s name. <code>processors</code> 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.</p>
1373<p><code>wait</code> waits for the program <code>pid</code> to change, for any of this program’s if <code>pid</code> is -1, or for any of the group <code>g</code> if <code>pid</code> is <code>-g</code>, as a shell waits for a job’s programs, and says which one, and how: <code>exited</code>, with its exit status; <code>killed</code>, with the number of the signal that ended it; or <code>stopped</code>, by Ctrl-Z or a signal, with the signal’s number. Without <code>block</code> it doesn’t wait, and is 0 and <code>running</code> if no program changed. A program that has nothing to wait for is -10 (ECHILD). <code>waitExit(pid)</code> is <code>wait</code> 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. <code>kill</code> sends a program a signal, <code>sigTerm</code> to end it; to a group, if <code>pid</code> is minus its number.</p>
1374<p><strong>Signals.</strong> <code>catch</code> takes the signals <code>sigs</code> 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 <code>ready</code> and <code>readyOf</code> as it waits for keys or a server. <code>caught</code> gives each signal that came, in turn. A later <code>catch</code> adds to the signals caught and gives the same fd. Catching <code>sigKill</code> or <code>sigStop</code>, or the signals <code>Rt</code> reports, SIGSEGV and SIGFPE, is -22 (EINVAL). <code>ignore</code> makes a signal do nothing, as a shell ignores <code>sigTtou</code> so that it can take its terminal back, and <code>ignore(sig, false)</code> gives it back what it does at first. On a signal that <code>catch</code> took, either gives it up: the signal is no longer caught, with its default action or ignored, and <code>catch</code>’s fd gives the signals still caught. A program that <code>spawn</code> starts begins with neither. <code>ignored(sig)</code> 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 <code>nohup</code> finds <code>sigInt</code> and <code>sigHup</code>: it should leave those alone, and <code>handle</code> or <code>catch</code> the rest.</p>
1375<p>To wait for a child, a signal or a time, whichever is first, <code>catch</code> <code>sigChld</code> with the other signals and wait in <code>ready</code> on <code>catch</code>’s fd: a child that ends makes <code>sigChld</code> ready there, as a signal that came before the wait does, since <code>catch</code> holds it until <code>caught</code> takes it, so none falls between a <code>wait</code> that found nothing and the sleep after it. When the fd is ready, call <code>caught</code>, then <code>wait(pid, false)</code>. <code>handle</code> can’t do this: a signal noted just before the call it should break isn’t seen by it.</p>
1376<p><code>handle</code> 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, <code>wait</code>, <code>read</code>, <code>ready</code> and the rest, fails with -4 (EINTR) rather than going on; <code>sleep</code> sleeps its time all the same. <code>came(sig)</code> 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; <code>Out</code> and <code>Files</code> try again after -4. <code>ignore(sig, false)</code> gives the signal back what it does at first, and the signals <code>catch</code> refuses, <code>handle</code> refuses too.</p>
1377<p><strong>Time.</strong> <code>clock</code> is for measuring how long something takes: it never goes back, and says nothing of the date. <code>now</code> is the date and time, which a person or the network may set back. <code>sleep</code> waits <code>ms</code> milliseconds.</p>
1378<p><strong>Sockets.</strong> <code>connect</code> is for talking to a server on the same machine, an X server at <code>/tmp/.X11-unix/X0</code> say; <code>connectTcp</code> for one across the network, given its address as numbers, <code>"127.0.0.1"</code> or <code>"::1"</code>: turning a name into an address is a library’s work over these. <code>connectUdp</code> gives a socket of datagrams, each <code>send</code> one message to that address and each <code>read</code> one message from it, as a program asks a name server. What a socket receives comes by <code>read</code>, what it sends goes by <code>send</code>, and <code>close</code> ends it. <code>send</code> is <code>write</code> for a socket, except when the other end has closed it: <code>write</code> would stop the program with the signal SIGPIPE, where <code>send</code> returns -32 (EPIPE), so that a program learns its server has gone and can end as it wants. <code>listen</code> and <code>listenTcp</code> are the other side: a server’s socket, on <code>path</code>, which must not be there yet, or on <code>port</code> at <code>addr</code>, <code>"0.0.0.0"</code> or <code>"::"</code> for every address the machine has; <code>accept</code> gives each connection that comes, as a socket of its own. A server started on port 0 gets a port the system chooses, which <code>localPort</code> says, as a test does that must not take a port in use. <code>connectTcp</code> waits as long as the system does, minutes for a host that never answers; <code>connectTcpWithin</code> gives up after <code>ms</code> milliseconds, with -110 (ETIMEDOUT).</p>
1379<p><code>listenUdp</code> is the server’s side of <code>connectUdp</code>: a socket of datagrams from anyone, as a name server has. <code>receive</code> gives the next datagram, at most <code>LEN(buf)</code> bytes of it, the rest lost, and a <code>Peer</code> that <code>reply</code> sends an answer to.</p>
1380<p><code>closeWrite</code> 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. <code>peer</code> 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. <code>sendNow</code> is <code>send</code> that never waits: where the socket has no room it gives -11 (<code>errAgain</code>), without making reads on it non-blocking too. <code>socketPair</code> makes two connected stream sockets at once, as a <code>listen</code>, <code>connect</code> and <code>accept</code> would, with no name on disk. Each is closed in a program exec starts. <code>accept</code> gives -103 (<code>errConnAborted</code>) for a client that went before it was taken.</p>
1381<p><strong>Passing files and sharing memory.</strong> A program can give another an open file over a Unix socket: <code>sendFds</code> sends <code>s</code>, at least one byte, and with it <code>fds</code>, at most 16, each a file the other program then has open too; <code>receiveFds</code> reads into <code>buf</code> as <code>read</code> does, puts the fds that came with it in <code>fds</code>, 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. <code>memFile</code> makes a file that lives in memory, of <code>size</code> zeroed bytes, and <code>mapFile</code> 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 <code>sendFds</code> of a <code>memFile</code> both map, rather than by copying them down a socket. <code>mapFile</code> needs a file open to read and write; <code>mapRead</code> 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. <code>protect</code> changes what may be done with pages <code>mmap</code> 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.</p>
1382<p><code>readyOf</code> 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 <code>fds</code>, and <code>connect</code> and <code>listen</code> take a path of at most 107 bytes, as <code>struct sockaddr_un</code> 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 <code>unix:abstract=</code>), which has no file: the address is as long as the name, with no zero after it.</p>
1383<p><code>poll</code> is <code>readyFor</code> without its limits. Each <code>Poll</code> names a descriptor <code>fd</code> and whether to wait to <code>read</code> from it, to <code>write</code> to it, or both; <code>poll</code> waits up to <code>ms</code> milliseconds (as long as it takes if <code>ms &lt; 0</code>), sets every one’s <code>ready</code>, 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 <code>mmap</code>, given back before it returns, for more; -12 if there is none). A descriptor at its end or failed is ready, as for <code>readyOf</code>; so is one that isn’t open, and a read or a write of it is -9 (EBADF); a negative <code>fd</code> is never ready. A timeout is 0 and a failure minus an errno (-4, if a signal <code>handle</code> took broke in), where <code>readyFor</code> gives -1 for both. <code>readyFor</code> and <code>readyOf</code> are written over it.</p>
1384<p>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. <code>setBlocking(fd, false)</code> has a read or a write on <code>fd</code> that would wait return -11 (EAGAIN) at once, a write having written what there was room for; <code>readyFor</code> waits, as <code>readyOf</code> does, for something to read on any of <code>reads</code> or for room to write on any of <code>writes</code>. A descriptor in both is given once, when it is ready for either; the 64 it looks at are <code>reads</code>, then <code>writes</code>.</p>
1385<p><strong>Strings, buffers and collections.</strong></p>
1386<pre><code>module Str;
1387proc cmp*(a, b: []const U8): INT; (* -1, 0 or 1 as a sorts before, with or after b, byte by byte *)
1388proc eq*(a, b: []const U8): BOOL;
1389proc eqFold*(a, b: []const U8): BOOL; (* eq, an ASCII letter&#39;s capital and small the same *)
1390proc copy*(a: ^Mem.Allocator; s: []const U8): ([]U8, BOOL); (* s&#39;s bytes in memory from a; false if a has none *)
1391proc free*(a: ^Mem.Allocator; s: []U8); (* what copy gave from a, given back; &quot;&quot; is none *)
1392proc hash*(s: []const U8): U64; (* FNV-1a, 64 bits *)
1393proc find*(s, sub: []const U8): INT; (* where sub first starts in s, or -1 *)
1394proc findFrom*(s, sub: []const U8; from: INT): INT; (* where sub first starts in s at or after from, or -1 *)
1395proc findLast*(s, sub: []const U8): INT; (* where sub last starts in s, or -1 *)
1396proc hasPrefix*(s, p: []const U8): BOOL;
1397proc hasSuffix*(s, x: []const U8): BOOL;
1398proc trim*(s: []const U8): []const U8; (* s without the spaces at either end *)
1399proc trimLeft*(s: []const U8): []const U8; (* s without the spaces at its start *)
1400proc trimRight*(s: []const U8): []const U8; (* s without the spaces at its end *)
1401proc cut*(s, sep: []const U8): ([]const U8, []const U8, BOOL); (* what comes before the first sep, and after it *)
1402proc field*(s: []const U8): ([]const U8, []const U8); (* the first run of bytes in s that aren&#39;t spaces, and what follows it *)
1403proc isDigit*(c: U8): BOOL; (* 0 to 9 *)
1404proc isLetter*(c: U8): BOOL; (* A to Z, a to z *)
1405proc isSpace*(c: U8): BOOL; (* a space, as trim takes it *)
1406proc isPunct*(c: U8): BOOL; (* printable, and neither a letter, a digit nor the blank *)
1407proc hexVal*(c: U8): INT; (* c&#39;s value as a hexadecimal digit, or -1 *)
1408proc lower*(s: []U8); (* s&#39;s ASCII capitals made small, in place *)
1409proc upper*(s: []U8); (* s&#39;s ASCII small letters made capitals, in place *)
1410proc join*(var b: Buf.Buf; parts: [][]const U8; sep: []const U8); (* the parts added to b, sep between each two *)
1411proc replace*(var b: Buf.Buf; s, old, new: []const U8); (* s added to b, with new for each old in it *)
1412proc encode*(c: I32): ([4]U8, INT); (* c in UTF-8: its bytes, and how many *)
1413proc decode*(s: []const U8): (I32, INT); (* the character s starts with, and its length in bytes *)
1414proc decodeLast*(s: []const U8): (I32, INT); (* the character s ends with, and its length in bytes *)
1415proc next*(s: []const U8; i: INT): (I32, INT); (* the character at i, and where the next starts; -1 at the end *)
1416proc valid*(s: []const U8): BOOL; (* s is UTF-8, every character rightly spelled *)
1417proc chars*(s: []const U8): INT; (* the characters in s, as decode reads them *)
1418proc toInt*(s: []const U8): (I64, BOOL); (* s, in decimal; false if it isn&#39;t a number an I64 holds *)
1419proc toHex*(s: []const U8): (U64, BOOL); (* s, in hexadecimal; false if it isn&#39;t a number a U64 holds *)
1420proc toU64*(s: []const U8): (U64, BOOL); (* s, decimal digits only; false if it isn&#39;t one, or a U64 can&#39;t hold it *)
1421proc fromC*(p: ^U8): []const U8; (* the bytes at p up to its zero byte, not copied; &quot;&quot; for nil *)
1422proc toC*(s: []const U8; out: []U8): ^U8; (* s copied into out with a zero byte after it, which holds LEN(s) + 1 bytes at least: PTR(out) *)
1423const Base64*, Base64Url*; (* the digits of RFC 4648, sections 4 and 5 *)
1424proc base64With*(s: []const U8; out: []U8; alphabet: []const U8; pad: BOOL): INT; (* s in base64 with alphabet&#39;s 64 digits into out, which holds base64Size(LEN(s)) bytes at least, padded with = if pad: the bytes written *)
1425proc unbase64With*(s: []const U8; out: []U8; alphabet: []const U8; pad: BOOL): (INT, BOOL); (* s, base64 as base64With wrote it, into out, which holds (LEN(s) + 3) div 4 * 3 bytes at least: the bytes written; false if s is not that *)
1426proc base64Size*(n: INT): INT; (* the bytes base64 makes of n bytes: 4 for each 3, or part of 3 *)
1427proc base64*(s: []const U8; out: []U8): INT; (* s in base64 into out, which holds base64Size(LEN(s)) bytes at least: the bytes written *)
1428proc unbase64*(s: []const U8; out: []U8): (INT, BOOL); (* s, base64, into out, which holds LEN(s) div 4 * 3 bytes at least: the bytes written; false if s is not base64 *)
1429proc fromInt*(n: I64): ([20]U8, INT); (* n in decimal: its bytes, and how many *)
1430proc le*(s: []const U8): U64; (* s, at most 8 bytes, the first the lowest *)
1431proc be*(s: []const U8): U64; (* s, at most 8 bytes, the first the highest *)
1432proc putLE*(s: []U8; v: U64); (* v into s, the lowest byte first *)
1433proc putBE*(s: []U8; v: U64); (* v into s, the highest byte first *)
1434
1435module Buf;
1436type Buf* = record len*: INT; ... end;
1437proc init*(var b: Buf; a: ^Mem.Allocator);
1438proc room*(var b: Buf; n: INT): BOOL; (* room for n more bytes; false if the allocator has none *)
1439proc add*(var b: Buf; c: U8);
1440proc str*(var b: Buf; s: []const U8);
1441proc spare*(var b: Buf; n: INT): []U8; (* room for n more bytes, and those bytes, to fill *)
1442proc bytes*(const b: Buf): []U8; (* what it holds, until it next grows *)
1443proc cut*(var b: Buf; n: INT); (* only the first n bytes kept, its memory kept *)
1444proc reset*(var b: Buf); (* emptied, its memory kept *)
1445proc done*(var b: Buf); (* its memory given back *)
1446
1447module Fmt;
1448type Arg* = variant
1449 int(i: I64);
1450 uint(u: U64);
1451 hex(h: U64);
1452 lowHex(h: U64);
1453 str(s: []const U8);
1454 char(c: U8);
1455 bool(b: BOOL);
1456 real(r: F64; places: INT);
1457end;
1458const ShortMost* = 24; (* the longest Fmt.short *)
1459proc short*(x: F64; var out: [ShortMost]U8): []U8; (* x in the fewest digits that read back, in out *)
1460proc print*(f: []const U8; args: []const Arg); (* to standard output *)
1461proc eprint*(f: []const U8; args: []const Arg); (* to standard error, once Out is flushed *)
1462proc write*(var b: Buf.Buf; f: []const U8; args: []const Arg); (* added to b *)
1463proc into*(out: []U8; f: []const U8; args: []const Arg): (INT, BOOL); (* into out: the bytes, and false if cut short *)
1464
1465module List(T);
1466type
1467 Node* = record next*: ^Node; val*: T; end;
1468 List* = record head*: ^Node; len*: INT; ... end;
1469proc init*(var l: List; a: ^Mem.Allocator);
1470proc push*(var l: List; v: T): BOOL; (* v at the front; false if the allocator has no room *)
1471proc pop*(var l: List): (T, BOOL); (* the front value, taken off; false if the list is empty *)
1472proc reverse*(var l: List);
1473proc clear*(var l: List);
1474
1475module Map(K, V; hash: proc(k: K): U64; eq: proc(a, b: K): BOOL);
1476type Map* = record len*: INT; ... end;
1477proc init*(var m: Map; a: ^Mem.Allocator);
1478proc put*(var m: Map; k: K; v: V): BOOL; (* k now maps to v; false if there was no room *)
1479proc remove*(var m: Map; k: K): BOOL; (* false if k wasn&#39;t there *)
1480proc get*(const m: Map; k: K): (V, BOOL); (* what k maps to, and whether it maps to anything *)
1481proc next*(const m: Map; i: INT): (INT, K, V); (* the entry after i *)
1482proc done*(var m: Map); (* its memory given back, leaving it empty *)
1483
1484module Vec(T);
1485type Vec* = record len*: INT; ... end;
1486proc init*(var v: Vec; a: ^Mem.Allocator);
1487proc room*(var v: Vec; n: INT): BOOL; (* room for n more; false if the allocator has none *)
1488proc push*(var v: Vec; x: T); (* x added at the end *)
1489proc pop*(var v: Vec): (T, BOOL); (* the last element, taken off; false if the array is empty *)
1490proc add*(var v: Vec): ^T; (* a new element at the end, zero, to fill in place *)
1491proc tryPush*(var v: Vec; x: T): BOOL; (* push; false, and v as it was, if there is no room *)
1492proc tryAdd*(var v: Vec): (^T, BOOL); (* add; nil and false, and v as it was, if there is no room *)
1493proc resize*(var v: Vec; n: INT); (* n elements: cut short, or the new ones zero *)
1494proc insert*(var v: Vec; i, n: INT); (* n zero elements opened at i; stops the program if there is no room *)
1495proc remove*(var v: Vec; i, n: INT); (* the n elements from i taken out, those after moved down *)
1496proc all*(const v: Vec): []T; (* the elements, until it next grows *)
1497proc reset*(var v: Vec); (* emptied, its memory kept *)
1498proc done*(var v: Vec); (* its memory given back *)
1499
1500module Sort(T; less: proc(a, b: T): BOOL);
1501proc sort*(s: []T);
1502
1503module Math;
1504const pi* = 3.141592653589793;
1505proc sqrt*(x: F64): F64;
1506proc pow*(x, y: F64): F64; (* x to the power y *)
1507proc floor*(x: F64): F64;
1508proc ceil*(x: F64): F64;
1509proc round*(x: F64): F64; (* to the nearest whole number; a half away from 0 *)
1510proc roundEven*(x: F64): F64; (* to the nearest whole number; a half to the even one *)
1511proc exp*(x: F64): F64;
1512proc ln*(x: F64): F64;
1513proc log2*(x: F64): F64;
1514proc log10*(x: F64): F64;
1515proc sin*(x: F64): F64;
1516proc cos*(x: F64): F64;
1517proc tan*(x: F64): F64;
1518proc tanh*(x: F64): F64; (* from -1 to 1 *)
1519proc asin*(x: F64): F64; (* from -pi/2 to pi/2 *)
1520proc acos*(x: F64): F64; (* from 0 to pi *)
1521proc atan*(x: F64): F64; (* from -pi/2 to pi/2 *)
1522proc atan2*(y, x: F64): F64; (* the angle of (x, y) from the x axis, from -pi to pi *)
1523proc bits*(x: F64): U64; (* the bits of x, as IEEE 754 lays them out *)
1524proc fromBits*(u: U64): F64; (* the F64 whose bits are u *)
1525proc mul*(a, b: U64): (U64, U64); (* a times b: the low 64 bits of the product, and the high *)
1526proc divMod*(hi, lo, d: U64): (U64, U64); (* hi, lo divided by d: the quotient and the remainder; hi &lt; d *)
1527proc toReal*(s: []const U8): (F64, BOOL); (* s as a real, the F64 nearest it; false if it isn&#39;t one *)</code></pre>
1528<p>A <code>Buf</code>, a <code>List</code>, a <code>Map</code> and a <code>Vec</code> take their memory from the allocator <code>init</code> gives them. <code>Buf.add</code>, <code>str</code> and <code>spare</code> stop the program, as a failed check does, if the allocator has no room; <code>room</code> asks first. A program reads into a <code>Buf</code> through <code>spare</code>, then adds what it read to <code>len</code>: <code>s := Buf.spare(b, 4096); n := Sys.read(fd, s); if n &gt; 0 then INC(b.len, n); end;</code>. <code>cut</code> takes back what was added, to a length it had: <code>start := b.len; ...; Buf.cut(b, start);</code>; a length past <code>len</code> stops the program, as an index past the end does. A <code>Vec</code> is <code>Buf</code> for any <code>T</code>: one block, which doubles when it is full, so <code>push</code> costs the same on average however long it grows. <code>all</code> gives the elements as a slice, indexed and checked as any is, and <code>v.len</code> is their number; the slice, and what <code>add</code> gives, are good until the array next grows. <code>pop</code> takes the last element off, keeping the memory. <code>push</code>, <code>add</code> and <code>resize</code> stop the program, as <code>Buf.add</code> does, if the allocator has no room; <code>room</code> asks first: <code>import Lines := Vec([]U8);</code>. <code>Fmt</code>’s format takes the next argument at each <code>{}</code>; <code>{{</code> and <code>}}</code> stand for <code>{</code> and <code>}</code>. A <code>Map</code> hashes and compares its keys with the procedures it is given: <code>import Count := Map([]const U8, INT, Str.hash, Str.eq);</code>.</p>
1529<p><code>Str</code> reads and writes UTF-8. <code>encode</code> 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. <code>decode</code> reads the first character of <code>s</code>, and gives FFFDH and 1 for a byte that doesn’t start one rightly, and 0 and 0 for an empty <code>s</code>: a continuation, a byte followed by too few continuations, a surrogate, a character beyond 10FFFFH or one spelled in more bytes than it needs. <code>decodeLast</code> reads the last character in the same way, to walk a string backwards. <code>valid</code> says that <code>decode</code> finds no such byte in <code>s</code>, and <code>chars</code> counts the characters, each such byte one. <code>next</code> walks a string a character at a time, as <code>decode</code> reads them: from 0, it gives the character at <code>i</code> and where the one after it starts, and 0 and -1 when <code>i</code> is at the end, or past it:</p>
1530<pre><code>c, i := Str.next(s, 0);
1531while i &gt;= 0 do
1532 ... (* c is a character of s *)
1533 c, i := Str.next(s, i);
1534end;</code></pre>
1535<p>A string is bytes, and <code>Str</code> takes no more of Unicode than UTF-8: <code>lower</code>, <code>upper</code> and <code>eqFold</code> change and match ASCII letters alone, the character tests know ASCII alone, and nothing says how wide a character is on a terminal, nor which spellings of a text are the same.</p>
1536<p>A space, to <code>isSpace</code>, <code>trim</code>, <code>trimLeft</code>, <code>trimRight</code> and <code>field</code>, is a blank, a tab, a line feed, a carriage return, a vertical tab or a form feed. <code>cut</code> gives what comes before the first <code>sep</code> in <code>s</code>, what comes after it, and <code>true</code>; or <code>s</code>, an empty string and <code>false</code> if <code>s</code> has no <code>sep</code>. <code>field</code> passes the spaces at the start of <code>s</code> and gives the bytes up to the next space or the end, and the rest of <code>s</code> from there; two empty strings if <code>s</code> holds only spaces. They take a string apart without memory of their own, each part a slice of <code>s</code>:</p>
1537<pre><code>line, rest, more := Str.cut(text, &quot;\n&quot;); (* the first line, and the others *)
1538key, val, ok := Str.cut(line, &quot;=&quot;);
1539w, rest := Str.field(line); (* the words of a line *)
1540while LEN(w) &gt; 0 do
1541 Out.str(w); Out.ln;
1542 w, rest := Str.field(rest);
1543end;</code></pre>
1544<p><code>lower</code> and <code>upper</code> write <code>s</code>’s bytes, so they take a variable’s, not a string literal’s (section 5.10). <code>join</code> and <code>replace</code> add to a <code>Buf</code> as <code>Buf.str</code> does; an empty <code>old</code> adds <code>s</code> as it is.</p>
1545<p><code>toInt</code> reads a decimal number, with a <code>-</code> or <code>+</code> before it if any, and nothing else. <code>toHex</code> reads hexadecimal digits, capitals or not, and nothing else: no sign, <code>0x</code> or <code>H</code>. <code>fromInt</code> writes a number as <code>Out.int</code> does, with a <code>-</code> if it is negative, its bytes the first of the 20 it gives. <code>toU64</code> reads a decimal number as <code>toInt</code> does, but digits only (no sign), up to the largest <code>U64</code>: what <code>Fmt.uint</code> writes.</p>
1546<p><code>fromC</code> and <code>toC</code> are the two ends of a call to C. <code>fromC</code> makes a slice of the bytes at a pointer up to its zero byte, without copying them; <code>nil</code> gives <code>""</code>. <code>toC</code> copies <code>s</code> into <code>out</code>, puts a zero after it and gives <code>PTR(out)</code>, so a call reads <code>C.realpath(Str.toC(path, room), ...)</code>. <code>out</code> holds <code>LEN(s) + 1</code> bytes at least; a shorter one stops the program, as any slice does.</p>
1547<p><code>base64With</code> and <code>unbase64With</code> take the 64 digits as <code>alphabet</code> and say with <code>pad</code> whether <code>=</code> pads a last group: <code>Base64Url</code> is section 5’s, with <code>-</code> and <code>_</code>, and <code>Base64</code> 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. <code>base64</code> and <code>unbase64</code> are <code>Base64</code> with padding. In detail, <code>base64</code> writes <code>s</code> as RFC 4648 (section 4) does: the digits <code>A</code> to <code>Z</code>, <code>a</code> to <code>z</code>, <code>0</code> to <code>9</code>, <code>+</code> and <code>/</code>, and <code>=</code> to pad a last group of 1 or 2 bytes to four. <code>unbase64</code> reads that and nothing else: its length a multiple of 4, <code>=</code> 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 <code>base64</code> gives it. Line breaks, missing padding and the <code>-</code> and <code>_</code> of base64url are the caller’s to mend first; <code>unbase64</code> of such a string is false, and what it wrote into <code>out</code> is not to be used. The caller gives the room, as <code>Fmt</code> does: an <code>out</code> shorter than the comment says stops the program, as indexing past a slice does.</p>
1548<p><code>le</code> and <code>be</code> read an unsigned number of up to 8 bytes in a fixed order, little-endian or big-endian, whatever the machine’s own, and <code>putLE</code> and <code>putBE</code> write one; more than 8 bytes stops the program. They are how a file format or a network protocol is read and written:</p>
1549<pre><code>len := U32(Str.le(header[4..8]));
1550Str.putBE(packet[0..2], U64(port));</code></pre>
1551<p><code>Math.toReal</code> reads a real as a constant is written (section 2), with a <code>-</code> or <code>+</code> before it if any, its point and the digits after it, or its exponent, left out if it has none, and <code>e</code> taken as <code>E</code>: <code>2</code>, <code>-0.5</code> and <code>1.5e-3</code> are reals to it. It gives the <code>F64</code> nearest the number, and <code>false</code> for anything else, or a number too big for an <code>F64</code>.</p>
1552<p><code>Map.next</code> walks a map: from 0, it gives the next entry and the number to pass for the one after it, and -1 when there are no more. A walk sees each entry once if the map doesn’t change during it:</p>
1553<pre><code>i, k, v := Names.next(names, 0);
1554while i &gt;= 0 do
1555 Fmt.print(&quot;{} is {}\n&quot;, [Fmt.str(k), Fmt.int(v)]);
1556 i, k, v := Names.next(names, i);
1557end;</code></pre>
1558<p><code>Sort.sort</code> puts <code>s</code> in the order <code>less</code> gives, in place, without memory of its own, in time <code>n log n</code> at most; two elements equal by <code>less</code> may change places. <code>Math</code>’s procedures are as C’s <code>math.h</code> has them, to within the last bit or so; <code>roundEven</code> is IEEE 754’s default rounding, as Pascal’s <code>Round</code>, where <code>round</code> is C’s. <code>Fmt.real(x, places)</code> writes <code>x</code> with <code>places</code> digits after the point, at most 9, rounded to the nearest; from 1E15 on, with an exponent, as <code>1.50E17</code>; and <code>nan</code>, <code>inf</code> and <code>-inf</code> as themselves. <code>Fmt.short(x, out)</code> writes <code>x</code> into <code>out</code>, from 0, and gives those bytes: the fewest significant digits that <code>Math.toReal</code> reads back as the same <code>F64</code>, and of two such the nearer <code>x</code>: <code>0.1</code>, not <code>0.10000000000000001</code>; <code>42</code>, with no point; <code>0.0001</code>; and below 1E-4 or from 1E15 on with an exponent, as <code>1.5E17</code> or <code>5E-324</code>. Zero keeps its sign, <code>0</code> or <code>-0</code>, and <code>nan</code> and <code>inf</code> are as <code>real</code> writes them. The longest is <code>Fmt.ShortMost</code> bytes, so a call is <code>var d: [Fmt.ShortMost]U8; Fmt.print("{}", [Fmt.str(Fmt.short(x, d))]);</code>, and a width goes with <code>str</code>. The bytes are <code>out</code>’s: a second call with the same <code>out</code> overwrites them. <code>hex</code> writes capitals and <code>lowHex</code> lower case, neither with a <code>0x</code>. A width between the braces pads an argument to that many bytes: <code>{2}</code> with spaces on the left, <code>{02}</code> with zeros on the left, after a sign (<code>{04}</code> of -7 is <code>-007</code>), <code>{-10}</code> with spaces on the right. A longer argument is written whole. A <code>{</code> followed by anything but <code>}</code> or a width is dropped, as before. <code>Fmt.print("{2}:{02} U+{04}", [Fmt.int(3), Fmt.int(7), Fmt.hex(0E9H)])</code> writes <code>3:07 U+00E9</code>. <code>Fmt.into</code> 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.</p>
1559<p><strong>Files and Opt</strong> are what most programs need of their command line. <code>Files.writeAll</code> writes again after a short write or a signal, as a pipe or a socket needs, and <code>write</code> is made over it. <code>realPath</code> adds to <code>b</code> the absolute path of what <code>path</code> names, with no <code>.</code>, <code>..</code> or symbolic link in it, and leaves the working directory alone: -2 (<code>ENOENT</code>) if a part isn’t there, -20 (<code>ENOTDIR</code>) if a file is used as a directory, and -40 (<code>ELOOP</code>) after 40 links. <code>b</code> is left as it was on an error. <code>removeTree</code> removes a file, or a directory with all it holds; a symbolic link is removed itself and never followed.</p>
1560<pre><code>module Files;
1561proc argCount*: INT; (* how many arguments there are, the program&#39;s name included *)
1562proc arg*(i: INT): []const U8; (* argument i; 0 is the program&#39;s name; &quot;&quot; if there is none *)
1563proc read*(path: []const U8; var b: Buf.Buf): BOOL; (* the whole file added to b *)
1564proc load*(path: []const U8; var b: Buf.Buf): INT; (* as read: 0, or minus the errno that stopped it *)
1565proc write*(path, data: []const U8): BOOL; (* the file made to hold data; false if it or its close failed *)
1566proc writeAll*(fd: INT; s: []const U8): INT; (* all of s written to fd; 0, or minus the errno *)
1567proc realPath*(path: []const U8; var b: Buf.Buf): INT; (* the absolute path of path, plain, added to b; 0, or minus an errno *)
1568proc removeTree*(path: []const U8): INT; (* the file, or the directory and all in it, removed; 0, or minus the first errno *)
1569
1570module Opt;
1571type
1572 Row* = variant
1573 usage(scope, line: []const U8); (* a synopsis line, without &quot;usage: &quot; *)
1574 sub(scope, name, help: []const U8); (* a subcommand *)
1575 option(scope: []const U8; letter: U8; long, value, help: []const U8);
1576 end;
1577 Parser* = record
1578 letter*: U8; (* the option just read *)
1579 value*: []const U8; (* its value; &quot;&quot; for a flag *)
1580 long*: BOOL; (* it was written by its long name *)
1581 spelt*: []const U8; (* as it was written, no dashes: &quot;b&quot; or &quot;bar&quot;; to read only *)
1582 ...
1583 end;
1584proc init*(var p: Parser; name: []const U8; table: []const Row); (* the arguments from 1 on, by table *)
1585proc next*(var p: Parser): BOOL; (* the next option; false when they end *)
1586proc operand*(var p: Parser): ([]const U8, BOOL); (* the next operand; false when there are no more *)
1587proc at*(var p: Parser): INT; (* the argument operand would give next *)
1588proc scope*(var p: Parser; name: []const U8); (* subcommand name&#39;s options, from the word after it *)
1589proc number*(const p: Parser; lo, hi: I64): I64; (* the value just read, a number from lo to hi *)
1590proc refuse*(const p: Parser; wants: []const U8); (* the value just read refused, as number refuses one *)
1591proc fail*(const p: Parser; text: []const U8); (* the program&#39;s own mistake *)
1592proc misuse*(const p: Parser; text: []const U8); (* the program&#39;s own mistake, with the synopsis *)</code></pre>
1593<p><code>Opt</code> reads a command line by the rules of the C library’s <code>getopt</code>, 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 <code>Row</code>s: 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 <code>p.letter</code> 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 <code>init</code> lives as long as the procedure that makes it, and a constant, <code>const Rows: []Opt.Row = [...]</code>, as long as the program.</p>
1594<p>A row’s <code>scope</code> is <code>""</code> for the program itself, or a subcommand’s name: <code>"start"</code>, or <code>"remote.add"</code> for a subcommand of <code>remote</code>. An option has a <code>letter</code>, a <code>long</code> name, or both. One with a long name only has a key of its own below <code>'!'</code> for a letter, so that the program can tell it from the others. With a <code>value</code>, the name the help and the messages give it, the option takes a value; with <code>""</code> it is a flag. A value written in brackets, <code>"[when]"</code>, may be left out, and is <code>""</code> then: it is given only in the option’s own word, <code>--color=always</code> or <code>-calways</code>, never as the next, as <code>getopt</code>’s <code>::</code> has it, and the help shows it as <code>--color[=when]</code>.</p>
1595<pre><code>const wait = 1; (* the key of --wait, which has no letter *)
1596...
1597Opt.init(p, &quot;keep&quot;, [
1598 Opt.usage(&quot;&quot;, &quot;keep [-v] [--wait secs] start ...&quot;),
1599 Opt.sub(&quot;&quot;, &quot;start&quot;, &quot;start a job&quot;),
1600 Opt.option(&quot;&quot;, &#39;v&#39;, &quot;verbose&quot;, &quot;&quot;, &quot;say more&quot;),
1601 Opt.option(&quot;&quot;, wait, &quot;wait&quot;, &quot;secs&quot;, &quot;give the job secs to start&quot;),
1602 Opt.usage(&quot;start&quot;, &quot;keep start [-b label] name command [argument ...]&quot;),
1603 Opt.option(&quot;start&quot;, &#39;b&#39;, &quot;bar&quot;, &quot;label&quot;, &quot;show the job in the bar as label&quot;)]);
1604while Opt.next(p) do
1605 if p.letter = &#39;v&#39; then verbose := true;
1606 elsif p.letter = wait then secs := Opt.number(p, 1, 600);
1607 end;
1608end;
1609w, ok := Opt.operand(p);
1610if not ok or (w # &quot;start&quot;) then Opt.fail(p, &quot;no command; see keep -h&quot;); end;
1611Opt.scope(p, &quot;start&quot;);
1612while Opt.next(p) do
1613 if p.letter = &#39;b&#39; then bar := p.value; end;
1614end;
1615job, ok := Opt.operand(p);</code></pre>
1616<p>The rules are <code>getopt</code>’s:</p>
1617<ul>
1618<li>Flags may share a dash: <code>-lw</code> is <code>-l -w</code>. A letter’s value is the rest of its word, <code>-bdev</code>, or the whole next word, <code>-b dev</code>, even one that starts with a dash or is empty; in a group, the first letter that takes a value takes the rest, <code>-qn12</code>.</li>
1619<li>A long option is written in full, with its value after a <code>=</code> or in the next word: <code>--bar=dev</code>, <code>--bar dev</code>. An abbreviation is unknown, not guessed, so that adding an option never breaks a script. A value given to a flag, <code>--follow=x</code>, is a mistake.</li>
1620<li><code>--</code> ends the options, and isn’t an operand; <code>-</code> alone is one. The options end at the first operand, so in <code>keep start site python -m http.server</code> the <code>-m</code> is python’s.</li>
1621<li>In a scope with no option whose letter is a digit, a word of <code>-</code> and a digit, such as <code>-33.87</code>, is an operand, and so ends the options. A scope that gives a digit a letter, as <code>head -5</code> has, reads it as an option.</li>
1622<li>Each scope has its own options. An option given twice is read twice.</li>
1623</ul>
1624<p><code>number</code> reads the value as <code>Str.toInt</code> does. <code>operand</code> reads what options are left first, and the program doesn’t see them. So does <code>at</code>, which says where the operands are: the arguments from <code>operand</code>’s next on are <code>Files.arg(i)</code> for <code>i</code> from <code>at(p)</code> to <code>ARGC() - 1</code>, so that an interpreter hands a script its arguments as they are:</p>
1625<pre><code>script, ok := Opt.operand(p); (* tery file arg ... *)
1626first := Opt.at(p); (* file&#39;s own arguments, from here on *)</code></pre>
1627<p><code>-h</code> or <code>--help</code> among a scope’s options prints its help on standard output and ends the program with status 0. <code>init</code> and <code>scope</code> answer it, looking through the scope’s options before <code>next</code> gives one, so that the program has done nothing yet: <code>keep -v -h -x</code> prints the help, and the program never sees <code>-v</code>, nor the mistake. The help is the scope’s synopsis lines, a blank line, and its subcommands, its options and the help itself, each with its line of help:</p>
1628<pre><code>usage: keep start [-b label] name command [argument ...]
1629
1630 -b, --bar label show the job in the bar as label
1631 -h, --help print this and exit</code></pre>
1632<p>A scope with several synopsis lines has the others indented under the first; one with none, <code>usage:</code> and its words, as <code>usage: keep start</code>. A scope may give <code>-h</code> to an option of its own, as grep’s “no file names”; help there is <code>--help</code> alone, and its row in the help has no letter.</p>
1633<p>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:</p>
1634<pre><code>keep: unknown option -x
1635usage: keep start [-b label] name command [argument ...]</code></pre>
1636<p>The sentences are <code>unknown option -x</code> (or <code>--name</code>, up to its <code>=</code>), <code>-b needs a label</code>, <code>--follow takes no value</code> and <code>--wait wants a number from 1 to 600, not '0'</code>; for a number with no top, given the largest <code>I64</code> for <code>hi</code>, <code>--jobs wants a number from 1 up, not '0'</code>. <code>refuse</code> refuses a value the program reads itself, as <code>number</code> refuses one, naming the option as the user wrote it, <code>-b</code> or <code>--bar</code>: <code>Opt.refuse(p, "a label with no spaces")</code> writes <code>keep: -b wants a label with no spaces, not 'a b'</code>, and the synopsis lines. <code>p.spelt</code> is that spelling, for the program’s own sentences. <code>fail</code> writes the program’s own mistakes the same way, but alone, so that the sentence can say where the help is: <code>keep: no command; see keep -h</code>. <code>misuse</code> writes one with the scope’s synopsis lines after it, for a mistake in the operands: <code>Opt.misuse(p, "no tests named")</code>.</p>
1637<p>A mistake in the table is the program’s, not its user’s. <code>init</code> checks the table before it reads a word, and ends the program with status 1: <code>keep: option table, row 3: the option is in the scope already</code>. The others are an option with neither a letter nor a long name, a long name with <code>=</code> in it, a letter <code>-</code>, a value with one bracket but not the other, and <code>--help</code> in the table, since it is <code>Opt</code>’s.</p>
1638<p><strong>Width</strong> 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.</p>
1639<pre><code>module Width;
1640proc width*(c: I32): INT; (* the columns the character c takes: 0, 1 or 2 *)
1641proc columns*(s: []const U8): INT; (* the columns the UTF-8 text s takes *)</code></pre>
1642<p>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 <code>wcwidth</code>’s answers, but for a control, which is -1 there. <code>Width</code> 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 <code>tools/Widths.raz</code> for a new version of Unicode; a program that imports <code>Width</code> and calls neither procedure carries none of them.</p>
1643<p><strong>Rand, Check and Prop</strong> are for testing a program, and are standard library, not core: a target may leave them out. <code>raztest(1)</code> builds and runs the tests that use them.</p>
1644<p><code>Rand</code> is a seeded generator of numbers, splitmix64: one <code>U64</code> of state. The same seed gives the same numbers on every machine, so a run can be replayed. It is not for secrets.</p>
1645<pre><code>module Rand;
1646type Rand* = record ... end;
1647proc init*(var r: Rand; seed: U64); (* starts r at seed; any seed, 0 too *)
1648proc next*(var r: Rand): U64; (* the next number, all 64 bits of it *)
1649proc below*(var r: Rand; n: U64): U64; (* 0 to n - 1, each as likely as another; n = 0 stops the program *)
1650proc range*(var r: Rand; lo, hi: I64): I64; (* lo to hi, both included; lo must not exceed hi *)
1651proc seed*(): U64; (* a fresh seed from the kernel, to print and give back to init *)</code></pre>
1652<pre><code>module Dice;
1653import Rand, Check;
1654
1655(* Five rolls of a die from seed, as the digits of a number. *)
1656proc rolls(seed: U64): INT;
1657var r: Rand.Rand; i, v: INT;
1658begin
1659 Rand.init(r, seed);
1660 for i := 1 to 5 do v := v * 10 + INT(Rand.range(r, 1, 6)); end;
1661 return v;
1662end;
1663
1664proc main*;
1665begin
1666 Check.int(&quot;the same seed, the same rolls&quot;, rolls(7), rolls(7));
1667 Check.ok(rolls(7) &gt;= 11111, &quot;every die shows 1 or more&quot;);
1668 Check.ok(rolls(7) &lt;= 66666, &quot;every die shows 6 or less&quot;);
1669end;
1670
1671end Dice.</code></pre>
1672<p><code>Check</code> says what a test expects. A check that fails writes <code>FAIL</code> 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 <code>Rt.atExit</code> to make it. A program that stops after a check failed, by <code>Rt.stop</code> or a failed check of the language, ends with status 1 too. <code>mute</code> is for <code>Prop</code>, which searches with the checks silenced.</p>
1673<pre><code>module Check;
1674proc ok*(cond: BOOL; what: []const U8); (* fails, saying what, when cond is false *)
1675proc str*(what, got, want: []const U8); (* fails when got is not want; shows both, escaped, and the byte where they differ *)
1676proc int*(what: []const U8; got, want: I64); (* fails when got is not want; shows both *)
1677proc mute*(on: BOOL); (* while on, checks say nothing and are not counted *)
1678proc mutedFailures*(): INT; (* how many failed since mute was turned on *)</code></pre>
1679<pre><code>module Digits;
1680import Check;
1681
1682(* How many decimal digits n, not negative, takes. *)
1683proc count(n: INT): INT;
1684var d: INT;
1685begin
1686 d := 1;
1687 while n &gt;= 10 do n := n div 10; INC(d); end;
1688 return d;
1689end;
1690
1691proc main*;
1692begin
1693 Check.int(&quot;0 is one digit&quot;, count(0), 1);
1694 Check.int(&quot;9 is one digit&quot;, count(9), 1);
1695 Check.int(&quot;10 is two digits&quot;, count(10), 2);
1696 Check.ok(count(1000000) = 7, &quot;a million is seven digits&quot;);
1697end;
1698
1699end Digits.</code></pre>
1700<p><code>Prop</code> tests a property: a procedure that draws values and checks them with <code>Check</code>. A case is the bytes the property drew, and <code>Source</code> 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, <code>Prop</code> 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.</p>
1701<pre><code>module Prop;
1702type Source* = record ... end;
1703type Property* = proc(var s: Source); (* draws from s, checks with Check *)
1704proc bits*(var s: Source): U64; (* 64 bits, from 8 bytes, the first the highest *)
1705proc int*(var s: Source; lo, hi: I64): I64; (* lo to hi, both included; zeros give lo *)
1706proc pick*(var s: Source; n: INT): INT; (* 0 to n - 1; n at least 1 *)
1707proc bool*(var s: Source): BOOL;
1708proc bytes*(var s: Source; max: INT; var b: Buf.Buf); (* b, emptied, then given at most max bytes *)
1709proc check*(name: []const U8; p: Property); (* runs p on the saved cases, then on fresh ones *)</code></pre>
1710<p><code>check</code> runs <code>p</code> on each case saved in the directory <code>$PROP_DIR/name</code> (<code>test/seeds/name</code> if <code>PROP_DIR</code> is unset), then on <code>$PROP_CASES</code> fresh cases (100 if unset), from the seed <code>$PROP_SEED</code> or a new one, or for as many seconds as <code>$PROP_TIME</code> 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 <code>Check</code> 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 <code>Rt.stop</code>, a failed check of the language or a signal, can’t be shrunk; it is saved as it was, when the program ends. <code>raztest --seed</code> and <code>--fuzz</code> set <code>PROP_SEED</code> and <code>PROP_TIME</code>.</p>
1711<pre><code>module Reverse;
1712import Prop, Check, Buf, Heap;
1713
1714var
1715 b, was: Buf.Buf; (* the bytes drawn, and a copy of them *)
1716
1717(* Turns s round, in place. *)
1718proc reverse(s: []U8);
1719var i: INT; c: U8;
1720begin
1721 for i := 0 to LEN(s) div 2 - 1 do
1722 c := s[i]; s[i] := s[LEN(s) - 1 - i]; s[LEN(s) - 1 - i] := c;
1723 end;
1724end;
1725
1726(* Reversing any string twice gives it back. *)
1727proc twice(var s: Prop.Source);
1728begin
1729 Prop.bytes(s, 64, b);
1730 Buf.reset(was);
1731 Buf.str(was, Buf.bytes(b));
1732 reverse(Buf.bytes(b));
1733 reverse(Buf.bytes(b));
1734 Check.str(&quot;reversed twice&quot;, Buf.bytes(b), Buf.bytes(was));
1735end;
1736
1737proc main*;
1738begin
1739 Buf.init(b, Heap.heap);
1740 Buf.init(was, Heap.heap);
1741 Prop.check(&quot;reverse&quot;, twice);
1742end;
1743
1744end Reverse.</code></pre>
1745</div>
1746</main>
1747<footer>raz is under the ISC license. <a href="source/index.html">Source</a></footer>
1748</body>
1749</html>