Revert "site: v0.24.0" This reverts commit 0809378c88a5cd8f493da02d3404b9053ff8f94e.
| @@ -0,0 +1,78 @@ | ||
| 1 | + | |
| 2 | + | |
| 3 | +# BEGIN ladle source | |
| 4 | +/source/* | |
| 5 | + X-Content-Type-Options: nosniff | |
| 6 | + Content-Security-Policy: default-src 'none'; style-src 'self'; img-src 'self' https:; base-uri 'none'; form-action 'none'; frame-ancestors 'none' | |
| 7 | +/source/raw/* | |
| 8 | + Content-Type: text/plain; charset=utf-8 | |
| 9 | +/source/commit/*.patch | |
| 10 | + Content-Type: text/plain; charset=utf-8 | |
| 11 | +/source/feed.xml | |
| 12 | + Content-Type: application/atom+xml; charset=utf-8 | |
| 13 | +/source/releases.xml | |
| 14 | + Content-Type: application/atom+xml; charset=utf-8 | |
| 15 | +/source/objects/* | |
| 16 | + Content-Type: application/octet-stream | |
| 17 | + Cache-Control: public, max-age=31536000, immutable | |
| 18 | +/source/HEAD | |
| 19 | + Content-Type: text/plain; charset=utf-8 | |
| 20 | + Cache-Control: no-cache | |
| 21 | +/source/line | |
| 22 | + Content-Type: text/plain; charset=utf-8 | |
| 23 | + Cache-Control: no-cache | |
| 24 | +/source/info/refs | |
| 25 | + Content-Type: text/plain; charset=utf-8 | |
| 26 | + Cache-Control: no-cache | |
| 27 | +/source/objects/info/packs | |
| 28 | + ! Content-Type | |
| 29 | + ! Cache-Control | |
| 30 | + Content-Type: text/plain; charset=utf-8 | |
| 31 | + Cache-Control: no-cache | |
| 32 | +/source/releases/* | |
| 33 | + Content-Type: application/octet-stream | |
| 34 | +/source/releases/*.sha256 | |
| 35 | + ! Content-Type | |
| 36 | + Content-Type: text/plain; charset=utf-8 | |
| 37 | +/source/releases/index.html | |
| 38 | + ! Content-Type | |
| 39 | + Content-Type: text/html; charset=utf-8 | |
| 40 | +/source/releases/:version/index.html | |
| 41 | + ! Content-Type | |
| 42 | + Content-Type: text/html; charset=utf-8 | |
| 43 | +/source/releases/ | |
| 44 | + ! Content-Type | |
| 45 | + Content-Type: text/html; charset=utf-8 | |
| 46 | +/source/releases/:version/ | |
| 47 | + ! Content-Type | |
| 48 | + Content-Type: text/html; charset=utf-8 | |
| 49 | +/source/raw/*.png | |
| 50 | + ! Content-Type | |
| 51 | + Content-Type: image/png | |
| 52 | +/source/raw/*.jpg | |
| 53 | + ! Content-Type | |
| 54 | + Content-Type: image/jpeg | |
| 55 | +/source/raw/*.jpeg | |
| 56 | + ! Content-Type | |
| 57 | + Content-Type: image/jpeg | |
| 58 | +/source/raw/*.gif | |
| 59 | + ! Content-Type | |
| 60 | + Content-Type: image/gif | |
| 61 | +/source/raw/*.webp | |
| 62 | + ! Content-Type | |
| 63 | + Content-Type: image/webp | |
| 64 | +/source/raw/*.avif | |
| 65 | + ! Content-Type | |
| 66 | + Content-Type: image/avif | |
| 67 | +/source/raw/*.ico | |
| 68 | + ! Content-Type | |
| 69 | + Content-Type: image/x-icon | |
| 70 | +/source/raw/*.bmp | |
| 71 | + ! Content-Type | |
| 72 | + Content-Type: image/bmp | |
| 73 | +/source/raw/*.svg | |
| 74 | + ! Content-Type | |
| 75 | + Content-Type: image/svg+xml | |
| 76 | + ! Content-Security-Policy | |
| 77 | + Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; img-src data:; font-src data:; sandbox; frame-ancestors 'none' | |
| 78 | +# END ladle source |
| @@ -0,0 +1 @@ | ||
| 1 | +/download/latest /download/raz-0.23.0-linux-x86_64.tar.gz 302 |
| @@ -0,0 +1,202 @@ | ||
| 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>Writing an allocator - More Raz</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="Writing an allocator - More Raz"> | |
| 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.lucelad.workers.dev/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" aria-current="page">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<div class="tour"><aside><h2>More Raz</h2><h3>The library</h3><ol start='1'> | |
| 22 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 23 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 24 | +<li><a href="collections.html">Lists, arrays, maps and sorting</a></li> | |
| 25 | +<li><a href="files.html">Files and the command line</a></li> | |
| 26 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 27 | +<li><a href="allocators.html" aria-current="page">Writing an allocator</a></li> | |
| 28 | +</ol> | |
| 29 | +<h3>Standing alone</h3><ol start='7'> | |
| 30 | +<li><a href="static.html">A program with no run time</a></li> | |
| 31 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 32 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 33 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 34 | +</ol> | |
| 35 | +<h3>The machine</h3><ol start='11'> | |
| 36 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 37 | +<li><a href="syscalls.html">System calls</a></li> | |
| 38 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 39 | +</ol> | |
| 40 | +<h3>Shared memory</h3><ol start='14'> | |
| 41 | +<li><a href="volatile.html">Volatile</a></li> | |
| 42 | +<li><a href="atomics.html">Atomics</a></li> | |
| 43 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 44 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 45 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 46 | +</ol></aside><article><p class="kicker">The library · lesson 6 of 18</p><h1>Writing an allocator</h1> | |
| 47 | +<p>An allocator is a record of two procedures, and that is all <code>Mem.Allocator</code> is:</p> | |
| 48 | +<pre class="code"><code>type Allocator* = record | |
| 49 | + alloc*: proc(a: ^Allocator; size, align: INT): ^U8; (* nil if out of room *) | |
| 50 | + free*: proc(a: ^Allocator; p: ^U8); | |
| 51 | +end;</code></pre> | |
| 52 | +<p><code>NEW(p, a)</code> calls <code>a^.alloc(a, SIZE(T), alignment)</code> and zeroes what it gets. <code>Buf</code>, <code>List</code> and <code>Map</code> call the same procedures. So anything that fills in these two fields is an allocator, and everything in the library works with it.</p> | |
| 53 | +<h2>An allocator over a fixed array</h2> | |
| 54 | +<p>Here is one that needs no system calls at all: it hands out memory from an array in the program, a bump allocator. This is the kind a program with no operating system, or no room for a heap, uses. <code>free</code> has nothing to do; <code>reset</code> forgets everything.</p> | |
| 55 | +<p>The trick that lets one procedure find its state is the same one <code>Arena</code> uses: the record puts <code>base: Mem.Allocator</code> first, so a <code>^Mem.Allocator</code> and a <code>^Bump</code> are the same address, and the procedure converts one to the other.</p> | |
| 56 | +<div class="file"><span>Bump.raz</span></div><pre class="code"><code><span class="kw">module</span> Bump; | |
| 57 | +<span class="kw">import</span> Mem; | |
| 58 | + | |
| 59 | +<span class="kw">type</span> | |
| 60 | + Bump* = <span class="kw">record</span> | |
| 61 | + base*: Mem.Allocator; <span class="comment">(* first, so that ^Bump(a) finds the rest *)</span> | |
| 62 | + mem: ^<span class="ty">U8</span>; | |
| 63 | + size, used*: <span class="ty">INT</span>; | |
| 64 | + <span class="kw">end</span>; | |
| 65 | + | |
| 66 | +<span class="kw">proc</span> alloc(a: ^Mem.Allocator; size, align: <span class="ty">INT</span>): ^<span class="ty">U8</span>; | |
| 67 | +<span class="kw">var</span> b: ^Bump; at: <span class="ty">INT</span>; | |
| 68 | +<span class="kw">begin</span> | |
| 69 | + b := ^Bump(a); | |
| 70 | + at := (b^.used + align - <span class="number">1</span>) <span class="kw">div</span> align * align; <span class="comment">(* round up to align *)</span> | |
| 71 | + <span class="kw">if</span> (size < <span class="number">0</span>) <span class="kw">or</span> (at + size > b^.size) <span class="kw">then</span> <span class="kw">return</span> <span class="ty">nil</span>; <span class="kw">end</span>; | |
| 72 | + b^.used := at + size; | |
| 73 | + <span class="kw">return</span> b^.mem + at; | |
| 74 | +<span class="kw">end</span>; | |
| 75 | + | |
| 76 | +<span class="kw">proc</span> free(_a: ^Mem.Allocator; _p: ^<span class="ty">U8</span>); | |
| 77 | +<span class="kw">begin</span> | |
| 78 | +<span class="kw">end</span>; | |
| 79 | + | |
| 80 | +<span class="comment">(* a bump allocator over the size bytes at mem *)</span> | |
| 81 | +<span class="kw">proc</span> init*(b: ^Bump; mem: ^<span class="ty">U8</span>; size: <span class="ty">INT</span>); | |
| 82 | +<span class="kw">begin</span> | |
| 83 | + b^.base := {alloc: alloc, free: free}; | |
| 84 | + b^.mem := mem; | |
| 85 | + b^.size := size; | |
| 86 | + b^.used := <span class="number">0</span>; | |
| 87 | +<span class="kw">end</span>; | |
| 88 | + | |
| 89 | +<span class="comment">(* everything forgotten, the memory used again *)</span> | |
| 90 | +<span class="kw">proc</span> reset*(b: ^Bump); | |
| 91 | +<span class="kw">begin</span> | |
| 92 | + b^.used := <span class="number">0</span>; | |
| 93 | +<span class="kw">end</span>; | |
| 94 | + | |
| 95 | +<span class="kw">end</span> Bump.</code></pre> | |
| 96 | +<div class="file"><span>Bumping.raz</span></div><pre class="code"><code><span class="kw">module</span> Bumping; | |
| 97 | +<span class="kw">import</span> Out, Bump; | |
| 98 | + | |
| 99 | +<span class="kw">type</span> Point = <span class="kw">record</span> x, y: <span class="ty">INT</span>; <span class="kw">end</span>; | |
| 100 | + | |
| 101 | +<span class="kw">var</span> arena: [<span class="number">256</span>]<span class="ty">U8</span>; <span class="comment">(* the allocator's whole world *)</span> | |
| 102 | + | |
| 103 | +<span class="kw">proc</span> main*; | |
| 104 | +<span class="kw">var</span> b: Bump.Bump; p, q: ^Point; many: <span class="ty">INT</span>; r: ^Point; | |
| 105 | +<span class="kw">begin</span> | |
| 106 | + Bump.init(<span class="ty">ADR</span>(b), <span class="ty">ADR</span>(arena[<span class="number">0</span>]), <span class="number">256</span>); | |
| 107 | + <span class="ty">NEW</span>(p, <span class="ty">ADR</span>(b.base)); | |
| 108 | + <span class="ty">NEW</span>(q, <span class="ty">ADR</span>(b.base)); | |
| 109 | + p^.x := <span class="number">1</span>; q^.y := <span class="number">2</span>; | |
| 110 | + Out.int(b.used); Out.str(<span class="string">" bytes used by two points\n"</span>); | |
| 111 | + many := <span class="number">2</span>; | |
| 112 | + <span class="kw">repeat</span> | |
| 113 | + <span class="ty">NEW</span>(r, <span class="ty">ADR</span>(b.base)); | |
| 114 | + <span class="kw">if</span> r # <span class="ty">nil</span> <span class="kw">then</span> <span class="ty">INC</span>(many); <span class="kw">end</span>; | |
| 115 | + <span class="kw">until</span> r = <span class="ty">nil</span>; | |
| 116 | + Out.int(many); Out.str(<span class="string">" points fit in 256 bytes\n"</span>); | |
| 117 | + Bump.reset(<span class="ty">ADR</span>(b)); | |
| 118 | + <span class="ty">NEW</span>(r, <span class="ty">ADR</span>(b.base)); | |
| 119 | + <span class="kw">if</span> r # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="string">"room again after a reset\n"</span>); <span class="kw">end</span>; | |
| 120 | +<span class="kw">end</span>; | |
| 121 | + | |
| 122 | +<span class="kw">end</span> Bumping.</code></pre> | |
| 123 | +<pre class="output"><code>32 bytes used by two points | |
| 124 | +16 points fit in 256 bytes | |
| 125 | +room again after a reset | |
| 126 | +</code></pre> | |
| 127 | +<p>An allocator that runs out says so with <code>nil</code>, and the caller decides what that means. Nothing else in the program is touched.</p> | |
| 128 | +<h2>An allocator that counts</h2> | |
| 129 | +<p>An allocator can wrap another. This one forwards to whatever it is given and keeps count, which is how to find out what a piece of code allocates, or to prove that a path allocates nothing.</p> | |
| 130 | +<div class="file"><span>Counted.raz</span></div><pre class="code"><code><span class="kw">module</span> Counted; | |
| 131 | +<span class="kw">import</span> Mem; | |
| 132 | + | |
| 133 | +<span class="kw">type</span> | |
| 134 | + Counted* = <span class="kw">record</span> | |
| 135 | + base*: Mem.Allocator; <span class="comment">(* first *)</span> | |
| 136 | + inner: ^Mem.Allocator; | |
| 137 | + allocs*, frees*, bytes*: <span class="ty">INT</span>; | |
| 138 | + <span class="kw">end</span>; | |
| 139 | + | |
| 140 | +<span class="kw">proc</span> alloc(a: ^Mem.Allocator; size, align: <span class="ty">INT</span>): ^<span class="ty">U8</span>; | |
| 141 | +<span class="kw">var</span> c: ^Counted; p: ^<span class="ty">U8</span>; | |
| 142 | +<span class="kw">begin</span> | |
| 143 | + c := ^Counted(a); | |
| 144 | + p := Mem.alloc(c^.inner, size, align); | |
| 145 | + <span class="kw">if</span> p # <span class="ty">nil</span> <span class="kw">then</span> <span class="ty">INC</span>(c^.allocs); <span class="ty">INC</span>(c^.bytes, size); <span class="kw">end</span>; | |
| 146 | + <span class="kw">return</span> p; | |
| 147 | +<span class="kw">end</span>; | |
| 148 | + | |
| 149 | +<span class="kw">proc</span> free(a: ^Mem.Allocator; p: ^<span class="ty">U8</span>); | |
| 150 | +<span class="kw">var</span> c: ^Counted; | |
| 151 | +<span class="kw">begin</span> | |
| 152 | + c := ^Counted(a); | |
| 153 | + <span class="ty">INC</span>(c^.frees); | |
| 154 | + Mem.free(c^.inner, p); | |
| 155 | +<span class="kw">end</span>; | |
| 156 | + | |
| 157 | +<span class="comment">(* a counting allocator in front of inner *)</span> | |
| 158 | +<span class="kw">proc</span> init*(c: ^Counted; inner: ^Mem.Allocator); | |
| 159 | +<span class="kw">begin</span> | |
| 160 | + c^.base := {alloc: alloc, free: free}; | |
| 161 | + c^.inner := inner; | |
| 162 | + c^.allocs := <span class="number">0</span>; | |
| 163 | + c^.frees := <span class="number">0</span>; | |
| 164 | + c^.bytes := <span class="number">0</span>; | |
| 165 | +<span class="kw">end</span>; | |
| 166 | + | |
| 167 | +<span class="kw">end</span> Counted.</code></pre> | |
| 168 | +<div class="file"><span>Audit.raz</span></div><pre class="code"><code><span class="kw">module</span> Audit; | |
| 169 | +<span class="kw">import</span> Fmt, Heap, Mem, Buf, Counted, Names := List([]<span class="ty">U8</span>); | |
| 170 | + | |
| 171 | +<span class="kw">proc</span> main*; | |
| 172 | +<span class="kw">var</span> c: Counted.Counted; b: Buf.Buf; l: Names.List; i: <span class="ty">INT</span>; p: ^<span class="ty">U8</span>; | |
| 173 | +<span class="kw">begin</span> | |
| 174 | + Counted.init(<span class="ty">ADR</span>(c), Heap.heap); | |
| 175 | + Buf.init(b, <span class="ty">ADR</span>(c.base)); | |
| 176 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">200</span> <span class="kw">do</span> Buf.str(b, <span class="string">"0123456789"</span>); <span class="kw">end</span>; | |
| 177 | + Fmt.print(<span class="string">"a buffer of {} bytes took {} allocations\n"</span>, | |
| 178 | + [Fmt.int(b.len), Fmt.int(c.allocs)]); | |
| 179 | + Buf.done(b); | |
| 180 | + | |
| 181 | + Names.init(l, <span class="ty">ADR</span>(c.base)); | |
| 182 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">10</span> <span class="kw">do</span> _ := Names.push(l, <span class="string">"x"</span>); <span class="kw">end</span>; | |
| 183 | + Fmt.print(<span class="string">"{} allocations in all, {} frees so far\n"</span>, [Fmt.int(c.allocs), Fmt.int(c.frees)]); | |
| 184 | + Names.clear(l); | |
| 185 | + Fmt.print(<span class="string">"{} frees after clear\n"</span>, [Fmt.int(c.frees)]); | |
| 186 | + | |
| 187 | + p := Mem.alloc(<span class="ty">ADR</span>(c.base), <span class="number">64</span>, <span class="number">8</span>); | |
| 188 | + Mem.free(<span class="ty">ADR</span>(c.base), p); | |
| 189 | +<span class="kw">end</span>; | |
| 190 | + | |
| 191 | +<span class="kw">end</span> Audit.</code></pre> | |
| 192 | +<pre class="output"><code>a buffer of 2000 bytes took 6 allocations | |
| 193 | +16 allocations in all, 6 frees so far | |
| 194 | +16 frees after clear | |
| 195 | +</code></pre> | |
| 196 | +<p>A <code>Buf</code> grows by doubling, so two thousand bytes took a handful of allocations and not two hundred. That is the sort of thing a counting allocator is for.</p> | |
| 197 | +<h2>What to take from this</h2> | |
| 198 | +<ul><li>An allocator is a value, so it is passed, wrapped, swapped in a test and replaced by a bump allocator in a program with no heap.</li><li>A library function that needs memory takes the allocator as a parameter, so its caller owns the policy.</li><li>An allocator can use the record-first trick to carry any state it needs, because converting a pointer to a record's first field and back is the same address.</li></ul><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="processes.html">← Time, randomness and other programs</a><a href="index.html">Contents</a><a class="next" href="static.html">A program with no run time →</a></div></article></div> | |
| 199 | +</main> | |
| 200 | +<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> | |
| 201 | +</body> | |
| 202 | +</html> |
| @@ -0,0 +1,259 @@ | ||
| 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>Procedures in assembly - More Raz</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="Procedures in assembly - More Raz"> | |
| 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.lucelad.workers.dev/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" aria-current="page">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<div class="tour"><aside><h2>More Raz</h2><h3>The library</h3><ol start='1'> | |
| 22 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 23 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 24 | +<li><a href="collections.html">Lists, arrays, maps and sorting</a></li> | |
| 25 | +<li><a href="files.html">Files and the command line</a></li> | |
| 26 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 27 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 28 | +</ol> | |
| 29 | +<h3>Standing alone</h3><ol start='7'> | |
| 30 | +<li><a href="static.html">A program with no run time</a></li> | |
| 31 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 32 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 33 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 34 | +</ol> | |
| 35 | +<h3>The machine</h3><ol start='11'> | |
| 36 | +<li><a href="asm.html" aria-current="page">Procedures in assembly</a></li> | |
| 37 | +<li><a href="syscalls.html">System calls</a></li> | |
| 38 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 39 | +</ol> | |
| 40 | +<h3>Shared memory</h3><ol start='14'> | |
| 41 | +<li><a href="volatile.html">Volatile</a></li> | |
| 42 | +<li><a href="atomics.html">Atomics</a></li> | |
| 43 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 44 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 45 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 46 | +</ol></aside><article><p class="kicker">The machine · lesson 11 of 18</p><h1>Procedures in assembly</h1> | |
| 47 | +<p>Sometimes a program needs an instruction the language has no word for: reading the cycle counter, asking the CPU what it is, counting bits in one instruction, a square root in the hardware. A procedure whose body is <code>code</code> is machine code, written by hand in the target's assembly language, one instruction to each <code>;</code>, up to <code>end</code>.</p> | |
| 48 | +<p>The compiler doesn't look past what the instructions say. It trusts you, and you owe it a few rules.</p> | |
| 49 | +<h2>A first one</h2> | |
| 50 | +<p>This reads the processor's time stamp counter. The result of a procedure goes in <code>rax</code>; <code>rdtsc</code> leaves the counter in <code>edx:eax</code>, so the two halves are joined first.</p> | |
| 51 | +<div class="file"><span>Cycles.raz</span></div><pre class="code"><code><span class="kw">module</span> Cycles; | |
| 52 | +<span class="kw">import</span> Out; | |
| 53 | + | |
| 54 | +<span class="kw">proc</span> rdtsc*: <span class="ty">U64</span>; | |
| 55 | +<span class="kw">code</span> | |
| 56 | + rdtsc; | |
| 57 | + <span class="kw">shl</span> rdx, <span class="number">32</span>; | |
| 58 | + <span class="kw">or</span> rax, rdx; | |
| 59 | + ret; | |
| 60 | +<span class="kw">end</span> rdtsc; | |
| 61 | + | |
| 62 | +<span class="kw">proc</span> main*; | |
| 63 | +<span class="kw">var</span> a, b: <span class="ty">U64</span>; | |
| 64 | +<span class="kw">begin</span> | |
| 65 | + a := rdtsc(); | |
| 66 | + b := rdtsc(); | |
| 67 | + <span class="kw">if</span> b > a <span class="kw">then</span> Out.str(<span class="string">"the counter moves forward\n"</span>); <span class="kw">end</span>; | |
| 68 | +<span class="kw">end</span>; | |
| 69 | + | |
| 70 | +<span class="kw">end</span> Cycles.</code></pre> | |
| 71 | +<pre class="output"><code>the counter moves forward | |
| 72 | +</code></pre> | |
| 73 | +<p>A code procedure is called like any procedure. Everything in it is yours, <code>ret</code> included.</p> | |
| 74 | +<h2>The convention</h2> | |
| 75 | +<p>A code procedure follows the System V convention, as every raz procedure does:</p> | |
| 76 | +<ul><li>Integer and pointer arguments 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>.</li><li>The result goes in <code>rax</code> (and <code>rdx</code> for a second) or <code>xmm0</code>.</li><li>It must keep <code>rbx</code>, <code>rbp</code>, <code>rsp</code> and <code>r12</code> to <code>r15</code> as it found them. <code>rax</code>, <code>rcx</code>, <code>rdx</code>, <code>rsi</code>, <code>rdi</code> and <code>r8</code> to <code>r11</code> are free to change.</li><li>A slice is two integers, its address and its length, as System V passes a struct of two. As a parameter it takes two registers in a row; as the result its address goes in <code>rax</code> and its length in <code>rdx</code>.</li><li>Its parameters and results are therefore of the types C can take, or slices: at most six integer and eight real parameters, and two results, a slice being the only one.</li></ul> | |
| 77 | +<p>That is why the next one is so short: the argument is already in <code>rdi</code>.</p> | |
| 78 | +<div class="file"><span>Bits.raz</span></div><pre class="code"><code><span class="kw">module</span> Bits; | |
| 79 | +<span class="kw">import</span> Out; | |
| 80 | + | |
| 81 | +<span class="comment">(* the bytes of x in the opposite order: bswap rax, which the assembler | |
| 82 | + doesn't know, written as its bytes *)</span> | |
| 83 | +<span class="kw">proc</span> swap64(x: <span class="ty">U64</span>): <span class="ty">U64</span>; | |
| 84 | +<span class="kw">code</span> | |
| 85 | + mov rax, rdi; | |
| 86 | + db <span class="number">48H</span>, <span class="number">0FH</span>, <span class="number">0C8H</span>; | |
| 87 | + ret; | |
| 88 | +<span class="kw">end</span> swap64; | |
| 89 | + | |
| 90 | +<span class="comment">(* the number of bits set in x *)</span> | |
| 91 | +<span class="kw">proc</span> ones(x: <span class="ty">U64</span>): <span class="ty">INT</span>; | |
| 92 | +<span class="kw">code</span> | |
| 93 | + popcnt rax, rdi; | |
| 94 | + ret; | |
| 95 | +<span class="kw">end</span> ones; | |
| 96 | + | |
| 97 | +<span class="kw">proc</span> main*; | |
| 98 | +<span class="kw">begin</span> | |
| 99 | + Out.str(<span class="string">"0x"</span>); Out.hex(swap64(<span class="number">0102030405060708H</span>), <span class="number">16</span>); Out.ln; | |
| 100 | + Out.int(ones(<span class="number">0FFH</span>)); Out.char(<span class="string">' '</span>); | |
| 101 | + Out.int(ones(<span class="number">0</span>)); Out.char(<span class="string">' '</span>); | |
| 102 | + Out.int(ones(<span class="number">0FFFFFFFFFFFFFFFFH</span>)); Out.ln; | |
| 103 | +<span class="kw">end</span>; | |
| 104 | + | |
| 105 | +<span class="kw">end</span> Bits.</code></pre> | |
| 106 | +<pre class="output"><code>0x0807060504030201 | |
| 107 | +8 0 64 | |
| 108 | +</code></pre> | |
| 109 | +<p><code>db</code> writes any bytes, for an instruction the assembler doesn't know. Which instructions it knows is the implementation's business: this one knows <code>popcnt</code> but not <code>bswap</code>, and <code>db</code> keeps you from waiting for it to learn one. (<code>bswap r64</code> is <code>REX.W 0F C8+r</code> in the processor manuals.)</p> | |
| 110 | +<h2>Labels and loops</h2> | |
| 111 | +<p>A label, <code>name:</code>, names the place of the instruction after it, within the procedure. Jumps go to labels, and a constant of the module may stand wherever a number does. This sums a slice of <code>INT</code>s, whose address arrives in <code>rdi</code> and its length in <code>rsi</code>:</p> | |
| 112 | +<div class="file"><span>Sum.raz</span></div><pre class="code"><code><span class="kw">module</span> Sum; | |
| 113 | +<span class="kw">import</span> Out; | |
| 114 | + | |
| 115 | +<span class="comment">(* the sum of the INTs of a *)</span> | |
| 116 | +<span class="kw">proc</span> sum(a: []<span class="ty">INT</span>): <span class="ty">INT</span>; | |
| 117 | +<span class="kw">code</span> | |
| 118 | + <span class="kw">xor</span> eax, eax; | |
| 119 | + test rsi, rsi; | |
| 120 | + jle done; | |
| 121 | +again: | |
| 122 | + add rax, [rdi]; | |
| 123 | + add rdi, <span class="number">8</span>; | |
| 124 | + dec rsi; | |
| 125 | + jnz again; | |
| 126 | +done: | |
| 127 | + ret; | |
| 128 | +<span class="kw">end</span> sum; | |
| 129 | + | |
| 130 | +<span class="comment">(* the same in raz, to check it against *)</span> | |
| 131 | +<span class="kw">proc</span> sumRaz(a: []<span class="ty">INT</span>): <span class="ty">INT</span>; | |
| 132 | +<span class="kw">var</span> i, t: <span class="ty">INT</span>; | |
| 133 | +<span class="kw">begin</span> | |
| 134 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="ty">LEN</span>(a) - <span class="number">1</span> <span class="kw">do</span> t := t + a[i]; <span class="kw">end</span>; | |
| 135 | + <span class="kw">return</span> t; | |
| 136 | +<span class="kw">end</span>; | |
| 137 | + | |
| 138 | +<span class="kw">proc</span> main*; | |
| 139 | +<span class="kw">var</span> a: [<span class="number">6</span>]<span class="ty">INT</span>; i: <span class="ty">INT</span>; | |
| 140 | +<span class="kw">begin</span> | |
| 141 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">5</span> <span class="kw">do</span> a[i] := (i + <span class="number">1</span>) * <span class="number">100</span>; <span class="kw">end</span>; | |
| 142 | + Out.int(sum(a)); Out.char(<span class="string">' '</span>); | |
| 143 | + Out.int(sumRaz(a)); Out.char(<span class="string">' '</span>); | |
| 144 | + Out.int(sum(a[<span class="number">2</span>..<span class="number">4</span>])); Out.char(<span class="string">' '</span>); | |
| 145 | + Out.int(sum(a[<span class="number">0</span>..<span class="number">0</span>])); Out.ln; | |
| 146 | +<span class="kw">end</span>; | |
| 147 | + | |
| 148 | +<span class="kw">end</span> Sum.</code></pre> | |
| 149 | +<pre class="output"><code>2100 2100 700 0 | |
| 150 | +</code></pre> | |
| 151 | +<p>The procedure trusts the length it is given, as it must: the checks of the language end where its code begins.</p> | |
| 152 | +<p>A slice comes back the same way, its address in <code>rax</code> and its length in <code>rdx</code>. This one returns what is left of a string past its leading blanks:</p> | |
| 153 | +<div class="file"><span>Trim.raz</span></div><pre class="code"><code><span class="kw">module</span> Trim; | |
| 154 | +<span class="kw">import</span> Out; | |
| 155 | + | |
| 156 | +<span class="comment">(* s past its leading blanks *)</span> | |
| 157 | +<span class="kw">proc</span> trim(s: []<span class="ty">U8</span>): []<span class="ty">U8</span>; | |
| 158 | +<span class="kw">code</span> | |
| 159 | + mov rax, rdi; | |
| 160 | + mov rdx, rsi; | |
| 161 | +again: | |
| 162 | + test rdx, rdx; | |
| 163 | + jz done; | |
| 164 | + cmp byte [rax], <span class="number">32</span>; | |
| 165 | + jne done; | |
| 166 | + inc rax; | |
| 167 | + dec rdx; | |
| 168 | + jmp again; | |
| 169 | +done: | |
| 170 | + ret; | |
| 171 | +<span class="kw">end</span> trim; | |
| 172 | + | |
| 173 | +<span class="kw">proc</span> main*; | |
| 174 | +<span class="kw">begin</span> | |
| 175 | + Out.char(<span class="string">'['</span>); Out.str(trim(<span class="string">" raz"</span>)); Out.str(<span class="string">"]\n"</span>); | |
| 176 | + Out.char(<span class="string">'['</span>); Out.str(trim(<span class="string">"raz"</span>)); Out.str(<span class="string">"]\n"</span>); | |
| 177 | + Out.char(<span class="string">'['</span>); Out.str(trim(<span class="string">" "</span>)); Out.str(<span class="string">"]\n"</span>); | |
| 178 | +<span class="kw">end</span>; | |
| 179 | + | |
| 180 | +<span class="kw">end</span> Trim.</code></pre> | |
| 181 | +<pre class="output"><code>[raz] | |
| 182 | +[raz] | |
| 183 | +[] | |
| 184 | +</code></pre> | |
| 185 | +<p>A procedure may have up to 64 labels. The check against the raz version is the habit worth keeping: write the procedure in raz first, then in assembly, and compare their results on awkward inputs.</p> | |
| 186 | +<h2>Two results, and reals</h2> | |
| 187 | +<p>A second result goes in <code>rdx</code>. That is exactly where <code>idiv</code> leaves the remainder, so <code>divmod</code> is four instructions. Reals travel in the <code>xmm</code> registers.</p> | |
| 188 | +<div class="file"><span>Divmod.raz</span></div><pre class="code"><code><span class="kw">module</span> Divmod; | |
| 189 | +<span class="kw">import</span> Out, Fmt; | |
| 190 | + | |
| 191 | +<span class="comment">(* quotient and remainder, as idiv gives them: rax and rdx *)</span> | |
| 192 | +<span class="kw">proc</span> divmod(a, b: <span class="ty">INT</span>): (<span class="ty">INT</span>, <span class="ty">INT</span>); | |
| 193 | +<span class="kw">code</span> | |
| 194 | + mov rax, rdi; | |
| 195 | + cqo; | |
| 196 | + idiv rsi; | |
| 197 | + ret; | |
| 198 | +<span class="kw">end</span> divmod; | |
| 199 | + | |
| 200 | +<span class="comment">(* a * x + b, on F64s in xmm0 to xmm2 *)</span> | |
| 201 | +<span class="kw">proc</span> fma(a, x, b: <span class="ty">F64</span>): <span class="ty">F64</span>; | |
| 202 | +<span class="kw">code</span> | |
| 203 | + mulsd xmm0, xmm1; | |
| 204 | + addsd xmm0, xmm2; | |
| 205 | + ret; | |
| 206 | +<span class="kw">end</span> fma; | |
| 207 | + | |
| 208 | +<span class="kw">proc</span> main*; | |
| 209 | +<span class="kw">var</span> q, r: <span class="ty">INT</span>; | |
| 210 | +<span class="kw">begin</span> | |
| 211 | + q, r := divmod(-<span class="number">17</span>, <span class="number">5</span>); | |
| 212 | + Out.int(q); Out.char(<span class="string">' '</span>); Out.int(r); Out.ln; | |
| 213 | + Fmt.print(<span class="string">"{}\n"</span>, [Fmt.real(fma(<span class="number">2.0</span>, <span class="number">3.5</span>, <span class="number">0.25</span>), <span class="number">2</span>)]); | |
| 214 | +<span class="kw">end</span>; | |
| 215 | + | |
| 216 | +<span class="kw">end</span> Divmod.</code></pre> | |
| 217 | +<pre class="output"><code>-3 -2 | |
| 218 | +7.25 | |
| 219 | +</code></pre> | |
| 220 | +<p><code>idiv</code> by zero stops the program with the machine's own division fault. It isn't a check the compiler added, since the compiler doesn't look inside a code procedure.</p> | |
| 221 | +<h2>Keeping what isn't yours</h2> | |
| 222 | +<p>A procedure that uses <code>rbx</code> must put it back. <code>cpuid</code> clobbers <code>rbx</code>, so the vendor-string example saves it with <code>push</code> and restores it with <code>pop</code>, and keeps the buffer's address in <code>r8</code> while it works:</p> | |
| 223 | +<div class="file"><span>Vendor.raz</span></div><pre class="code"><code><span class="kw">module</span> Vendor; | |
| 224 | +<span class="kw">import</span> Out; | |
| 225 | + | |
| 226 | +<span class="comment">(* the 12 bytes of the processor vendor, in buf (rdi) *)</span> | |
| 227 | +<span class="kw">proc</span> vendor(buf: ^<span class="ty">U8</span>); | |
| 228 | +<span class="kw">code</span> | |
| 229 | + push rbx; | |
| 230 | + mov r8, rdi; | |
| 231 | + <span class="kw">xor</span> eax, eax; | |
| 232 | + cpuid; | |
| 233 | + mov [r8], ebx; | |
| 234 | + mov [r8 + <span class="number">4</span>], edx; | |
| 235 | + mov [r8 + <span class="number">8</span>], ecx; | |
| 236 | + pop rbx; | |
| 237 | + ret; | |
| 238 | +<span class="kw">end</span> vendor; | |
| 239 | + | |
| 240 | +<span class="kw">proc</span> main*; | |
| 241 | +<span class="kw">var</span> buf: [<span class="number">12</span>]<span class="ty">U8</span>; i: <span class="ty">INT</span>; ok: <span class="ty">BOOL</span>; | |
| 242 | +<span class="kw">begin</span> | |
| 243 | + vendor(<span class="ty">ADR</span>(buf[<span class="number">0</span>])); | |
| 244 | + ok := <span class="ty">true</span>; | |
| 245 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">11</span> <span class="kw">do</span> | |
| 246 | + <span class="kw">if</span> (buf[i] < <span class="string">' '</span>) <span class="kw">or</span> (buf[i] > <span class="string">'~'</span>) <span class="kw">then</span> ok := <span class="ty">false</span>; <span class="kw">end</span>; | |
| 247 | + <span class="kw">end</span>; | |
| 248 | + <span class="kw">if</span> ok <span class="kw">then</span> Out.str(<span class="string">"the vendor is 12 printable bytes\n"</span>); <span class="kw">end</span>; | |
| 249 | +<span class="kw">end</span>; | |
| 250 | + | |
| 251 | +<span class="kw">end</span> Vendor.</code></pre> | |
| 252 | +<pre class="output"><code>the vendor is 12 printable bytes | |
| 253 | +</code></pre> | |
| 254 | +<h2>What goes wrong</h2> | |
| 255 | +<p>A code procedure that breaks its rules breaks the program, and what follows isn't defined. Writing through a wrong pointer, a changed <code>rbx</code>, a missing <code>ret</code>, a stack left unbalanced: the language can't help, because it doesn't see inside. Keep them short, give each a comment that says what it expects in which register, test each against a raz twin, and use them for what only the machine can do.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="targets.html">← One module, one file per target</a><a href="index.html">Contents</a><a class="next" href="syscalls.html">System calls →</a></div></article></div> | |
| 256 | +</main> | |
| 257 | +<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> | |
| 258 | +</body> | |
| 259 | +</html> |
| @@ -0,0 +1,204 @@ | ||
| 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>Atomics - More Raz</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="Atomics - More Raz"> | |
| 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.lucelad.workers.dev/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" aria-current="page">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<div class="tour"><aside><h2>More Raz</h2><h3>The library</h3><ol start='1'> | |
| 22 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 23 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 24 | +<li><a href="collections.html">Lists, arrays, maps and sorting</a></li> | |
| 25 | +<li><a href="files.html">Files and the command line</a></li> | |
| 26 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 27 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 28 | +</ol> | |
| 29 | +<h3>Standing alone</h3><ol start='7'> | |
| 30 | +<li><a href="static.html">A program with no run time</a></li> | |
| 31 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 32 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 33 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 34 | +</ol> | |
| 35 | +<h3>The machine</h3><ol start='11'> | |
| 36 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 37 | +<li><a href="syscalls.html">System calls</a></li> | |
| 38 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 39 | +</ol> | |
| 40 | +<h3>Shared memory</h3><ol start='14'> | |
| 41 | +<li><a href="volatile.html">Volatile</a></li> | |
| 42 | +<li><a href="atomics.html" aria-current="page">Atomics</a></li> | |
| 43 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 44 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 45 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 46 | +</ol></aside><article><p class="kicker">Shared memory · lesson 15 of 18</p><h1>Atomics</h1> | |
| 47 | +<p>A volatile access is one access. An atomic is one *indivisible* step: nothing can happen between its read and its write, so two threads using it can't lose each other's work. There are three, built into the language as procedures, and they are sequentially consistent on every target:</p> | |
| 48 | +<table><thead><tr><th>Call</th><th>Does</th></tr></thead><tbody><tr><td data-label="Call"><code>XADD(p, x)</code></td><td data-label="Does">adds <code>x</code> to <code>p^</code> and returns the value before</td></tr><tr><td data-label="Call"><code>XCHG(p, x)</code></td><td data-label="Does">sets <code>p^ := x</code> and returns the value before</td></tr><tr><td data-label="Call"><code>CAS(p, old, new)</code></td><td data-label="Does">if <code>p^ = old</code>, sets <code>p^ := new</code> and returns <code>true</code>; otherwise <code>false</code></td></tr></tbody></table> | |
| 49 | +<p><code>p</code> is a <code>^T</code> or <code>^VOLATILE T</code> where <code>T</code> is <code>INT</code>, <code>UINT</code> or a pointer type (<code>INT</code> or <code>UINT</code> for <code>XADD</code>). They compile to single x86-64 instructions: <code>lock xadd</code>, <code>xchg</code> (which is always locked when it touches memory) and <code>lock cmpxchg</code>:</p> | |
| 50 | +<div class="file"><span>Ops.raz</span></div><pre class="code"><code><span class="kw">module</span> Ops; | |
| 51 | + | |
| 52 | +<span class="kw">var</span> counter: <span class="ty">INT</span>; | |
| 53 | + | |
| 54 | +<span class="kw">proc</span> main*; | |
| 55 | +<span class="kw">begin</span> | |
| 56 | + _ := <span class="ty">XADD</span>(<span class="ty">ADR</span>(counter), <span class="number">5</span>); | |
| 57 | + _ := <span class="ty">XCHG</span>(<span class="ty">ADR</span>(counter), <span class="number">100</span>); | |
| 58 | + _ := <span class="ty">CAS</span>(<span class="ty">ADR</span>(counter), <span class="number">100</span>, <span class="number">7</span>); | |
| 59 | +<span class="kw">end</span>; | |
| 60 | + | |
| 61 | +<span class="kw">end</span> Ops.</code></pre> | |
| 62 | +<pre class="output term"><code><span class="cmd">$ raz -S Ops.raz | grep -i "lock\|xchg"</span> | |
| 63 | + 23 lock xadd [r8], rax | |
| 64 | + 8 _ := XCHG(ADR(counter), 100); | |
| 65 | + 43 xchg [r8], rax | |
| 66 | + 67 lock cmpxchg [r8], r10</code></pre> | |
| 67 | +<h2>What each one gives you</h2> | |
| 68 | +<p><code>XADD</code> is a counter, or a ticket dispenser: every caller gets a different number. <code>XCHG</code> takes the old value and leaves a new one, which is a flag, a swap, or the release of a lock. <code>CAS</code> is the general one: "if nobody changed it since I looked, change it". Most lock-free code is a loop around it.</p> | |
| 69 | +<div class="file"><span>Tickets.raz</span></div><pre class="code"><code><span class="kw">module</span> Tickets; | |
| 70 | +<span class="kw">import</span> Out, Thread; | |
| 71 | + | |
| 72 | +<span class="kw">var</span> | |
| 73 | + next: <span class="ty">INT</span>; <span class="comment">(* the next ticket to give out *)</span> | |
| 74 | + seen: [<span class="number">4000</span>]<span class="ty">U8</span>; <span class="comment">(* which tickets were taken, one byte each *)</span> | |
| 75 | + | |
| 76 | +<span class="kw">proc</span> work(_arg: ^<span class="ty">U8</span>); | |
| 77 | +<span class="kw">var</span> i, t: <span class="ty">INT</span>; | |
| 78 | +<span class="kw">begin</span> | |
| 79 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">1000</span> <span class="kw">do</span> | |
| 80 | + t := <span class="ty">XADD</span>(<span class="ty">ADR</span>(next), <span class="number">1</span>); <span class="comment">(* a ticket no other thread gets *)</span> | |
| 81 | + seen[t] := <span class="number">1</span>; | |
| 82 | + <span class="kw">end</span>; | |
| 83 | +<span class="kw">end</span>; | |
| 84 | + | |
| 85 | +<span class="kw">proc</span> main*; | |
| 86 | +<span class="kw">var</span> th: [<span class="number">4</span>]^Thread.Thread; i, taken: <span class="ty">INT</span>; err: <span class="ty">ERROR</span>; | |
| 87 | +<span class="kw">begin</span> | |
| 88 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> | |
| 89 | + th[i], err := Thread.spawn(work, <span class="ty">nil</span>); | |
| 90 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">return</span>; <span class="kw">end</span>; | |
| 91 | + <span class="kw">end</span>; | |
| 92 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> Thread.join(th[i]); <span class="kw">end</span>; | |
| 93 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3999</span> <span class="kw">do</span> taken := taken + seen[i]; <span class="kw">end</span>; | |
| 94 | + Out.int(next); Out.char(<span class="string">' '</span>); Out.int(taken); Out.ln; | |
| 95 | +<span class="kw">end</span>; | |
| 96 | + | |
| 97 | +<span class="kw">end</span> Tickets.</code></pre> | |
| 98 | +<pre class="output"><code>4000 4000 | |
| 99 | +</code></pre> | |
| 100 | +<p>Four thousand tickets, four thousand different numbers, no two threads with the same one. Each thread writes into its own bytes of <code>seen</code>, so no plain write is shared.</p> | |
| 101 | +<h2>A compare-and-swap loop</h2> | |
| 102 | +<p>Anything that can be computed from the old value can be made atomic with a loop around <code>CAS</code>: read the value, compute the new one, and try to swap it in; if someone got there first, read again. Here is an atomic maximum, which no single instruction does.</p> | |
| 103 | +<div class="file"><span>Peak.raz</span></div><pre class="code"><code><span class="kw">module</span> Peak; | |
| 104 | +<span class="kw">import</span> Out, Thread; | |
| 105 | + | |
| 106 | +<span class="kw">var</span> peak: <span class="ty">INT</span>; | |
| 107 | + | |
| 108 | +<span class="comment">(* raises peak to v if v is bigger, however many threads call it *)</span> | |
| 109 | +<span class="kw">proc</span> raise(v: <span class="ty">INT</span>); | |
| 110 | +<span class="kw">var</span> seen: <span class="ty">INT</span>; | |
| 111 | +<span class="kw">begin</span> | |
| 112 | + seen := peak; | |
| 113 | + <span class="kw">while</span> seen < v <span class="kw">do</span> | |
| 114 | + <span class="kw">if</span> <span class="ty">CAS</span>(<span class="ty">ADR</span>(peak), seen, v) <span class="kw">then</span> <span class="kw">return</span>; <span class="kw">end</span>; | |
| 115 | + seen := peak; <span class="comment">(* someone changed it: look again *)</span> | |
| 116 | + <span class="kw">end</span>; | |
| 117 | +<span class="kw">end</span>; | |
| 118 | + | |
| 119 | +<span class="kw">proc</span> work(arg: ^<span class="ty">U8</span>); | |
| 120 | +<span class="kw">var</span> i, base: <span class="ty">INT</span>; | |
| 121 | +<span class="kw">begin</span> | |
| 122 | + base := <span class="ty">INT</span>(arg); | |
| 123 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">999</span> <span class="kw">do</span> raise(base + i * <span class="number">7</span> <span class="kw">mod</span> <span class="number">1001</span>); <span class="kw">end</span>; | |
| 124 | +<span class="kw">end</span>; | |
| 125 | + | |
| 126 | +<span class="kw">proc</span> main*; | |
| 127 | +<span class="kw">var</span> th: [<span class="number">4</span>]^Thread.Thread; i: <span class="ty">INT</span>; err: <span class="ty">ERROR</span>; | |
| 128 | +<span class="kw">begin</span> | |
| 129 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> | |
| 130 | + th[i], err := Thread.spawn(work, ^<span class="ty">U8</span>(i * <span class="number">1000</span>)); | |
| 131 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">return</span>; <span class="kw">end</span>; | |
| 132 | + <span class="kw">end</span>; | |
| 133 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> Thread.join(th[i]); <span class="kw">end</span>; | |
| 134 | + Out.int(peak); Out.ln; | |
| 135 | +<span class="kw">end</span>; | |
| 136 | + | |
| 137 | +<span class="kw">end</span> Peak.</code></pre> | |
| 138 | +<pre class="output"><code>3994 | |
| 139 | +</code></pre> | |
| 140 | +<p>The result doesn't depend on how the threads interleave: it is the largest value any of them offered. That is the test of a correct atomic algorithm, and why this kind of code is written once, carefully, and used everywhere.</p> | |
| 141 | +<h2>A lock, from first principles</h2> | |
| 142 | +<p>A lock is a word that is 0 when free and 1 when held. To take it, <code>CAS</code> it from 0 to 1; if that fails, someone holds it, so try again. To give it up, <code>XCHG</code> it back to 0. This is exactly the library's <code>Lock</code>, printed from <code>lib/Lock.raz</code>:</p> | |
| 143 | +<pre class="output term"><code><span class="cmd">$ sed -n '/^type Lock/,/^proc main/p' $RAZLIB/Lock.raz | head -n -2</span> | |
| 144 | +type Lock* = record held: INT; end; | |
| 145 | + | |
| 146 | +(* Takes l, waiting while another thread holds it. *) | |
| 147 | +proc take*(var l: Lock); | |
| 148 | +var tries: INT; | |
| 149 | +begin | |
| 150 | + tries := 0; | |
| 151 | + while not CAS(ADR(l.held), 0, 1) do | |
| 152 | + INC(tries); | |
| 153 | + if tries = 64 then Sys.yield; tries := 0; end; | |
| 154 | + end; | |
| 155 | +end; | |
| 156 | + | |
| 157 | +(* Gives up l, which the caller holds. *) | |
| 158 | +proc give*(var l: Lock); | |
| 159 | +begin | |
| 160 | + _ := XCHG(ADR(l.held), 0); | |
| 161 | +end;</code></pre> | |
| 162 | +<p>And here is a use of it: a structure with two fields that must stay in step, which no single atomic can protect.</p> | |
| 163 | +<div class="file"><span>Account.raz</span></div><pre class="code"><code><span class="kw">module</span> Account; | |
| 164 | +<span class="kw">import</span> Out, Lock, Thread; | |
| 165 | + | |
| 166 | +<span class="kw">var</span> | |
| 167 | + lock: Lock.Lock; | |
| 168 | + deposits, balance: <span class="ty">INT</span>; <span class="comment">(* balance = 3 * deposits, always, under lock *)</span> | |
| 169 | + | |
| 170 | +<span class="kw">proc</span> work(_arg: ^<span class="ty">U8</span>); | |
| 171 | +<span class="kw">var</span> i: <span class="ty">INT</span>; | |
| 172 | +<span class="kw">begin</span> | |
| 173 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">20000</span> <span class="kw">do</span> | |
| 174 | + Lock.take(lock); | |
| 175 | + <span class="ty">INC</span>(deposits); | |
| 176 | + <span class="ty">INC</span>(balance, <span class="number">3</span>); | |
| 177 | + Lock.give(lock); | |
| 178 | + <span class="kw">end</span>; | |
| 179 | +<span class="kw">end</span>; | |
| 180 | + | |
| 181 | +<span class="kw">proc</span> main*; | |
| 182 | +<span class="kw">var</span> th: [<span class="number">4</span>]^Thread.Thread; i: <span class="ty">INT</span>; err: <span class="ty">ERROR</span>; | |
| 183 | +<span class="kw">begin</span> | |
| 184 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> | |
| 185 | + th[i], err := Thread.spawn(work, <span class="ty">nil</span>); | |
| 186 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">return</span>; <span class="kw">end</span>; | |
| 187 | + <span class="kw">end</span>; | |
| 188 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> Thread.join(th[i]); <span class="kw">end</span>; | |
| 189 | + Out.int(deposits); Out.char(<span class="string">' '</span>); Out.int(balance); Out.ln; | |
| 190 | + <span class="kw">if</span> balance = <span class="number">3</span> * deposits <span class="kw">then</span> Out.str(<span class="string">"in step\n"</span>); <span class="kw">end</span>; | |
| 191 | +<span class="kw">end</span>; | |
| 192 | + | |
| 193 | +<span class="kw">end</span> Account.</code></pre> | |
| 194 | +<pre class="output"><code>80000 240000 | |
| 195 | +in step | |
| 196 | +</code></pre> | |
| 197 | +<p>A <code>Lock</code> spins, giving up the processor now and then, so it is for sections of a few instructions. <code>Thread.Mutex</code> sleeps on a futex, so it is for longer ones. A spinning lock held for a long time, or by a thread that was descheduled, burns processors; that is the price of its speed when contention is short.</p> | |
| 198 | +<h2>Choosing</h2> | |
| 199 | +<ul><li>A counter, a ticket, a flag: <code>XADD</code> or <code>XCHG</code>.</li><li>A value computed from the old one: a <code>CAS</code> loop.</li><li>Several variables that must change together: a <code>Lock</code> or a <code>Mutex</code>. Don't try to be clever with several atomics; the one invariant spanning them is the thing that breaks.</li></ul> | |
| 200 | +<p>All three act on a word. For anything bigger, the thing you swap is a pointer to the bigger thing: the next lessons do exactly that.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="volatile.html">← Volatile</a><a href="index.html">Contents</a><a class="next" href="ordering.html">Ordering and publication →</a></div></article></div> | |
| 201 | +</main> | |
| 202 | +<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> | |
| 203 | +</body> | |
| 204 | +</html> |
| @@ -0,0 +1,247 @@ | ||
| 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>Strings and bytes - More Raz</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="Strings and bytes - More Raz"> | |
| 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.lucelad.workers.dev/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" aria-current="page">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<div class="tour"><aside><h2>More Raz</h2><h3>The library</h3><ol start='1'> | |
| 22 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 23 | +<li><a href="bytes.html" aria-current="page">Strings and bytes</a></li> | |
| 24 | +<li><a href="collections.html">Lists, arrays, maps and sorting</a></li> | |
| 25 | +<li><a href="files.html">Files and the command line</a></li> | |
| 26 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 27 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 28 | +</ol> | |
| 29 | +<h3>Standing alone</h3><ol start='7'> | |
| 30 | +<li><a href="static.html">A program with no run time</a></li> | |
| 31 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 32 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 33 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 34 | +</ol> | |
| 35 | +<h3>The machine</h3><ol start='11'> | |
| 36 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 37 | +<li><a href="syscalls.html">System calls</a></li> | |
| 38 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 39 | +</ol> | |
| 40 | +<h3>Shared memory</h3><ol start='14'> | |
| 41 | +<li><a href="volatile.html">Volatile</a></li> | |
| 42 | +<li><a href="atomics.html">Atomics</a></li> | |
| 43 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 44 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 45 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 46 | +</ol></aside><article><p class="kicker">The library · lesson 2 of 18</p><h1>Strings and bytes</h1> | |
| 47 | +<p>A <code>[]U8</code> is both a string and a block of bytes. <code>Str</code> has what is done with them: comparing, finding, hashing, copying into memory of your own, UTF-8, numbers, and the fixed byte orders of file formats and network protocols. <code>Bytes</code> has the searches, made fast.</p> | |
| 48 | +<h2>Ordering and hashing</h2> | |
| 49 | +<p><code>Str.cmp</code> gives -1, 0 or 1, byte by byte, so it orders UTF-8 text by code point. <code>Str.eq</code> is equality. <code>Str.hash</code> is FNV-1a, 64 bits; it is what a <code>Map</code> of strings uses.</p> | |
| 50 | +<div class="file"><span>Order.raz</span></div><pre class="code"><code><span class="kw">module</span> Order; | |
| 51 | +<span class="kw">import</span> Out, Str, Fmt; | |
| 52 | + | |
| 53 | +<span class="kw">proc</span> main*; | |
| 54 | +<span class="kw">var</span> names: [<span class="number">4</span>][]<span class="ty">U8</span>; i, j: <span class="ty">INT</span>; t: []<span class="ty">U8</span>; | |
| 55 | +<span class="kw">begin</span> | |
| 56 | + names := [<span class="string">"pear"</span>, <span class="string">"Apple"</span>, <span class="string">"fig"</span>, <span class="string">"apple"</span>]; | |
| 57 | + <span class="comment">(* a small insertion sort, with Str.cmp *)</span> | |
| 58 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> | |
| 59 | + t := names[i]; | |
| 60 | + j := i - <span class="number">1</span>; | |
| 61 | + <span class="kw">while</span> (j >= <span class="number">0</span>) <span class="kw">and</span> (Str.cmp(names[j], t) > <span class="number">0</span>) <span class="kw">do</span> | |
| 62 | + names[j + <span class="number">1</span>] := names[j]; | |
| 63 | + <span class="ty">DEC</span>(j); | |
| 64 | + <span class="kw">end</span>; | |
| 65 | + names[j + <span class="number">1</span>] := t; | |
| 66 | + <span class="kw">end</span>; | |
| 67 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> Out.str(names[i]); Out.char(<span class="string">' '</span>); <span class="kw">end</span>; | |
| 68 | + Out.ln; | |
| 69 | + Fmt.print(<span class="string">"{}\n"</span>, [Fmt.hex(Str.hash(<span class="string">"raz"</span>))]); | |
| 70 | + <span class="kw">if</span> Str.hash(<span class="string">"raz"</span>) = Str.hash(<span class="string">"raz"</span>) <span class="kw">then</span> Out.str(<span class="string">"stable\n"</span>); <span class="kw">end</span>; | |
| 71 | +<span class="kw">end</span>; | |
| 72 | + | |
| 73 | +<span class="kw">end</span> Order.</code></pre> | |
| 74 | +<pre class="output"><code>Apple apple fig pear | |
| 75 | +89F6BC1960FF4912 | |
| 76 | +stable | |
| 77 | +</code></pre> | |
| 78 | +<p>Upper case sorts before lower, since 'A' is 65 and 'a' is 97: <code>Str.cmp</code> doesn't pretend to know a language's alphabet.</p> | |
| 79 | +<h2>Keeping a string</h2> | |
| 80 | +<p>A slice of a string constant lives forever, but a slice of a buffer lives only as long as the buffer. To keep one past that, <code>Str.copy</code> takes memory from an allocator and says whether it got any.</p> | |
| 81 | +<div class="file"><span>Keep.raz</span></div><pre class="code"><code><span class="kw">module</span> Keep; | |
| 82 | +<span class="kw">import</span> Out, Str, Heap, Mem; | |
| 83 | + | |
| 84 | +<span class="kw">type</span> Entry = <span class="kw">record</span> name: []<span class="ty">U8</span>; n: <span class="ty">INT</span>; <span class="kw">end</span>; | |
| 85 | + | |
| 86 | +<span class="kw">var</span> entries: [<span class="number">3</span>]Entry; | |
| 87 | + | |
| 88 | +<span class="comment">(* remembers a name that the caller will overwrite *)</span> | |
| 89 | +<span class="kw">proc</span> remember(slot: <span class="ty">INT</span>; name: []<span class="ty">U8</span>); | |
| 90 | +<span class="kw">var</span> copy: []<span class="ty">U8</span>; ok: <span class="ty">BOOL</span>; | |
| 91 | +<span class="kw">begin</span> | |
| 92 | + copy, ok := Str.copy(Heap.heap, name); | |
| 93 | + <span class="kw">if</span> ok <span class="kw">then</span> entries[slot].name := copy; entries[slot].n := slot; <span class="kw">end</span>; | |
| 94 | +<span class="kw">end</span>; | |
| 95 | + | |
| 96 | +<span class="kw">proc</span> main*; | |
| 97 | +<span class="kw">var</span> scratch: [<span class="number">16</span>]<span class="ty">U8</span>; i: <span class="ty">INT</span>; | |
| 98 | +<span class="kw">begin</span> | |
| 99 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">2</span> <span class="kw">do</span> | |
| 100 | + scratch := <span class="string">"name-"</span>; | |
| 101 | + scratch[<span class="number">5</span>] := <span class="ty">U8</span>(<span class="string">'0'</span> + i); | |
| 102 | + remember(i, scratch[<span class="number">0</span>..<span class="number">6</span>]); | |
| 103 | + scratch := <span class="string">"overwritten!"</span>; | |
| 104 | + <span class="kw">end</span>; | |
| 105 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">2</span> <span class="kw">do</span> | |
| 106 | + Out.str(entries[i].name); Out.char(<span class="string">' '</span>); | |
| 107 | + Mem.free(Heap.heap, ^<span class="ty">U8</span>(<span class="ty">ADR</span>(entries[i].name[<span class="number">0</span>]))); | |
| 108 | + <span class="kw">end</span>; | |
| 109 | + Out.ln; | |
| 110 | +<span class="kw">end</span>; | |
| 111 | + | |
| 112 | +<span class="kw">end</span> Keep.</code></pre> | |
| 113 | +<pre class="output"><code>name-0 name-1 name-2 | |
| 114 | +</code></pre> | |
| 115 | +<h2>Searching</h2> | |
| 116 | +<p><code>Bytes</code> finds bytes many at a time: <code>Bytes.index</code> and <code>Bytes.last</code> give the first and the last place of a byte in a <code>[]U8</code>, or -1, <code>Bytes.count</code> how many places it has, and <code>Bytes.find</code> where one <code>[]U8</code> first starts in another (<code>Str.find</code> is the same). Each is what a loop over the bytes would give, only faster: the library's own body compares eight bytes at once in a <code>U64</code>, and on x86-64 a file of its own, <code>Bytes.x86_64.raz</code>, compares sixteen with SSE2, in code procedures.</p> | |
| 117 | +<div class="file"><span>Paths.raz</span></div><pre class="code"><code><span class="kw">module</span> Paths; | |
| 118 | +<span class="kw">import</span> Out, Fmt, Bytes; | |
| 119 | + | |
| 120 | +<span class="comment">(* the last part of a path: what follows its last slash *)</span> | |
| 121 | +<span class="kw">proc</span> base(path: []<span class="ty">U8</span>): []<span class="ty">U8</span>; | |
| 122 | +<span class="kw">begin</span> | |
| 123 | + <span class="kw">return</span> path[Bytes.last(path, <span class="string">'/'</span>) + <span class="number">1</span>..<span class="ty">LEN</span>(path)]; | |
| 124 | +<span class="kw">end</span>; | |
| 125 | + | |
| 126 | +<span class="kw">proc</span> main*; | |
| 127 | +<span class="kw">var</span> text: []<span class="ty">U8</span>; at, n, line: <span class="ty">INT</span>; | |
| 128 | +<span class="kw">begin</span> | |
| 129 | + Out.str(base(<span class="string">"/usr/local/lib/raz/Bytes.raz"</span>)); Out.char(<span class="string">' '</span>); | |
| 130 | + Out.str(base(<span class="string">"Out.raz"</span>)); Out.ln; | |
| 131 | + | |
| 132 | + text := <span class="string">"one line\nanother line\nthe line with raz in it\nthe last\n"</span>; | |
| 133 | + Fmt.print(<span class="string">"{} lines\n"</span>, [Fmt.int(Bytes.count(text, <span class="number">10</span>))]); | |
| 134 | + at := Bytes.find(text, <span class="string">"raz"</span>); | |
| 135 | + <span class="kw">if</span> at >= <span class="number">0</span> <span class="kw">then</span> | |
| 136 | + <span class="comment">(* the line it is on: the newlines before it, plus one *)</span> | |
| 137 | + line := Bytes.count(text[<span class="number">0</span>..at], <span class="number">10</span>) + <span class="number">1</span>; | |
| 138 | + n := Bytes.index(text[at..<span class="ty">LEN</span>(text)], <span class="number">10</span>); | |
| 139 | + Fmt.print(<span class="string">"raz on line {}, at {}, and the line goes on {} more\n"</span>, | |
| 140 | + [Fmt.int(line), Fmt.int(at), Fmt.int(n)]); | |
| 141 | + <span class="kw">end</span>; | |
| 142 | + Fmt.print(<span class="string">"{} {}\n"</span>, [Fmt.int(Bytes.find(text, <span class="string">"zzz"</span>)), Fmt.int(Bytes.find(text, <span class="string">""</span>))]); | |
| 143 | +<span class="kw">end</span>; | |
| 144 | + | |
| 145 | +<span class="kw">end</span> Paths.</code></pre> | |
| 146 | +<pre class="output"><code>Bytes.raz Out.raz | |
| 147 | +4 lines | |
| 148 | +raz on line 3, at 36, and the line goes on 9 more | |
| 149 | +-1 0 | |
| 150 | +</code></pre> | |
| 151 | +<p>When the byte isn't there, <code>Bytes.last</code> gives -1, so <code>base</code> of a name with no slash is the whole name. A search of a slice gives places in the slice, counted from its own start: add the place the slice starts at to get one in the whole.</p> | |
| 152 | +<h2>Binary formats</h2> | |
| 153 | +<p>A file format or a network protocol has a byte order of its own, not the machine's. <code>Str.le</code> and <code>Str.be</code> read an unsigned number of up to 8 bytes in a fixed order (little- or big-endian) and <code>Str.putLE</code> and <code>Str.putBE</code> write one. They work on any slice, so a header is read where it lies, with no struct to overlay and no byte swapping to forget.</p> | |
| 154 | +<p>Here is a small record format: a 4-byte tag, a 2-byte big-endian length, a 4-byte little-endian checksum, then the data.</p> | |
| 155 | +<div class="file"><span>Frame.raz</span></div><pre class="code"><code><span class="kw">module</span> Frame; | |
| 156 | +<span class="kw">import</span> Out, Fmt, Str; | |
| 157 | + | |
| 158 | +<span class="kw">const</span> HeaderSize = <span class="number">10</span>; | |
| 159 | + | |
| 160 | +<span class="comment">(* the sum of the bytes of data, all mod 2^32 *)</span> | |
| 161 | +<span class="kw">proc</span> checksum(data: []<span class="ty">U8</span>): <span class="ty">U32</span>; | |
| 162 | +<span class="kw">var</span> i: <span class="ty">INT</span>; sum: <span class="ty">U32</span>; | |
| 163 | +<span class="kw">begin</span> | |
| 164 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="ty">LEN</span>(data) - <span class="number">1</span> <span class="kw">do</span> sum := sum + <span class="ty">U32</span>(data[i]); <span class="kw">end</span>; | |
| 165 | + <span class="kw">return</span> sum; | |
| 166 | +<span class="kw">end</span>; | |
| 167 | + | |
| 168 | +<span class="comment">(* writes a frame to out, which must have room; its length *)</span> | |
| 169 | +<span class="kw">proc</span> pack(out: []<span class="ty">U8</span>; tag, data: []<span class="ty">U8</span>): <span class="ty">INT</span>; | |
| 170 | +<span class="kw">begin</span> | |
| 171 | + COPY(out[<span class="number">0</span>..<span class="number">4</span>], tag); | |
| 172 | + Str.putBE(out[<span class="number">4</span>..<span class="number">6</span>], <span class="ty">U64</span>(<span class="ty">LEN</span>(data))); | |
| 173 | + Str.putLE(out[<span class="number">6</span>..<span class="number">10</span>], <span class="ty">U64</span>(checksum(data))); | |
| 174 | + COPY(out[HeaderSize..HeaderSize + <span class="ty">LEN</span>(data)], data); | |
| 175 | + <span class="kw">return</span> HeaderSize + <span class="ty">LEN</span>(data); | |
| 176 | +<span class="kw">end</span>; | |
| 177 | + | |
| 178 | +<span class="kw">proc</span> main*; | |
| 179 | +<span class="kw">var</span> buf: [<span class="number">64</span>]<span class="ty">U8</span>; n, len: <span class="ty">INT</span>; sum: <span class="ty">U32</span>; i: <span class="ty">INT</span>; | |
| 180 | +<span class="kw">begin</span> | |
| 181 | + n := pack(buf, <span class="string">"DATA"</span>, <span class="string">"hello"</span>); | |
| 182 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> n - <span class="number">1</span> <span class="kw">do</span> | |
| 183 | + Out.hex(<span class="ty">U64</span>(buf[i]), <span class="number">2</span>); Out.char(<span class="string">' '</span>); | |
| 184 | + <span class="kw">end</span>; | |
| 185 | + Out.ln; | |
| 186 | + <span class="comment">(* and back *)</span> | |
| 187 | + len := <span class="ty">INT</span>(Str.be(buf[<span class="number">4</span>..<span class="number">6</span>])); | |
| 188 | + sum := <span class="ty">U32</span>(Str.le(buf[<span class="number">6</span>..<span class="number">10</span>])); | |
| 189 | + Fmt.print(<span class="string">"tag {}, {} bytes, checksum {}, "</span>, [Fmt.str(buf[<span class="number">0</span>..<span class="number">4</span>]), Fmt.int(len), Fmt.hex(<span class="ty">U64</span>(sum))]); | |
| 190 | + <span class="kw">if</span> sum = checksum(buf[HeaderSize..HeaderSize + len]) <span class="kw">then</span> | |
| 191 | + Out.str(<span class="string">"valid: "</span>); Out.str(buf[HeaderSize..HeaderSize + len]); | |
| 192 | + <span class="kw">else</span> | |
| 193 | + Out.str(<span class="string">"corrupt"</span>); | |
| 194 | + <span class="kw">end</span>; | |
| 195 | + Out.ln; | |
| 196 | +<span class="kw">end</span>; | |
| 197 | + | |
| 198 | +<span class="kw">end</span> Frame.</code></pre> | |
| 199 | +<pre class="output"><code>44 41 54 41 00 05 14 02 00 00 68 65 6C 6C 6F | |
| 200 | +tag DATA, 5 bytes, checksum 214, valid: hello | |
| 201 | +</code></pre> | |
| 202 | +<p>The output is the same on a little-endian and a big-endian machine, because the bytes are written one at a time in the order the format says.</p> | |
| 203 | +<h2>Numbers and text</h2> | |
| 204 | +<p><code>Str.toInt</code> reads a decimal number with an optional sign and nothing else, and says whether it was one; <code>Str.toHex</code> reads hexadecimal digits, and <code>Math.toReal</code> a real, as a constant is written but with <code>e</code> for <code>E</code> too, to the nearest <code>F64</code> exactly. <code>Str.fromInt</code> goes the other way into an array of 20 bytes, with no allocator, and <code>Fmt</code> does the rest. <code>Str.encode</code> and <code>Str.decode</code> move between characters and UTF-8, as the first tour showed.</p> | |
| 205 | +<div class="file"><span>Numbers.raz</span></div><pre class="code"><code><span class="kw">module</span> Numbers; | |
| 206 | +<span class="kw">import</span> Out, Str, Math, Fmt; | |
| 207 | + | |
| 208 | +<span class="comment">(* the sum of the numbers in a comma separated list, or -1 if any isn't *)</span> | |
| 209 | +<span class="kw">proc</span> total(s: []<span class="ty">U8</span>): <span class="ty">I64</span>; | |
| 210 | +<span class="kw">var</span> part: []<span class="ty">U8</span>; sum, n: <span class="ty">I64</span>; ok, more: <span class="ty">BOOL</span>; | |
| 211 | +<span class="kw">begin</span> | |
| 212 | + more := <span class="ty">true</span>; | |
| 213 | + <span class="kw">while</span> more <span class="kw">do</span> | |
| 214 | + part, s, more := Str.cut(s, <span class="string">","</span>); | |
| 215 | + n, ok := Str.toInt(part); | |
| 216 | + <span class="kw">if</span> <span class="kw">not</span> ok <span class="kw">then</span> <span class="kw">return</span> -<span class="number">1</span>; <span class="kw">end</span>; | |
| 217 | + sum := sum + n; | |
| 218 | + <span class="kw">end</span>; | |
| 219 | + <span class="kw">return</span> sum; | |
| 220 | +<span class="kw">end</span>; | |
| 221 | + | |
| 222 | +<span class="kw">proc</span> main*; | |
| 223 | +<span class="kw">var</span> u: <span class="ty">U64</span>; x: <span class="ty">F64</span>; ok: <span class="ty">BOOL</span>; digits: [<span class="number">20</span>]<span class="ty">U8</span>; k: <span class="ty">INT</span>; | |
| 224 | +<span class="kw">begin</span> | |
| 225 | + Out.int(total(<span class="string">"10,20,-5,+7"</span>)); Out.ln; | |
| 226 | + Out.int(total(<span class="string">"10,x,20"</span>)); Out.ln; | |
| 227 | + Out.int(total(<span class="string">"10,,20"</span>)); Out.ln; | |
| 228 | + u, ok := Str.toHex(<span class="string">"ff00"</span>); | |
| 229 | + <span class="kw">if</span> ok <span class="kw">then</span> Out.hex(u, <span class="number">1</span>); Out.ln; <span class="kw">end</span>; | |
| 230 | + x, ok := Math.toReal(<span class="string">"-1.5e3"</span>); | |
| 231 | + <span class="kw">if</span> ok <span class="kw">then</span> Fmt.print(<span class="string">"{}\n"</span>, [Fmt.real(x, <span class="number">1</span>)]); <span class="kw">end</span>; | |
| 232 | + digits, k := Str.fromInt(-<span class="number">9223372036854775807</span> - <span class="number">1</span>); | |
| 233 | + Out.str(digits[<span class="number">0</span>..k]); Out.ln; | |
| 234 | +<span class="kw">end</span>; | |
| 235 | + | |
| 236 | +<span class="kw">end</span> Numbers.</code></pre> | |
| 237 | +<pre class="output"><code>32 | |
| 238 | +-1 | |
| 239 | +-1 | |
| 240 | +FF00 | |
| 241 | +-1500.0 | |
| 242 | +-9223372036854775808 | |
| 243 | +</code></pre><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="fmt.html">← Output and formatting</a><a href="index.html">Contents</a><a class="next" href="collections.html">Lists, arrays, maps and sorting →</a></div></article></div> | |
| 244 | +</main> | |
| 245 | +<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> | |
| 246 | +</body> | |
| 247 | +</html> |
| @@ -0,0 +1,192 @@ | ||
| 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>Lists, arrays, maps and sorting - More Raz</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="Lists, arrays, maps and sorting - More Raz"> | |
| 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.lucelad.workers.dev/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" aria-current="page">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<div class="tour"><aside><h2>More Raz</h2><h3>The library</h3><ol start='1'> | |
| 22 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 23 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 24 | +<li><a href="collections.html" aria-current="page">Lists, arrays, maps and sorting</a></li> | |
| 25 | +<li><a href="files.html">Files and the command line</a></li> | |
| 26 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 27 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 28 | +</ol> | |
| 29 | +<h3>Standing alone</h3><ol start='7'> | |
| 30 | +<li><a href="static.html">A program with no run time</a></li> | |
| 31 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 32 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 33 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 34 | +</ol> | |
| 35 | +<h3>The machine</h3><ol start='11'> | |
| 36 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 37 | +<li><a href="syscalls.html">System calls</a></li> | |
| 38 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 39 | +</ol> | |
| 40 | +<h3>Shared memory</h3><ol start='14'> | |
| 41 | +<li><a href="volatile.html">Volatile</a></li> | |
| 42 | +<li><a href="atomics.html">Atomics</a></li> | |
| 43 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 44 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 45 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 46 | +</ol></aside><article><p class="kicker">The library · lesson 3 of 18</p><h1>Lists, arrays, maps and sorting</h1> | |
| 47 | +<p>The four generic modules are instantiated like any other generic module, with the types and procedures they need. All four take their memory from an allocator you give them; none of them allocates anything you didn't ask for.</p> | |
| 48 | +<h2><code>List(T)</code></h2> | |
| 49 | +<p>A singly linked list with <code>push</code> at the front, <code>pop</code> from the front, and the nodes exported, so a program walks it itself. Both can fail if the allocator is out of room, and say so.</p> | |
| 50 | +<div class="file"><span>Pile.raz</span></div><pre class="code"><code><span class="kw">module</span> Pile; | |
| 51 | +<span class="kw">import</span> Out, Heap, Ints := List(<span class="ty">INT</span>); | |
| 52 | + | |
| 53 | +<span class="kw">proc</span> main*; | |
| 54 | +<span class="kw">var</span> l: Ints.List; n: ^Ints.Node; v: <span class="ty">INT</span>; | |
| 55 | +<span class="kw">begin</span> | |
| 56 | + Ints.init(l, Heap.heap); | |
| 57 | + <span class="kw">defer</span> Ints.clear(l); | |
| 58 | + <span class="kw">for</span> v := <span class="number">1</span> <span class="kw">to</span> <span class="number">5</span> <span class="kw">do</span> _ := Ints.push(l, v * v); <span class="kw">end</span>; | |
| 59 | + Ints.reverse(l); <span class="comment">(* oldest first *)</span> | |
| 60 | + n := l.head; | |
| 61 | + <span class="kw">while</span> n # <span class="ty">nil</span> <span class="kw">do</span> Out.int(n^.val); Out.char(<span class="string">' '</span>); n := n^.next; <span class="kw">end</span>; | |
| 62 | + Out.ln; | |
| 63 | + v, _ := Ints.pop(l); | |
| 64 | + Out.int(v); Out.str(<span class="string">" popped, "</span>); Out.int(l.len); Out.str(<span class="string">" left\n"</span>); | |
| 65 | +<span class="kw">end</span>; | |
| 66 | + | |
| 67 | +<span class="kw">end</span> Pile.</code></pre> | |
| 68 | +<pre class="output"><code>1 4 9 16 25 | |
| 69 | +1 popped, 4 left | |
| 70 | +</code></pre> | |
| 71 | +<h2><code>Vec(T)</code></h2> | |
| 72 | +<p>A growable array: one block of elements that doubles when it is full, for what a program learns the length of only as it reads. <code>push</code> adds at the end, <code>add</code> adds a zero element and gives a pointer to fill it in place, <code>resize</code> cuts it short or grows it with zeros. <code>all</code> gives the elements as a slice, indexed and checked as any slice is; the slice is good until the array next grows. Running out of memory stops the program, as with <code>Buf</code>: an element dropped silently would be wrong data. <code>room</code> asks first, for a program that can do better.</p> | |
| 73 | +<div class="file"><span>Squares.raz</span></div><pre class="code"><code><span class="kw">module</span> Squares; | |
| 74 | +<span class="kw">import</span> Out, Heap, Ints := Vec(<span class="ty">INT</span>); | |
| 75 | + | |
| 76 | +<span class="kw">proc</span> main*; | |
| 77 | +<span class="kw">var</span> v: Ints.Vec; i: <span class="ty">INT</span>; s: []<span class="ty">INT</span>; | |
| 78 | +<span class="kw">begin</span> | |
| 79 | + Ints.init(v, Heap.heap); | |
| 80 | + <span class="kw">defer</span> Ints.done(v); | |
| 81 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">1000</span> <span class="kw">do</span> Ints.push(v, i * i); <span class="kw">end</span>; | |
| 82 | + s := Ints.all(v); | |
| 83 | + Out.int(v.len); Out.str(<span class="string">" squares, the last "</span>); Out.int(s[<span class="ty">LEN</span>(s) - <span class="number">1</span>]); Out.ln; | |
| 84 | + Ints.resize(v, <span class="number">3</span>); | |
| 85 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> v.len - <span class="number">1</span> <span class="kw">do</span> Out.int(Ints.all(v)[i]); Out.char(<span class="string">' '</span>); <span class="kw">end</span>; | |
| 86 | + Out.ln; | |
| 87 | +<span class="kw">end</span>; | |
| 88 | + | |
| 89 | +<span class="kw">end</span> Squares.</code></pre> | |
| 90 | +<pre class="output"><code>1000 squares, the last 1000000 | |
| 91 | +1 4 9 | |
| 92 | +</code></pre> | |
| 93 | +<h2><code>Map(K, V; hash, eq)</code></h2> | |
| 94 | +<p>A hash map. Its key's hash and equality are procedure arguments, so any type can be a key. <code>put</code> replaces what a key maps to; <code>get</code> says what it maps to and whether it maps to anything; <code>remove</code> says whether the key was there. <code>next</code> walks the map: from 0, it gives the next entry and the number to pass for the one after, and -1 when there are no more.</p> | |
| 95 | +<div class="file"><span>Ages.raz</span></div><pre class="code"><code><span class="kw">module</span> Ages; | |
| 96 | +<span class="kw">import</span> Out, Fmt, Str, Heap, Book := Map([]<span class="ty">U8</span>, <span class="ty">INT</span>, Str.hash, Str.eq); | |
| 97 | + | |
| 98 | +<span class="kw">proc</span> main*; | |
| 99 | +<span class="kw">var</span> m: Book.Map; age: <span class="ty">INT</span>; found, ok: <span class="ty">BOOL</span>; i: <span class="ty">INT</span>; v: <span class="ty">INT</span>; | |
| 100 | +<span class="kw">begin</span> | |
| 101 | + Book.init(m, Heap.heap); | |
| 102 | + _ := Book.put(m, <span class="string">"ada"</span>, <span class="number">36</span>); | |
| 103 | + _ := Book.put(m, <span class="string">"grace"</span>, <span class="number">45</span>); | |
| 104 | + _ := Book.put(m, <span class="string">"alan"</span>, <span class="number">41</span>); | |
| 105 | + _ := Book.put(m, <span class="string">"ada"</span>, <span class="number">37</span>); <span class="comment">(* replaces *)</span> | |
| 106 | + age, found := Book.get(m, <span class="string">"ada"</span>); | |
| 107 | + Fmt.print(<span class="string">"ada: {} ({})\n"</span>, [Fmt.int(age), Fmt.bool(found)]); | |
| 108 | + age, found := Book.get(m, <span class="string">"linus"</span>); | |
| 109 | + Fmt.print(<span class="string">"linus: {} ({})\n"</span>, [Fmt.int(age), Fmt.bool(found)]); | |
| 110 | + ok := Book.remove(m, <span class="string">"alan"</span>); | |
| 111 | + Fmt.print(<span class="string">"{} entries, removed {}\n"</span>, [Fmt.int(m.len), Fmt.bool(ok)]); | |
| 112 | + v := <span class="number">0</span>; | |
| 113 | + i, _, age := Book.next(m, <span class="number">0</span>); | |
| 114 | + <span class="kw">while</span> i >= <span class="number">0</span> <span class="kw">do</span> | |
| 115 | + <span class="ty">INC</span>(v, age); | |
| 116 | + i, _, age := Book.next(m, i); | |
| 117 | + <span class="kw">end</span>; | |
| 118 | + Out.int(v); Out.str(<span class="string">" years in all\n"</span>); | |
| 119 | +<span class="kw">end</span>; | |
| 120 | + | |
| 121 | +<span class="kw">end</span> Ages.</code></pre> | |
| 122 | +<pre class="output"><code>ada: 37 (true) | |
| 123 | +linus: 0 (false) | |
| 124 | +2 entries, removed true | |
| 125 | +82 years in all | |
| 126 | +</code></pre> | |
| 127 | +<p>A map's order is its own, so a program that wants an order collects the entries and sorts them, as the next section does.</p> | |
| 128 | +<h2><code>Sort(T; less)</code></h2> | |
| 129 | +<p>An in-place sort of a slice, by a <code>less</code> procedure, in <code>n log n</code> at most and with no memory of its own. Elements equal by <code>less</code> may change places.</p> | |
| 130 | +<h2>Putting them together</h2> | |
| 131 | +<p>Counting words, then listing them by count and then alphabetically: a <code>Map</code> for the counts, a <code>Vec</code> of records to sort, however many words there are, and <code>Sort</code> with a two-level <code>less</code>.</p> | |
| 132 | +<div class="file"><span>Freq.raz</span></div><pre class="code"><code><span class="kw">module</span> Freq; | |
| 133 | +<span class="kw">import</span> Fmt, Str, Heap, | |
| 134 | + Count := Map([]<span class="ty">U8</span>, <span class="ty">INT</span>, Str.hash, Str.eq), | |
| 135 | + Entries := Vec(Entry), | |
| 136 | + Rank := Sort(Entry, before); | |
| 137 | + | |
| 138 | +<span class="kw">type</span> Entry = <span class="kw">record</span> word: []<span class="ty">U8</span>; n: <span class="ty">INT</span>; <span class="kw">end</span>; | |
| 139 | + | |
| 140 | +<span class="kw">const</span> Text = <span class="string">"the cat and the hat and the bat sat on the mat and the cat sat"</span>; | |
| 141 | + | |
| 142 | +<span class="comment">(* more first; equal counts alphabetically *)</span> | |
| 143 | +<span class="kw">proc</span> before(a, b: Entry): <span class="ty">BOOL</span>; | |
| 144 | +<span class="kw">begin</span> | |
| 145 | + <span class="kw">if</span> a.n # b.n <span class="kw">then</span> <span class="kw">return</span> a.n > b.n; <span class="kw">end</span>; | |
| 146 | + <span class="kw">return</span> Str.cmp(a.word, b.word) < <span class="number">0</span>; | |
| 147 | +<span class="kw">end</span>; | |
| 148 | + | |
| 149 | +<span class="kw">proc</span> main*; | |
| 150 | +<span class="kw">var</span> | |
| 151 | + m: Count.Map; entries: Entries.Vec; i, k, found: <span class="ty">INT</span>; | |
| 152 | + w, rest: []<span class="ty">U8</span>; key: []<span class="ty">U8</span>; v: <span class="ty">INT</span>; all: []Entry; | |
| 153 | +<span class="kw">begin</span> | |
| 154 | + Count.init(m, Heap.heap); | |
| 155 | + <span class="kw">defer</span> Count.done(m); | |
| 156 | + w, rest := Str.field(Text); | |
| 157 | + <span class="kw">while</span> <span class="ty">LEN</span>(w) > <span class="number">0</span> <span class="kw">do</span> | |
| 158 | + k, _ := Count.get(m, w); | |
| 159 | + _ := Count.put(m, w, k + <span class="number">1</span>); | |
| 160 | + w, rest := Str.field(rest); | |
| 161 | + <span class="kw">end</span>; | |
| 162 | + Entries.init(entries, Heap.heap); | |
| 163 | + <span class="kw">defer</span> Entries.done(entries); | |
| 164 | + found, key, v := Count.next(m, <span class="number">0</span>); | |
| 165 | + <span class="kw">while</span> found >= <span class="number">0</span> <span class="kw">do</span> | |
| 166 | + Entries.push(entries, {word: key, n: v}); | |
| 167 | + found, key, v := Count.next(m, found); | |
| 168 | + <span class="kw">end</span>; | |
| 169 | + all := Entries.all(entries); | |
| 170 | + Rank.sort(all); | |
| 171 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="ty">LEN</span>(all) - <span class="number">1</span> <span class="kw">do</span> | |
| 172 | + Fmt.print(<span class="string">"{} {}\n"</span>, [Fmt.int(all[i].n), Fmt.str(all[i].word)]); | |
| 173 | + <span class="kw">end</span>; | |
| 174 | +<span class="kw">end</span>; | |
| 175 | + | |
| 176 | +<span class="kw">end</span> Freq.</code></pre> | |
| 177 | +<pre class="output"><code>5 the | |
| 178 | +3 and | |
| 179 | +2 cat | |
| 180 | +2 sat | |
| 181 | +1 bat | |
| 182 | +1 hat | |
| 183 | +1 mat | |
| 184 | +1 on | |
| 185 | +</code></pre> | |
| 186 | +<p>The keys here are slices of the constant text, so they outlive the map; a program whose keys come from a buffer it will reuse copies them first with <code>Str.copy</code>, and gives each back with <code>Str.free</code> before <code>Count.done</code> gives back the map's own memory.</p> | |
| 187 | +<h2>Choosing</h2> | |
| 188 | +<p>Use a <code>List</code> when you push and pop at one end and walk it in order. Use a <code>Vec</code> when you add at the end and index, and don't know how many will come; an array when you do. Use a <code>Map</code> when you look things up by key. Use <code>Sort</code> on either's slice when you want an order. When none of them fits, they are each under a hundred lines of raz in <code>lib/</code>, and the advanced tour's allocator lesson shows what is underneath.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="bytes.html">← Strings and bytes</a><a href="index.html">Contents</a><a class="next" href="files.html">Files and the command line →</a></div></article></div> | |
| 189 | +</main> | |
| 190 | +<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> | |
| 191 | +</body> | |
| 192 | +</html> |
| @@ -0,0 +1,277 @@ | ||
| 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>Files and the command line - More Raz</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="Files and the command line - More Raz"> | |
| 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.lucelad.workers.dev/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" aria-current="page">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<div class="tour"><aside><h2>More Raz</h2><h3>The library</h3><ol start='1'> | |
| 22 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 23 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 24 | +<li><a href="collections.html">Lists, arrays, maps and sorting</a></li> | |
| 25 | +<li><a href="files.html" aria-current="page">Files and the command line</a></li> | |
| 26 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 27 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 28 | +</ol> | |
| 29 | +<h3>Standing alone</h3><ol start='7'> | |
| 30 | +<li><a href="static.html">A program with no run time</a></li> | |
| 31 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 32 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 33 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 34 | +</ol> | |
| 35 | +<h3>The machine</h3><ol start='11'> | |
| 36 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 37 | +<li><a href="syscalls.html">System calls</a></li> | |
| 38 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 39 | +</ol> | |
| 40 | +<h3>Shared memory</h3><ol start='14'> | |
| 41 | +<li><a href="volatile.html">Volatile</a></li> | |
| 42 | +<li><a href="atomics.html">Atomics</a></li> | |
| 43 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 44 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 45 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 46 | +</ol></aside><article><p class="kicker">The library · lesson 4 of 18</p><h1>Files and the command line</h1> | |
| 47 | +<p><code>Files</code> is for the common case: a whole file read or written in one call. <code>Sys</code> is the system underneath, for everything else. <code>Opt</code> reads a command line from a table, so that the help and the error messages can't drift from the code.</p> | |
| 48 | +<h2>A whole file</h2> | |
| 49 | +<p><code>Files.write(path, data)</code> makes the file hold <code>data</code>, and <code>Files.read(path, b)</code> adds the whole file to a <code>Buf</code>. Both say whether they worked.</p> | |
| 50 | +<div class="file"><span>Notes.raz</span></div><pre class="code"><code><span class="kw">module</span> Notes; | |
| 51 | +<span class="kw">import</span> Out, Files, Buf, Heap; | |
| 52 | + | |
| 53 | +<span class="kw">proc</span> main*; | |
| 54 | +<span class="kw">var</span> b: Buf.Buf; ok: <span class="ty">BOOL</span>; | |
| 55 | +<span class="kw">begin</span> | |
| 56 | + ok := Files.write(<span class="string">"notes.txt"</span>, <span class="string">"first line\nsecond line\n"</span>); | |
| 57 | + <span class="kw">if</span> <span class="kw">not</span> ok <span class="kw">then</span> Out.str(<span class="string">"can't write\n"</span>); <span class="kw">return</span>; <span class="kw">end</span>; | |
| 58 | + Buf.init(b, Heap.heap); | |
| 59 | + <span class="kw">defer</span> Buf.done(b); | |
| 60 | + ok := Files.read(<span class="string">"notes.txt"</span>, b); | |
| 61 | + <span class="kw">if</span> ok <span class="kw">then</span> | |
| 62 | + Out.int(b.len); Out.str(<span class="string">" bytes: "</span>); Out.str(Buf.bytes(b)); | |
| 63 | + <span class="kw">end</span>; | |
| 64 | + ok := Files.read(<span class="string">"missing.txt"</span>, b); | |
| 65 | + <span class="kw">if</span> <span class="kw">not</span> ok <span class="kw">then</span> Out.str(<span class="string">"missing.txt: not there\n"</span>); <span class="kw">end</span>; | |
| 66 | + <span class="kw">if</span> Files.load(<span class="string">"missing.txt"</span>, b) = -<span class="number">2</span> <span class="kw">then</span> Out.str(<span class="string">"missing.txt: ENOENT\n"</span>); <span class="kw">end</span>; | |
| 67 | +<span class="kw">end</span>; | |
| 68 | + | |
| 69 | +<span class="kw">end</span> Notes.</code></pre> | |
| 70 | +<pre class="output"><code>23 bytes: first line | |
| 71 | +second line | |
| 72 | +missing.txt: not there | |
| 73 | +missing.txt: ENOENT | |
| 74 | +</code></pre> | |
| 75 | +<p>When the reason matters, <code>Files.load</code> says it: 0, or minus the errno of what failed, -2 (ENOENT) for no such file, -13 (EACCES) for one not allowed.</p> | |
| 76 | +<h2>Descriptors</h2> | |
| 77 | +<p>Underneath, a file is a descriptor, an <code>INT</code>. <code>Sys.open</code> takes the path and the way to open it as a set; <code>read</code>, <code>write</code>, <code>seek</code> and <code>close</code> do what they say. A result that can fail is a number, and minus an errno if it failed, as on Linux itself. Reading in a loop is the pattern for anything too big to hold at once.</p> | |
| 78 | +<div class="file"><span>Count.raz</span></div><pre class="code"><code><span class="kw">module</span> Count; | |
| 79 | +<span class="kw">import</span> Out, Sys; | |
| 80 | + | |
| 81 | +<span class="comment">(* the lines of the file at path, or minus an errno *)</span> | |
| 82 | +<span class="kw">proc</span> lines(path: []<span class="ty">U8</span>): <span class="ty">INT</span>; | |
| 83 | +<span class="kw">var</span> fd, n, i, count: <span class="ty">INT</span>; buf: [<span class="number">4096</span>]<span class="ty">U8</span>; | |
| 84 | +<span class="kw">begin</span> | |
| 85 | + fd := Sys.openRead(path); | |
| 86 | + <span class="kw">if</span> fd < <span class="number">0</span> <span class="kw">then</span> <span class="kw">return</span> fd; <span class="kw">end</span>; | |
| 87 | + <span class="kw">defer</span> Sys.close(fd); | |
| 88 | + n := Sys.read(fd, buf); | |
| 89 | + <span class="kw">while</span> n > <span class="number">0</span> <span class="kw">do</span> | |
| 90 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> n - <span class="number">1</span> <span class="kw">do</span> | |
| 91 | + <span class="kw">if</span> buf[i] = <span class="string">'\n'</span> <span class="kw">then</span> <span class="ty">INC</span>(count); <span class="kw">end</span>; | |
| 92 | + <span class="kw">end</span>; | |
| 93 | + n := Sys.read(fd, buf); | |
| 94 | + <span class="kw">end</span>; | |
| 95 | + <span class="kw">if</span> n < <span class="number">0</span> <span class="kw">then</span> <span class="kw">return</span> n; <span class="kw">end</span>; | |
| 96 | + <span class="kw">return</span> count; | |
| 97 | +<span class="kw">end</span>; | |
| 98 | + | |
| 99 | +<span class="kw">proc</span> main*; | |
| 100 | +<span class="kw">var</span> fd: <span class="ty">INT</span>; pos: <span class="ty">I64</span>; | |
| 101 | +<span class="kw">begin</span> | |
| 102 | + fd := Sys.create(<span class="string">"log.txt"</span>); | |
| 103 | + _ := Sys.write(fd, <span class="string">"a\nb\nc\n"</span>); | |
| 104 | + pos := Sys.seek(fd, <span class="number">2</span>, <span class="ty">false</span>); <span class="comment">(* from the start *)</span> | |
| 105 | + Out.int(pos); Out.ln; | |
| 106 | + Sys.close(fd); | |
| 107 | + Out.int(lines(<span class="string">"log.txt"</span>)); Out.str(<span class="string">" lines\n"</span>); | |
| 108 | + Out.int(lines(<span class="string">"/no/such/file"</span>)); Out.ln; <span class="comment">(* -2: ENOENT *)</span> | |
| 109 | + fd := Sys.open(<span class="string">"log.txt"</span>, {Sys.writing, Sys.appending}); | |
| 110 | + _ := Sys.write(fd, <span class="string">"d\n"</span>); | |
| 111 | + Sys.close(fd); | |
| 112 | + Out.int(lines(<span class="string">"log.txt"</span>)); Out.str(<span class="string">" lines now\n"</span>); | |
| 113 | +<span class="kw">end</span>; | |
| 114 | + | |
| 115 | +<span class="kw">end</span> Count.</code></pre> | |
| 116 | +<pre class="output"><code>2 | |
| 117 | +3 lines | |
| 118 | +-2 | |
| 119 | +4 lines now | |
| 120 | +</code></pre> | |
| 121 | +<h2>Looking at a file, and a directory</h2> | |
| 122 | +<p><code>Sys.info</code> says a file's size, modification time, permissions, and whether it is a directory, a regular file or a link. <code>Sys.openDir</code> and <code>nextEntry</code> list a directory, in no particular order, so a program that prints one sorts it first. A name from <code>nextEntry</code> is good only until the next call, so the program keeps a copy.</p> | |
| 123 | +<div class="file"><span>Tree.raz</span></div><pre class="code"><code><span class="kw">module</span> Tree; | |
| 124 | +<span class="kw">import</span> Out, Sys, Str, Heap, Mem, Buf, Order := Sort([]<span class="ty">U8</span>, before); | |
| 125 | + | |
| 126 | +<span class="kw">proc</span> before(a, b: []<span class="ty">U8</span>): <span class="ty">BOOL</span>; | |
| 127 | +<span class="kw">begin</span> | |
| 128 | + <span class="kw">return</span> Str.cmp(a, b) < <span class="number">0</span>; | |
| 129 | +<span class="kw">end</span>; | |
| 130 | + | |
| 131 | +<span class="comment">(* a file made to hold text *)</span> | |
| 132 | +<span class="kw">proc</span> put(path, text: []<span class="ty">U8</span>); | |
| 133 | +<span class="kw">var</span> fd: <span class="ty">INT</span>; | |
| 134 | +<span class="kw">begin</span> | |
| 135 | + fd := Sys.create(path); | |
| 136 | + _ := Sys.write(fd, text); | |
| 137 | + Sys.close(fd); | |
| 138 | +<span class="kw">end</span>; | |
| 139 | + | |
| 140 | +<span class="kw">proc</span> main*; | |
| 141 | +<span class="kw">var</span> | |
| 142 | + d: Sys.Dir; name, copy: []<span class="ty">U8</span>; more, ok: <span class="ty">BOOL</span>; i, n: <span class="ty">INT</span>; | |
| 143 | + info: Sys.Info; err: <span class="ty">INT</span>; names: [<span class="number">16</span>][]<span class="ty">U8</span>; path: Buf.Buf; | |
| 144 | +<span class="kw">begin</span> | |
| 145 | + _ := Sys.makeDir(<span class="string">"proj"</span>); | |
| 146 | + _ := Sys.makeDir(<span class="string">"proj/src"</span>); | |
| 147 | + put(<span class="string">"proj/b.txt"</span>, <span class="string">"bb"</span>); | |
| 148 | + put(<span class="string">"proj/a.txt"</span>, <span class="string">"a"</span>); | |
| 149 | + <span class="kw">if</span> Sys.openDir(d, <span class="string">"proj"</span>) < <span class="number">0</span> <span class="kw">then</span> <span class="kw">return</span>; <span class="kw">end</span>; | |
| 150 | + n := <span class="number">0</span>; | |
| 151 | + name, more := Sys.nextEntry(d); | |
| 152 | + <span class="kw">while</span> more <span class="kw">do</span> | |
| 153 | + copy, ok := Str.copy(Heap.heap, name); | |
| 154 | + <span class="kw">if</span> ok <span class="kw">and</span> (n < <span class="number">16</span>) <span class="kw">then</span> names[n] := copy; <span class="ty">INC</span>(n); <span class="kw">end</span>; | |
| 155 | + name, more := Sys.nextEntry(d); | |
| 156 | + <span class="kw">end</span>; | |
| 157 | + Sys.closeDir(d); | |
| 158 | + Order.sort(names[<span class="number">0</span>..n]); | |
| 159 | + Buf.init(path, Heap.heap); | |
| 160 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> n - <span class="number">1</span> <span class="kw">do</span> | |
| 161 | + Buf.reset(path); | |
| 162 | + Buf.str(path, <span class="string">"proj/"</span>); | |
| 163 | + Buf.str(path, names[i]); | |
| 164 | + info, err := Sys.info(Buf.bytes(path)); | |
| 165 | + Out.str(names[i]); | |
| 166 | + <span class="kw">if</span> err < <span class="number">0</span> <span class="kw">then</span> Out.str(<span class="string">" ?"</span>); | |
| 167 | + <span class="kw">elsif</span> info.dir <span class="kw">then</span> Out.str(<span class="string">"/"</span>); | |
| 168 | + <span class="kw">else</span> Out.str(<span class="string">", "</span>); Out.int(info.size); Out.str(<span class="string">" bytes"</span>); | |
| 169 | + <span class="kw">end</span>; | |
| 170 | + Out.ln; | |
| 171 | + Mem.free(Heap.heap, ^<span class="ty">U8</span>(<span class="ty">ADR</span>(names[i][<span class="number">0</span>]))); | |
| 172 | + <span class="kw">end</span>; | |
| 173 | + Buf.done(path); | |
| 174 | +<span class="kw">end</span>; | |
| 175 | + | |
| 176 | +<span class="kw">end</span> Tree.</code></pre> | |
| 177 | +<pre class="output"><code>a.txt, 1 bytes | |
| 178 | +b.txt, 2 bytes | |
| 179 | +src/ | |
| 180 | +</code></pre> | |
| 181 | +<h2>Modes, links, and a lock</h2> | |
| 182 | +<p><code>Sys.openMode</code> is <code>open</code> with the permissions a file it makes should have, less those the umask takes away: 1EDH (755) for a script, 124H (444) for a file never to be written. <code>Sys.linkInfo</code> looks at a symbolic link itself, where <code>info</code> follows it, so a link whose target is gone is still seen. <code>Info.ino</code> is the file's inode: a file renamed over another has a new one, though its size and time may match, which is how a program knows a file it cached is still the same.</p> | |
| 183 | +<p><code>Sys.lock</code> takes the lock on an open file, which one open file holds at a time; another that asks for it waits, or with <code>wait</code> false gets -11 at once. The lock goes when the file is closed or the program ends, however it ends, so it can't go stale as a lock file can. <code>Sys.syncAll</code> puts everything written to a file system on the disk at once, before the one file that names it all is written: a database's or a version control system's commit.</p> | |
| 184 | +<div class="file"><span>Store.raz</span></div><pre class="code"><code><span class="kw">module</span> Store; | |
| 185 | +<span class="kw">import</span> Fmt, Sys; | |
| 186 | + | |
| 187 | +<span class="kw">proc</span> main*; | |
| 188 | +<span class="kw">var</span> fd, other: <span class="ty">INT</span>; named, target: Sys.Info; | |
| 189 | +<span class="kw">begin</span> | |
| 190 | + fd := Sys.openMode(<span class="string">"run.sh"</span>, {Sys.writing, Sys.creating, Sys.truncating}, <span class="number">1EDH</span>); | |
| 191 | + _ := Sys.write(fd, <span class="string">"echo hi\n"</span>); | |
| 192 | + _ := Sys.syncAll(fd); | |
| 193 | + Sys.close(fd); | |
| 194 | + target, _ := Sys.info(<span class="string">"run.sh"</span>); | |
| 195 | + Fmt.print(<span class="string">"its owner may run it: {}\n"</span>, [Fmt.bool(target.mode & <span class="number">40H</span> # <span class="number">0</span>)]); | |
| 196 | + | |
| 197 | + _ := Sys.remove(<span class="string">"current"</span>); | |
| 198 | + _ := Sys.symlink(<span class="string">"run.sh"</span>, <span class="string">"current"</span>); | |
| 199 | + named, _ := Sys.linkInfo(<span class="string">"current"</span>); | |
| 200 | + Fmt.print(<span class="string">"a link: {}, of {} bytes\n"</span>, [Fmt.bool(named.symlink), Fmt.int(named.size)]); | |
| 201 | + named, _ := Sys.info(<span class="string">"current"</span>); | |
| 202 | + Fmt.print(<span class="string">"the same file: {}\n"</span>, [Fmt.bool(named.ino = target.ino)]); | |
| 203 | + | |
| 204 | + fd := Sys.openRead(<span class="string">"run.sh"</span>); | |
| 205 | + other := Sys.openRead(<span class="string">"run.sh"</span>); | |
| 206 | + Fmt.print(<span class="string">"{} {}\n"</span>, [Fmt.int(Sys.lock(fd, <span class="ty">false</span>)), Fmt.int(Sys.lock(other, <span class="ty">false</span>))]); <span class="comment">(* -11: held *)</span> | |
| 207 | + Sys.close(fd); | |
| 208 | + Fmt.print(<span class="string">"{}\n"</span>, [Fmt.int(Sys.lock(other, <span class="ty">false</span>))]); <span class="comment">(* free again *)</span> | |
| 209 | + Sys.close(other); | |
| 210 | +<span class="kw">end</span>; | |
| 211 | + | |
| 212 | +<span class="kw">end</span> Store.</code></pre> | |
| 213 | +<pre class="output"><code>its owner may run it: true | |
| 214 | +a link: true, of 6 bytes | |
| 215 | +the same file: true | |
| 216 | +0 -11 | |
| 217 | +0 | |
| 218 | +</code></pre> | |
| 219 | +<h2>A command line, from a table</h2> | |
| 220 | +<p>A program describes its options once, in a table of <code>Opt.Row</code>s: its synopsis lines, its subcommands and its options. The help and the error messages are made from the table. The parser reads by the rules of the C library's <code>getopt</code> with GNU's long options, so <code>-vn3</code>, <code>-n 3</code>, <code>--count=3</code> and <code>--count 3</code> all work, and <code>--</code> ends the options.</p> | |
| 221 | +<div class="file"><span>Tool.raz</span></div><pre class="code"><code><span class="kw">module</span> Tool; | |
| 222 | +<span class="kw">import</span> Out, Fmt, Opt; | |
| 223 | + | |
| 224 | +<span class="kw">const</span> count = <span class="number">1</span>; <span class="comment">(* the key of --count, which has no letter *)</span> | |
| 225 | + | |
| 226 | +<span class="kw">proc</span> main*; | |
| 227 | +<span class="kw">var</span> p: Opt.Parser; verbose: <span class="ty">BOOL</span>; n, i: <span class="ty">INT</span>; w: []<span class="ty">U8</span>; ok: <span class="ty">BOOL</span>; | |
| 228 | +<span class="kw">begin</span> | |
| 229 | + n := <span class="number">1</span>; | |
| 230 | + Opt.init(p, <span class="string">"tool"</span>, [ | |
| 231 | + Opt.usage(<span class="string">""</span>, <span class="string">"tool [-v] [--count n] word ..."</span>), | |
| 232 | + Opt.option(<span class="string">""</span>, <span class="string">'v'</span>, <span class="string">"verbose"</span>, <span class="string">""</span>, <span class="string">"say more"</span>), | |
| 233 | + Opt.option(<span class="string">""</span>, count, <span class="string">"count"</span>, <span class="string">"n"</span>, <span class="string">"repeat each word n times"</span>)]); | |
| 234 | + <span class="kw">while</span> Opt.next(p) <span class="kw">do</span> | |
| 235 | + <span class="kw">if</span> p.letter = <span class="string">'v'</span> <span class="kw">then</span> verbose := <span class="ty">true</span>; | |
| 236 | + <span class="kw">elsif</span> p.letter = count <span class="kw">then</span> n := <span class="ty">INT</span>(Opt.number(p, <span class="number">1</span>, <span class="number">5</span>)); | |
| 237 | + <span class="kw">end</span>; | |
| 238 | + <span class="kw">end</span>; | |
| 239 | + w, ok := Opt.operand(p); | |
| 240 | + <span class="kw">if</span> <span class="kw">not</span> ok <span class="kw">then</span> Opt.fail(p, <span class="string">"no words; see tool -h"</span>); <span class="kw">end</span>; | |
| 241 | + <span class="kw">while</span> ok <span class="kw">do</span> | |
| 242 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> n <span class="kw">do</span> | |
| 243 | + <span class="kw">if</span> verbose <span class="kw">then</span> Out.str(<span class="string">"word: "</span>); <span class="kw">end</span>; | |
| 244 | + Fmt.print(<span class="string">"{}\n"</span>, [Fmt.str(w)]); | |
| 245 | + <span class="kw">end</span>; | |
| 246 | + w, ok := Opt.operand(p); | |
| 247 | + <span class="kw">end</span>; | |
| 248 | +<span class="kw">end</span>; | |
| 249 | + | |
| 250 | +<span class="kw">end</span> Tool.</code></pre> | |
| 251 | +<pre class="output term"><code><span class="cmd">$ raz Tool.raz</span> | |
| 252 | +<span class="cmd">$ ./Tool -h</span> | |
| 253 | +usage: tool [-v] [--count n] word ... | |
| 254 | + | |
| 255 | + -v, --verbose say more | |
| 256 | + --count n repeat each word n times | |
| 257 | + -h, --help print this and exit | |
| 258 | +<span class="cmd">$ ./Tool -v hello world</span> | |
| 259 | +word: hello | |
| 260 | +word: world | |
| 261 | +<span class="cmd">$ ./Tool --count 9 hello; echo "status $?"</span> | |
| 262 | +tool: --count wants a number from 1 to 5, not '9' | |
| 263 | +usage: tool [-v] [--count n] word ... | |
| 264 | +status 2 | |
| 265 | +<span class="cmd">$ ./Tool -x; echo "status $?"</span> | |
| 266 | +tool: unknown option -x | |
| 267 | +usage: tool [-v] [--count n] word ... | |
| 268 | +status 2 | |
| 269 | +<span class="cmd">$ ./Tool; echo "status $?"</span> | |
| 270 | +tool: no words; see tool -h | |
| 271 | +status 2</code></pre> | |
| 272 | +<p><code>-h</code> and <code>--help</code> are <code>Opt</code>'s: the program never sees them. A mistake on the command line is a sentence on standard error with the program's name first, then the synopsis, and status 2. Nothing in <code>Tool</code> wrote any of that.</p> | |
| 273 | +<p>A mistake in the table itself, such as an option given twice, is the program's, and <code>init</code> says so and ends with status 1 before it reads a word.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="collections.html">← Lists, arrays, maps and sorting</a><a href="index.html">Contents</a><a class="next" href="processes.html">Time, randomness and other programs →</a></div></article></div> | |
| 274 | +</main> | |
| 275 | +<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> | |
| 276 | +</body> | |
| 277 | +</html> |
| @@ -0,0 +1,198 @@ | ||
| 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>Output and formatting - More Raz</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="Output and formatting - More Raz"> | |
| 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.lucelad.workers.dev/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" aria-current="page">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<div class="tour"><aside><h2>More Raz</h2><h3>The library</h3><ol start='1'> | |
| 22 | +<li><a href="fmt.html" aria-current="page">Output and formatting</a></li> | |
| 23 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 24 | +<li><a href="collections.html">Lists, arrays, maps and sorting</a></li> | |
| 25 | +<li><a href="files.html">Files and the command line</a></li> | |
| 26 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 27 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 28 | +</ol> | |
| 29 | +<h3>Standing alone</h3><ol start='7'> | |
| 30 | +<li><a href="static.html">A program with no run time</a></li> | |
| 31 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 32 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 33 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 34 | +</ol> | |
| 35 | +<h3>The machine</h3><ol start='11'> | |
| 36 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 37 | +<li><a href="syscalls.html">System calls</a></li> | |
| 38 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 39 | +</ol> | |
| 40 | +<h3>Shared memory</h3><ol start='14'> | |
| 41 | +<li><a href="volatile.html">Volatile</a></li> | |
| 42 | +<li><a href="atomics.html">Atomics</a></li> | |
| 43 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 44 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 45 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 46 | +</ol></aside><article><p class="kicker">The library · lesson 1 of 18</p><h1>Output and formatting</h1> | |
| 47 | +<p>The first tour used <code>Out</code> for everything it printed. Two modules do the work: <code>Out</code>, which owns standard output and its buffer, and <code>Fmt</code>, which turns values into text.</p> | |
| 48 | +<h2>What <code>Out</code> does with its buffer</h2> | |
| 49 | +<p><code>Out</code> keeps a buffer of 4 KB. It writes it out when it is full, at each line feed when standard output is a terminal, at <code>Out.flush</code>, and when the program ends by <code>Rt.exit</code> (which a normal end and a failed check both are). A lock keeps what each call writes together when threads write at once.</p> | |
| 50 | +<p>You can see the effect with <code>strace</code>, which lists the system calls a program makes. A program that prints three lines to a file makes one <code>write</code>:</p> | |
| 51 | +<div class="file"><span>Three.raz</span></div><pre class="code"><code><span class="kw">module</span> Three; | |
| 52 | +<span class="kw">import</span> Out; | |
| 53 | + | |
| 54 | +<span class="kw">proc</span> main*; | |
| 55 | +<span class="kw">begin</span> | |
| 56 | + Out.str(<span class="string">"one\n"</span>); | |
| 57 | + Out.str(<span class="string">"two\n"</span>); | |
| 58 | + Out.str(<span class="string">"three\n"</span>); | |
| 59 | +<span class="kw">end</span>; | |
| 60 | + | |
| 61 | +<span class="kw">end</span> Three.</code></pre> | |
| 62 | +<pre class="output term"><code><span class="cmd">$ raz Three.raz</span> | |
| 63 | +<span class="cmd">$ strace -e trace=write ./Three > /dev/null</span> | |
| 64 | +write(1, "one\ntwo\nthree\n", 14) = 14 | |
| 65 | ++++ exited with 0 +++</code></pre> | |
| 66 | +<p>Three lines, one system call. That is why <code>Out</code> is cheap, and why a program that mixes it with C's <code>printf</code>, which keeps a buffer of its own, must flush one before the other.</p> | |
| 67 | +<h2><code>Fmt.print</code></h2> | |
| 68 | +<p><code>Fmt.print(format, args)</code> writes to standard output. Each <code>{}</code> in the format takes the next argument, and <code>{{</code> and <code>}}</code> stand for the braces. The arguments are a slice of <code>Fmt.Arg</code>, a variant, so each is built with the constructor for its kind: <code>int</code>, <code>uint</code>, <code>hex</code>, <code>str</code>, <code>char</code>, <code>bool</code> and <code>real</code>, which takes the number of digits after the point.</p> | |
| 69 | +<div class="file"><span>Kinds.raz</span></div><pre class="code"><code><span class="kw">module</span> Kinds; | |
| 70 | +<span class="kw">import</span> Fmt; | |
| 71 | + | |
| 72 | +<span class="kw">proc</span> main*; | |
| 73 | +<span class="kw">var</span> big: <span class="ty">U64</span>; small: <span class="ty">I8</span>; | |
| 74 | +<span class="kw">begin</span> | |
| 75 | + big := <span class="number">0FFFFFFFFFFFFFFFFH</span>; | |
| 76 | + small := -<span class="number">5</span>; | |
| 77 | + Fmt.print(<span class="string">"int {}, uint {}, hex {}\n"</span>, | |
| 78 | + [Fmt.int(-<span class="number">42</span>), Fmt.uint(big), Fmt.hex(<span class="number">255</span>)]); | |
| 79 | + Fmt.print(<span class="string">"str {}, char {}, bool {}\n"</span>, | |
| 80 | + [Fmt.str(<span class="string">"hi"</span>), Fmt.char(<span class="string">'x'</span>), Fmt.bool(<span class="number">1</span> < <span class="number">2</span>)]); | |
| 81 | + Fmt.print(<span class="string">"real {} and {} and {}\n"</span>, | |
| 82 | + [Fmt.real(<span class="number">3.14159</span>, <span class="number">2</span>), Fmt.real(<span class="number">2.5</span>, <span class="number">0</span>), Fmt.real(<span class="number">1.0</span> / <span class="number">3.0</span>, <span class="number">9</span>)]); | |
| 83 | + Fmt.print(<span class="string">"an I8: {}; braces: {{ and }}\n"</span>, [Fmt.int(<span class="ty">I64</span>(small))]); | |
| 84 | +<span class="kw">end</span>; | |
| 85 | + | |
| 86 | +<span class="kw">end</span> Kinds.</code></pre> | |
| 87 | +<pre class="output"><code>int -42, uint 18446744073709551615, hex FF | |
| 88 | +str hi, char x, bool true | |
| 89 | +real 3.14 and 3 and 0.333333333 | |
| 90 | +an I8: -5; braces: { and } | |
| 91 | +</code></pre> | |
| 92 | +<p>An argument whose type is wrong doesn't compile: there is no <code>%d</code> that disagrees with its argument. A <code>{}</code> with no argument left prints nothing, and arguments left over are not printed, so a mismatch shows up as missing text, never as a crash or as memory read by mistake.</p> | |
| 93 | +<h2>Into a buffer</h2> | |
| 94 | +<p><code>Fmt.write(b, format, args)</code> does the same into a <code>Buf</code> instead of standard output. That is how a message is built to send somewhere else: a file, a socket, a window, a string kept for later.</p> | |
| 95 | +<div class="file"><span>Message.raz</span></div><pre class="code"><code><span class="kw">module</span> Message; | |
| 96 | +<span class="kw">import</span> Out, Buf, Fmt, Heap; | |
| 97 | + | |
| 98 | +<span class="comment">(* "name (age n)", built in a Buf the caller owns *)</span> | |
| 99 | +<span class="kw">proc</span> describe(<span class="kw">var</span> b: Buf.Buf; name: []<span class="ty">U8</span>; age: <span class="ty">INT</span>); | |
| 100 | +<span class="kw">begin</span> | |
| 101 | + Fmt.write(b, <span class="string">"{} (age {})"</span>, [Fmt.str(name), Fmt.int(age)]); | |
| 102 | +<span class="kw">end</span>; | |
| 103 | + | |
| 104 | +<span class="kw">proc</span> main*; | |
| 105 | +<span class="kw">var</span> b: Buf.Buf; | |
| 106 | +<span class="kw">begin</span> | |
| 107 | + Buf.init(b, Heap.heap); | |
| 108 | + <span class="kw">defer</span> Buf.done(b); | |
| 109 | + describe(b, <span class="string">"Ada"</span>, <span class="number">36</span>); | |
| 110 | + Buf.str(b, <span class="string">"; "</span>); | |
| 111 | + describe(b, <span class="string">"Grace"</span>, <span class="number">45</span>); | |
| 112 | + Out.str(Buf.bytes(b)); Out.ln; | |
| 113 | + Out.int(b.len); Out.str(<span class="string">" bytes\n"</span>); | |
| 114 | +<span class="kw">end</span>; | |
| 115 | + | |
| 116 | +<span class="kw">end</span> Message.</code></pre> | |
| 117 | +<pre class="output"><code>Ada (age 36); Grace (age 45) | |
| 118 | +28 bytes | |
| 119 | +</code></pre> | |
| 120 | +<h2>Columns</h2> | |
| 121 | +<p><code>Fmt</code> writes values as they are, with no widths. A program that wants columns pads in one small procedure and uses it everywhere, which is easier to read than a format language.</p> | |
| 122 | +<div class="file"><span>Table.raz</span></div><pre class="code"><code><span class="kw">module</span> Table; | |
| 123 | +<span class="kw">import</span> Out; | |
| 124 | + | |
| 125 | +<span class="comment">(* s, then spaces up to width *)</span> | |
| 126 | +<span class="kw">proc</span> left(s: []<span class="ty">U8</span>; width: <span class="ty">INT</span>); | |
| 127 | +<span class="kw">var</span> i: <span class="ty">INT</span>; | |
| 128 | +<span class="kw">begin</span> | |
| 129 | + Out.str(s); | |
| 130 | + <span class="kw">for</span> i := <span class="ty">LEN</span>(s) <span class="kw">to</span> width - <span class="number">1</span> <span class="kw">do</span> Out.char(<span class="string">' '</span>); <span class="kw">end</span>; | |
| 131 | +<span class="kw">end</span>; | |
| 132 | + | |
| 133 | +<span class="comment">(* n, right aligned in width *)</span> | |
| 134 | +<span class="kw">proc</span> right(n: <span class="ty">INT</span>; width: <span class="ty">INT</span>); | |
| 135 | +<span class="kw">var</span> digits: <span class="ty">INT</span>; v: <span class="ty">INT</span>; i: <span class="ty">INT</span>; | |
| 136 | +<span class="kw">begin</span> | |
| 137 | + digits := <span class="number">1</span>; | |
| 138 | + v := n; | |
| 139 | + <span class="kw">if</span> v < <span class="number">0</span> <span class="kw">then</span> <span class="ty">INC</span>(digits); v := -v; <span class="kw">end</span>; | |
| 140 | + <span class="kw">while</span> v >= <span class="number">10</span> <span class="kw">do</span> <span class="ty">INC</span>(digits); v := v <span class="kw">div</span> <span class="number">10</span>; <span class="kw">end</span>; | |
| 141 | + <span class="kw">for</span> i := digits <span class="kw">to</span> width - <span class="number">1</span> <span class="kw">do</span> Out.char(<span class="string">' '</span>); <span class="kw">end</span>; | |
| 142 | + Out.int(n); | |
| 143 | +<span class="kw">end</span>; | |
| 144 | + | |
| 145 | +<span class="kw">proc</span> row(name: []<span class="ty">U8</span>; qty, price: <span class="ty">INT</span>); | |
| 146 | +<span class="kw">begin</span> | |
| 147 | + left(name, <span class="number">10</span>); | |
| 148 | + right(qty, <span class="number">5</span>); | |
| 149 | + right(price, <span class="number">8</span>); | |
| 150 | + right(qty * price, <span class="number">9</span>); | |
| 151 | + Out.ln; | |
| 152 | +<span class="kw">end</span>; | |
| 153 | + | |
| 154 | +<span class="kw">proc</span> main*; | |
| 155 | +<span class="kw">begin</span> | |
| 156 | + Out.str(<span class="string">"item qty price total\n"</span>); | |
| 157 | + row(<span class="string">"bolts"</span>, <span class="number">120</span>, <span class="number">3</span>); | |
| 158 | + row(<span class="string">"washers"</span>, <span class="number">1000</span>, <span class="number">1</span>); | |
| 159 | + row(<span class="string">"gears"</span>, <span class="number">8</span>, <span class="number">250</span>); | |
| 160 | + row(<span class="string">"shims"</span>, <span class="number">12</span>, -<span class="number">4</span>); | |
| 161 | +<span class="kw">end</span>; | |
| 162 | + | |
| 163 | +<span class="kw">end</span> Table.</code></pre> | |
| 164 | +<pre class="output"><code>item qty price total | |
| 165 | +bolts 120 3 360 | |
| 166 | +washers 1000 1 1000 | |
| 167 | +gears 8 250 2000 | |
| 168 | +shims 12 -4 -48 | |
| 169 | +</code></pre> | |
| 170 | +<h2>Writing numbers in other bases</h2> | |
| 171 | +<p><code>Out.hex(n, digits)</code> writes <code>n</code> in hexadecimal, padded with zeros to <code>digits</code>. A binary dump is a <code>for</code> loop over a slice, one <code>Out.hex(U64(b), 2)</code> to a byte.</p> | |
| 172 | +<div class="file"><span>Dump.raz</span></div><pre class="code"><code><span class="kw">module</span> Dump; | |
| 173 | +<span class="kw">import</span> Out; | |
| 174 | + | |
| 175 | +<span class="kw">proc</span> dump(data: []<span class="ty">U8</span>); | |
| 176 | +<span class="kw">var</span> i: <span class="ty">INT</span>; | |
| 177 | +<span class="kw">begin</span> | |
| 178 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="ty">LEN</span>(data) - <span class="number">1</span> <span class="kw">do</span> | |
| 179 | + <span class="kw">if</span> i > <span class="number">0</span> <span class="kw">then</span> Out.char(<span class="string">' '</span>); <span class="kw">end</span>; | |
| 180 | + Out.hex(<span class="ty">U64</span>(data[i]), <span class="number">2</span>); | |
| 181 | + <span class="kw">end</span>; | |
| 182 | + Out.ln; | |
| 183 | +<span class="kw">end</span>; | |
| 184 | + | |
| 185 | +<span class="kw">proc</span> main*; | |
| 186 | +<span class="kw">begin</span> | |
| 187 | + dump(<span class="string">"raz\n"</span>); | |
| 188 | + dump(<span class="string">"\u{3BB}"</span>); | |
| 189 | +<span class="kw">end</span>; | |
| 190 | + | |
| 191 | +<span class="kw">end</span> Dump.</code></pre> | |
| 192 | +<pre class="output"><code>72 61 7A 0A | |
| 193 | +CE BB | |
| 194 | +</code></pre><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="index.html">Contents</a><a class="next" href="bytes.html">Strings and bytes →</a></div></article></div> | |
| 195 | +</main> | |
| 196 | +<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> | |
| 197 | +</body> | |
| 198 | +</html> |
| @@ -0,0 +1,60 @@ | ||
| 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>More Raz</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="More Raz"> | |
| 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.lucelad.workers.dev/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" aria-current="page">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<div class="contents"><h1>More Raz</h1> | |
| 22 | +<p>The second tour, for the part of raz that sits close to the machine. It | |
| 23 | +assumes you have taken <a href="../tour/index.html">Raz, Set, Go</a> or know | |
| 24 | +Pascal or C well enough not to need it.</p> | |
| 25 | +<p>It has four parts: <strong>The library</strong>, the modules every program | |
| 26 | +reaches for; <strong>Standing alone</strong>, programs that need no C and no | |
| 27 | +run time; <strong>The machine</strong>, procedures written in assembly and | |
| 28 | +direct system calls; and <strong>Shared memory</strong>, volatile accesses, | |
| 29 | +atomics and threads. Every program is compiled and run when this page is | |
| 30 | +made, as before.</p> | |
| 31 | +<h2>The library</h2><ol start='1'> | |
| 32 | +<li><a href="fmt.html">Output and formatting</a> <span>Out's buffer, Fmt's arguments, formatting into a Buf, and laying out columns.</span></li> | |
| 33 | +<li><a href="bytes.html">Strings and bytes</a> <span>Copying, hashing and ordering strings, searching bytes many at a time, and reading and writing binary formats.</span></li> | |
| 34 | +<li><a href="collections.html">Lists, arrays, maps and sorting</a> <span>List(T), Vec(T), Map(K, V) and Sort(T), put together in a word-frequency program.</span></li> | |
| 35 | +<li><a href="files.html">Files and the command line</a> <span>Whole files with Files, descriptors and directories with Sys, and options with Opt.</span></li> | |
| 36 | +<li><a href="processes.html">Time, randomness and other programs</a> <span>Clocks, sleeping, random bytes, running a program with its output piped back, and signals.</span></li> | |
| 37 | +<li><a href="allocators.html">Writing an allocator</a> <span>Mem.Allocator is two procedures; make one over a fixed array, and one that counts.</span></li> | |
| 38 | +</ol> | |
| 39 | +<h2>Standing alone</h2><ol start='7'> | |
| 40 | +<li><a href="static.html">A program with no run time</a> <span>What is in an executable, what isn't, and how to see it.</span></li> | |
| 41 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a> <span>link static, what a module that makes its own system calls promises, and the error when it breaks.</span></li> | |
| 42 | +<li><a href="lifecycle.html">Starting, ending, and signals</a> <span>What runs before main, what runs after, and how to wait for a signal.</span></li> | |
| 43 | +<li><a href="targets.html">One module, one file per target</a> <span>Portable programs, the code that isn't, and how the compiler keeps them in step.</span></li> | |
| 44 | +</ol> | |
| 45 | +<h2>The machine</h2><ol start='11'> | |
| 46 | +<li><a href="asm.html">Procedures in assembly</a> <span>code procedures: the convention, registers, labels, db for what the assembler doesn't know.</span></li> | |
| 47 | +<li><a href="syscalls.html">System calls</a> <span>SYSCALL directly: the numbers, the arguments, negative errno, and a cat without a library.</span></li> | |
| 48 | +<li><a href="listing.html">What the compiler makes</a> <span>raz -S, reading a listing, what a check costs and what check off removes.</span></li> | |
| 49 | +</ol> | |
| 50 | +<h2>Shared memory</h2><ol start='14'> | |
| 51 | +<li><a href="volatile.html">Volatile</a> <span>^VOLATILE T: memory that something else may change, laid over with a record.</span></li> | |
| 52 | +<li><a href="atomics.html">Atomics</a> <span>XADD, XCHG and CAS; a compare-and-swap loop; a lock built from them.</span></li> | |
| 53 | +<li><a href="ordering.html">Ordering and publication</a> <span>Why a flag isn't enough, what FENCE and the atomics order, and the pattern that works.</span></li> | |
| 54 | +<li><a href="lockfree.html">A lock-free stack</a> <span>CAS on pointers, a push loop that never blocks, and the ABA problem that makes pop harder.</span></li> | |
| 55 | +<li><a href="ring.html">A ring buffer between threads</a> <span>A single-producer, single-consumer queue, put together from what the tour has covered.</span></li> | |
| 56 | +</ol></div> | |
| 57 | +</main> | |
| 58 | +<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> | |
| 59 | +</body> | |
| 60 | +</html> |
| @@ -0,0 +1,164 @@ | ||
| 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>Starting, ending, and signals - More Raz</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="Starting, ending, and signals - More Raz"> | |
| 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.lucelad.workers.dev/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" aria-current="page">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<div class="tour"><aside><h2>More Raz</h2><h3>The library</h3><ol start='1'> | |
| 22 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 23 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 24 | +<li><a href="collections.html">Lists, arrays, maps and sorting</a></li> | |
| 25 | +<li><a href="files.html">Files and the command line</a></li> | |
| 26 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 27 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 28 | +</ol> | |
| 29 | +<h3>Standing alone</h3><ol start='7'> | |
| 30 | +<li><a href="static.html">A program with no run time</a></li> | |
| 31 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 32 | +<li><a href="lifecycle.html" aria-current="page">Starting, ending, and signals</a></li> | |
| 33 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 34 | +</ol> | |
| 35 | +<h3>The machine</h3><ol start='11'> | |
| 36 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 37 | +<li><a href="syscalls.html">System calls</a></li> | |
| 38 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 39 | +</ol> | |
| 40 | +<h3>Shared memory</h3><ol start='14'> | |
| 41 | +<li><a href="volatile.html">Volatile</a></li> | |
| 42 | +<li><a href="atomics.html">Atomics</a></li> | |
| 43 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 44 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 45 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 46 | +</ol></aside><article><p class="kicker">Standing alone · lesson 9 of 18</p><h1>Starting, ending, and signals</h1> | |
| 47 | +<p>With no run time, the life of a program is short enough to say in a few lines. What happens, in order:</p> | |
| 48 | +<p>1. The entry code sets up a stack for signal handlers and installs the handlers for <code>SIGSEGV</code> and <code>SIGFPE</code>. A program that uses C starts through C instead, so that C's own set-up runs. 2. The bodies of the modules run, each once, imported modules first. 3. The main module's <code>main</code> runs. 4. <code>Rt.exit</code> runs the procedures registered with <code>Rt.atExit</code>, the last registered first, and ends the program with <code>main</code>'s status.</p> | |
| 49 | +<h2>Bodies, then main</h2> | |
| 50 | +<p>The first tour showed bodies running before <code>main</code>. They are the place to set a module up, and they can end early with <code>return;</code>.</p> | |
| 51 | +<div class="file"><span>Order.raz</span></div><pre class="code"><code><span class="kw">module</span> Order; | |
| 52 | +<span class="kw">import</span> Out; | |
| 53 | + | |
| 54 | +<span class="kw">var</span> steps*: <span class="ty">INT</span>; | |
| 55 | + | |
| 56 | +<span class="kw">proc</span> note(what: []<span class="ty">U8</span>); | |
| 57 | +<span class="kw">begin</span> | |
| 58 | + <span class="ty">INC</span>(steps); | |
| 59 | + Out.int(steps); Out.str(<span class="string">". "</span>); Out.str(what); Out.ln; | |
| 60 | +<span class="kw">end</span>; | |
| 61 | + | |
| 62 | +<span class="kw">begin</span> | |
| 63 | + note(<span class="string">"the body runs before main"</span>); | |
| 64 | + <span class="kw">if</span> steps > <span class="number">5</span> <span class="kw">then</span> <span class="kw">return</span>; <span class="kw">end</span>; | |
| 65 | + note(<span class="string">"and carries on if it isn't ended early"</span>); | |
| 66 | +<span class="kw">end</span> Order.</code></pre> | |
| 67 | +<pre class="output"><code>1. the body runs before main | |
| 68 | +2. and carries on if it isn't ended early | |
| 69 | +</code></pre> | |
| 70 | +<p>That file is a module with a body and no <code>main</code>: it can be imported, or its body run as a program. Add the <code>main</code> and see both:</p> | |
| 71 | +<div class="file"><span>Both.raz</span></div><pre class="code"><code><span class="kw">module</span> Both; | |
| 72 | +<span class="kw">import</span> Out, Order; | |
| 73 | + | |
| 74 | +<span class="kw">proc</span> main*; | |
| 75 | +<span class="kw">begin</span> | |
| 76 | + Out.str(<span class="string">"main: "</span>); Out.int(Order.steps); Out.str(<span class="string">" steps happened first\n"</span>); | |
| 77 | +<span class="kw">end</span>; | |
| 78 | + | |
| 79 | +<span class="kw">end</span> Both.</code></pre> | |
| 80 | +<pre class="output"><code>1. the body runs before main | |
| 81 | +2. and carries on if it isn't ended early | |
| 82 | +main: 2 steps happened first | |
| 83 | +</code></pre> | |
| 84 | +<h2>Things to do at the end</h2> | |
| 85 | +<p><code>Rt.atExit(p)</code> registers a procedure with no parameters to run when the program ends by <code>Rt.exit</code>: at the end of <code>main</code>, by a call to <code>Rt.exit</code>, or by a failed check, after its message. It is where a program restores a terminal or removes a lock file. At most 32 are registered, and each runs at most once. Out's buffer is flushed this way, which is why a program that ends in a failure still shows what it printed.</p> | |
| 86 | +<div class="file"><span>Cleanup.raz</span></div><pre class="code"><code><span class="kw">module</span> Cleanup; | |
| 87 | +<span class="kw">import</span> Out, Rt; | |
| 88 | + | |
| 89 | +<span class="kw">proc</span> first; | |
| 90 | +<span class="kw">begin</span> | |
| 91 | + Out.str(<span class="string">"registered first, runs last\n"</span>); | |
| 92 | +<span class="kw">end</span>; | |
| 93 | + | |
| 94 | +<span class="kw">proc</span> second; | |
| 95 | +<span class="kw">begin</span> | |
| 96 | + Out.str(<span class="string">"registered second, runs first\n"</span>); | |
| 97 | +<span class="kw">end</span>; | |
| 98 | + | |
| 99 | +<span class="kw">proc</span> main*; | |
| 100 | +<span class="kw">begin</span> | |
| 101 | + _ := Rt.atExit(first); | |
| 102 | + _ := Rt.atExit(second); | |
| 103 | + Out.str(<span class="string">"main is done\n"</span>); | |
| 104 | +<span class="kw">end</span>; | |
| 105 | + | |
| 106 | +<span class="kw">end</span> Cleanup.</code></pre> | |
| 107 | +<pre class="output"><code>main is done | |
| 108 | +registered second, runs first | |
| 109 | +registered first, runs last | |
| 110 | +</code></pre> | |
| 111 | +<h2>Two ways to leave in a hurry</h2> | |
| 112 | +<p><code>Rt.exit(status)</code> ends the program after the <code>atExit</code> procedures. <code>Sys.exit(status)</code> ends it at once, without them. A failed check and <code>Rt.exit</code> also skip the <code>defer</code> statements still pending in the calls under way. <code>Sys.exit</code> is for a child process that must not run what it inherited, and for nothing else.</p> | |
| 113 | +<div class="file"><span>Hurry.raz</span></div><pre class="code"><code><span class="kw">module</span> Hurry; | |
| 114 | +<span class="kw">import</span> Out, Rt, Sys; | |
| 115 | + | |
| 116 | +<span class="kw">proc</span> bye; | |
| 117 | +<span class="kw">begin</span> | |
| 118 | + Out.str(<span class="string">"atExit ran\n"</span>); | |
| 119 | +<span class="kw">end</span>; | |
| 120 | + | |
| 121 | +<span class="kw">proc</span> main*; | |
| 122 | +<span class="kw">begin</span> | |
| 123 | + _ := Rt.atExit(bye); | |
| 124 | + <span class="kw">defer</span> Out.str(<span class="string">"a deferred statement ran\n"</span>); | |
| 125 | + Out.str(<span class="string">"leaving\n"</span>); | |
| 126 | + Out.flush; | |
| 127 | + Sys.exit(<span class="number">3</span>); | |
| 128 | +<span class="kw">end</span>; | |
| 129 | + | |
| 130 | +<span class="kw">end</span> Hurry.</code></pre> | |
| 131 | +<pre class="output term"><code><span class="cmd">$ raz Hurry.raz</span> | |
| 132 | +<span class="cmd">$ ./Hurry; echo "status $?"</span> | |
| 133 | +leaving | |
| 134 | +status 3</code></pre> | |
| 135 | +<p>Neither the deferred statement nor <code>bye</code> ran. That's the rule, and the reason to keep cleanup that matters (a terminal, a lock file) in <code>atExit</code> and use <code>Rt.exit</code> for ending.</p> | |
| 136 | +<h2>Signals</h2> | |
| 137 | +<p>A program is stopped by a signal it doesn't catch, with a message that names the place for <code>SIGSEGV</code> and <code>SIGFPE</code>, and without one for the others, and ends with status 2. A program that wants to handle one, say <code>SIGTERM</code> for a clean shutdown, doesn't write a handler that runs at an arbitrary moment. It asks for the signals to arrive as data: <code>Sys.catch</code> takes a list of signals and gives a descriptor that is ready to read when one comes, and <code>Sys.caught</code> says which. So the program waits for signals the way it waits for input.</p> | |
| 138 | +<div class="file"><span>Terms.raz</span></div><pre class="code"><code><span class="kw">module</span> Terms; | |
| 139 | +<span class="kw">import</span> Out, Sys; | |
| 140 | + | |
| 141 | +<span class="kw">proc</span> main*; | |
| 142 | +<span class="kw">var</span> fd, sig: <span class="ty">INT</span>; | |
| 143 | +<span class="kw">begin</span> | |
| 144 | + fd := Sys.catch([Sys.sigTerm, Sys.sigWinch]); | |
| 145 | + Out.str(<span class="string">"asking myself to stop\n"</span>); | |
| 146 | + _ := Sys.kill(Sys.pid(), Sys.sigTerm); | |
| 147 | + <span class="kw">if</span> Sys.ready(fd, <span class="number">1000</span>) <span class="kw">then</span> | |
| 148 | + sig := Sys.caught(fd); | |
| 149 | + <span class="kw">if</span> sig = Sys.sigTerm <span class="kw">then</span> Out.str(<span class="string">"caught SIGTERM, stopping cleanly\n"</span>); <span class="kw">end</span>; | |
| 150 | + <span class="kw">end</span>; | |
| 151 | + sig := Sys.caught(fd); | |
| 152 | + Out.int(sig); Out.str(<span class="string">" waiting after that\n"</span>); <span class="comment">(* 0: none *)</span> | |
| 153 | +<span class="kw">end</span>; | |
| 154 | + | |
| 155 | +<span class="kw">end</span> Terms.</code></pre> | |
| 156 | +<pre class="output"><code>asking myself to stop | |
| 157 | +caught SIGTERM, stopping cleanly | |
| 158 | +0 waiting after that | |
| 159 | +</code></pre> | |
| 160 | +<p><code>Sys.ready(fd, ms)</code> waits up to <code>ms</code> milliseconds for something to read; with <code>Sys.readyOf</code> it waits on several descriptors, so one loop serves a socket, a terminal and a stop signal together. <code>Sys.ignore(sig, true)</code> makes a signal do nothing, as a shell ignores <code>SIGTTOU</code>.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="linkstatic.html">← Threads without C, and keeping the two apart</a><a href="index.html">Contents</a><a class="next" href="targets.html">One module, one file per target →</a></div></article></div> | |
| 161 | +</main> | |
| 162 | +<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> | |
| 163 | +</body> | |
| 164 | +</html> |
| @@ -0,0 +1,122 @@ | ||
| 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>Threads without C, and keeping the two apart - More Raz</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="Threads without C, and keeping the two apart - More Raz"> | |
| 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.lucelad.workers.dev/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" aria-current="page">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<div class="tour"><aside><h2>More Raz</h2><h3>The library</h3><ol start='1'> | |
| 22 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 23 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 24 | +<li><a href="collections.html">Lists, arrays, maps and sorting</a></li> | |
| 25 | +<li><a href="files.html">Files and the command line</a></li> | |
| 26 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 27 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 28 | +</ol> | |
| 29 | +<h3>Standing alone</h3><ol start='7'> | |
| 30 | +<li><a href="static.html">A program with no run time</a></li> | |
| 31 | +<li><a href="linkstatic.html" aria-current="page">Threads without C, and keeping the two apart</a></li> | |
| 32 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 33 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 34 | +</ol> | |
| 35 | +<h3>The machine</h3><ol start='11'> | |
| 36 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 37 | +<li><a href="syscalls.html">System calls</a></li> | |
| 38 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 39 | +</ol> | |
| 40 | +<h3>Shared memory</h3><ol start='14'> | |
| 41 | +<li><a href="volatile.html">Volatile</a></li> | |
| 42 | +<li><a href="atomics.html">Atomics</a></li> | |
| 43 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 44 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 45 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 46 | +</ol></aside><article><p class="kicker">Standing alone · lesson 8 of 18</p><h1>Threads without C, and keeping the two apart</h1> | |
| 47 | +<p>A program without C can do things a program with C can't. The most useful is to make threads of its own: C's thread functions rely on C's own set-up, which a program that never started C has not done. <code>Thread</code> creates threads directly with the <code>clone</code> system call and gives each a stack of its own.</p> | |
| 48 | +<p>A module like that says so, with <code>link static;</code> after its imports. It means: "I make my own system calls or my own threads, which the C library wouldn't know about; a program that includes me must not use C." <code>static</code> isn't a reserved word; it is only meaningful after <code>link</code>.</p> | |
| 49 | +<h2>What <code>Thread</code> does</h2> | |
| 50 | +<p><code>Thread</code> is a module of raz, in the library, that says <code>link static;</code> and makes the <code>clone</code>, <code>mmap</code> and <code>futex</code> system calls itself. Here is its beginning, printed from the library:</p> | |
| 51 | +<pre class="output term"><code><span class="cmd">$ sed -n '1,22p' $RAZLIB/Thread.linux-x86_64.raz</span> | |
| 52 | +(* Threads, made with the clone system call in a program without C. | |
| 53 | + Each runs on a stack of its own, mmaped, with a page below it that | |
| 54 | + can't be touched, so that running off the stack stops the program | |
| 55 | + rather than spoiling what lies below; above it, a little stack for | |
| 56 | + Rt's signal handlers, so that they can say so. join waits on the | |
| 57 | + thread's id, which the kernel clears, and wakes it for, when the | |
| 58 | + thread ends; a Mutex sleeps on a futex. | |
| 59 | + | |
| 60 | + A program that uses C makes them with C's pthread_create instead, | |
| 61 | + since C keeps things of each thread's own, errno and its buffers, | |
| 62 | + that a thread clone makes wouldn't have. The compiler's entry point | |
| 63 | + finds cCreate and cJoin by name and stores C's calls in them, as it | |
| 64 | + stores C's exit in Rt.cExit; so this module uses no C itself, and | |
| 65 | + serves both kinds of program. C's thread has a stack and a guard | |
| 66 | + page of C's; the mapping here holds only the handlers' stack and | |
| 67 | + the Thread. Its test uses Check. *) | |
| 68 | +module Thread; | |
| 69 | +import Sys, Rt, Check; | |
| 70 | + | |
| 71 | +const | |
| 72 | + Failed*: ERROR = "can't start a thread"; | |
| 73 | + Stack = 1 shl 20;</code></pre> | |
| 74 | +<p>A program that imports it is therefore a static executable, and every thread it spawns is a Linux thread with a stack of its own, mapped with a page below it that can't be touched, so that running off the stack ends the program with a message and not with corruption.</p> | |
| 75 | +<div class="file"><span>Hello.raz</span></div><pre class="code"><code><span class="kw">module</span> Hello; | |
| 76 | +<span class="kw">import</span> Out, Thread; | |
| 77 | + | |
| 78 | +<span class="kw">var</span> done: <span class="ty">INT</span>; | |
| 79 | + | |
| 80 | +<span class="kw">proc</span> greet(arg: ^<span class="ty">U8</span>); | |
| 81 | +<span class="kw">begin</span> | |
| 82 | + Out.str(<span class="string">"hello from thread "</span>); Out.int(<span class="ty">INT</span>(arg)); Out.ln; | |
| 83 | + _ := <span class="ty">XADD</span>(<span class="ty">ADR</span>(done), <span class="number">1</span>); | |
| 84 | +<span class="kw">end</span>; | |
| 85 | + | |
| 86 | +<span class="kw">proc</span> main*; | |
| 87 | +<span class="kw">var</span> t: ^Thread.Thread; err: <span class="ty">ERROR</span>; | |
| 88 | +<span class="kw">begin</span> | |
| 89 | + t, err := Thread.spawn(greet, ^<span class="ty">U8</span>(<span class="number">7</span>)); | |
| 90 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">return</span>; <span class="kw">end</span>; | |
| 91 | + Thread.join(t); | |
| 92 | + Out.str(<span class="string">"joined; done = "</span>); Out.int(done); Out.ln; | |
| 93 | +<span class="kw">end</span>; | |
| 94 | + | |
| 95 | +<span class="kw">end</span> Hello.</code></pre> | |
| 96 | +<pre class="output term"><code><span class="cmd">$ raz Hello.raz</span> | |
| 97 | +<span class="cmd">$ ./Hello</span> | |
| 98 | +hello from thread 7 | |
| 99 | +joined; done = 1 | |
| 100 | +<span class="cmd">$ file Hello | sed 's/,.*statically/, statically/'</span> | |
| 101 | +Hello: ELF 64-bit LSB executable, statically linked, with debug_info, not stripped</code></pre> | |
| 102 | +<h2>When you mix them</h2> | |
| 103 | +<p>C's <code>pthread_create</code> and <code>Thread</code> can't share a process, and the compiler won't let you try. A program that imports a module that says <code>link static;</code> and another that uses C is an error, and the error names both:</p> | |
| 104 | +<div class="file"><span>Mixed.raz</span></div><pre class="code"><code><span class="kw">module</span> Mixed; | |
| 105 | +<span class="kw">import</span> Out, Thread, C; | |
| 106 | + | |
| 107 | +<span class="kw">proc</span> main*; | |
| 108 | +<span class="kw">begin</span> | |
| 109 | + Out.str(<span class="ty">MSG</span>(Thread.Failed)); Out.ln; | |
| 110 | + _ := C.printf(<span class="string">"%d\n"</span>, <span class="ty">I32</span>(<span class="number">1</span>)); | |
| 111 | + Out.str(<span class="string">"and Out\n"</span>); | |
| 112 | +<span class="kw">end</span>; | |
| 113 | + | |
| 114 | +<span class="kw">end</span> Mixed.</code></pre> | |
| 115 | +<pre class="output term"><code><span class="cmd">$ raz Mixed.raz</span></code></pre> | |
| 116 | +<p>Which one you want depends on what the program is for. A program that calls a C library (a window system, a database client) uses C's threads, <code>C.pthread_create</code>, because the library may assume them. A program that talks only to the kernel uses <code>Thread</code>, and is a static executable.</p> | |
| 117 | +<h2>The same promise for your own modules</h2> | |
| 118 | +<p>The rule isn't special to <code>Thread</code>. A module of yours that makes <code>SYSCALL</code>s directly, or relies on being the only owner of signal handlers, or sets up its own stacks, says <code>link static;</code> too, and then the compiler keeps C away from it for you. The module is documenting a fact about itself, and the compiler checks it where the program is assembled.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="static.html">← A program with no run time</a><a href="index.html">Contents</a><a class="next" href="lifecycle.html">Starting, ending, and signals →</a></div></article></div> | |
| 119 | +</main> | |
| 120 | +<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> | |
| 121 | +</body> | |
| 122 | +</html> |
| @@ -0,0 +1,264 @@ | ||
| 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>What the compiler makes - More Raz</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="What the compiler makes - More Raz"> | |
| 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.lucelad.workers.dev/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" aria-current="page">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<div class="tour"><aside><h2>More Raz</h2><h3>The library</h3><ol start='1'> | |
| 22 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 23 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 24 | +<li><a href="collections.html">Lists, arrays, maps and sorting</a></li> | |
| 25 | +<li><a href="files.html">Files and the command line</a></li> | |
| 26 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 27 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 28 | +</ol> | |
| 29 | +<h3>Standing alone</h3><ol start='7'> | |
| 30 | +<li><a href="static.html">A program with no run time</a></li> | |
| 31 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 32 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 33 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 34 | +</ol> | |
| 35 | +<h3>The machine</h3><ol start='11'> | |
| 36 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 37 | +<li><a href="syscalls.html">System calls</a></li> | |
| 38 | +<li><a href="listing.html" aria-current="page">What the compiler makes</a></li> | |
| 39 | +</ol> | |
| 40 | +<h3>Shared memory</h3><ol start='14'> | |
| 41 | +<li><a href="volatile.html">Volatile</a></li> | |
| 42 | +<li><a href="atomics.html">Atomics</a></li> | |
| 43 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 44 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 45 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 46 | +</ol></aside><article><p class="kicker">The machine · lesson 13 of 18</p><h1>What the compiler makes</h1> | |
| 47 | +<p>The compiler has no optimizer and no intermediate form. It reads the source once and writes x86-64 machine code as it goes, so the code is what the source says, in the order it says it. That makes the output readable, and there is a switch for reading it: <code>raz -S Main.raz</code> prints the main module's code instead of writing it, each line of source and under it the instructions made for it, at their offsets in the procedure.</p> | |
| 48 | +<h2>A small procedure</h2> | |
| 49 | +<div class="file"><span>Add.raz</span></div><pre class="code"><code><span class="kw">module</span> Add; | |
| 50 | + | |
| 51 | +<span class="kw">proc</span> add*(a, b: <span class="ty">INT</span>): <span class="ty">INT</span>; | |
| 52 | +<span class="kw">begin</span> | |
| 53 | + <span class="kw">return</span> a + b; | |
| 54 | +<span class="kw">end</span>; | |
| 55 | + | |
| 56 | +<span class="kw">proc</span> main*; | |
| 57 | +<span class="kw">begin</span> | |
| 58 | + _ := add(<span class="number">1</span>, <span class="number">2</span>); | |
| 59 | +<span class="kw">end</span>; | |
| 60 | + | |
| 61 | +<span class="kw">end</span> Add.</code></pre> | |
| 62 | +<pre class="output term"><code><span class="cmd">$ raz -S Add.raz</span> | |
| 63 | + | |
| 64 | +Add.main: | |
| 65 | + 8 proc main*; | |
| 66 | + 0 push rbp | |
| 67 | + 1 mov rbp, rsp | |
| 68 | + 4 sub rsp, 16 | |
| 69 | + 10 _ := add(1, 2); | |
| 70 | + 11 mov qword [rbp - 8], 2 | |
| 71 | + 19 mov qword [rbp - 16], 1 | |
| 72 | + 27 mov r8, [rbp - 16] | |
| 73 | + 31 add r8, [rbp - 8] | |
| 74 | + 11 end; | |
| 75 | + 35 leave | |
| 76 | + 36 ret</code></pre> | |
| 77 | +<p>Every procedure starts by saving the caller's frame pointer and making its own (<code>push rbp; mov rbp, rsp</code>) and reserves room for what it needs. The arguments arrive in <code>rdi</code> and <code>rsi</code>, as the convention says, and the result leaves in <code>rax</code>. A call is <code>mov rdi, 1; mov rsi, 2; call Add.add</code>. Nothing is hidden: the frame pointer chain is what lets a failure show the calls under way with their variables.</p> | |
| 78 | +<h2>A loop with its checks</h2> | |
| 79 | +<p>This is the dot product of two slices. A slice is a pointer and a length, and it travels in two registers:</p> | |
| 80 | +<div class="file"><span>Dot.raz</span></div><pre class="code"><code><span class="kw">module</span> Dot; | |
| 81 | + | |
| 82 | +<span class="comment">(* the dot product of two slices of equal length *)</span> | |
| 83 | +<span class="kw">proc</span> dot*(a, b: []<span class="ty">INT</span>): <span class="ty">INT</span>; | |
| 84 | +<span class="kw">var</span> i, sum: <span class="ty">INT</span>; | |
| 85 | +<span class="kw">begin</span> | |
| 86 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="ty">LEN</span>(a) - <span class="number">1</span> <span class="kw">do</span> | |
| 87 | + sum := sum + a[i] * b[i]; | |
| 88 | + <span class="kw">end</span>; | |
| 89 | + <span class="kw">return</span> sum; | |
| 90 | +<span class="kw">end</span>; | |
| 91 | + | |
| 92 | +<span class="kw">proc</span> main*; | |
| 93 | +<span class="kw">var</span> x, y: [<span class="number">3</span>]<span class="ty">INT</span>; | |
| 94 | +<span class="kw">begin</span> | |
| 95 | + x := [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]; | |
| 96 | + y := [<span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>]; | |
| 97 | + _ := dot(x, y); | |
| 98 | +<span class="kw">end</span>; | |
| 99 | + | |
| 100 | +<span class="kw">end</span> Dot.</code></pre> | |
| 101 | +<pre class="output term"><code><span class="cmd">$ raz -S Dot.raz | sed -n '/^Dot.dot:/,/^$/p'</span> | |
| 102 | +Dot.dot: | |
| 103 | + 4 proc dot*(a, b: []INT): INT; | |
| 104 | + 0 push rbp | |
| 105 | + 1 mov rbp, rsp | |
| 106 | + 4 sub rsp, 64 | |
| 107 | + 11 mov [rbp - 56], rbx | |
| 108 | + 15 xor ebx, ebx | |
| 109 | + 17 mov [rbp - 48], r12 | |
| 110 | + 21 xor r12d, r12d | |
| 111 | + 24 mov [rbp - 40], r13 | |
| 112 | + 28 xor r13d, r13d | |
| 113 | + 31 mov [rbp - 32], rdx | |
| 114 | + 35 mov [rbp - 24], rcx | |
| 115 | + 7 for i := 0 to LEN(a) - 1 do | |
| 116 | + 39 xor ebx, ebx | |
| 117 | + 41 mov r8, rsi | |
| 118 | + 44 lea r8, [r8 - 1] | |
| 119 | + 48 mov r13, r8 | |
| 120 | + 51 cmp rbx, r13 | |
| 121 | + 54 jg 175 | |
| 122 | + 60 jmp 100 | |
| 123 | + 65 nop | |
| 124 | + 73 nop | |
| 125 | + 81 nop | |
| 126 | + 89 nop | |
| 127 | + 96 add rbx, 1 | |
| 128 | + 8 sum := sum + a[i] * b[i]; | |
| 129 | + 100 cmp rbx, rsi | |
| 130 | + 103 jae 192 | |
| 131 | + 109 mov r10, rbx | |
| 132 | + 112 cmp r10, [rbp - 24] | |
| 133 | + 116 jae 203 | |
| 134 | + 122 shl r10, 3 | |
| 135 | + 126 add r10, [rbp - 32] | |
| 136 | + 130 mov r10, [r10] | |
| 137 | + 133 mov r9, [rdi + rbx * 8] | |
| 138 | + 137 imul r9, r10 | |
| 139 | + 141 add r12, r9 | |
| 140 | + 144 cmp rbx, r13 | |
| 141 | + 147 jl 96 | |
| 142 | + 153 cmp rbx, r13 | |
| 143 | + 156 je 175 | |
| 144 | + 162 add rbx, 1 | |
| 145 | + 166 cmp rbx, r13 | |
| 146 | + 169 jle 100 | |
| 147 | + 10 return sum; | |
| 148 | + 175 mov rax, r12 | |
| 149 | + 11 end; | |
| 150 | + 178 mov rbx, [rbp - 56] | |
| 151 | + 182 mov r12, [rbp - 48] | |
| 152 | + 186 mov r13, [rbp - 40] | |
| 153 | + 190 leave | |
| 154 | + 191 ret | |
| 155 | + 8 sum := sum + a[i] * b[i]; | |
| 156 | + 192 mov rax, rbx | |
| 157 | + 195 mov rcx, rsi | |
| 158 | + 198 call Rt.check0 | |
| 159 | + 203 mov rax, r10 | |
| 160 | + 206 mov rcx, [rbp - 24] | |
| 161 | + 210 call Rt.check0</code></pre> | |
| 162 | +<p>Read it from the top. <code>a</code> arrives in <code>rdi</code> and <code>rsi</code>, pointer and length; <code>b</code> in <code>rdx</code> and <code>rcx</code>, which the procedure saves in its frame. <code>i</code> and <code>sum</code> live in <code>rbx</code> and <code>r12</code>, which the procedure saves and restores because the convention says they belong to the caller. The loop's test is at the bottom, and its limit, <code>LEN(a) - 1</code>, is taken once.</p> | |
| 163 | +<p>In the body, each index has a check: <code>cmp rbx, rsi; jae</code> compares <code>i</code> with <code>a</code>'s length in a single instruction and jumps to a stub at the end of the procedure, which calls <code>Rt.check0</code> with the values it needs to say what failed. When the index is in range, which is nearly always, the cost is one compare and a branch that isn't taken.</p> | |
| 164 | +<h2>Taking the checks out</h2> | |
| 165 | +<p><code>check off;</code> after the imports leaves out the module's own checks of indexes and slice bounds. Here is the same procedure with it:</p> | |
| 166 | +<div class="file"><span>Dot2.raz</span></div><pre class="code"><code><span class="kw">module</span> Dot2; | |
| 167 | +check off; | |
| 168 | + | |
| 169 | +<span class="kw">proc</span> dot*(a, b: []<span class="ty">INT</span>): <span class="ty">INT</span>; | |
| 170 | +<span class="kw">var</span> i, sum: <span class="ty">INT</span>; | |
| 171 | +<span class="kw">begin</span> | |
| 172 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="ty">LEN</span>(a) - <span class="number">1</span> <span class="kw">do</span> | |
| 173 | + sum := sum + a[i] * b[i]; | |
| 174 | + <span class="kw">end</span>; | |
| 175 | + <span class="kw">return</span> sum; | |
| 176 | +<span class="kw">end</span>; | |
| 177 | + | |
| 178 | +<span class="kw">proc</span> main*; | |
| 179 | +<span class="kw">var</span> x, y: [<span class="number">3</span>]<span class="ty">INT</span>; | |
| 180 | +<span class="kw">begin</span> | |
| 181 | + x := [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]; | |
| 182 | + y := [<span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>]; | |
| 183 | + _ := dot(x, y); | |
| 184 | +<span class="kw">end</span>; | |
| 185 | + | |
| 186 | +<span class="kw">end</span> Dot2.</code></pre> | |
| 187 | +<pre class="output term"><code><span class="cmd">$ raz -S Dot2.raz | sed -n '/^Dot2.dot:/,/^$/p'</span> | |
| 188 | +Dot2.dot: | |
| 189 | + 4 proc dot*(a, b: []INT): INT; | |
| 190 | + 0 push rbp | |
| 191 | + 1 mov rbp, rsp | |
| 192 | + 4 sub rsp, 64 | |
| 193 | + 11 mov [rbp - 56], rbx | |
| 194 | + 15 xor ebx, ebx | |
| 195 | + 17 mov [rbp - 48], r12 | |
| 196 | + 21 xor r12d, r12d | |
| 197 | + 24 mov [rbp - 40], r13 | |
| 198 | + 28 xor r13d, r13d | |
| 199 | + 31 mov [rbp - 32], rdx | |
| 200 | + 35 mov [rbp - 24], rcx | |
| 201 | + 7 for i := 0 to LEN(a) - 1 do | |
| 202 | + 39 xor ebx, ebx | |
| 203 | + 41 mov r8, rsi | |
| 204 | + 44 lea r8, [r8 - 1] | |
| 205 | + 48 mov r13, r8 | |
| 206 | + 51 cmp rbx, r13 | |
| 207 | + 54 jg 156 | |
| 208 | + 60 jmp 100 | |
| 209 | + 65 nop | |
| 210 | + 73 nop | |
| 211 | + 81 nop | |
| 212 | + 89 nop | |
| 213 | + 96 add rbx, 1 | |
| 214 | + 8 sum := sum + a[i] * b[i]; | |
| 215 | + 100 mov r10, rbx | |
| 216 | + 103 shl r10, 3 | |
| 217 | + 107 add r10, [rbp - 32] | |
| 218 | + 111 mov r10, [r10] | |
| 219 | + 114 mov r9, [rdi + rbx * 8] | |
| 220 | + 118 imul r9, r10 | |
| 221 | + 122 add r12, r9 | |
| 222 | + 125 cmp rbx, r13 | |
| 223 | + 128 jl 96 | |
| 224 | + 134 cmp rbx, r13 | |
| 225 | + 137 je 156 | |
| 226 | + 143 add rbx, 1 | |
| 227 | + 147 cmp rbx, r13 | |
| 228 | + 150 jle 100 | |
| 229 | + 10 return sum; | |
| 230 | + 156 mov rax, r12 | |
| 231 | + 11 end; | |
| 232 | + 159 mov rbx, [rbp - 56] | |
| 233 | + 163 mov r12, [rbp - 48] | |
| 234 | + 167 mov r13, [rbp - 40] | |
| 235 | + 171 leave | |
| 236 | + 172 ret | |
| 237 | +<span class="cmd">$ raz -S Dot.raz | sed -n '/^Dot.dot:/,/^$/p' | wc -l</span> | |
| 238 | +61 | |
| 239 | +<span class="cmd">$ raz -S Dot2.raz | sed -n '/^Dot2.dot:/,/^$/p' | wc -l</span> | |
| 240 | +50</code></pre> | |
| 241 | +<p>The compares, the branches and the stubs are gone. It is faster, and it is no longer safe: an index out of range reads or writes whatever memory it reaches, and what follows isn't defined. A program turns checks off where it has measured and is sure, and says so at the top of the module, where a reader can see it.</p> | |
| 242 | +<h2>Comparing with C</h2> | |
| 243 | +<p><code>make kernels</code> in the compiler's sources measures <code>test/bench</code>'s kernels against the same kernels written in Pascal and compiled by Free Pascal at <code>-O2</code>. The compiler's own guide, <code>doc/compiler.md</code>, gives the numbers and says what the compiler does and doesn't do. It is not the fastest code: it is code whose every instruction you can account for.</p> | |
| 244 | +<h2>Tools that read what it made</h2> | |
| 245 | +<ul><li><code>gdb</code> finds procedures by name and lines by number, since the executable carries them: <code>break Dot.dot</code> and <code>list</code> work, and so does stepping a line at a time.</li><li><code>RAZ_PROFILE=1</code> samples the program every millisecond and says which procedures and lines took the time.</li><li><code>objdump -d</code> disassembles what is really in the file, if you want to see the bytes behind a listing.</li></ul> | |
| 246 | +<pre class="output term"><code><span class="cmd">$ raz -o Dot Dot.raz</span> | |
| 247 | +<span class="cmd">$ objdump -d -M intel --no-show-raw-insn Dot | sed -n '/<Dot.dot>:/,/ret/p' | head -12</span> | |
| 248 | +0000000000403c60 <Dot.dot>: | |
| 249 | + 403c60: push rbp | |
| 250 | + 403c61: mov rbp,rsp | |
| 251 | + 403c64: sub rsp,0x40 | |
| 252 | + 403c6b: mov QWORD PTR [rbp-0x38],rbx | |
| 253 | + 403c6f: xor ebx,ebx | |
| 254 | + 403c71: mov QWORD PTR [rbp-0x30],r12 | |
| 255 | + 403c75: xor r12d,r12d | |
| 256 | + 403c78: mov QWORD PTR [rbp-0x28],r13 | |
| 257 | + 403c7c: xor r13d,r13d | |
| 258 | + 403c7f: mov QWORD PTR [rbp-0x20],rdx | |
| 259 | + 403c83: mov QWORD PTR [rbp-0x18],rcx</code></pre> | |
| 260 | +<p>The listing is what the encoder meant; <code>objdump</code> is what the processor will read. They tell the same story.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="syscalls.html">← System calls</a><a href="index.html">Contents</a><a class="next" href="volatile.html">Volatile →</a></div></article></div> | |
| 261 | +</main> | |
| 262 | +<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> | |
| 263 | +</body> | |
| 264 | +</html> |
| @@ -0,0 +1,167 @@ | ||
| 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>A lock-free stack - More Raz</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="A lock-free stack - More Raz"> | |
| 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.lucelad.workers.dev/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" aria-current="page">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<div class="tour"><aside><h2>More Raz</h2><h3>The library</h3><ol start='1'> | |
| 22 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 23 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 24 | +<li><a href="collections.html">Lists, arrays, maps and sorting</a></li> | |
| 25 | +<li><a href="files.html">Files and the command line</a></li> | |
| 26 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 27 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 28 | +</ol> | |
| 29 | +<h3>Standing alone</h3><ol start='7'> | |
| 30 | +<li><a href="static.html">A program with no run time</a></li> | |
| 31 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 32 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 33 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 34 | +</ol> | |
| 35 | +<h3>The machine</h3><ol start='11'> | |
| 36 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 37 | +<li><a href="syscalls.html">System calls</a></li> | |
| 38 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 39 | +</ol> | |
| 40 | +<h3>Shared memory</h3><ol start='14'> | |
| 41 | +<li><a href="volatile.html">Volatile</a></li> | |
| 42 | +<li><a href="atomics.html">Atomics</a></li> | |
| 43 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 44 | +<li><a href="lockfree.html" aria-current="page">A lock-free stack</a></li> | |
| 45 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 46 | +</ol></aside><article><p class="kicker">Shared memory · lesson 17 of 18</p><h1>A lock-free stack</h1> | |
| 47 | +<p><code>CAS</code> works on pointers as well as integers, and a pointer is how a bigger thing is swapped in atomically: build the new structure privately, then make it visible by changing one word. The classic example is a stack as a linked list whose head is that word.</p> | |
| 48 | +<h2>Push</h2> | |
| 49 | +<p>To push a node: point its <code>next</code> at the current head, then <code>CAS</code> the head from what you saw to the new node. If another thread pushed first, the <code>CAS</code> fails, because the head is no longer what you saw, so look again and retry. No thread ever waits for another, and none can stop the others by being slow.</p> | |
| 50 | +<div class="file"><span>Treiber.raz</span></div><pre class="code"><code><span class="kw">module</span> Treiber; | |
| 51 | +<span class="kw">import</span> Out, Thread; | |
| 52 | + | |
| 53 | +<span class="kw">type</span> Node = <span class="kw">record</span> next: ^Node; val: <span class="ty">INT</span>; <span class="kw">end</span>; | |
| 54 | + | |
| 55 | +<span class="kw">const</span> Threads = <span class="number">4</span>; Each = <span class="number">5000</span>; | |
| 56 | + | |
| 57 | +<span class="kw">var</span> | |
| 58 | + top: ^Node; <span class="comment">(* the head, changed only by CAS *)</span> | |
| 59 | + nodes: [Threads * Each]Node; <span class="comment">(* every node a thread will push *)</span> | |
| 60 | + | |
| 61 | +<span class="comment">(* n onto the stack, without a lock *)</span> | |
| 62 | +<span class="kw">proc</span> push(n: ^Node); | |
| 63 | +<span class="kw">var</span> old: ^Node; | |
| 64 | +<span class="kw">begin</span> | |
| 65 | + old := top; | |
| 66 | + n^.next := old; | |
| 67 | + <span class="kw">while</span> <span class="kw">not</span> <span class="ty">CAS</span>(<span class="ty">ADR</span>(top), old, n) <span class="kw">do</span> | |
| 68 | + old := top; <span class="comment">(* lost the race: look again *)</span> | |
| 69 | + n^.next := old; | |
| 70 | + <span class="kw">end</span>; | |
| 71 | +<span class="kw">end</span>; | |
| 72 | + | |
| 73 | +<span class="kw">proc</span> work(arg: ^<span class="ty">U8</span>); | |
| 74 | +<span class="kw">var</span> first, i: <span class="ty">INT</span>; | |
| 75 | +<span class="kw">begin</span> | |
| 76 | + first := <span class="ty">INT</span>(arg) * Each; | |
| 77 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> Each - <span class="number">1</span> <span class="kw">do</span> | |
| 78 | + nodes[first + i].val := first + i; | |
| 79 | + push(<span class="ty">ADR</span>(nodes[first + i])); | |
| 80 | + <span class="kw">end</span>; | |
| 81 | +<span class="kw">end</span>; | |
| 82 | + | |
| 83 | +<span class="kw">proc</span> main*; | |
| 84 | +<span class="kw">var</span> th: [Threads]^Thread.Thread; i, count, sum: <span class="ty">INT</span>; err: <span class="ty">ERROR</span>; n: ^Node; | |
| 85 | +<span class="kw">begin</span> | |
| 86 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> Threads - <span class="number">1</span> <span class="kw">do</span> | |
| 87 | + th[i], err := Thread.spawn(work, ^<span class="ty">U8</span>(i)); | |
| 88 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">return</span>; <span class="kw">end</span>; | |
| 89 | + <span class="kw">end</span>; | |
| 90 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> Threads - <span class="number">1</span> <span class="kw">do</span> Thread.join(th[i]); <span class="kw">end</span>; | |
| 91 | + n := top; | |
| 92 | + <span class="kw">while</span> n # <span class="ty">nil</span> <span class="kw">do</span> | |
| 93 | + <span class="ty">INC</span>(count); | |
| 94 | + sum := sum + n^.val; | |
| 95 | + n := n^.next; | |
| 96 | + <span class="kw">end</span>; | |
| 97 | + Out.int(count); Out.char(<span class="string">' '</span>); Out.int(sum); Out.ln; | |
| 98 | + Out.int(Threads * Each * (Threads * Each - <span class="number">1</span>) <span class="kw">div</span> <span class="number">2</span>); Out.ln; | |
| 99 | +<span class="kw">end</span>; | |
| 100 | + | |
| 101 | +<span class="kw">end</span> Treiber.</code></pre> | |
| 102 | +<pre class="output"><code>20000 199990000 | |
| 103 | +199990000 | |
| 104 | +</code></pre> | |
| 105 | +<p>Twenty thousand nodes pushed by four threads at once; every one is on the stack exactly once, and the sum of their values is the sum of 0 to 19999. Nothing was lost, and there is no lock anywhere in the program.</p> | |
| 106 | +<p>The loop in <code>push</code> is the shape of every lock-free algorithm: read, compute, <code>CAS</code>, and read again on failure. The <code>CAS</code> is sequentially consistent, so the node's <code>val</code> and <code>next</code>, written before it with ordinary stores, are visible to a thread that finds the node through <code>top</code>.</p> | |
| 107 | +<h2>Pop, and the ABA problem</h2> | |
| 108 | +<p>Pop takes the head off: read <code>top</code>, read its <code>next</code>, <code>CAS</code> the head from <code>top</code> to <code>next</code>. It looks as easy as push, and it isn't. Between the two reads and the <code>CAS</code>, other threads may pop that node, pop others, and push the same node back, now with a different <code>next</code>. The head is the same pointer again, so the <code>CAS</code> succeeds, and installs a <code>next</code> that is stale: nodes disappear, or the stack points into freed memory. This is the <strong>ABA problem</strong>: the word changed from A to B and back to A, and the <code>CAS</code> can't tell.</p> | |
| 109 | +<p>There are three common ways out, and each has a cost:</p> | |
| 110 | +<ul><li><strong>Never reuse a node while anyone might hold it.</strong> Nodes from an arena that is reset only when all threads are done, as the nodes above come from a fixed array, can't come back as a different node.</li><li><strong>Add a counter to the head</strong>, so that A-B-A is A1-B2-A3. That is a word and a counter swapped together, and raz's <code>CAS</code> is for one word, so a program packs a small index and a counter into one <code>UINT</code>.</li><li><strong>Don't pop concurrently.</strong> Many threads push and one thread, at the end, takes everything with a single <code>XCHG(ADR(top), nil)</code> and walks the list in peace. A stack used this way for work lists and logs needs no more.</li></ul> | |
| 111 | +<div class="file"><span>Drain.raz</span></div><pre class="code"><code><span class="kw">module</span> Drain; | |
| 112 | +<span class="kw">import</span> Out, Thread; | |
| 113 | + | |
| 114 | +<span class="kw">type</span> Node = <span class="kw">record</span> next: ^Node; val: <span class="ty">INT</span>; <span class="kw">end</span>; | |
| 115 | + | |
| 116 | +<span class="kw">const</span> Threads = <span class="number">3</span>; Each = <span class="number">1000</span>; | |
| 117 | + | |
| 118 | +<span class="kw">var</span> | |
| 119 | + top: ^Node; | |
| 120 | + nodes: [Threads * Each]Node; | |
| 121 | + | |
| 122 | +<span class="kw">proc</span> push(n: ^Node); | |
| 123 | +<span class="kw">var</span> old: ^Node; | |
| 124 | +<span class="kw">begin</span> | |
| 125 | + old := top; | |
| 126 | + n^.next := old; | |
| 127 | + <span class="kw">while</span> <span class="kw">not</span> <span class="ty">CAS</span>(<span class="ty">ADR</span>(top), old, n) <span class="kw">do</span> | |
| 128 | + old := top; | |
| 129 | + n^.next := old; | |
| 130 | + <span class="kw">end</span>; | |
| 131 | +<span class="kw">end</span>; | |
| 132 | + | |
| 133 | +<span class="kw">proc</span> work(arg: ^<span class="ty">U8</span>); | |
| 134 | +<span class="kw">var</span> first, i: <span class="ty">INT</span>; | |
| 135 | +<span class="kw">begin</span> | |
| 136 | + first := <span class="ty">INT</span>(arg) * Each; | |
| 137 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> Each - <span class="number">1</span> <span class="kw">do</span> | |
| 138 | + nodes[first + i].val := <span class="number">1</span>; | |
| 139 | + push(<span class="ty">ADR</span>(nodes[first + i])); | |
| 140 | + <span class="kw">end</span>; | |
| 141 | +<span class="kw">end</span>; | |
| 142 | + | |
| 143 | +<span class="kw">proc</span> main*; | |
| 144 | +<span class="kw">var</span> th: [Threads]^Thread.Thread; i, count: <span class="ty">INT</span>; err: <span class="ty">ERROR</span>; all, n: ^Node; | |
| 145 | +<span class="kw">begin</span> | |
| 146 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> Threads - <span class="number">1</span> <span class="kw">do</span> | |
| 147 | + th[i], err := Thread.spawn(work, ^<span class="ty">U8</span>(i)); | |
| 148 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">return</span>; <span class="kw">end</span>; | |
| 149 | + <span class="kw">end</span>; | |
| 150 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> Threads - <span class="number">1</span> <span class="kw">do</span> Thread.join(th[i]); <span class="kw">end</span>; | |
| 151 | + all := <span class="ty">XCHG</span>(<span class="ty">ADR</span>(top), <span class="ty">nil</span>); <span class="comment">(* take the whole stack, atomically *)</span> | |
| 152 | + n := all; | |
| 153 | + <span class="kw">while</span> n # <span class="ty">nil</span> <span class="kw">do</span> <span class="ty">INC</span>(count); n := n^.next; <span class="kw">end</span>; | |
| 154 | + Out.int(count); Out.str(<span class="string">" taken at once, "</span>); | |
| 155 | + <span class="kw">if</span> top = <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="string">"none left\n"</span>); <span class="kw">end</span>; | |
| 156 | +<span class="kw">end</span>; | |
| 157 | + | |
| 158 | +<span class="kw">end</span> Drain.</code></pre> | |
| 159 | +<pre class="output"><code>3000 taken at once, none left | |
| 160 | +</code></pre> | |
| 161 | +<p>The atomic exchange takes everything pushed so far in one step, so the walk that follows races with nobody.</p> | |
| 162 | +<h2>When to use it</h2> | |
| 163 | +<p>A lock-free structure is worth it when a lock would be held by a thread that can be descheduled, when the critical section is a single pointer, or when a signal handler or an interrupt must share data with the code it interrupts. Everywhere else a <code>Mutex</code> is shorter, easier to check, and fast enough. The advantage of knowing how to write the other kind is that you understand what the lock is doing for you.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="ordering.html">← Ordering and publication</a><a href="index.html">Contents</a><a class="next" href="ring.html">A ring buffer between threads →</a></div></article></div> | |
| 164 | +</main> | |
| 165 | +<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> | |
| 166 | +</body> | |
| 167 | +</html> |
| @@ -0,0 +1,131 @@ | ||
| 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>Ordering and publication - More Raz</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="Ordering and publication - More Raz"> | |
| 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.lucelad.workers.dev/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" aria-current="page">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<div class="tour"><aside><h2>More Raz</h2><h3>The library</h3><ol start='1'> | |
| 22 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 23 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 24 | +<li><a href="collections.html">Lists, arrays, maps and sorting</a></li> | |
| 25 | +<li><a href="files.html">Files and the command line</a></li> | |
| 26 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 27 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 28 | +</ol> | |
| 29 | +<h3>Standing alone</h3><ol start='7'> | |
| 30 | +<li><a href="static.html">A program with no run time</a></li> | |
| 31 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 32 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 33 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 34 | +</ol> | |
| 35 | +<h3>The machine</h3><ol start='11'> | |
| 36 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 37 | +<li><a href="syscalls.html">System calls</a></li> | |
| 38 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 39 | +</ol> | |
| 40 | +<h3>Shared memory</h3><ol start='14'> | |
| 41 | +<li><a href="volatile.html">Volatile</a></li> | |
| 42 | +<li><a href="atomics.html">Atomics</a></li> | |
| 43 | +<li><a href="ordering.html" aria-current="page">Ordering and publication</a></li> | |
| 44 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 45 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 46 | +</ol></aside><article><p class="kicker">Shared memory · lesson 16 of 18</p><h1>Ordering and publication</h1> | |
| 47 | +<p>Atomics make one word safe. The harder question is about the *other* words: if one thread writes a value and then raises a flag, can another thread that sees the flag be sure it sees the value?</p> | |
| 48 | +<p>The report is careful. 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 the report says. A variable that one thread writes while another reads or writes it, unless both use volatile accesses or the atomic built-ins, or a <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. Nothing else of the program becomes undefined by it.</p> | |
| 49 | +<p>In plain words: two threads that share an ordinary variable with no atomic, volatile or fence between them get no guarantee about what each sees.</p> | |
| 50 | +<h2>The pattern that is guaranteed: publish through an atomic</h2> | |
| 51 | +<p>The simplest correct way to hand a value to another thread: write it with ordinary stores, then store a flag with an atomic. The reader loops on the flag with an atomic read, and then reads the data. <code>XCHG</code> is the store; <code>XADD(p, 0)</code> is the load, which adds nothing and returns the value. Both are sequentially consistent, so everything written before the flag is visible after it is seen.</p> | |
| 52 | +<div class="file"><span>Publish.raz</span></div><pre class="code"><code><span class="kw">module</span> Publish; | |
| 53 | +<span class="kw">import</span> Out, Sys, Thread; | |
| 54 | + | |
| 55 | +<span class="kw">type</span> Message = <span class="kw">record</span> id: <span class="ty">INT</span>; text: [<span class="number">32</span>]<span class="ty">U8</span>; len: <span class="ty">INT</span>; <span class="kw">end</span>; | |
| 56 | + | |
| 57 | +<span class="kw">var</span> | |
| 58 | + msg: Message; <span class="comment">(* ordinary memory, written once, then published *)</span> | |
| 59 | + ready: <span class="ty">INT</span>; <span class="comment">(* the flag: only touched by atomics *)</span> | |
| 60 | + | |
| 61 | +<span class="kw">proc</span> producer(_arg: ^<span class="ty">U8</span>); | |
| 62 | +<span class="kw">begin</span> | |
| 63 | + Sys.sleep(<span class="number">10</span>); | |
| 64 | + msg.id := <span class="number">7</span>; | |
| 65 | + msg.text := <span class="string">"built before the flag"</span>; | |
| 66 | + msg.len := <span class="number">21</span>; | |
| 67 | + _ := <span class="ty">XCHG</span>(<span class="ty">ADR</span>(ready), <span class="number">1</span>); <span class="comment">(* publish *)</span> | |
| 68 | +<span class="kw">end</span>; | |
| 69 | + | |
| 70 | +<span class="kw">proc</span> main*; | |
| 71 | +<span class="kw">var</span> t: ^Thread.Thread; err: <span class="ty">ERROR</span>; | |
| 72 | +<span class="kw">begin</span> | |
| 73 | + t, err := Thread.spawn(producer, <span class="ty">nil</span>); | |
| 74 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">return</span>; <span class="kw">end</span>; | |
| 75 | + <span class="kw">while</span> <span class="ty">XADD</span>(<span class="ty">ADR</span>(ready), <span class="number">0</span>) = <span class="number">0</span> <span class="kw">do</span> Sys.yield; <span class="kw">end</span>; <span class="comment">(* wait for it *)</span> | |
| 76 | + Out.int(msg.id); Out.char(<span class="string">' '</span>); Out.str(msg.text[<span class="number">0</span>..msg.len]); Out.ln; | |
| 77 | + Thread.join(t); | |
| 78 | +<span class="kw">end</span>; | |
| 79 | + | |
| 80 | +<span class="kw">end</span> Publish.</code></pre> | |
| 81 | +<pre class="output"><code>7 built before the flag | |
| 82 | +</code></pre> | |
| 83 | +<p>The reader's loop makes no ordinary read of <code>ready</code>: it can't be kept in a register and read once, which is the danger of <code>while ready = 0 do end</code>. And the write of <code>msg</code> can't be delayed past the <code>XCHG</code>.</p> | |
| 84 | +<h2>The same with a fence</h2> | |
| 85 | +<p><code>FENCE</code> is a full memory barrier: it orders the program's ordinary accesses against those of other processors and devices. With volatile accesses for the flag and a fence between the data and the flag, the same handoff works. This is the form device code takes, as in the last lesson.</p> | |
| 86 | +<div class="file"><span>Fenced.raz</span></div><pre class="code"><code><span class="kw">module</span> Fenced; | |
| 87 | +<span class="kw">import</span> Out, Sys, Thread; | |
| 88 | + | |
| 89 | +<span class="kw">var</span> | |
| 90 | + data: <span class="ty">INT</span>; <span class="comment">(* ordinary *)</span> | |
| 91 | + flag: <span class="ty">INT</span>; <span class="comment">(* only reached through a volatile pointer *)</span> | |
| 92 | + | |
| 93 | +<span class="kw">proc</span> producer(_arg: ^<span class="ty">U8</span>); | |
| 94 | +<span class="kw">var</span> f: ^<span class="kw">VOLATILE</span> <span class="ty">INT</span>; | |
| 95 | +<span class="kw">begin</span> | |
| 96 | + f := ^<span class="kw">VOLATILE</span> <span class="ty">INT</span>(<span class="ty">ADR</span>(flag)); | |
| 97 | + Sys.sleep(<span class="number">10</span>); | |
| 98 | + data := <span class="number">1234</span>; | |
| 99 | + FENCE; <span class="comment">(* data is written before the flag is *)</span> | |
| 100 | + f^ := <span class="number">1</span>; | |
| 101 | +<span class="kw">end</span>; | |
| 102 | + | |
| 103 | +<span class="kw">proc</span> main*; | |
| 104 | +<span class="kw">var</span> t: ^Thread.Thread; err: <span class="ty">ERROR</span>; f: ^<span class="kw">VOLATILE</span> <span class="ty">INT</span>; | |
| 105 | +<span class="kw">begin</span> | |
| 106 | + f := ^<span class="kw">VOLATILE</span> <span class="ty">INT</span>(<span class="ty">ADR</span>(flag)); | |
| 107 | + t, err := Thread.spawn(producer, <span class="ty">nil</span>); | |
| 108 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">return</span>; <span class="kw">end</span>; | |
| 109 | + <span class="kw">while</span> f^ = <span class="number">0</span> <span class="kw">do</span> Sys.yield; <span class="kw">end</span>; | |
| 110 | + FENCE; <span class="comment">(* and read after the flag is seen *)</span> | |
| 111 | + Out.int(data); Out.ln; | |
| 112 | + Thread.join(t); | |
| 113 | +<span class="kw">end</span>; | |
| 114 | + | |
| 115 | +<span class="kw">end</span> Fenced.</code></pre> | |
| 116 | +<pre class="output"><code>1234 | |
| 117 | +</code></pre> | |
| 118 | +<p>Both sides need a fence. A fence on the writer only says the data is written first; the reader must not read <code>data</code> before it has seen the flag.</p> | |
| 119 | +<h2>The version that is not guaranteed</h2> | |
| 120 | +<p>This is what *not* to write, and it is the most common bug in this area:</p> | |
| 121 | +<pre class="code"><code>var data, ready: INT; | |
| 122 | + | |
| 123 | +(* thread A *) data := 42; ready := 1; | |
| 124 | +(* thread B *) while ready = 0 do end; use(data);</code></pre> | |
| 125 | +<p>Both threads use ordinary accesses to shared variables. B's loop may read <code>ready</code> once into a register and spin forever; A's two writes may reach memory in either order; B may read <code>data</code> before the flag, or an old copy. On a particular machine with a particular compiler it may well work, until it is changed. The language says it holds no particular value, and it means it.</p> | |
| 126 | +<h2>The lesson of the three versions</h2> | |
| 127 | +<ul><li>Shared and written by someone: reach it through an atomic, a volatile pointer or a fence, every time, on both sides.</li><li>To hand over a bundle, publish a single atomic word *after* writing the bundle, and read the bundle only *after* seeing the word.</li><li>Everything under a <code>Lock</code> or a <code>Mutex</code> is ordered by the lock itself, so the data it guards can be ordinary variables. That is the simplest discipline, and the one to prefer until it is measured to be too slow.</li></ul><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="atomics.html">← Atomics</a><a href="index.html">Contents</a><a class="next" href="lockfree.html">A lock-free stack →</a></div></article></div> | |
| 128 | +</main> | |
| 129 | +<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> | |
| 130 | +</body> | |
| 131 | +</html> |
| @@ -0,0 +1,213 @@ | ||
| 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>Time, randomness and other programs - More Raz</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="Time, randomness and other programs - More Raz"> | |
| 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.lucelad.workers.dev/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" aria-current="page">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<div class="tour"><aside><h2>More Raz</h2><h3>The library</h3><ol start='1'> | |
| 22 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 23 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 24 | +<li><a href="collections.html">Lists, arrays, maps and sorting</a></li> | |
| 25 | +<li><a href="files.html">Files and the command line</a></li> | |
| 26 | +<li><a href="processes.html" aria-current="page">Time, randomness and other programs</a></li> | |
| 27 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 28 | +</ol> | |
| 29 | +<h3>Standing alone</h3><ol start='7'> | |
| 30 | +<li><a href="static.html">A program with no run time</a></li> | |
| 31 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 32 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 33 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 34 | +</ol> | |
| 35 | +<h3>The machine</h3><ol start='11'> | |
| 36 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 37 | +<li><a href="syscalls.html">System calls</a></li> | |
| 38 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 39 | +</ol> | |
| 40 | +<h3>Shared memory</h3><ol start='14'> | |
| 41 | +<li><a href="volatile.html">Volatile</a></li> | |
| 42 | +<li><a href="atomics.html">Atomics</a></li> | |
| 43 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 44 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 45 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 46 | +</ol></aside><article><p class="kicker">The library · lesson 5 of 18</p><h1>Time, randomness and other programs</h1> | |
| 47 | +<p>Everything here is in <code>Sys</code>, and is the same procedures on every target raz supports: through system calls on Linux, through the C library elsewhere.</p> | |
| 48 | +<h2>Clocks and sleeping</h2> | |
| 49 | +<p><code>Sys.clock</code> is a clock that only goes forward, in nanoseconds: the one to measure a duration with. <code>Sys.now</code> is the wall clock, in nanoseconds since 1970 UTC, which can be set backwards, so it is for dates, not durations. <code>Sys.sleep</code> waits some milliseconds.</p> | |
| 50 | +<div class="file"><span>Timing.raz</span></div><pre class="code"><code><span class="kw">module</span> Timing; | |
| 51 | +<span class="kw">import</span> Out, Sys; | |
| 52 | + | |
| 53 | +<span class="kw">proc</span> main*; | |
| 54 | +<span class="kw">var</span> t0, t1, elapsed: <span class="ty">I64</span>; wall: <span class="ty">I64</span>; | |
| 55 | +<span class="kw">begin</span> | |
| 56 | + t0 := Sys.clock(); | |
| 57 | + Sys.sleep(<span class="number">25</span>); | |
| 58 | + t1 := Sys.clock(); | |
| 59 | + elapsed := (t1 - t0) <span class="kw">div</span> <span class="number">1000000</span>; <span class="comment">(* milliseconds *)</span> | |
| 60 | + <span class="kw">if</span> (elapsed >= <span class="number">25</span>) <span class="kw">and</span> (elapsed < <span class="number">1000</span>) <span class="kw">then</span> | |
| 61 | + Out.str(<span class="string">"slept about 25 ms\n"</span>); | |
| 62 | + <span class="kw">end</span>; | |
| 63 | + wall := Sys.now(); | |
| 64 | + <span class="kw">if</span> wall > <span class="number">1700000000000000000</span> <span class="kw">then</span> Out.str(<span class="string">"after 2023\n"</span>); <span class="kw">end</span>; | |
| 65 | +<span class="kw">end</span>; | |
| 66 | + | |
| 67 | +<span class="kw">end</span> Timing.</code></pre> | |
| 68 | +<pre class="output"><code>slept about 25 ms | |
| 69 | +after 2023 | |
| 70 | +</code></pre> | |
| 71 | +<p>Every duration is an <code>I64</code> of nanoseconds, because a 32-bit <code>INT</code> would hold only a couple of seconds of them. The library's rule is that what may overflow a small target's <code>INT</code> is an <code>I64</code>.</p> | |
| 72 | +<h2>Random bytes</h2> | |
| 73 | +<p><code>Sys.random</code> fills a slice with random bytes from the system. Anything else is made from that: a number in a range, a shuffle.</p> | |
| 74 | +<div class="file"><span>Dice.raz</span></div><pre class="code"><code><span class="kw">module</span> Dice; | |
| 75 | +<span class="kw">import</span> Out, Sys, Str; | |
| 76 | + | |
| 77 | +<span class="comment">(* a number from 0 up to n, without bias *)</span> | |
| 78 | +<span class="kw">proc</span> below(n: <span class="ty">INT</span>): <span class="ty">INT</span>; | |
| 79 | +<span class="kw">var</span> b: [<span class="number">8</span>]<span class="ty">U8</span>; x, limit: <span class="ty">U64</span>; | |
| 80 | +<span class="kw">begin</span> | |
| 81 | + limit := <span class="number">0FFFFFFFFFFFFFFFFH</span> - (<span class="number">0FFFFFFFFFFFFFFFFH</span> <span class="kw">mod</span> <span class="ty">U64</span>(n)) - <span class="number">1</span>; | |
| 82 | + Sys.random(b); | |
| 83 | + x := Str.le(b); | |
| 84 | + <span class="kw">while</span> x > limit <span class="kw">do</span> | |
| 85 | + Sys.random(b); | |
| 86 | + x := Str.le(b); | |
| 87 | + <span class="kw">end</span>; | |
| 88 | + <span class="kw">return</span> <span class="ty">INT</span>(x <span class="kw">mod</span> <span class="ty">U64</span>(n)); | |
| 89 | +<span class="kw">end</span>; | |
| 90 | + | |
| 91 | +<span class="kw">proc</span> main*; | |
| 92 | +<span class="kw">var</span> counts: [<span class="number">6</span>]<span class="ty">INT</span>; i: <span class="ty">INT</span>; ok: <span class="ty">BOOL</span>; | |
| 93 | +<span class="kw">begin</span> | |
| 94 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">6000</span> <span class="kw">do</span> <span class="ty">INC</span>(counts[below(<span class="number">6</span>)]); <span class="kw">end</span>; | |
| 95 | + ok := <span class="ty">true</span>; | |
| 96 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">5</span> <span class="kw">do</span> | |
| 97 | + <span class="kw">if</span> (counts[i] < <span class="number">800</span>) <span class="kw">or</span> (counts[i] > <span class="number">1200</span>) <span class="kw">then</span> ok := <span class="ty">false</span>; <span class="kw">end</span>; | |
| 98 | + <span class="kw">end</span>; | |
| 99 | + <span class="kw">if</span> ok <span class="kw">then</span> Out.str(<span class="string">"all six faces came up about a thousand times\n"</span>); <span class="kw">end</span>; | |
| 100 | +<span class="kw">end</span>; | |
| 101 | + | |
| 102 | +<span class="kw">end</span> Dice.</code></pre> | |
| 103 | +<pre class="output"><code>all six faces came up about a thousand times | |
| 104 | +</code></pre> | |
| 105 | +<h2>Running a program</h2> | |
| 106 | +<p><code>Sys.spawn</code> starts the program at a path with its arguments, environment, working directory and standard streams in a <code>Sys.Program</code> record. A zero field means this program's own. <code>Sys.wait</code> waits for it to end and says how: <code>exited</code> with its status, <code>killed</code> by a signal, or <code>stopped</code>.</p> | |
| 107 | +<div class="file"><span>Run.raz</span></div><pre class="code"><code><span class="kw">module</span> Run; | |
| 108 | +<span class="kw">import</span> Out, Sys; | |
| 109 | + | |
| 110 | +<span class="kw">proc</span> main*; | |
| 111 | +<span class="kw">var</span> p: Sys.Program; pid, status: <span class="ty">INT</span>; how: Sys.Status; | |
| 112 | +<span class="kw">begin</span> | |
| 113 | + p := {path: <span class="string">"/bin/echo"</span>, args: [<span class="string">"echo"</span>, <span class="string">"hello from a child"</span>]}; | |
| 114 | + pid := Sys.spawn(p); | |
| 115 | + <span class="kw">if</span> pid < <span class="number">0</span> <span class="kw">then</span> Out.str(<span class="string">"can't start\n"</span>); <span class="kw">return</span>; <span class="kw">end</span>; | |
| 116 | + Out.flush; <span class="comment">(* so that our text isn't behind the child's *)</span> | |
| 117 | + _, how, status := Sys.wait(pid, <span class="ty">true</span>); | |
| 118 | + <span class="kw">if</span> how = Sys.exited <span class="kw">then</span> | |
| 119 | + Out.str(<span class="string">"it exited with "</span>); Out.int(status); Out.ln; | |
| 120 | + <span class="kw">end</span>; | |
| 121 | +<span class="kw">end</span>; | |
| 122 | + | |
| 123 | +<span class="kw">end</span> Run.</code></pre> | |
| 124 | +<pre class="output"><code>hello from a child | |
| 125 | +it exited with 0 | |
| 126 | +</code></pre> | |
| 127 | +<h2>Capturing its output</h2> | |
| 128 | +<p>A program's standard output can be a pipe. <code>Sys.pipe</code> gives the descriptor to read and the one to write; give the write end to the child as <code>fds[1]</code>, close it here, and read until the end. This is how a program drives another: <code>ls</code>, a compiler, a script.</p> | |
| 129 | +<div class="file"><span>Capture.raz</span></div><pre class="code"><code><span class="kw">module</span> Capture; | |
| 130 | +<span class="kw">import</span> Out, Sys, Buf, Heap; | |
| 131 | + | |
| 132 | +<span class="kw">proc</span> main*; | |
| 133 | +<span class="kw">var</span> | |
| 134 | + p: Sys.Program; pid, rd, wr, n, status: <span class="ty">INT</span>; how: Sys.Status; | |
| 135 | + chunk: [<span class="number">256</span>]<span class="ty">U8</span>; b: Buf.Buf; | |
| 136 | +<span class="kw">begin</span> | |
| 137 | + rd, wr := Sys.pipe(); | |
| 138 | + p := {path: <span class="string">"/bin/sh"</span>, args: [<span class="string">"sh"</span>, <span class="string">"-c"</span>, <span class="string">"echo one; echo two; exit 7"</span>]}; | |
| 139 | + p.fds[<span class="number">1</span>] := wr; | |
| 140 | + pid := Sys.spawn(p); | |
| 141 | + Sys.close(wr); <span class="comment">(* only the child writes now *)</span> | |
| 142 | + Buf.init(b, Heap.heap); | |
| 143 | + <span class="kw">defer</span> Buf.done(b); | |
| 144 | + n := Sys.read(rd, chunk); | |
| 145 | + <span class="kw">while</span> n > <span class="number">0</span> <span class="kw">do</span> | |
| 146 | + Buf.str(b, chunk[<span class="number">0</span>..n]); | |
| 147 | + n := Sys.read(rd, chunk); | |
| 148 | + <span class="kw">end</span>; | |
| 149 | + Sys.close(rd); | |
| 150 | + _, how, status := Sys.wait(pid, <span class="ty">true</span>); | |
| 151 | + Out.str(<span class="string">"captured: "</span>); Out.str(Buf.bytes(b)); | |
| 152 | + Out.str(<span class="string">"status "</span>); Out.int(status); Out.ln; | |
| 153 | + <span class="kw">if</span> how = Sys.exited <span class="kw">then</span> Out.str(<span class="string">"(a normal exit)\n"</span>); <span class="kw">end</span>; | |
| 154 | +<span class="kw">end</span>; | |
| 155 | + | |
| 156 | +<span class="kw">end</span> Capture.</code></pre> | |
| 157 | +<pre class="output"><code>captured: one | |
| 158 | +two | |
| 159 | +status 7 | |
| 160 | +(a normal exit) | |
| 161 | +</code></pre> | |
| 162 | +<p>Closing the write end in the parent matters: the read ends only when every holder of the write end has closed it.</p> | |
| 163 | +<h2>Environment and working directory</h2> | |
| 164 | +<p><code>Sys.env("HOME")</code> is an environment variable's value, or an empty string if it is unset. <code>Sys.workDir</code> and <code>Sys.setWorkDir</code> read and change the directory. The <code>Sys.Program</code> record's <code>env</code>, <code>onlyEnv</code> and <code>dir</code> give a child its own.</p> | |
| 165 | +<div class="file"><span>Where.raz</span></div><pre class="code"><code><span class="kw">module</span> Where; | |
| 166 | +<span class="kw">import</span> Out, Sys; | |
| 167 | + | |
| 168 | +<span class="kw">proc</span> main*; | |
| 169 | +<span class="kw">var</span> p: Sys.Program; pid, rd, wr, n: <span class="ty">INT</span>; chunk: [<span class="number">64</span>]<span class="ty">U8</span>; | |
| 170 | +<span class="kw">begin</span> | |
| 171 | + <span class="kw">if</span> Sys.env(<span class="string">"RAZ_SURELY_UNSET"</span>) = <span class="string">""</span> <span class="kw">then</span> Out.str(<span class="string">"unset reads as empty\n"</span>); <span class="kw">end</span>; | |
| 172 | + rd, wr := Sys.pipe(); | |
| 173 | + p := {path: <span class="string">"/bin/sh"</span>, args: [<span class="string">"sh"</span>, <span class="string">"-c"</span>, <span class="string">"echo $GREETING from $(pwd)"</span>], | |
| 174 | + env: [<span class="string">"GREETING=hello"</span>], dir: <span class="string">"/tmp"</span>}; | |
| 175 | + p.fds[<span class="number">1</span>] := wr; | |
| 176 | + pid := Sys.spawn(p); | |
| 177 | + Sys.close(wr); | |
| 178 | + n := Sys.read(rd, chunk); | |
| 179 | + Out.str(chunk[<span class="number">0</span>..n]); | |
| 180 | + Sys.close(rd); | |
| 181 | + _, _, _ := Sys.wait(pid, <span class="ty">true</span>); | |
| 182 | +<span class="kw">end</span>; | |
| 183 | + | |
| 184 | +<span class="kw">end</span> Where.</code></pre> | |
| 185 | +<pre class="output"><code>unset reads as empty | |
| 186 | +hello from /tmp | |
| 187 | +</code></pre> | |
| 188 | +<h2>Signals</h2> | |
| 189 | +<p>A signal, Ctrl-C's <code>sigInt</code> or <code>sigTerm</code> from <code>kill</code>, ends a program unless it says otherwise. <code>Sys.catch</code> takes signals away from what they would do and gives an fd that is ready to read when one comes, so a program that waits on fds anyway, with <code>Sys.readyOf</code>, waits for signals the same way; <code>Sys.caught</code> gives each in turn. <code>Sys.handle</code> is for a program that waits inside a system call, as a shell waits for its program: the signal is noted for <code>Sys.came</code>, and the call it comes during fails with -4 (EINTR) rather than going on. Nothing of the program runs when the signal comes; it looks after the call returns.</p> | |
| 190 | +<div class="file"><span>Signals.raz</span></div><pre class="code"><code><span class="kw">module</span> Signals; | |
| 191 | +<span class="kw">import</span> Out, Sys; | |
| 192 | + | |
| 193 | +<span class="kw">proc</span> main*; | |
| 194 | +<span class="kw">var</span> fd: <span class="ty">INT</span>; | |
| 195 | +<span class="kw">begin</span> | |
| 196 | + fd := Sys.catch([Sys.sigUsr1]); | |
| 197 | + _ := Sys.kill(Sys.pid(), Sys.sigUsr1); | |
| 198 | + <span class="kw">if</span> Sys.ready(fd, <span class="number">1000</span>) <span class="kw">and</span> (Sys.caught(fd) = Sys.sigUsr1) <span class="kw">then</span> Out.str(<span class="string">"caught sigUsr1\n"</span>); <span class="kw">end</span>; | |
| 199 | + _ := Sys.handle(Sys.sigUsr2); | |
| 200 | + _ := Sys.kill(Sys.pid(), Sys.sigUsr2); | |
| 201 | + <span class="kw">if</span> Sys.came(Sys.sigUsr2) <span class="kw">then</span> Out.str(<span class="string">"sigUsr2 came\n"</span>); <span class="kw">end</span>; | |
| 202 | + <span class="kw">if</span> <span class="kw">not</span> Sys.came(Sys.sigUsr2) <span class="kw">then</span> Out.str(<span class="string">"and was seen once\n"</span>); <span class="kw">end</span>; | |
| 203 | +<span class="kw">end</span>; | |
| 204 | + | |
| 205 | +<span class="kw">end</span> Signals.</code></pre> | |
| 206 | +<pre class="output"><code>caught sigUsr1 | |
| 207 | +sigUsr2 came | |
| 208 | +and was seen once | |
| 209 | +</code></pre><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="files.html">← Files and the command line</a><a href="index.html">Contents</a><a class="next" href="allocators.html">Writing an allocator →</a></div></article></div> | |
| 210 | +</main> | |
| 211 | +<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> | |
| 212 | +</body> | |
| 213 | +</html> |
| @@ -0,0 +1,139 @@ | ||
| 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>A ring buffer between threads - More Raz</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="A ring buffer between threads - More Raz"> | |
| 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.lucelad.workers.dev/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" aria-current="page">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<div class="tour"><aside><h2>More Raz</h2><h3>The library</h3><ol start='1'> | |
| 22 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 23 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 24 | +<li><a href="collections.html">Lists, arrays, maps and sorting</a></li> | |
| 25 | +<li><a href="files.html">Files and the command line</a></li> | |
| 26 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 27 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 28 | +</ol> | |
| 29 | +<h3>Standing alone</h3><ol start='7'> | |
| 30 | +<li><a href="static.html">A program with no run time</a></li> | |
| 31 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 32 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 33 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 34 | +</ol> | |
| 35 | +<h3>The machine</h3><ol start='11'> | |
| 36 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 37 | +<li><a href="syscalls.html">System calls</a></li> | |
| 38 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 39 | +</ol> | |
| 40 | +<h3>Shared memory</h3><ol start='14'> | |
| 41 | +<li><a href="volatile.html">Volatile</a></li> | |
| 42 | +<li><a href="atomics.html">Atomics</a></li> | |
| 43 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 44 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 45 | +<li><a href="ring.html" aria-current="page">A ring buffer between threads</a></li> | |
| 46 | +</ol></aside><article><p class="kicker">Shared memory · lesson 18 of 18</p><h1>A ring buffer between threads</h1> | |
| 47 | +<p>To finish, here is a small piece of real concurrent code that uses nearly everything in this part of the tour: a queue through which one thread sends numbers to another, with no lock and no allocation.</p> | |
| 48 | +<h2>The design</h2> | |
| 49 | +<p>The queue is a fixed array of slots, used as a circle, and two counters that only ever grow: <code>tail</code>, the number of items the producer has put in, and <code>head</code>, the number the consumer has taken out. The item <code>n</code> lives in slot <code>n mod Size</code>. The queue is empty when the two are equal, and full when they differ by <code>Size</code>.</p> | |
| 50 | +<p>The design rule is that <strong>each counter has exactly one writer</strong>. Only the producer changes <code>tail</code>; only the consumer changes <code>head</code>. Each thread reads its own counter with an ordinary read, since nobody else changes it, and the other thread's with an atomic one. No <code>CAS</code> is needed, because there is never a race to resolve: only a handoff.</p> | |
| 51 | +<p>The handoff is the publish pattern of the ordering lesson. The producer writes the slot, then publishes it with an atomic store of <code>tail</code>; the consumer sees the new <code>tail</code> with an atomic load and only then reads the slot. In the other direction, the consumer frees a slot by storing <code>head</code>, and the producer only reuses it after loading <code>head</code> and seeing that.</p> | |
| 52 | +<h2>The module</h2> | |
| 53 | +<div class="file"><span>Ring.raz</span></div><pre class="code"><code><span class="kw">module</span> Ring; | |
| 54 | +<span class="kw">import</span> Sys; | |
| 55 | + | |
| 56 | +<span class="kw">const</span> Size* = <span class="number">64</span>; | |
| 57 | + | |
| 58 | +<span class="kw">type</span> | |
| 59 | + Ring* = <span class="kw">record</span> | |
| 60 | + slots: [Size]<span class="ty">INT</span>; | |
| 61 | + head, tail: <span class="ty">INT</span>; <span class="comment">(* items taken, items put; each has one writer *)</span> | |
| 62 | + <span class="kw">end</span>; | |
| 63 | + | |
| 64 | +<span class="comment">(* v into the ring, waiting while it is full *)</span> | |
| 65 | +<span class="kw">proc</span> put*(r: ^Ring; v: <span class="ty">INT</span>); | |
| 66 | +<span class="kw">var</span> t: <span class="ty">INT</span>; | |
| 67 | +<span class="kw">begin</span> | |
| 68 | + t := r^.tail; <span class="comment">(* mine: an ordinary read *)</span> | |
| 69 | + <span class="kw">while</span> t - <span class="ty">XADD</span>(<span class="ty">ADR</span>(r^.head), <span class="number">0</span>) = Size <span class="kw">do</span> Sys.yield; <span class="kw">end</span>; <span class="comment">(* full *)</span> | |
| 70 | + r^.slots[t <span class="kw">mod</span> Size] := v; | |
| 71 | + _ := <span class="ty">XCHG</span>(<span class="ty">ADR</span>(r^.tail), t + <span class="number">1</span>); <span class="comment">(* publish the slot *)</span> | |
| 72 | +<span class="kw">end</span>; | |
| 73 | + | |
| 74 | +<span class="comment">(* the next value, waiting while the ring is empty *)</span> | |
| 75 | +<span class="kw">proc</span> take*(r: ^Ring): <span class="ty">INT</span>; | |
| 76 | +<span class="kw">var</span> h, v: <span class="ty">INT</span>; | |
| 77 | +<span class="kw">begin</span> | |
| 78 | + h := r^.head; <span class="comment">(* mine *)</span> | |
| 79 | + <span class="kw">while</span> <span class="ty">XADD</span>(<span class="ty">ADR</span>(r^.tail), <span class="number">0</span>) = h <span class="kw">do</span> Sys.yield; <span class="kw">end</span>; <span class="comment">(* empty *)</span> | |
| 80 | + v := r^.slots[h <span class="kw">mod</span> Size]; | |
| 81 | + _ := <span class="ty">XCHG</span>(<span class="ty">ADR</span>(r^.head), h + <span class="number">1</span>); <span class="comment">(* give the slot back *)</span> | |
| 82 | + <span class="kw">return</span> v; | |
| 83 | +<span class="kw">end</span>; | |
| 84 | + | |
| 85 | +<span class="kw">end</span> Ring.</code></pre> | |
| 86 | +<h2>Using it</h2> | |
| 87 | +<p>One thread sends the numbers 1 to 100000 through a ring of 64 slots, so it is stopped by a full ring many times over and has to wait for the consumer. The consumer checks each number arrives in order, and adds them.</p> | |
| 88 | +<div class="file"><span>Pipe.raz</span></div><pre class="code"><code><span class="kw">module</span> Pipe; | |
| 89 | +<span class="kw">import</span> Out, Fmt, Ring, Thread; | |
| 90 | + | |
| 91 | +<span class="kw">const</span> Count = <span class="number">100000</span>; | |
| 92 | + | |
| 93 | +<span class="kw">var</span> | |
| 94 | + ring: Ring.Ring; | |
| 95 | + sum, outOfOrder: <span class="ty">INT</span>; | |
| 96 | + | |
| 97 | +<span class="kw">proc</span> producer(_arg: ^<span class="ty">U8</span>); | |
| 98 | +<span class="kw">var</span> i: <span class="ty">INT</span>; | |
| 99 | +<span class="kw">begin</span> | |
| 100 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> Count <span class="kw">do</span> Ring.put(<span class="ty">ADR</span>(ring), i); <span class="kw">end</span>; | |
| 101 | +<span class="kw">end</span>; | |
| 102 | + | |
| 103 | +<span class="kw">proc</span> consumer(_arg: ^<span class="ty">U8</span>); | |
| 104 | +<span class="kw">var</span> i, v: <span class="ty">INT</span>; | |
| 105 | +<span class="kw">begin</span> | |
| 106 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> Count <span class="kw">do</span> | |
| 107 | + v := Ring.take(<span class="ty">ADR</span>(ring)); | |
| 108 | + <span class="kw">if</span> v # i <span class="kw">then</span> <span class="ty">INC</span>(outOfOrder); <span class="kw">end</span>; | |
| 109 | + sum := sum + v; | |
| 110 | + <span class="kw">end</span>; | |
| 111 | +<span class="kw">end</span>; | |
| 112 | + | |
| 113 | +<span class="kw">proc</span> main*; | |
| 114 | +<span class="kw">var</span> p, c: ^Thread.Thread; err: <span class="ty">ERROR</span>; | |
| 115 | +<span class="kw">begin</span> | |
| 116 | + p, err := Thread.spawn(producer, <span class="ty">nil</span>); | |
| 117 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">return</span>; <span class="kw">end</span>; | |
| 118 | + c, err := Thread.spawn(consumer, <span class="ty">nil</span>); | |
| 119 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">return</span>; <span class="kw">end</span>; | |
| 120 | + Thread.join(p); | |
| 121 | + Thread.join(c); | |
| 122 | + Fmt.print(<span class="string">"{} items, sum {}, {} out of order\n"</span>, | |
| 123 | + [Fmt.int(Count), Fmt.int(sum), Fmt.int(outOfOrder)]); | |
| 124 | +<span class="kw">end</span>; | |
| 125 | + | |
| 126 | +<span class="kw">end</span> Pipe.</code></pre> | |
| 127 | +<pre class="output"><code>100000 items, sum 5000050000, 0 out of order | |
| 128 | +</code></pre> | |
| 129 | +<p>The sum of 1 to 100000 is 5000050000, and nothing arrives out of order. <code>sum</code> and <code>outOfOrder</code> are written only by the consumer thread and read by <code>main</code> after <code>Thread.join</code>, which is the synchronization that makes them visible: a join is the thread's end, observed.</p> | |
| 130 | +<h2>What it used</h2> | |
| 131 | +<ul><li><strong>Modules</strong> (<code>Ring</code>, with its record's own fields unexported).</li><li><strong>Atomics</strong> for the handoff, and an ordering argument for why a slot is complete when its counter moves.</li><li><strong>Threads</strong> from <code>Thread</code>, with no C in the program.</li><li><strong>The checks</strong>, which stay on: <code>slots[t mod Size]</code> is an indexed array access that can't leave the array, whatever the counters do.</li></ul> | |
| 132 | +<p>It is not a finished library: it is one producer and one consumer, and a second of either breaks the one-writer rule. That is the sort of statement a comment above <code>put</code> and <code>take</code> should make, and the sort a reader should demand.</p> | |
| 133 | +<h2>Where next</h2> | |
| 134 | +<p>That is the end of the tour. A few places to continue:</p> | |
| 135 | +<ul><li><strong><a href="../spec.html">The report</a></strong> defines the language, and is short enough to read through.</li><li><strong><code>doc/compiler.md</code></strong> in the sources is a guide to reading the compiler, file by file; it is a model of the style the project is written in.</li><li><strong><code>lib/</code></strong> is the library, in raz. Each module's own <code>main</code> is its test. Reading <code>Heap</code>, <code>Map</code>, <code>Opt</code> and <code>Thread</code> is the best remaining education.</li><li><strong><code>tools/Doc.raz</code></strong> prints what a module exports with its comments: <code>raz -o Doc tools/Doc.raz && ./Doc lib/Str.raz</code>.</li><li><strong><code>examples/</code></strong> holds small programs with the output each should give, and <code>conform/</code> holds what any implementation must do.</li></ul><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="lockfree.html">← A lock-free stack</a><a href="index.html">Contents</a><a class="next" href="../spec.html">The report →</a></div></article></div> | |
| 136 | +</main> | |
| 137 | +<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> | |
| 138 | +</body> | |
| 139 | +</html> |
| @@ -0,0 +1,152 @@ | ||
| 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>A program with no run time - More Raz</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="A program with no run time - More Raz"> | |
| 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.lucelad.workers.dev/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" aria-current="page">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<div class="tour"><aside><h2>More Raz</h2><h3>The library</h3><ol start='1'> | |
| 22 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 23 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 24 | +<li><a href="collections.html">Lists, arrays, maps and sorting</a></li> | |
| 25 | +<li><a href="files.html">Files and the command line</a></li> | |
| 26 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 27 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 28 | +</ol> | |
| 29 | +<h3>Standing alone</h3><ol start='7'> | |
| 30 | +<li><a href="static.html" aria-current="page">A program with no run time</a></li> | |
| 31 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 32 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 33 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 34 | +</ol> | |
| 35 | +<h3>The machine</h3><ol start='11'> | |
| 36 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 37 | +<li><a href="syscalls.html">System calls</a></li> | |
| 38 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 39 | +</ol> | |
| 40 | +<h3>Shared memory</h3><ol start='14'> | |
| 41 | +<li><a href="volatile.html">Volatile</a></li> | |
| 42 | +<li><a href="atomics.html">Atomics</a></li> | |
| 43 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 44 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 45 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 46 | +</ol></aside><article><p class="kicker">Standing alone · lesson 7 of 18</p><h1>A program with no run time</h1> | |
| 47 | +<p>Most languages arrive with a run time: a collector, a loader of libraries, start-up code you didn't write. A raz program that doesn't use C has none of that. The executable holds the code the program reaches, a few lines of start-up code, and nothing else. This part of the tour looks at what that means in practice, and what a program can do when nothing stands between it and the kernel.</p> | |
| 48 | +<h2>The smallest program</h2> | |
| 49 | +<p>This program imports nothing. It makes the <code>write</code> system call itself, with the built-in <code>SYSCALL</code>, and returns.</p> | |
| 50 | +<div class="file"><span>Bare.raz</span></div><pre class="code"><code><span class="kw">module</span> Bare; | |
| 51 | + | |
| 52 | +<span class="kw">const</span> Msg = <span class="string">"hello from raw system calls\n"</span>; | |
| 53 | + | |
| 54 | +<span class="kw">proc</span> main*; | |
| 55 | +<span class="kw">begin</span> | |
| 56 | + _ := SYSCALL(<span class="number">1</span>, <span class="number">1</span>, <span class="ty">ADR</span>(Msg[<span class="number">0</span>]), <span class="ty">LEN</span>(Msg)); | |
| 57 | +<span class="kw">end</span>; | |
| 58 | + | |
| 59 | +<span class="kw">end</span> Bare.</code></pre> | |
| 60 | +<pre class="output term"><code><span class="cmd">$ raz Bare.raz</span> | |
| 61 | +<span class="cmd">$ ./Bare</span> | |
| 62 | +hello from raw system calls | |
| 63 | +<span class="cmd">$ file Bare</span> | |
| 64 | +Bare: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, with debug_info, not stripped | |
| 65 | +<span class="cmd">$ ldd Bare</span> | |
| 66 | + not a dynamic executable | |
| 67 | +<span class="cmd">$ ls -l Bare | awk '{print $5, "bytes"}'</span> | |
| 68 | +26488 bytes</code></pre> | |
| 69 | +<p>It is statically linked: no interpreter, no shared libraries, no <code>libc</code>. <code>ldd</code> says so.</p> | |
| 70 | +<h2>What it does when it runs</h2> | |
| 71 | +<p><code>strace</code> lists every system call a program makes. This is the whole of it:</p> | |
| 72 | +<pre class="output term"><code><span class="cmd">$ strace ./Bare 2>&1 >/dev/null | sed -e 's/0x[0-9a-f]\{5,\}/ADDR/g' -e 's/[0-9]* vars/N vars/'</span> | |
| 73 | +execve("./Bare", ["./Bare"], ADDR /* N vars */) = 0 | |
| 74 | +sigaltstack({ss_sp=ADDR, ss_flags=0, ss_size=16384}, NULL) = 0 | |
| 75 | +rt_sigaction(SIGSEGV, {sa_handler=ADDR, sa_mask=[], sa_flags=SA_RESTORER|SA_ONSTACK|SA_RESETHAND|SA_SIGINFO, sa_restorer=ADDR}, NULL, 8) = 0 | |
| 76 | +rt_sigaction(SIGFPE, {sa_handler=ADDR, sa_mask=[], sa_flags=SA_RESTORER|SA_ONSTACK|SA_RESETHAND|SA_SIGINFO, sa_restorer=ADDR}, NULL, 8) = 0 | |
| 77 | +write(1, "hello from raw system calls\n", 28) = 28 | |
| 78 | +exit_group(0) = ? | |
| 79 | ++++ exited with 0 +++</code></pre> | |
| 80 | +<p>The start-up code does four things before <code>main</code> runs: it sets up a stack of its own for signal handlers (<code>sigaltstack</code>), and installs handlers for <code>SIGSEGV</code> and <code>SIGFPE</code>. That is what turns a <code>nil</code> pointer or a division by zero into a message that names the place, instead of a bare "Segmentation fault". Then <code>main</code> runs its single <code>write</code>, and the program ends with <code>exit_group</code>. Nothing is mapped, loaded, or looked up.</p> | |
| 81 | +<h2>Programs that use C</h2> | |
| 82 | +<p>A program that declares an <code>extern</code> procedure, or links a library, is a different animal. It is linked dynamically and starts through the C library, so that C's own set-up and clean-up run. Compare the same kind of hello, with C's <code>printf</code>:</p> | |
| 83 | +<div class="file"><span>Cprint.raz</span></div><pre class="code"><code><span class="kw">module</span> Cprint; | |
| 84 | + | |
| 85 | +<span class="kw">extern</span> <span class="kw">proc</span> puts(s: ^<span class="ty">U8</span>): <span class="ty">I32</span>; | |
| 86 | + | |
| 87 | +<span class="kw">proc</span> main*; | |
| 88 | +<span class="kw">begin</span> | |
| 89 | + _ := puts(<span class="string">"hello from C"</span>); | |
| 90 | +<span class="kw">end</span>; | |
| 91 | + | |
| 92 | +<span class="kw">end</span> Cprint.</code></pre> | |
| 93 | +<pre class="output term"><code><span class="cmd">$ raz Cprint.raz</span> | |
| 94 | +<span class="cmd">$ ./Cprint</span> | |
| 95 | +hello from C | |
| 96 | +<span class="cmd">$ file Cprint</span> | |
| 97 | +Cprint: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, with debug_info, not stripped | |
| 98 | +<span class="cmd">$ ldd Cprint | sed 's/ (0x[0-9a-f]*)//'</span> | |
| 99 | + linux-vdso.so.1 | |
| 100 | + libc.so.6 => /usr/lib/libc.so.6 | |
| 101 | + /lib64/ld-linux-x86-64.so.2 => /usr/lib64/ld-linux-x86-64.so.2</code></pre> | |
| 102 | +<p>Both are fine. The point is that you choose, and the language says which you chose: a program uses C exactly when a module of it has an <code>extern</code> or a <code>link</code> of a library.</p> | |
| 103 | +<h2>Only what is reached</h2> | |
| 104 | +<p>The compiler keeps only what can be reached from <code>main</code> and the module bodies. Unused procedures, variables and strings are left out. Here are two programs that differ by one large procedure that nothing calls.</p> | |
| 105 | +<div class="file"><span>Lean.raz</span></div><pre class="code"><code><span class="kw">module</span> Lean; | |
| 106 | +<span class="kw">import</span> Out; | |
| 107 | + | |
| 108 | +<span class="kw">proc</span> main*; | |
| 109 | +<span class="kw">begin</span> | |
| 110 | + Out.str(<span class="string">"same program\n"</span>); | |
| 111 | +<span class="kw">end</span>; | |
| 112 | + | |
| 113 | +<span class="kw">end</span> Lean.</code></pre> | |
| 114 | +<div class="file"><span>Heavy.raz</span></div><pre class="code"><code><span class="kw">module</span> Heavy; | |
| 115 | +<span class="kw">import</span> Out; | |
| 116 | + | |
| 117 | +<span class="kw">var</span> table: [<span class="number">100000</span>]<span class="ty">INT</span>; | |
| 118 | + | |
| 119 | +<span class="comment">(* exported, but never called, so never in the executable *)</span> | |
| 120 | +<span class="kw">proc</span> unused*(n: <span class="ty">INT</span>): <span class="ty">INT</span>; | |
| 121 | +<span class="kw">var</span> i, s: <span class="ty">INT</span>; | |
| 122 | +<span class="kw">begin</span> | |
| 123 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">99999</span> <span class="kw">do</span> table[i] := n * i; s := s + table[i]; <span class="kw">end</span>; | |
| 124 | + Out.str(<span class="string">"a long string that nobody will ever print, to give it some weight"</span>); | |
| 125 | + <span class="kw">return</span> s; | |
| 126 | +<span class="kw">end</span>; | |
| 127 | + | |
| 128 | +<span class="kw">proc</span> main*; | |
| 129 | +<span class="kw">begin</span> | |
| 130 | + Out.str(<span class="string">"same program\n"</span>); | |
| 131 | +<span class="kw">end</span>; | |
| 132 | + | |
| 133 | +<span class="kw">end</span> Heavy.</code></pre> | |
| 134 | +<pre class="output term"><code><span class="cmd">$ raz Lean.raz</span> | |
| 135 | +<span class="cmd">$ raz Heavy.raz</span> | |
| 136 | +<span class="cmd">$ ls -l Lean Heavy | awk '{print $9, $5}'</span> | |
| 137 | +Heavy 28680 | |
| 138 | +Lean 28672</code></pre> | |
| 139 | +<p>The sizes differ by a few bytes, not by the hundreds of kilobytes that the table and the procedure would take: they are not in the executable at all. You can link in a library module without worrying what else it offers.</p> | |
| 140 | +<h2>Stripping</h2> | |
| 141 | +<p><code>-s</code> leaves out what is there for finding faults: the symbols and line numbers, the places a failure is told by, and the profiler. It is for the final build of a size-conscious program; the default keeps them so that gdb and failure messages work.</p> | |
| 142 | +<pre class="output term"><code><span class="cmd">$ raz -s -o Lean-stripped Lean.raz</span> | |
| 143 | +<span class="cmd">$ ls -l Lean Lean-stripped | awk '{print $9, $5}'</span> | |
| 144 | +Lean 28672 | |
| 145 | +Lean-stripped 6920 | |
| 146 | +<span class="cmd">$ ./Lean-stripped</span> | |
| 147 | +same program</code></pre> | |
| 148 | +<p><code>raz -S Lean.raz</code> is the other direction: it prints the machine code the compiler made, one source line at a time. The next two parts of the tour use it.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="allocators.html">← Writing an allocator</a><a href="index.html">Contents</a><a class="next" href="linkstatic.html">Threads without C, and keeping the two apart →</a></div></article></div> | |
| 149 | +</main> | |
| 150 | +<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> | |
| 151 | +</body> | |
| 152 | +</html> |
| @@ -0,0 +1,199 @@ | ||
| 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>System calls - More Raz</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="System calls - More Raz"> | |
| 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.lucelad.workers.dev/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" aria-current="page">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<div class="tour"><aside><h2>More Raz</h2><h3>The library</h3><ol start='1'> | |
| 22 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 23 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 24 | +<li><a href="collections.html">Lists, arrays, maps and sorting</a></li> | |
| 25 | +<li><a href="files.html">Files and the command line</a></li> | |
| 26 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 27 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 28 | +</ol> | |
| 29 | +<h3>Standing alone</h3><ol start='7'> | |
| 30 | +<li><a href="static.html">A program with no run time</a></li> | |
| 31 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 32 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 33 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 34 | +</ol> | |
| 35 | +<h3>The machine</h3><ol start='11'> | |
| 36 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 37 | +<li><a href="syscalls.html" aria-current="page">System calls</a></li> | |
| 38 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 39 | +</ol> | |
| 40 | +<h3>Shared memory</h3><ol start='14'> | |
| 41 | +<li><a href="volatile.html">Volatile</a></li> | |
| 42 | +<li><a href="atomics.html">Atomics</a></li> | |
| 43 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 44 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 45 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 46 | +</ol></aside><article><p class="kicker">The machine · lesson 12 of 18</p><h1>System calls</h1> | |
| 47 | +<p>Under <code>Sys</code> there is one built-in: <code>SYSCALL(n, x1, ..., x6)</code>. It makes Linux system call number <code>n</code> with up to six arguments, each a pointer or an integer no wider than <code>INT</code>, and gives the raw result, an <code>INT</code>. A negative result is <code>-errno</code>. That is all the interface there is; <code>Sys.write</code>, <code>Sys.open</code> and the rest of <code>lib/Sys.linux-x86_64.raz</code> are written with it, in raz, in a few lines each.</p> | |
| 48 | +<p><code>SYSCALL</code> exists only on Linux targets. Other systems have no stable system call interface, which is why their <code>Sys</code> calls the C library instead.</p> | |
| 49 | +<h2>The shape of a call</h2> | |
| 50 | +<p><code>write(fd, buf, count)</code> is call number 1. The arguments are the descriptor, a pointer to the bytes, and how many.</p> | |
| 51 | +<div class="file"><span>Raw.raz</span></div><pre class="code"><code><span class="kw">module</span> Raw; | |
| 52 | + | |
| 53 | +<span class="kw">const</span> Msg = <span class="string">"straight to the kernel\n"</span>; | |
| 54 | + | |
| 55 | +<span class="kw">proc</span> main*; | |
| 56 | +<span class="kw">var</span> n: <span class="ty">INT</span>; | |
| 57 | +<span class="kw">begin</span> | |
| 58 | + n := SYSCALL(<span class="number">1</span>, <span class="number">1</span>, <span class="ty">ADR</span>(Msg[<span class="number">0</span>]), <span class="ty">LEN</span>(Msg)); | |
| 59 | + <span class="kw">if</span> n # <span class="ty">LEN</span>(Msg) <span class="kw">then</span> _ := SYSCALL(<span class="number">60</span>, <span class="number">1</span>); <span class="kw">end</span>; <span class="comment">(* exit(1), if it came up short *)</span> | |
| 60 | +<span class="kw">end</span>; | |
| 61 | + | |
| 62 | +<span class="kw">end</span> Raw.</code></pre> | |
| 63 | +<pre class="output term"><code><span class="cmd">$ raz -Werror Raw.raz</span> | |
| 64 | +<span class="cmd">$ ./Raw</span> | |
| 65 | +straight to the kernel</code></pre> | |
| 66 | +<p>That program has no <code>Out</code>, no <code>Sys</code>, and no output buffer. What it needs of the library is <code>Rt</code>'s start-up, which the compiler links in anyway.</p> | |
| 67 | +<h2>Reading the result</h2> | |
| 68 | +<p>A result that is negative is a failure, and its negation is the <code>errno</code>. <code>open</code> is call 2 and wants a C string: the path's bytes followed by a zero. A <code>[N]U8</code> made from a string literal is zero-filled past its length, so there is always a terminator.</p> | |
| 69 | +<div class="file"><span>Open.raz</span></div><pre class="code"><code><span class="kw">module</span> Open; | |
| 70 | +<span class="kw">import</span> Out; | |
| 71 | + | |
| 72 | +<span class="kw">proc</span> main*; | |
| 73 | +<span class="kw">var</span> path: [<span class="number">32</span>]<span class="ty">U8</span>; fd: <span class="ty">INT</span>; | |
| 74 | +<span class="kw">begin</span> | |
| 75 | + path := <span class="string">"/no/such/file"</span>; | |
| 76 | + fd := SYSCALL(<span class="number">2</span>, <span class="ty">ADR</span>(path[<span class="number">0</span>]), <span class="number">0</span>, <span class="number">0</span>); <span class="comment">(* open(path, O_RDONLY) *)</span> | |
| 77 | + Out.str(<span class="string">"open gave "</span>); Out.int(fd); Out.ln; <span class="comment">(* -2: ENOENT *)</span> | |
| 78 | + path := <span class="string">"/dev/null"</span>; | |
| 79 | + fd := SYSCALL(<span class="number">2</span>, <span class="ty">ADR</span>(path[<span class="number">0</span>]), <span class="number">0</span>, <span class="number">0</span>); | |
| 80 | + <span class="kw">if</span> fd >= <span class="number">0</span> <span class="kw">then</span> | |
| 81 | + Out.str(<span class="string">"opened /dev/null\n"</span>); | |
| 82 | + _ := SYSCALL(<span class="number">3</span>, fd); <span class="comment">(* close *)</span> | |
| 83 | + <span class="kw">end</span>; | |
| 84 | +<span class="kw">end</span>; | |
| 85 | + | |
| 86 | +<span class="kw">end</span> Open.</code></pre> | |
| 87 | +<pre class="output"><code>open gave -2 | |
| 88 | +opened /dev/null | |
| 89 | +</code></pre> | |
| 90 | +<p>The library's <code>Sys.openRead</code> does exactly this, and <code>Sys.close</code> too. Reading <code>lib/Sys.linux-x86_64.raz</code> is the best reference there is for what each call wants.</p> | |
| 91 | +<h2>A call that fills a structure</h2> | |
| 92 | +<p><code>uname</code> (call 63) fills a structure of six 65-byte fields: the system name, node name, release, version, machine and domain. It is not a type raz knows; it is an array of bytes, with a <code>ADR</code> of it given to the kernel.</p> | |
| 93 | +<div class="file"><span>Who.raz</span></div><pre class="code"><code><span class="kw">module</span> Who; | |
| 94 | +<span class="kw">import</span> Out; | |
| 95 | + | |
| 96 | +<span class="comment">(* the length of the zero-ended string at the start of s *)</span> | |
| 97 | +<span class="kw">proc</span> cstr(s: []<span class="ty">U8</span>): <span class="ty">INT</span>; | |
| 98 | +<span class="kw">var</span> n: <span class="ty">INT</span>; | |
| 99 | +<span class="kw">begin</span> | |
| 100 | + n := <span class="number">0</span>; | |
| 101 | + <span class="kw">while</span> (n < <span class="ty">LEN</span>(s)) <span class="kw">and</span> (s[n] # <span class="number">0</span>) <span class="kw">do</span> <span class="ty">INC</span>(n); <span class="kw">end</span>; | |
| 102 | + <span class="kw">return</span> n; | |
| 103 | +<span class="kw">end</span>; | |
| 104 | + | |
| 105 | +<span class="kw">proc</span> main*; | |
| 106 | +<span class="kw">var</span> u: [<span class="number">390</span>]<span class="ty">U8</span>; | |
| 107 | +<span class="kw">begin</span> | |
| 108 | + <span class="kw">if</span> SYSCALL(<span class="number">63</span>, <span class="ty">ADR</span>(u[<span class="number">0</span>])) = <span class="number">0</span> <span class="kw">then</span> | |
| 109 | + Out.str(<span class="string">"system: "</span>); Out.str(u[<span class="number">0</span>..cstr(u[<span class="number">0</span>..<span class="number">65</span>])]); Out.ln; | |
| 110 | + Out.str(<span class="string">"machine: "</span>); Out.str(u[<span class="number">260</span>..<span class="number">260</span> + cstr(u[<span class="number">260</span>..<span class="number">325</span>])]); Out.ln; | |
| 111 | + <span class="kw">end</span>; | |
| 112 | +<span class="kw">end</span>; | |
| 113 | + | |
| 114 | +<span class="kw">end</span> Who.</code></pre> | |
| 115 | +<pre class="output"><code>system: Linux | |
| 116 | +machine: x86_64 | |
| 117 | +</code></pre> | |
| 118 | +<h2>Memory straight from the kernel</h2> | |
| 119 | +<p><code>mmap</code> is call 9: six arguments, the most one call can take. This asks for a page of anonymous, zeroed memory, writes in it, and gives it back with <code>munmap</code> (call 11). It is what <code>Mem.pages</code> does, and so what every allocator is ultimately made of.</p> | |
| 120 | +<div class="file"><span>Pages.raz</span></div><pre class="code"><code><span class="kw">module</span> Pages; | |
| 121 | +<span class="kw">import</span> Out; | |
| 122 | + | |
| 123 | +<span class="kw">proc</span> main*; | |
| 124 | +<span class="kw">var</span> p: ^<span class="ty">U8</span>; i: <span class="ty">INT</span>; total: <span class="ty">INT</span>; | |
| 125 | +<span class="kw">begin</span> | |
| 126 | + <span class="comment">(* length 4096; PROT_READ|WRITE = 3; MAP_PRIVATE|ANONYMOUS = 22H; no fd *)</span> | |
| 127 | + p := ^<span class="ty">U8</span>(SYSCALL(<span class="number">9</span>, <span class="number">0</span>, <span class="number">4096</span>, <span class="number">3</span>, <span class="number">22H</span>, -<span class="number">1</span>, <span class="number">0</span>)); | |
| 128 | + <span class="kw">if</span> <span class="ty">INT</span>(p) < <span class="number">0</span> <span class="kw">then</span> Out.str(<span class="string">"no memory\n"</span>); <span class="kw">return</span>; <span class="kw">end</span>; | |
| 129 | + Out.int(<span class="ty">INT</span>(p[<span class="number">0</span>]) + p[<span class="number">4095</span>]); Out.str(<span class="string">" (zero, as promised)\n"</span>); | |
| 130 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">4095</span> <span class="kw">do</span> p[i] := <span class="ty">U8</span>(i); <span class="kw">end</span>; | |
| 131 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">4095</span> <span class="kw">do</span> <span class="ty">INC</span>(total, p[i]); <span class="kw">end</span>; | |
| 132 | + Out.int(total); Out.ln; | |
| 133 | + _ := SYSCALL(<span class="number">11</span>, p, <span class="number">4096</span>); | |
| 134 | +<span class="kw">end</span>; | |
| 135 | + | |
| 136 | +<span class="kw">end</span> Pages.</code></pre> | |
| 137 | +<pre class="output"><code>0 (zero, as promised) | |
| 138 | +522240 | |
| 139 | +</code></pre> | |
| 140 | +<h2>A cat with no library</h2> | |
| 141 | +<p>Reading and writing in a loop is all <code>cat</code> does. With system calls, it is one procedure. Call 0 is <code>read</code> and call 1 is <code>write</code>; 0 and 1 are standard input and output.</p> | |
| 142 | +<div class="file"><span>Cat.raz</span></div><pre class="code"><code><span class="kw">module</span> Cat; | |
| 143 | + | |
| 144 | +<span class="kw">proc</span> main*: <span class="ty">INT</span>; | |
| 145 | +<span class="kw">var</span> buf: [<span class="number">4096</span>]<span class="ty">U8</span>; n, wrote, at: <span class="ty">INT</span>; | |
| 146 | +<span class="kw">begin</span> | |
| 147 | + n := SYSCALL(<span class="number">0</span>, <span class="number">0</span>, <span class="ty">ADR</span>(buf[<span class="number">0</span>]), <span class="ty">LEN</span>(buf)); | |
| 148 | + <span class="kw">while</span> n > <span class="number">0</span> <span class="kw">do</span> | |
| 149 | + at := <span class="number">0</span>; | |
| 150 | + <span class="kw">while</span> at < n <span class="kw">do</span> <span class="comment">(* a write may be partial *)</span> | |
| 151 | + wrote := SYSCALL(<span class="number">1</span>, <span class="number">1</span>, <span class="ty">ADR</span>(buf[at]), n - at); | |
| 152 | + <span class="kw">if</span> wrote < <span class="number">0</span> <span class="kw">then</span> <span class="kw">return</span> <span class="number">1</span>; <span class="kw">end</span>; | |
| 153 | + <span class="ty">INC</span>(at, wrote); | |
| 154 | + <span class="kw">end</span>; | |
| 155 | + n := SYSCALL(<span class="number">0</span>, <span class="number">0</span>, <span class="ty">ADR</span>(buf[<span class="number">0</span>]), <span class="ty">LEN</span>(buf)); | |
| 156 | + <span class="kw">end</span>; | |
| 157 | + <span class="kw">if</span> n < <span class="number">0</span> <span class="kw">then</span> <span class="kw">return</span> <span class="number">1</span>; <span class="kw">end</span>; | |
| 158 | + <span class="kw">return</span> <span class="number">0</span>; | |
| 159 | +<span class="kw">end</span>; | |
| 160 | + | |
| 161 | +<span class="kw">end</span> Cat.</code></pre> | |
| 162 | +<pre class="output term"><code><span class="cmd">$ raz Cat.raz</span> | |
| 163 | +<span class="cmd">$ echo "through the pipe" | ./Cat</span> | |
| 164 | +through the pipe | |
| 165 | +<span class="cmd">$ ./Cat < /dev/null; echo "status $?"</span> | |
| 166 | +status 0 | |
| 167 | +<span class="cmd">$ echo "see the calls" | strace -e trace=read,write ./Cat 2>&1 >/dev/null | grep -v '^+++'</span> | |
| 168 | +read(0, "see the calls\n", 4096) = 14 | |
| 169 | +write(1, "see the calls\n", 14) = 14 | |
| 170 | +read(0, "", 4096) = 0</code></pre> | |
| 171 | +<p>The partial-write loop is the kind of detail <code>Sys.write</code> leaves to the caller on purpose: it returns the bytes written, and the program decides what to do about the rest.</p> | |
| 172 | +<h2>In a code procedure</h2> | |
| 173 | +<p>A system call is also an instruction. <code>syscall</code> takes its number in <code>rax</code> and its arguments in <code>rdi</code>, <code>rsi</code>, <code>rdx</code>, <code>r10</code>, <code>r8</code> and <code>r9</code>, which is not quite the order a procedure's arguments arrive in, since <code>r10</code> takes the place of <code>rcx</code>, and <code>syscall</code> itself clobbers <code>rcx</code> and <code>r11</code>.</p> | |
| 174 | +<div class="file"><span>Ppid.raz</span></div><pre class="code"><code><span class="kw">module</span> Ppid; | |
| 175 | +<span class="kw">import</span> Out; | |
| 176 | + | |
| 177 | +<span class="comment">(* getppid, call 110: no arguments *)</span> | |
| 178 | +<span class="kw">proc</span> getppid: <span class="ty">INT</span>; | |
| 179 | +<span class="kw">code</span> | |
| 180 | + mov eax, <span class="number">110</span>; | |
| 181 | + syscall; | |
| 182 | + ret; | |
| 183 | +<span class="kw">end</span> getppid; | |
| 184 | + | |
| 185 | +<span class="kw">proc</span> main*; | |
| 186 | +<span class="kw">begin</span> | |
| 187 | + <span class="kw">if</span> (getppid() > <span class="number">0</span>) <span class="kw">and</span> (SYSCALL(<span class="number">110</span>) = getppid()) <span class="kw">then</span> | |
| 188 | + Out.str(<span class="string">"two ways to ask, one answer\n"</span>); | |
| 189 | + <span class="kw">end</span>; | |
| 190 | +<span class="kw">end</span>; | |
| 191 | + | |
| 192 | +<span class="kw">end</span> Ppid.</code></pre> | |
| 193 | +<pre class="output"><code>two ways to ask, one answer | |
| 194 | +</code></pre> | |
| 195 | +<p><code>SYSCALL</code> is the right tool nearly always: the compiler puts the arguments where they belong, and the result is checked in the open. A code procedure is for the rare call you want to make from inside another piece of assembly.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="asm.html">← Procedures in assembly</a><a href="index.html">Contents</a><a class="next" href="listing.html">What the compiler makes →</a></div></article></div> | |
| 196 | +</main> | |
| 197 | +<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> | |
| 198 | +</body> | |
| 199 | +</html> |
| @@ -0,0 +1,112 @@ | ||
| 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>One module, one file per target - More Raz</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="One module, one file per target - More Raz"> | |
| 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.lucelad.workers.dev/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" aria-current="page">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<div class="tour"><aside><h2>More Raz</h2><h3>The library</h3><ol start='1'> | |
| 22 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 23 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 24 | +<li><a href="collections.html">Lists, arrays, maps and sorting</a></li> | |
| 25 | +<li><a href="files.html">Files and the command line</a></li> | |
| 26 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 27 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 28 | +</ol> | |
| 29 | +<h3>Standing alone</h3><ol start='7'> | |
| 30 | +<li><a href="static.html">A program with no run time</a></li> | |
| 31 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 32 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 33 | +<li><a href="targets.html" aria-current="page">One module, one file per target</a></li> | |
| 34 | +</ol> | |
| 35 | +<h3>The machine</h3><ol start='11'> | |
| 36 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 37 | +<li><a href="syscalls.html">System calls</a></li> | |
| 38 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 39 | +</ol> | |
| 40 | +<h3>Shared memory</h3><ol start='14'> | |
| 41 | +<li><a href="volatile.html">Volatile</a></li> | |
| 42 | +<li><a href="atomics.html">Atomics</a></li> | |
| 43 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 44 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 45 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 46 | +</ol></aside><article><p class="kicker">Standing alone · lesson 10 of 18</p><h1>One module, one file per target</h1> | |
| 47 | +<p>raz is first made for x86-64 Linux, but the language is written to be implemented elsewhere, and the library is arranged for it. The part of a program that depends on the system goes in a module of its own, one file per target. This is how <code>Sys</code> is made, and it is how your own code should keep its system-dependent parts apart.</p> | |
| 48 | +<h2>The files</h2> | |
| 49 | +<p>A module <code>Name</code> lives in <code>Name.raz</code>. A module whose code depends on the system comes in one file per target, <code>Name.linux-x86_64.raz</code>, which the compiler looks for first. The library has <code>Sys.linux-x86_64.raz</code>, which makes system calls, and <code>Sys.raz</code>, which calls the C library instead, for every other system. A program that imports <code>Sys</code> doesn't know or care which it got.</p> | |
| 50 | +<pre class="output term"><code><span class="cmd">$ ls $RAZLIB | grep -i "^sys\|^thread"</span> | |
| 51 | +Sys.linux-x86_64.raz | |
| 52 | +Sys.raz | |
| 53 | +Thread.linux-x86_64.raz | |
| 54 | +<span class="cmd">$ cd $RAZLIB && grep -c SYSCALL Sys.linux-x86_64.raz Sys.raz</span> | |
| 55 | +Sys.linux-x86_64.raz:151 | |
| 56 | +Sys.raz:0</code></pre> | |
| 57 | +<h2>A module of your own</h2> | |
| 58 | +<p>Here is a module with two files. <code>Clock.linux-x86_64.raz</code> is for this target; <code>Clock.raz</code> is what any other target would use. Both say what they are in <code>Name</code>, and both make <code>ticks</code>.</p> | |
| 59 | +<div class="file"><span>Clock.linux-x86_64.raz</span></div><pre class="code"><code><span class="kw">module</span> Clock; | |
| 60 | +<span class="kw">import</span> Sys; | |
| 61 | + | |
| 62 | +<span class="kw">const</span> Name* = <span class="string">"the linux-x86_64 file"</span>; | |
| 63 | + | |
| 64 | +<span class="comment">(* a number that only grows *)</span> | |
| 65 | +<span class="kw">proc</span> ticks*: <span class="ty">I64</span>; | |
| 66 | +<span class="kw">begin</span> | |
| 67 | + <span class="kw">return</span> Sys.clock(); | |
| 68 | +<span class="kw">end</span>; | |
| 69 | + | |
| 70 | +<span class="kw">end</span> Clock.</code></pre> | |
| 71 | +<div class="file"><span>Clock.raz</span></div><pre class="code"><code><span class="kw">module</span> Clock; | |
| 72 | +<span class="kw">import</span> Sys; | |
| 73 | + | |
| 74 | +<span class="kw">const</span> Name* = <span class="string">"the portable file"</span>; | |
| 75 | + | |
| 76 | +<span class="comment">(* a number that only grows *)</span> | |
| 77 | +<span class="kw">proc</span> ticks*: <span class="ty">I64</span>; | |
| 78 | +<span class="kw">begin</span> | |
| 79 | + <span class="kw">return</span> Sys.clock(); | |
| 80 | +<span class="kw">end</span>; | |
| 81 | + | |
| 82 | +<span class="kw">end</span> Clock.</code></pre> | |
| 83 | +<p>A program that imports <code>Clock</code> gets the first of them here:</p> | |
| 84 | +<div class="file"><span>Show.raz</span></div><pre class="code"><code><span class="kw">module</span> Show; | |
| 85 | +<span class="kw">import</span> Out, Clock; | |
| 86 | + | |
| 87 | +<span class="kw">proc</span> main*; | |
| 88 | +<span class="kw">begin</span> | |
| 89 | + Out.str(<span class="string">"using "</span>); Out.str(Clock.Name); Out.ln; | |
| 90 | + <span class="kw">if</span> Clock.ticks() > <span class="number">0</span> <span class="kw">then</span> Out.str(<span class="string">"and it ticks\n"</span>); <span class="kw">end</span>; | |
| 91 | +<span class="kw">end</span>; | |
| 92 | + | |
| 93 | +<span class="kw">end</span> Show.</code></pre> | |
| 94 | +<pre class="output"><code>using the linux-x86_64 file | |
| 95 | +and it ticks | |
| 96 | +</code></pre> | |
| 97 | +<h2>Held to one interface</h2> | |
| 98 | +<p>Two files can't be told apart by their callers, so the compiler holds them to the same interface. Here is the pair again with <code>ticks</code> changed in the portable file to return an <code>INT</code>:</p> | |
| 99 | +<pre class="output term"><code><span class="cmd">$ mkdir drift && cp Clock*.raz Show.raz drift && cd drift</span> | |
| 100 | +<span class="cmd">$ sed -i 's/proc ticks\*: I64/proc ticks*: INT/; s/return Sys.clock()/return INT(Sys.clock())/' Clock.raz</span> | |
| 101 | +<span class="cmd">$ raz Show.raz</span> | |
| 102 | +raz: ./Clock.raz: ticks isn't exported as in ./Clock.linux-x86_64.raz</code></pre> | |
| 103 | +<p>The program stops compiling on every target, including the ones that would never have used that file. A mismatch is found where it is made, not where someone first builds for a second target.</p> | |
| 104 | +<h2>What the compiler checks</h2> | |
| 105 | +<p>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: a constant of the same type (its value may differ), a type of the same kind with the same exported fields, a variable of the same type, a procedure of the same signature. The code, the unexported fields, and so the size and layout, may differ.</p> | |
| 106 | +<p>So a program written against the interface works on every target that has the module, and the places where it doesn't are the compiler's to find, not yours.</p> | |
| 107 | +<h2>What stays the same everywhere</h2> | |
| 108 | +<p>The core of the library is what every target must have: <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. <code>Thread</code>, <code>link</code> and <code>extern</code>, and most of <code>Sys</code>, are what a target may leave out when its system can't give them.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="lifecycle.html">← Starting, ending, and signals</a><a href="index.html">Contents</a><a class="next" href="asm.html">Procedures in assembly →</a></div></article></div> | |
| 109 | +</main> | |
| 110 | +<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> | |
| 111 | +</body> | |
| 112 | +</html> |
| @@ -0,0 +1,154 @@ | ||
| 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>Volatile - More Raz</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="Volatile - More Raz"> | |
| 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.lucelad.workers.dev/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" aria-current="page">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<div class="tour"><aside><h2>More Raz</h2><h3>The library</h3><ol start='1'> | |
| 22 | +<li><a href="fmt.html">Output and formatting</a></li> | |
| 23 | +<li><a href="bytes.html">Strings and bytes</a></li> | |
| 24 | +<li><a href="collections.html">Lists, arrays, maps and sorting</a></li> | |
| 25 | +<li><a href="files.html">Files and the command line</a></li> | |
| 26 | +<li><a href="processes.html">Time, randomness and other programs</a></li> | |
| 27 | +<li><a href="allocators.html">Writing an allocator</a></li> | |
| 28 | +</ol> | |
| 29 | +<h3>Standing alone</h3><ol start='7'> | |
| 30 | +<li><a href="static.html">A program with no run time</a></li> | |
| 31 | +<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> | |
| 32 | +<li><a href="lifecycle.html">Starting, ending, and signals</a></li> | |
| 33 | +<li><a href="targets.html">One module, one file per target</a></li> | |
| 34 | +</ol> | |
| 35 | +<h3>The machine</h3><ol start='11'> | |
| 36 | +<li><a href="asm.html">Procedures in assembly</a></li> | |
| 37 | +<li><a href="syscalls.html">System calls</a></li> | |
| 38 | +<li><a href="listing.html">What the compiler makes</a></li> | |
| 39 | +</ol> | |
| 40 | +<h3>Shared memory</h3><ol start='14'> | |
| 41 | +<li><a href="volatile.html" aria-current="page">Volatile</a></li> | |
| 42 | +<li><a href="atomics.html">Atomics</a></li> | |
| 43 | +<li><a href="ordering.html">Ordering and publication</a></li> | |
| 44 | +<li><a href="lockfree.html">A lock-free stack</a></li> | |
| 45 | +<li><a href="ring.html">A ring buffer between threads</a></li> | |
| 46 | +</ol></aside><article><p class="kicker">Shared memory · lesson 14 of 18</p><h1>Volatile</h1> | |
| 47 | +<p>Most memory is the program's own: only it reads and writes it, so the compiler may keep a variable in a register, leave out a write that nothing reads, and change the order of accesses, as long as the program does what the report says. Some memory is not: a device's registers, memory another processor or thread is changing, a page the kernel fills. There, each access matters, and its order.</p> | |
| 48 | +<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 one of a basic, enumeration, set or pointer type is exactly one memory access, of exactly its size, and volatile accesses happen in the order the program writes them.</p> | |
| 49 | +<h2>A device laid over memory</h2> | |
| 50 | +<p>The classic use is a device's registers: a record that says what is at which offset, laid over the address the hardware answers at. The record's layout is C's, so it is the same as the datasheet's struct. Here a page of the program's own stands in for the device.</p> | |
| 51 | +<div class="file"><span>Uart.raz</span></div><pre class="code"><code><span class="kw">module</span> Uart; | |
| 52 | +<span class="kw">import</span> Out; | |
| 53 | + | |
| 54 | +<span class="kw">type</span> | |
| 55 | + Regs = <span class="kw">record</span> | |
| 56 | + data: <span class="ty">U32</span>; <span class="comment">(* offset 0 *)</span> | |
| 57 | + status: <span class="ty">U32</span>; <span class="comment">(* offset 4 *)</span> | |
| 58 | + control: <span class="ty">U8</span>; <span class="comment">(* offset 8 *)</span> | |
| 59 | + <span class="kw">end</span>; | |
| 60 | + | |
| 61 | +<span class="kw">var</span> page: [<span class="number">64</span>]<span class="ty">U8</span>; <span class="comment">(* where the device would be *)</span> | |
| 62 | + | |
| 63 | +<span class="kw">proc</span> main*; | |
| 64 | +<span class="kw">var</span> dev: ^<span class="kw">VOLATILE</span> Regs; i: <span class="ty">INT</span>; | |
| 65 | +<span class="kw">begin</span> | |
| 66 | + dev := ^<span class="kw">VOLATILE</span> Regs(<span class="ty">ADR</span>(page)); <span class="comment">(* the conversion is written *)</span> | |
| 67 | + dev^.control := <span class="number">1</span>; | |
| 68 | + dev^.status := <span class="number">0FFH</span>; | |
| 69 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">2</span> <span class="kw">do</span> | |
| 70 | + dev^.data := <span class="ty">U32</span>(<span class="string">'a'</span> + i); | |
| 71 | + Out.char(<span class="ty">U8</span>(dev^.data)); | |
| 72 | + <span class="kw">end</span>; | |
| 73 | + Out.ln; | |
| 74 | + FENCE; | |
| 75 | + Out.int(<span class="ty">INT</span>(page[<span class="number">8</span>])); Out.char(<span class="string">' '</span>); Out.int(<span class="ty">INT</span>(dev^.status)); Out.ln; | |
| 76 | +<span class="kw">end</span>; | |
| 77 | + | |
| 78 | +<span class="kw">end</span> Uart.</code></pre> | |
| 79 | +<pre class="output"><code>abc | |
| 80 | +1 255 | |
| 81 | +</code></pre> | |
| 82 | +<p>On real hardware the address would be a constant, <code>^VOLATILE Regs(0FEC00000H)</code>, which is a legal conversion since an integer constant converts to a pointer. The program is otherwise unchanged.</p> | |
| 83 | +<h2>What each access is</h2> | |
| 84 | +<p>The listing shows what the guarantee means: each field access is one instruction of the field's size, and so is a write to a field that is never read afterwards, which an optimizer would be allowed to drop from an ordinary variable.</p> | |
| 85 | +<pre class="output term"><code><span class="cmd">$ raz -S Uart.raz | grep -n "dword\|byte" | head -2</span> | |
| 86 | +15: 34 mov byte [rbx + 8], 1 | |
| 87 | +17: 38 mov dword [rbx + 4], 255</code></pre> | |
| 88 | +<p>The <code>U8</code> control byte is written with a <code>byte</code> store, and the <code>U32</code> status with a <code>dword</code> one. Never a wider access that touches the neighbour, never two narrower ones.</p> | |
| 89 | +<h2>Waiting for something else to change</h2> | |
| 90 | +<p>Where a program waits for another thread or a device to change a value, the loop must read the value each time. A volatile read does. This "device" is a thread that sets a bit in a status word after a delay; the main thread polls.</p> | |
| 91 | +<div class="file"><span>Poll.raz</span></div><pre class="code"><code><span class="kw">module</span> Poll; | |
| 92 | +<span class="kw">import</span> Out, Sys, Thread; | |
| 93 | + | |
| 94 | +<span class="kw">type</span> Dev = <span class="kw">record</span> status: <span class="ty">INT</span>; data: <span class="ty">INT</span>; <span class="kw">end</span>; | |
| 95 | + | |
| 96 | +<span class="kw">var</span> dev: Dev; | |
| 97 | + | |
| 98 | +<span class="kw">proc</span> device(_arg: ^<span class="ty">U8</span>); | |
| 99 | +<span class="kw">var</span> d: ^<span class="kw">VOLATILE</span> Dev; | |
| 100 | +<span class="kw">begin</span> | |
| 101 | + d := ^<span class="kw">VOLATILE</span> Dev(<span class="ty">ADR</span>(dev)); | |
| 102 | + Sys.sleep(<span class="number">20</span>); | |
| 103 | + d^.data := <span class="number">42</span>; | |
| 104 | + FENCE; <span class="comment">(* data before the flag that announces it *)</span> | |
| 105 | + d^.status := <span class="number">1</span>; | |
| 106 | +<span class="kw">end</span>; | |
| 107 | + | |
| 108 | +<span class="kw">proc</span> main*; | |
| 109 | +<span class="kw">var</span> t: ^Thread.Thread; err: <span class="ty">ERROR</span>; d: ^<span class="kw">VOLATILE</span> Dev; spins: <span class="ty">INT</span>; | |
| 110 | +<span class="kw">begin</span> | |
| 111 | + d := ^<span class="kw">VOLATILE</span> Dev(<span class="ty">ADR</span>(dev)); | |
| 112 | + t, err := Thread.spawn(device, <span class="ty">nil</span>); | |
| 113 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">return</span>; <span class="kw">end</span>; | |
| 114 | + <span class="kw">while</span> d^.status = <span class="number">0</span> <span class="kw">do</span> <span class="ty">INC</span>(spins); Sys.yield; <span class="kw">end</span>; | |
| 115 | + Out.int(d^.data); Out.ln; | |
| 116 | + <span class="kw">if</span> spins > <span class="number">0</span> <span class="kw">then</span> Out.str(<span class="string">"it waited for the device\n"</span>); <span class="kw">end</span>; | |
| 117 | + Thread.join(t); | |
| 118 | +<span class="kw">end</span>; | |
| 119 | + | |
| 120 | +<span class="kw">end</span> Poll.</code></pre> | |
| 121 | +<pre class="output"><code>42 | |
| 122 | +it waited for the device | |
| 123 | +</code></pre> | |
| 124 | +<p>The <code>FENCE</code> between the two writes matters. It is a full memory barrier, ordering the program's ordinary accesses against those of other processors and devices. Without it, volatile accesses are ordered among themselves, but nothing says another processor sees <code>data</code> before <code>status</code>. The next lessons are about this.</p> | |
| 125 | +<h2>What volatile is not</h2> | |
| 126 | +<ul><li><strong>Not atomic across a read-modify-write.</strong> <code>INC(d^.count)</code> reads and then writes: two accesses, even through a volatile pointer. <code>XADD</code> is the atomic one.</li><li><strong>Not a lock.</strong> It says each access happens as written; it says nothing about what happens between them.</li><li><strong>Not for whole records or arrays.</strong> Copying a whole record through a volatile pointer isn't allowed, since it can't be one access. A field of a packed record can't be reached volatilely at all, since a misaligned access can't be promised as one.</li><li><strong>Not silently dropped.</strong> A <code>^VOLATILE T</code> doesn't convert to a <code>^T</code> without a written conversion, so the volatile can't be lost by accident.</li></ul> | |
| 127 | +<p>The compiler holds the line on each of them:</p> | |
| 128 | +<div class="file"><span>Wrong.raz</span></div><pre class="code"><code><span class="kw">module</span> Wrong; | |
| 129 | + | |
| 130 | +<span class="kw">type</span> Pair = <span class="kw">record</span> a, b: <span class="ty">U32</span>; <span class="kw">end</span>; | |
| 131 | + | |
| 132 | +<span class="kw">var</span> cell: Pair; | |
| 133 | + | |
| 134 | +<span class="kw">proc</span> main*; | |
| 135 | +<span class="kw">var</span> v: ^<span class="kw">VOLATILE</span> Pair; p: ^Pair; copy: Pair; | |
| 136 | +<span class="kw">begin</span> | |
| 137 | + v := ^<span class="kw">VOLATILE</span> Pair(<span class="ty">ADR</span>(cell)); | |
| 138 | + p := v; | |
| 139 | + copy := v^; | |
| 140 | +<span class="kw">end</span>; | |
| 141 | + | |
| 142 | +<span class="kw">end</span> Wrong.</code></pre> | |
| 143 | +<pre class="output term"><code><span class="cmd">$ raz Wrong.raz</span> | |
| 144 | +Wrong.raz:11:10: error: can't use ^VOLATILE Pair as ^Pair | |
| 145 | + 11 | p := v; | |
| 146 | + | ^ | |
| 147 | +Wrong.raz:12:13: error: can't copy through a volatile pointer | |
| 148 | + 12 | copy := v^; | |
| 149 | + | ^^ | |
| 150 | +raz: 2 errors</code></pre><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="listing.html">← What the compiler makes</a><a href="index.html">Contents</a><a class="next" href="atomics.html">Atomics →</a></div></article></div> | |
| 151 | +</main> | |
| 152 | +<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> | |
| 153 | +</body> | |
| 154 | +</html> |
| @@ -0,0 +1,143 @@ | ||
| 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>raz: a small systems language</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="raz: a small systems language"> | |
| 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.lucelad.workers.dev/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">Report</a><a href="source/index.html">Source</a><a href="index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<section class="hero"> | |
| 22 | + <h1>raz</h1> | |
| 23 | + <p class="tag">A small systems language in Wirth’s tradition, for x86-64 Linux. | |
| 24 | + <em>Raz</em> is Polish for <em>one</em>, as in counting.</p> | |
| 25 | + <div class="cta"> | |
| 26 | + <a class="btn primary" href="tour/index.html">Take the tour: Raz, Set, Go</a> | |
| 27 | + <a class="btn" href="advanced/index.html">More Raz</a> | |
| 28 | + <a class="btn" href="#download">Download</a> | |
| 29 | + <a class="btn" href="spec.html">Read the report</a> | |
| 30 | + <a class="btn" href="source/index.html">Browse the source</a> | |
| 31 | + </div> | |
| 32 | +</section> | |
| 33 | + | |
| 34 | +<p>A raz program can lay a record over a device’s registers, read and | |
| 35 | +write memory exactly as written, take part in lock-free algorithms, make | |
| 36 | +system calls and call C libraries. It has no garbage collector and no hidden | |
| 37 | +run time: what the program does is what its text says.</p> | |
| 38 | + | |
| 39 | +<p>The compiler is written in raz, about 10,700 lines, and builds itself. It makes | |
| 40 | +x86-64 machine code and the ELF file itself, with no assembler or linker, in | |
| 41 | +one pass, at about 500,000 lines a second.</p> | |
| 42 | + | |
| 43 | +<div class="facts"> | |
| 44 | + <span><b>~10,700</b> lines of compiler</span> | |
| 45 | + <span><b>~500K</b> lines compiled a second</span> | |
| 46 | + <span><b>1</b> report, <b>35</b> pages</span> | |
| 47 | + <span><b>static</b> executables, no run time to install</span> | |
| 48 | +</div> | |
| 49 | + | |
| 50 | +<div class="cols"> | |
| 51 | + <div> | |
| 52 | + <h2>A taste</h2> | |
| 53 | + <div class="file"><span>Taste.raz</span></div> | |
| 54 | +<pre class="code"><code><span class="comment">(* Several results, slices, and checks that say what failed. *)</span> | |
| 55 | +<span class="kw">module</span> Taste; | |
| 56 | +<span class="kw">import</span> Out; | |
| 57 | + | |
| 58 | +<span class="kw">proc</span> divmod(a, b: <span class="ty">INT</span>): (<span class="ty">INT</span>, <span class="ty">INT</span>); | |
| 59 | +<span class="kw">begin</span> | |
| 60 | + <span class="kw">return</span> a <span class="kw">div</span> b, a <span class="kw">mod</span> b; | |
| 61 | +<span class="kw">end</span>; | |
| 62 | + | |
| 63 | +<span class="kw">proc</span> sum(s: []<span class="ty">INT</span>): <span class="ty">INT</span>; | |
| 64 | +<span class="kw">var</span> i, t: <span class="ty">INT</span>; | |
| 65 | +<span class="kw">begin</span> | |
| 66 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="ty">LEN</span>(s) - <span class="number">1</span> <span class="kw">do</span> t := t + s[i]; <span class="kw">end</span>; | |
| 67 | + <span class="kw">return</span> t; | |
| 68 | +<span class="kw">end</span>; | |
| 69 | + | |
| 70 | +<span class="kw">proc</span> main*; | |
| 71 | +<span class="kw">var</span> q, r: <span class="ty">INT</span>; a: [<span class="number">5</span>]<span class="ty">INT</span>; i: <span class="ty">INT</span>; | |
| 72 | +<span class="kw">begin</span> | |
| 73 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">4</span> <span class="kw">do</span> a[i] := i * i; <span class="kw">end</span>; | |
| 74 | + q, r := divmod(sum(a), <span class="number">7</span>); | |
| 75 | + Out.int(q); Out.str(<span class="string">" remainder "</span>); Out.int(r); Out.ln; | |
| 76 | + Out.int(sum(a[<span class="number">1</span>..<span class="number">3</span>])); Out.ln; | |
| 77 | +<span class="kw">end</span>; | |
| 78 | + | |
| 79 | +<span class="kw">end</span> Taste.</code></pre> | |
| 80 | +<pre class="output"><code>4 remainder 2 | |
| 81 | +5</code></pre> | |
| 82 | + </div> | |
| 83 | + <div> | |
| 84 | + <h2>What it has</h2> | |
| 85 | + <ul class="features"> | |
| 86 | + <li>Integers of 8 to 64 bits, signed and unsigned, which wrap; <code>BOOL</code>, <code>F32</code>, <code>F64</code>. Nothing converts unless it is written.</li> | |
| 87 | + <li>Arrays, checked slices, pointers, records laid out as C lays them out, packed records, enumerations, sets, and variants with <code>match</code>.</li> | |
| 88 | + <li>Every index and slice is checked; a failure says where it was, with the values, and the calls under way.</li> | |
| 89 | + <li>Strings of UTF-8 bytes, raw strings over lines that keep the code's indent, and <code>match</code> on a string.</li> | |
| 90 | + <li>Every variable starts at zero. Behaviour is defined everywhere but through pointers.</li> | |
| 91 | + <li>No garbage collector: memory comes from an allocator the program chooses and passes.</li> | |
| 92 | + <li>Several results, <code>ERROR</code> values and <code>defer</code>, in place of exceptions.</li> | |
| 93 | + <li>Modules with bodies, and generic modules: <code>Map(K, V; hash, eq)</code>.</li> | |
| 94 | + <li><code>^VOLATILE T</code> and the atomics <code>CAS</code>, <code>XCHG</code>, <code>XADD</code>, <code>FENCE</code>, for devices and lock-free code.</li> | |
| 95 | + <li><code>extern</code> procedures and variables from C, code procedures in assembly, and <code>SYSCALL</code>.</li> | |
| 96 | + <li>Threads without C, a library of <code>Out</code>, <code>Str</code>, <code>Bytes</code>, <code>Fmt</code>, <code>Map</code>, <code>Sort</code> and more, and gdb that knows your lines.</li> | |
| 97 | + <li>A formatter, a documentation tool, and editor support for vim and emacs.</li> | |
| 98 | + </ul> | |
| 99 | + </div> | |
| 100 | +</div> | |
| 101 | + | |
| 102 | +<h2>Learn it</h2> | |
| 103 | +<p><a href="tour/index.html"><strong>Raz, Set, Go</strong></a> is a tour of the | |
| 104 | +language in 15 lessons, each with programs you can run. <a | |
| 105 | +href="advanced/index.html"><strong>More Raz</strong></a> is the second tour: | |
| 106 | +the library, programs with no run time, procedures in assembly, system calls, | |
| 107 | +volatile accesses, atomics and lock-free code, in 18 more.</p> | |
| 108 | + | |
| 109 | +<h2>The language, in writing</h2> | |
| 110 | +<p>The language is defined by <a href="spec.html">the report</a>, which is | |
| 111 | +short on purpose: whatever it doesn’t allow, raz doesn’t have. | |
| 112 | +Its second volume describes the library. Both are on one page, and each is | |
| 113 | +a PDF: <a href="raz.pdf">the language</a> (35 pages) and | |
| 114 | +<a href="raz-lib.pdf">the library</a>.</p> | |
| 115 | + | |
| 116 | +<h2 id="download">Download</h2> | |
| 117 | +<p>raz 0.23.0 is a tarball for x86-64 Linux with the compiler, <code>raz</code>, | |
| 118 | +its library, <code>lib/</code>, which it finds beside itself, the formatter | |
| 119 | +and the documentation tool as sources in <code>tools/</code>, and the manual | |
| 120 | +pages. It needs nothing else installed.</p> | |
| 121 | +<div class="cta"> | |
| 122 | + <a class="btn primary" href="download/raz-0.23.0-linux-x86_64.tar.gz">Download raz 0.23.0</a> | |
| 123 | + <a class="btn" href="download/raz-0.23.0-linux-x86_64.tar.gz.sha256">SHA-256</a> | |
| 124 | +</div> | |
| 125 | +<pre class="code"><code>$ tar xzf raz-0.23.0-linux-x86_64.tar.gz | |
| 126 | +$ ln -s $PWD/raz-0.23.0-linux-x86_64/raz ~/.local/bin/raz | |
| 127 | +$ raz run Hello.raz</code></pre> | |
| 128 | +<p>The link works since raz finds <code>lib/</code> beside its real path. The | |
| 129 | +manual pages are in <code>man/</code>: <code>man ./man/raz-tutorial.7</code>. | |
| 130 | +The address <code>download/latest</code> always leads to the newest release, | |
| 131 | +and <code>download/raz-0.23.0-linux-x86_64.tar.gz</code> to this one, for | |
| 132 | +good. Earlier releases: <a href="download/raz-0.22.0-linux-x86_64.tar.gz">0.22.0</a>, <a href="download/raz-0.21.0-linux-x86_64.tar.gz">0.21.0</a>, <a href="download/raz-0.20.0-linux-x86_64.tar.gz">0.20.0</a>, <a href="download/raz-0.19.0-linux-x86_64.tar.gz">0.19.0</a>, <a href="download/raz-0.18.1-linux-x86_64.tar.gz">0.18.1</a>, <a href="download/raz-0.18.0-linux-x86_64.tar.gz">0.18.0</a>, <a href="download/raz-0.17.2-linux-x86_64.tar.gz">0.17.2</a>, <a href="download/raz-0.17.1-linux-x86_64.tar.gz">0.17.1</a>, <a href="download/raz-0.17.0-linux-x86_64.tar.gz">0.17.0</a>, <a href="download/raz-0.16.0-linux-x86_64.tar.gz">0.16.0</a>, <a href="download/raz-0.15.0-linux-x86_64.tar.gz">0.15.0</a>, <a href="download/raz-0.14.0-linux-x86_64.tar.gz">0.14.0</a>, <a href="download/raz-0.13.0-linux-x86_64.tar.gz">0.13.0</a>, <a href="download/raz-0.12.0-linux-x86_64.tar.gz">0.12.0</a>, <a href="download/raz-0.11.1-linux-x86_64.tar.gz">0.11.1</a>, <a href="download/raz-0.11.0-linux-x86_64.tar.gz">0.11.0</a>, <a href="download/raz-0.10.1-linux-x86_64.tar.gz">0.10.1</a>, <a href="download/raz-0.10.0-linux-x86_64.tar.gz">0.10.0</a>, <a href="download/raz-0.9.1-linux-x86_64.tar.gz">0.9.1</a>, <a href="download/raz-0.9.0-linux-x86_64.tar.gz">0.9.0</a>, <a href="download/raz-0.8.0-linux-x86_64.tar.gz">0.8.0</a>, <a href="download/raz-0.7.1-linux-x86_64.tar.gz">0.7.1</a>; each has its SHA-256 beside it, with | |
| 133 | +<code>.sha256</code> added to its name.</p> | |
| 134 | +<p class="sha">SHA-256 <code>103eb421a7fcca1c1495c1a9c699297d460ab72067fa04854da8f21edc07347c</code></p> | |
| 135 | +<p><a href="source/releases/index.html">Release pages</a> give each | |
| 136 | +version's commit, notes, compiler and source archives, with checksums. | |
| 137 | +Browse the <a href="source/index.html">source and history</a>, or clone: | |
| 138 | +<code>git clone https://raz.lucelad.workers.dev/source/</code>.</p> | |
| 139 | + | |
| 140 | +</main> | |
| 141 | +<footer>raz is under the ISC license. <a href="source/index.html">Source</a></footer> | |
| 142 | +</body> | |
| 143 | +</html> |
Binary file; the patch has it.
Binary file; the patch has it.
| @@ -0,0 +1,1745 @@ | ||
| 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.lucelad.workers.dev/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> · <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.37 of the report; section 11 says where each version’s changes are told. 2026-10.11 and 2026-10.12 are a thaw the owner chose, for a language anyone can build again. They break programs written for 2026-10.10 and before: for 2026-10.9, say, the report of compiler 0.5.0, the last release before them; and 2026-10.12 breaks code procedures written for 2026-10.11. 2026-10.20 is a third, for <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 takes all of these as before, until 0.24.</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; | |
| 45 | +import Out; | |
| 46 | + | |
| 47 | +proc main*; | |
| 48 | +begin | |
| 49 | + Out.str("hello, world\n"); | |
| 50 | +end; | |
| 51 | + | |
| 52 | +end 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 | |
| 59 | +extern for forward if import in link match mod module not of or packed | |
| 60 | +proc record repeat return set shl shr then to try type until var | |
| 61 | +variant 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; | |
| 72 | +begin | |
| 73 | + Out.str(` | |
| 74 | + usage: tool [-v] file ... | |
| 75 | + -v say what is done | |
| 76 | + `); | |
| 77 | +end;</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>+ - * / & | ~ = # < <= > >= := : ; , . .. ... ( ) [ ] { } ^</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 = "module" ident [ "(" ModParams ")" ] ";" | |
| 87 | + { Import } { Link } [ Check ] { Declaration } | |
| 88 | + [ "begin" Statements ] "end" ident "." . | |
| 89 | +ModParams = ident { "," ident } { ";" ident ":" "proc" Signature } . | |
| 90 | +Import = "import" ImportItem { "," ImportItem } ";" . | |
| 91 | +ImportItem = ident [ ":=" ident [ "(" Type { "," Type } ")" ] ] . | |
| 92 | +Link = "link" ( string | "static" ) ";" . | |
| 93 | +Check = "check" "off" ";" .</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); | |
| 108 | +type | |
| 109 | + Node* = record next*: ^Node; val*: T; end; | |
| 110 | +... | |
| 111 | +end 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([]U8, Colour, Str.hash, Str.eq); | |
| 115 | + | |
| 116 | +type Colour = (red, green, blue); | |
| 117 | + | |
| 118 | +var 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([]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 = "const" { IdentDef [ ":" Type ] "=" Expr ";" } | |
| 139 | + | "type" { IdentDef "=" Type ";" } | |
| 140 | + | "var" { IdentList ":" Type ";" } | |
| 141 | + | ProcDeclaration ";" | |
| 142 | + | ExternDeclaration ";" . | |
| 143 | +IdentDef = ident [ "*" ] . | |
| 144 | +IdentList = IdentDef { "," 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 = "the cat"; | |
| 148 | + Line = Text + "\n"; | |
| 149 | +... | |
| 150 | +w := Text[4..7]; (* "cat" *)</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]; | |
| 153 | +type Rule = record class: []const U8; tag: INT; float: BOOL; end; | |
| 154 | +const Rules: [2]Rule = [{class: "firefox", tag: 2}, {class: "mpv", float: true}]; | |
| 155 | +const Shapes: []Shape = [circle(1.0), rect(2.0, 3.0), dot]; (* Shape of section 5.6 *) | |
| 156 | +const Rows: [][]const INT = [[1, 2], [3]]; (* each row an array constant of its own *) | |
| 157 | +... | |
| 158 | +p := 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 | + | "[" Expr "]" Type (* array *) | |
| 168 | + | "[" "]" [ "const" ] Type (* slice *) | |
| 169 | + | "^" [ "VOLATILE" ] Type (* pointer *) | |
| 170 | + | [ "packed" ] "record" { IdentList ":" Type ";" } "end" | |
| 171 | + | "variant" { Case ";" } "end" | |
| 172 | + | "(" ident { "," ident } ")" (* enumeration *) | |
| 173 | + | "set" "of" QualIdent | |
| 174 | + | "proc" Signature . | |
| 175 | +Case = ident [ "(" FieldList { ";" FieldList } ")" ] . | |
| 176 | +FieldList = ident { "," ident } ":" Type . | |
| 177 | +QualIdent = [ ident "." ] 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); | |
| 264 | +proc rule; (* a procedure, beside Elem's rule *) | |
| 265 | +... | |
| 266 | +s := Style.bold; e := Elem.bold; e := Elem.rule; | |
| 267 | +e := para; (* para is Elem's alone *) | |
| 268 | +rule; (* the procedure *) | |
| 269 | +s := 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 = "not found";</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 | +... | |
| 279 | +n, err := Table.find(7); | |
| 280 | +if 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; | |
| 305 | +n := s[i]; (* an element: widens *) | |
| 306 | +n := n * 10 + s[i] - '0'; (* n * 10 + s[i] is an INT, and so the rest *) | |
| 307 | +d := s[i] - '0'; (* an error: a U8, which may have wrapped *) | |
| 308 | +d := INT(s[i]) - '0'; (* below '0' too, it is negative *)</code></pre> | |
| 309 | +<h1 id="expressions">6. Expressions</h1> | |
| 310 | +<pre><code>Expr = Conjunct { "or" Conjunct } . | |
| 311 | +Conjunct = Relation { "and" Relation } . | |
| 312 | +Relation = SimpleExpr [ RelOp SimpleExpr ] . | |
| 313 | +RelOp = "=" | "#" | "<" | "<=" | ">" | ">=" | "in" . | |
| 314 | +SimpleExpr = [ "-" ] Term { AddOp Term } . | |
| 315 | +AddOp = "+" | "-" | "|" | "xor" . | |
| 316 | +Term = Factor { MulOp Factor } . | |
| 317 | +MulOp = "*" | "/" | "div" | "mod" | "&" | "shl" | "shr" . | |
| 318 | +Factor = number | char | string | Designator | "(" Expr ")" | |
| 319 | + | "not" Factor | "~" Factor | |
| 320 | + | "[" [ Expr { "," Expr } ] "]" | |
| 321 | + | "{" [ Element { "," Element } ] "}" | |
| 322 | + | "^" [ "VOLATILE" ] Type "(" Expr ")" | |
| 323 | + | "try" Designator . | |
| 324 | +Element = Expr | ident ":" Expr . | |
| 325 | +Designator = QualIdent { Selector } . | |
| 326 | +Selector = "." ident | "^" | "[" Expr [ ".." Expr ] "]" | |
| 327 | + | "(" [ Expr { "," Expr } ] ")" | "." "(" Type ")" .</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 & 0FH = 0</code> is <code>(x & 0FH) = 0</code>, and <code>i < n and a[i] # 0 or done</code> is <code>((i < 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>&</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 & | 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 < LEN(s)</code> is an error, and <code>i</code> should be an <code>INT</code>; with <code>c: U8</code>, <code>c < 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>&</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 < 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 < 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>= # < <= > >=</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 <= lo <= hi <= 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: 'A', attr: 7}; | |
| 359 | +Fmt.print("{} of {}\n", [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><=</code> and <code>>=</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 < 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 *) | |
| 560 | +n := 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 | + | |
| 565 | +proc valueOf(s: []const U8): Value; | |
| 566 | +begin | |
| 567 | + return {n: LEN(s), p: SYSTEM.PTR(s)}; (* "" too *) | |
| 568 | +end;</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 *) | |
| 573 | +FILL(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 | + | |
| 580 | +mem[16].(I64) := -1; (* the 8 bytes mem[16] to mem[23] now hold -1 *) | |
| 581 | +n := mem[16].(I64); (* and are read back as an I64: n is -1 *) | |
| 582 | +bits := 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; | |
| 585 | +var buf: [512]U8; k: U32; | |
| 586 | + | |
| 587 | +k := buf[0].(Header).count; (* bytes 4 to 7 of buf, as a U32 *) | |
| 588 | +buf[0].(Header).count := 0; | |
| 589 | +INC(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])); | |
| 603 | +p^ := 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 ";" } . | |
| 608 | +Statement = Designator [ ":=" Expr ] | |
| 609 | + | "_" ":=" Expr | |
| 610 | + | Target "," Target { "," Target } ":=" Expr | |
| 611 | + | "if" Expr "then" Statements | |
| 612 | + { "elsif" Expr "then" Statements } [ "else" Statements ] "end" | |
| 613 | + | "while" Expr "do" Statements "end" | |
| 614 | + | "repeat" Statements "until" Expr | |
| 615 | + | "for" ident ":=" Expr "to" Expr [ "by" Expr ] "do" Statements "end" | |
| 616 | + | "match" Expr "of" { "|" Arm } "end" | |
| 617 | + | "return" [ Expr { "," Expr } ] | |
| 618 | + | "break" | |
| 619 | + | "continue" | |
| 620 | + | "defer" Statement | |
| 621 | + | "try" Designator . | |
| 622 | +Arm = ( ident { "." ident } [ "(" ident { "," ident } ")" ] | |
| 623 | + | Label { "," Label } | "else" ) ":" Statements . | |
| 624 | +Label = Expr [ ".." Expr ] . | |
| 625 | +Target = Designator | "_" .</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 <= b</code> (or <code>i >= 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 <= b</code> and <code>b - i < 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 <= 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 < 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 | + ... | |
| 642 | +end;</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 *) | |
| 647 | +begin | |
| 648 | + return h[0..8]; (* an error: h is the procedure's copy *) | |
| 649 | +end;</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; | |
| 656 | +end;</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: | |
| 663 | +end;</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 | +| ' ', '\t': skip := true; | |
| 669 | +| '0' .. '9': digit := true; | |
| 670 | +| else: | |
| 671 | +end;</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 | +| "add", "plus": op := add; | |
| 676 | +| "sub": op := sub; | |
| 677 | +| else: op := none; | |
| 678 | +end;</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; | |
| 690 | +import Sys, Out; | |
| 691 | + | |
| 692 | +(* Prints the first line of the file at path. *) | |
| 693 | +proc head(path: []U8): BOOL; | |
| 694 | +var fd, n, i: INT; buf: [256]U8; | |
| 695 | +begin | |
| 696 | + fd := Sys.openRead(path); | |
| 697 | + if fd < 0 then return false; end; | |
| 698 | + defer Sys.close(fd); | |
| 699 | + n := Sys.read(fd, buf); | |
| 700 | + if n < 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; | |
| 707 | +end; | |
| 708 | + | |
| 709 | +proc main*; | |
| 710 | +begin | |
| 711 | + if not head("/etc/hostname") then Out.str("no hostname\n"); end; | |
| 712 | +end; | |
| 713 | + | |
| 714 | +end 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); | |
| 719 | +var i, sum: INT; | |
| 720 | +begin | |
| 721 | + for i := 0 to LEN(words) - 1 do | |
| 722 | + sum := sum + try number(words[i]); | |
| 723 | + end; | |
| 724 | + return sum, nil; | |
| 725 | +end;</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); | |
| 730 | +if 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 = "proc" IdentDef Signature ";" | |
| 751 | + ( "forward" | { LocalDeclaration } "begin" Statements "end" [ ident ] | |
| 752 | + | "code" { [ ident ":" ] [ Instruction ] ";" } "end" [ ident ] ) . | |
| 753 | +LocalDeclaration = "const" { ident [ ":" Type ] "=" Expr ";" } | |
| 754 | + | "type" { ident "=" Type ";" } | |
| 755 | + | "var" { ident { "," ident } ":" Type ";" } . | |
| 756 | +Signature = "(" [ Params { ";" Params } [ ";" "..." ] ] ")" [ ":" Results ] | |
| 757 | + | [ ":" Results ] . | |
| 758 | +Params = [ "var" | "const" ] ident { "," ident } ":" Type . | |
| 759 | +Results = Type | "(" Type { "," Type } ")" .</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 | + | |
| 765 | +proc current(const p: Parser): []U8; (* reads p, many words, in place *) | |
| 766 | +begin | |
| 767 | + return p.args[p.at]; | |
| 768 | +end; | |
| 769 | + | |
| 770 | +proc advance(var p: Parser); (* changes p *) | |
| 771 | +begin | |
| 772 | + INC(p.at); | |
| 773 | +end;</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('a')[0..4]; (* f returns a [8]U8: s is good to the end of the procedure *) | |
| 778 | +t := f('b')[0..4]; (* a hidden variable of its own: s is unchanged *)</code></pre> | |
| 779 | +<pre><code>module Divide; | |
| 780 | +import Out; | |
| 781 | + | |
| 782 | +proc divmod(a, b: I64): (I64, I64); | |
| 783 | +begin | |
| 784 | + return a div b, a mod b; | |
| 785 | +end; | |
| 786 | + | |
| 787 | +proc main*; | |
| 788 | +var q, r: I64; | |
| 789 | +begin | |
| 790 | + q, r := divmod(17, 5); | |
| 791 | + Out.int(q); Out.str(" rest "); Out.int(r); Out.ln; | |
| 792 | +end; | |
| 793 | + | |
| 794 | +end 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; | |
| 800 | +code | |
| 801 | + rdtsc; | |
| 802 | + shl rdx, 32; | |
| 803 | + or rax, rdx; | |
| 804 | + ret; | |
| 805 | +end 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. 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 = "extern" ( "proc" IdentDef Signature | |
| 810 | + | "var" IdentDef ":" Type ) .</code></pre> | |
| 811 | +<pre><code>link "libX11.so.6"; | |
| 812 | +extern proc XOpenDisplay(name: ^U8): ^U8; | |
| 813 | +extern proc printf(format: ^U8; ...): I32; | |
| 814 | +extern 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 | +... | |
| 821 | +XNextEvent(dpy, SYSTEM.ADR(ev)); | |
| 822 | +if I32(ev[0]) = KeyPress then | |
| 823 | + key := ^XKeyEvent(SYSTEM.ADR(ev)); | |
| 824 | + ... | |
| 825 | +end;</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 *) | |
| 831 | +proc exit*(status: INT); | |
| 832 | +proc 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 | +<h1 id="versions">11. Versions</h1> | |
| 838 | +<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> | |
| 839 | +<p>The history of the versions, what each changed, is in <code>doc/report-history.md</code>.</p> | |
| 840 | +<h1 id="appendix-a.-what-an-implementation-chooses">Appendix A. What an implementation chooses</h1> | |
| 841 | +<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> | |
| 842 | +<ul> | |
| 843 | +<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> | |
| 844 | +<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> | |
| 845 | +<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> | |
| 846 | +<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> | |
| 847 | +<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> | |
| 848 | +<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> | |
| 849 | +<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> | |
| 850 | +<li><strong>The executable.</strong> Its format, and the names and line numbers it carries for a debugger (section 10).</li> | |
| 851 | +<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> | |
| 852 | +<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> | |
| 853 | +<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> | |
| 854 | +<li><strong>The command line.</strong> How the compiler is run, its options, and where its library lives (sections 1 and 3).</li> | |
| 855 | +</ul> | |
| 856 | +<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> | |
| 857 | +<h1 id="appendix-b.-the-grammar">Appendix B. The grammar</h1> | |
| 858 | +<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> | |
| 859 | +<pre><code>ident = letter { letter | digit } . | |
| 860 | +letter = "A" .. "Z" | "a" .. "z" | "_" . | |
| 861 | +digit = "0" .. "9" . | |
| 862 | +hexDigit = digit | "A" .. "F" . | |
| 863 | +number = digit { digit } | |
| 864 | + | digit { hexDigit } "H" | |
| 865 | + | digit { digit } "." digit { digit } [ "E" [ "+" | "-" ] digit { digit } ] . | |
| 866 | +char = "'" ( character | escape ) "'" . | |
| 867 | +string = '"' { character | escape | "\x" anyHex anyHex } '"' | |
| 868 | + | "`" { rawChar } "`" . | |
| 869 | +escape = "\n" | "\t" | "\r" | "\0" | "\\" | "\'" | '\"' | |
| 870 | + | "\u{" anyHex { anyHex } "}" . | |
| 871 | +anyHex = hexDigit | "a" .. "f" . | |
| 872 | + | |
| 873 | +Module = "module" ident [ "(" ModParams ")" ] ";" | |
| 874 | + { Import } { Link } [ Check ] { Declaration } | |
| 875 | + [ "begin" Statements ] "end" ident "." . | |
| 876 | +ModParams = ident { "," ident } { ";" ident ":" "proc" Signature } . | |
| 877 | +Import = "import" ImportItem { "," ImportItem } ";" . | |
| 878 | +ImportItem = ident [ ":=" ident [ "(" Type { "," Type } ")" ] ] . | |
| 879 | +Link = "link" ( string | "static" ) ";" . | |
| 880 | +Check = "check" "off" ";" . | |
| 881 | + | |
| 882 | +Declaration = "const" { IdentDef [ ":" Type ] "=" Expr ";" } | |
| 883 | + | "type" { IdentDef "=" Type ";" } | |
| 884 | + | "var" { IdentList ":" Type ";" } | |
| 885 | + | ProcDeclaration ";" | |
| 886 | + | ExternDeclaration ";" . | |
| 887 | +IdentDef = ident [ "*" ] . | |
| 888 | +IdentList = IdentDef { "," IdentDef } . | |
| 889 | + | |
| 890 | +Type = QualIdent | |
| 891 | + | "[" Expr "]" Type | |
| 892 | + | "[" "]" [ "const" ] Type | |
| 893 | + | "^" [ "VOLATILE" ] Type | |
| 894 | + | [ "packed" ] "record" { IdentList ":" Type ";" } "end" | |
| 895 | + | "variant" { Case ";" } "end" | |
| 896 | + | "(" ident { "," ident } ")" | |
| 897 | + | "set" "of" QualIdent | |
| 898 | + | "proc" Signature . | |
| 899 | +Case = ident [ "(" FieldList { ";" FieldList } ")" ] . | |
| 900 | +FieldList = ident { "," ident } ":" Type . | |
| 901 | +QualIdent = [ ident "." ] ident . | |
| 902 | + | |
| 903 | +Expr = Conjunct { "or" Conjunct } . | |
| 904 | +Conjunct = Relation { "and" Relation } . | |
| 905 | +Relation = SimpleExpr [ RelOp SimpleExpr ] . | |
| 906 | +RelOp = "=" | "#" | "<" | "<=" | ">" | ">=" | "in" . | |
| 907 | +SimpleExpr = [ "-" ] Term { AddOp Term } . | |
| 908 | +AddOp = "+" | "-" | "|" | "xor" . | |
| 909 | +Term = Factor { MulOp Factor } . | |
| 910 | +MulOp = "*" | "/" | "div" | "mod" | "&" | "shl" | "shr" . | |
| 911 | +Factor = number | char | string | Designator | "(" Expr ")" | |
| 912 | + | "not" Factor | "~" Factor | |
| 913 | + | "[" [ Expr { "," Expr } ] "]" | |
| 914 | + | "{" [ Element { "," Element } ] "}" | |
| 915 | + | "^" [ "VOLATILE" ] Type "(" Expr ")" | |
| 916 | + | "try" Designator . | |
| 917 | +Element = Expr | ident ":" Expr . | |
| 918 | +Designator = QualIdent { Selector } . | |
| 919 | +Selector = "." ident | "^" | "[" Expr [ ".." Expr ] "]" | |
| 920 | + | "(" [ Expr { "," Expr } ] ")" | "." "(" Type ")" . | |
| 921 | + | |
| 922 | +Statements = { Statement ";" } . | |
| 923 | +Statement = Designator [ ":=" Expr ] | |
| 924 | + | "_" ":=" Expr | |
| 925 | + | Target "," Target { "," Target } ":=" Expr | |
| 926 | + | "if" Expr "then" Statements | |
| 927 | + { "elsif" Expr "then" Statements } [ "else" Statements ] "end" | |
| 928 | + | "while" Expr "do" Statements "end" | |
| 929 | + | "repeat" Statements "until" Expr | |
| 930 | + | "for" ident ":=" Expr "to" Expr [ "by" Expr ] "do" Statements "end" | |
| 931 | + | "match" Expr "of" { "|" Arm } "end" | |
| 932 | + | "return" [ Expr { "," Expr } ] | |
| 933 | + | "break" | |
| 934 | + | "continue" | |
| 935 | + | "defer" Statement | |
| 936 | + | "try" Designator . | |
| 937 | +Arm = ( ident { "." ident } [ "(" ident { "," ident } ")" ] | |
| 938 | + | Label { "," Label } | "else" ) ":" Statements . | |
| 939 | +Label = Expr [ ".." Expr ] . | |
| 940 | +Target = Designator | "_" . | |
| 941 | + | |
| 942 | +ProcDeclaration = "proc" IdentDef Signature ";" | |
| 943 | + ( "forward" | { LocalDeclaration } "begin" Statements "end" [ ident ] | |
| 944 | + | "code" { [ ident ":" ] [ Instruction ] ";" } "end" [ ident ] ) . | |
| 945 | +LocalDeclaration = "const" { ident [ ":" Type ] "=" Expr ";" } | |
| 946 | + | "type" { ident "=" Type ";" } | |
| 947 | + | "var" { ident { "," ident } ":" Type ";" } . | |
| 948 | +Signature = "(" [ Params { ";" Params } [ ";" "..." ] ] ")" [ ":" Results ] | |
| 949 | + | [ ":" Results ] . | |
| 950 | +Params = [ "var" | "const" ] ident { "," ident } ":" Type . | |
| 951 | +Results = Type | "(" Type { "," Type } ")" . | |
| 952 | +ExternDeclaration = "extern" ( "proc" IdentDef Signature | |
| 953 | + | "var" IdentDef ":" Type ) .</code></pre> | |
| 954 | +<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> | |
| 955 | +<h1 id="the-library-volume-2">The library, volume 2</h1> | |
| 956 | +<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> | |
| 957 | +<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> | |
| 958 | +<p>Modules written in raz, in the compiler’s <code>lib</code> directory:</p> | |
| 959 | +<table> | |
| 960 | +<thead> | |
| 961 | +<tr> | |
| 962 | +<th>Module</th> | |
| 963 | +<th>What</th> | |
| 964 | +</tr> | |
| 965 | +</thead> | |
| 966 | +<tbody> | |
| 967 | +<tr> | |
| 968 | +<td><code>Rt</code></td> | |
| 969 | +<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> | |
| 970 | +</tr> | |
| 971 | +<tr> | |
| 972 | +<td><code>Sys</code></td> | |
| 973 | +<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> | |
| 974 | +</tr> | |
| 975 | +<tr> | |
| 976 | +<td><code>Out</code></td> | |
| 977 | +<td>writing text and numbers to standard output, buffered; safe to call from several threads</td> | |
| 978 | +</tr> | |
| 979 | +<tr> | |
| 980 | +<td><code>C</code></td> | |
| 981 | +<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> | |
| 982 | +</tr> | |
| 983 | +<tr> | |
| 984 | +<td><code>Lock</code></td> | |
| 985 | +<td>a lock for short sections, for C’s threads and <code>Thread</code>’s alike</td> | |
| 986 | +</tr> | |
| 987 | +<tr> | |
| 988 | +<td><code>Thread</code></td> | |
| 989 | +<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> | |
| 990 | +</tr> | |
| 991 | +<tr> | |
| 992 | +<td><code>Task</code></td> | |
| 993 | +<td>a thread given a value of its own, <code>Task(T)</code>: <code>spawn</code> copies it, with no cast</td> | |
| 994 | +</tr> | |
| 995 | +<tr> | |
| 996 | +<td><code>Guarded</code></td> | |
| 997 | +<td>a value with its lock, <code>Guarded(T)</code>: reached only through <code>with</code></td> | |
| 998 | +</tr> | |
| 999 | +<tr> | |
| 1000 | +<td><code>Mem</code></td> | |
| 1001 | +<td><code>Allocator</code>, the interface of every allocator, and pages from the system</td> | |
| 1002 | +</tr> | |
| 1003 | +<tr> | |
| 1004 | +<td><code>Heap</code></td> | |
| 1005 | +<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> | |
| 1006 | +</tr> | |
| 1007 | +<tr> | |
| 1008 | +<td><code>Arena</code></td> | |
| 1009 | +<td>an allocator that frees everything at once; <code>ADR(arena.base)</code> is its allocator</td> | |
| 1010 | +</tr> | |
| 1011 | +<tr> | |
| 1012 | +<td><code>Str</code></td> | |
| 1013 | +<td>operations on <code>[]U8</code> strings: comparing, hashing, finding, trimming and cutting, case, joining and replacing, UTF-8, numbers to and from text</td> | |
| 1014 | +</tr> | |
| 1015 | +<tr> | |
| 1016 | +<td><code>Bytes</code></td> | |
| 1017 | +<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> | |
| 1018 | +</tr> | |
| 1019 | +<tr> | |
| 1020 | +<td><code>Buf</code></td> | |
| 1021 | +<td>a growable byte buffer</td> | |
| 1022 | +</tr> | |
| 1023 | +<tr> | |
| 1024 | +<td><code>Fmt</code></td> | |
| 1025 | +<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> | |
| 1026 | +</tr> | |
| 1027 | +<tr> | |
| 1028 | +<td><code>List</code></td> | |
| 1029 | +<td>a generic singly linked list, <code>List(T)</code></td> | |
| 1030 | +</tr> | |
| 1031 | +<tr> | |
| 1032 | +<td><code>Map</code></td> | |
| 1033 | +<td>a generic hash map, <code>Map(K, V; hash, eq)</code></td> | |
| 1034 | +</tr> | |
| 1035 | +<tr> | |
| 1036 | +<td><code>Vec</code></td> | |
| 1037 | +<td>a generic growable array, <code>Vec(T)</code>, indexed as a slice</td> | |
| 1038 | +</tr> | |
| 1039 | +<tr> | |
| 1040 | +<td><code>Sort</code></td> | |
| 1041 | +<td>sorting a slice in place, <code>Sort(T; less)</code></td> | |
| 1042 | +</tr> | |
| 1043 | +<tr> | |
| 1044 | +<td><code>Math</code></td> | |
| 1045 | +<td>roots, powers, logarithms, rounding and trigonometry, and <code>pi</code>, for <code>F64</code></td> | |
| 1046 | +</tr> | |
| 1047 | +<tr> | |
| 1048 | +<td><code>Files</code></td> | |
| 1049 | +<td>an argument as a string, and a whole file read or written</td> | |
| 1050 | +</tr> | |
| 1051 | +<tr> | |
| 1052 | +<td><code>Opt</code></td> | |
| 1053 | +<td>a command line read through one table, by <code>getopt</code>’s rules with long options; its help and its mistakes</td> | |
| 1054 | +</tr> | |
| 1055 | +<tr> | |
| 1056 | +<td><code>Width</code></td> | |
| 1057 | +<td>how many columns of a terminal a character, or a string, takes: 0, 1 or 2, as <code>wcwidth</code> says</td> | |
| 1058 | +</tr> | |
| 1059 | +<tr> | |
| 1060 | +<td><code>Rand</code></td> | |
| 1061 | +<td>a seeded random number generator, splitmix64: the same seed, the same numbers; for tests and simulations, not secrets</td> | |
| 1062 | +</tr> | |
| 1063 | +<tr> | |
| 1064 | +<td><code>Check</code></td> | |
| 1065 | +<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> | |
| 1066 | +</tr> | |
| 1067 | +<tr> | |
| 1068 | +<td><code>Prop</code></td> | |
| 1069 | +<td>property tests and fuzzing: a property draws values, a failing case is shrunk and saved, and run first next time</td> | |
| 1070 | +</tr> | |
| 1071 | +</tbody> | |
| 1072 | +</table> | |
| 1073 | +<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> | |
| 1074 | +<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> | |
| 1075 | +<pre><code>module Rt; | |
| 1076 | +const Full*: ERROR = "too many procedures to run at exit"; | |
| 1077 | +proc atExit*(p: proc): ERROR; (* p run when the program ends by exit *) | |
| 1078 | +proc exit*(status: INT); (* the atExit procedures, the last first, then the end *) | |
| 1079 | +proc exitStatus*: INT; (* the status exit was given, in an atExit procedure; 0 before *) | |
| 1080 | +proc stop*(msg: []U8); (* msg, and a line feed, on standard error, then exit with status 2 *) | |
| 1081 | +proc trace*; (* the calls under way, and their variables, on standard error *)</code></pre> | |
| 1082 | +<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> | |
| 1083 | +<pre><code>module Mem; | |
| 1084 | +type | |
| 1085 | + Allocator* = record | |
| 1086 | + alloc*: proc(a: ^Allocator; size, align: INT): ^U8; (* nil if out of room *) | |
| 1087 | + free*: proc(a: ^Allocator; p: ^U8); | |
| 1088 | + end; | |
| 1089 | +const Page* = 4096; | |
| 1090 | +proc pages*(size: INT): ^U8; (* size bytes, in whole pages, zeroed; or nil *) | |
| 1091 | +proc unmap*(p: ^U8; size: INT); (* pages given back *) | |
| 1092 | +proc alloc*(a: ^Allocator; size, align: INT): ^U8; (* a^.alloc(a, size, align) *) | |
| 1093 | +proc free*(a: ^Allocator; p: ^U8); (* a^.free(a, p) *) | |
| 1094 | + | |
| 1095 | +module Heap; | |
| 1096 | +proc debug*(on: BOOL); (* debug mode on or off, for the blocks given from now on *) | |
| 1097 | +var heap*: ^Mem.Allocator; | |
| 1098 | +var sure*: ^Mem.Allocator; (* heap, but running out of memory stops the program *) | |
| 1099 | + | |
| 1100 | +module Arena; | |
| 1101 | +type Arena* = record | |
| 1102 | + base*: Mem.Allocator; (* first, so that ^Arena(a) finds the rest *) | |
| 1103 | + ... | |
| 1104 | +end; | |
| 1105 | +proc init*(var ar: Arena; size: INT): BOOL; (* an arena of size bytes; false if the system has none *) | |
| 1106 | +proc mark*(const ar: Arena): INT; (* where ar stands now, for release *) | |
| 1107 | +proc release*(var ar: Arena; m: INT); (* all allocated since mark m freed; a mark past where it stands stops the program *) | |
| 1108 | +proc reset*(var ar: Arena); (* every allocation forgotten; the memory used again *) | |
| 1109 | +proc done*(var ar: Arena); (* its memory given back *)</code></pre> | |
| 1110 | +<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> | |
| 1111 | +<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> | |
| 1112 | +<pre><code>module Lock; | |
| 1113 | +type Lock* = record ... end; | |
| 1114 | +proc take*(var l: Lock); | |
| 1115 | +proc give*(var l: Lock); | |
| 1116 | + | |
| 1117 | +module Thread; | |
| 1118 | +const Failed*: ERROR = "can't start a thread"; | |
| 1119 | +type | |
| 1120 | + Thread* = record ... end; | |
| 1121 | + Mutex* = record ... end; (* zero is free *) | |
| 1122 | +proc spawn*(p: proc(arg: ^U8); arg: ^U8): (^Thread, ERROR); (* p(arg) in a new thread *) | |
| 1123 | +proc join*(t: ^Thread); (* waits for t to end, then frees its stack *) | |
| 1124 | +proc signal*(t: ^Thread; sig: INT): INT; (* sig sent to t alone: 0, or minus an errno *) | |
| 1125 | +proc lock*(var m: Mutex); | |
| 1126 | +proc unlock*(var m: Mutex); | |
| 1127 | + | |
| 1128 | +module Task(T); | |
| 1129 | +proc spawn*(p: proc(var x: T); x: T): (^Thread.Thread, ERROR); (* p run on a copy of x in a new thread *) | |
| 1130 | + | |
| 1131 | +module Guarded(T); | |
| 1132 | +type Guarded* = record ... end; (* a value and its Thread.Mutex; zero is ready *) | |
| 1133 | +proc with*(var g: Guarded; p: proc(var x: T)); (* p run on the value, under the lock *)</code></pre> | |
| 1134 | +<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> | |
| 1135 | +<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> | |
| 1136 | +<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> | |
| 1137 | +<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> | |
| 1138 | +<pre><code>module Out; | |
| 1139 | +proc str*(s: []U8); | |
| 1140 | +proc char*(c: U8); | |
| 1141 | +proc ln*; (* a line feed *) | |
| 1142 | +proc int*(n: I64); (* n in decimal *) | |
| 1143 | +proc hex*(n: U64; digits: INT); (* n in hexadecimal, digits digits at least *) | |
| 1144 | +proc flush*; | |
| 1145 | +proc lines*(on: BOOL); (* written at each line feed, or only when full *)</code></pre> | |
| 1146 | +<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> | |
| 1147 | +<pre><code>module Both; | |
| 1148 | +import Out, C; (* C: printf, fflush and C's FILE *stdout *) | |
| 1149 | + | |
| 1150 | +proc main*; | |
| 1151 | +begin | |
| 1152 | + Out.str("from raz\n"); | |
| 1153 | + Out.flush; | |
| 1154 | + C.printf("from C\n"); | |
| 1155 | + C.fflush(C.stdout); | |
| 1156 | + Out.str("from raz again\n"); | |
| 1157 | +end; | |
| 1158 | + | |
| 1159 | +end Both.</code></pre> | |
| 1160 | +<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> | |
| 1161 | +<pre><code>module Sys; | |
| 1162 | +const | |
| 1163 | + stdin* = 0; stdout* = 1; stderr* = 2; | |
| 1164 | + outSize* = 4096; (* the bytes Out keeps; each target has its own *) | |
| 1165 | + (* signals, by their numbers on Linux; each target has its own *) | |
| 1166 | + sigHup* = 1; sigInt* = 2; sigQuit* = 3; sigKill* = 9; sigPipe* = 13; | |
| 1167 | + sigTerm* = 15; sigChld* = 17; sigCont* = 18; sigStop* = 19; | |
| 1168 | + sigTstp* = 20; sigTtin* = 21; sigTtou* = 22; sigWinch* = 28; | |
| 1169 | + sigUsr1* = 10; sigUsr2* = 12; sigAlrm* = 14; | |
| 1170 | + (* the limits limit and setLimit take, by their numbers on Linux; each target has its own *) | |
| 1171 | + limitCpu* = 0; limitFileSize* = 1; limitData* = 2; limitStack* = 3; | |
| 1172 | + limitCore* = 4; limitProcs* = 6; limitFiles* = 7; limitMemory* = 9; | |
| 1173 | + (* errors, minus Linux's errnos on every target *) | |
| 1174 | + errPerm* = -1; errNoEntry* = -2; errNoProcess* = -3; errIntr* = -4; | |
| 1175 | + errIo* = -5; errBadFd* = -9; errChild* = -10; errAgain* = -11; | |
| 1176 | + errNoMemory* = -12; errDenied* = -13; errExists* = -17; | |
| 1177 | + errNotDir* = -20; errIsDir* = -21; errInvalid* = -22; | |
| 1178 | + errNotTerminal* = -25; errNoSpace* = -28; errPipe* = -32; | |
| 1179 | + errNameTooLong* = -36; errNotEmpty* = -39; errLoop* = -40; | |
| 1180 | + errAddrInUse* = -98; errNetUnreach* = -101; errConnAborted* = -103; errConnReset* = -104; | |
| 1181 | + errTimedOut* = -110; errRefused* = -111; errHostUnreach* = -113; | |
| 1182 | + errInProgress* = -115; | |
| 1183 | + | |
| 1184 | +type | |
| 1185 | + Access* = (reading, writing, creating, exclusive, truncating, appending, executing, nonblocking); | |
| 1186 | + Accesses* = set of Access; | |
| 1187 | + Info* = record | |
| 1188 | + size*: I64; (* in bytes *) | |
| 1189 | + mtime*: I64; (* when its contents last changed, in nanoseconds since 1970 *) | |
| 1190 | + seconds*: I64; (* mtime in whole seconds, rounded down: exact past 2262 and before 1677, where mtime wraps *) | |
| 1191 | + mode*: INT; (* its permission bits, as chmod takes them: 1EDH is rwxr-xr-x *) | |
| 1192 | + dir*: BOOL; (* a directory *) | |
| 1193 | + file*: BOOL; (* a regular file: not a directory, device, pipe or socket *) | |
| 1194 | + symlink*: BOOL; (* the path itself is a symbolic link *) | |
| 1195 | + ino*: U64; (* its inode, which a rename keeps and a new file doesn't *) | |
| 1196 | + dev*: U64; (* the file system it is on; with ino, it names the file *) | |
| 1197 | + links*: U64; (* how many names it has: 1 for a file no hard link shares *) | |
| 1198 | + special*: INT; (* its set-user-id, set-group-id and sticky bits, as chmod takes them: 800H, 400H, 200H *) | |
| 1199 | + uid*: INT; (* its owner's user number *) | |
| 1200 | + gid*: INT; (* its group's number *) | |
| 1201 | + end; | |
| 1202 | + Kind* = (unknown, isFile, isDir, isLink, isOther); (* what a directory says a name in it is *) | |
| 1203 | + Dir* = record ... end; (* an open directory; its fields are the target's *) | |
| 1204 | + Program* = record | |
| 1205 | + path*: []U8; | |
| 1206 | + args*: [][]U8; (* the first is its name *) | |
| 1207 | + env*: [][]U8; (* NAME=value, each added to this program's environment *) | |
| 1208 | + onlyEnv*: BOOL; (* env is its whole environment *) | |
| 1209 | + dir*: []U8; (* its working directory; "" for this program's *) | |
| 1210 | + fds*: [3]INT; (* its standard input, output and error; 0 for this program's own *) | |
| 1211 | + group*: INT; (* the process group it joins: 0 for this program's, -1 a new one it leads *) | |
| 1212 | + foreground*: BOOL; (* its group takes the terminal on standard input *) | |
| 1213 | + tty*: INT; (* a pseudo-terminal's fd, to start a session on; 0 for none *) | |
| 1214 | + more*: []INT; (* fds above 2 passed on to it, at the same numbers *) | |
| 1215 | + keepIgnored*: BOOL; (* signals this program ignores stay ignored in it *) | |
| 1216 | + end; | |
| 1217 | + Status* = (running, exited, killed, stopped); | |
| 1218 | + Mode* = record ... end; (* a terminal's modes; its fields are the target's *) | |
| 1219 | + Peer* = record ... end; (* whom a datagram came from *) | |
| 1220 | + Remote* = record (* who is at the other end of a connected socket *) | |
| 1221 | + unix*: BOOL; (* a Unix socket: uid and pid say who *) | |
| 1222 | + ipv6*: BOOL; (* addr is 16 bytes of IPv6, else 4 bytes of IPv4 then zeros *) | |
| 1223 | + addr*: [16]U8; | |
| 1224 | + port*: INT; | |
| 1225 | + uid*, pid*: INT; | |
| 1226 | + end; | |
| 1227 | + Poll* = record (* a descriptor for poll to wait on *) | |
| 1228 | + fd*: INT; | |
| 1229 | + read*, write*: BOOL; (* wait until it may be read, written *) | |
| 1230 | + ready*: BOOL; (* set by poll *) | |
| 1231 | + end; | |
| 1232 | + | |
| 1233 | +proc write*(fd: INT; s: []U8): INT; (* the bytes written *) | |
| 1234 | +proc read*(fd: INT; buf: []U8): INT; (* the bytes read; 0 at the end *) | |
| 1235 | +proc open*(path: []U8; how: Accesses): INT; (* its fd, closed on exec *) | |
| 1236 | +proc openMode*(path: []U8; how: Accesses; mode: INT): INT; (* open, a file it makes given mode *) | |
| 1237 | +proc openRead*(path: []U8): INT; (* open(path, {reading}) *) | |
| 1238 | +proc create*(path: []U8): INT; (* open(path, {writing, creating, truncating}) *) | |
| 1239 | +proc seek*(fd: INT; pos: I64; fromEnd: BOOL): I64; (* the new position *) | |
| 1240 | +proc position*(fd: INT): I64; (* where the next read or write is *) | |
| 1241 | +proc truncate*(fd: INT; size: I64): INT; (* the file made size bytes long *) | |
| 1242 | +proc sync*(fd: INT): INT; (* what was written to it, on the disk *) | |
| 1243 | +proc syncAll*(fd: INT): INT; (* all that was written to its file system, on the disk *) | |
| 1244 | +proc lock*(fd: INT; wait: BOOL): INT; (* the file's lock, held until fd is closed *) | |
| 1245 | +proc lockShared*(fd: INT; wait: BOOL): INT; (* lock, shared with others that ask it so *) | |
| 1246 | +proc close*(fd: INT); | |
| 1247 | +proc closeChecked*(fd: INT): INT; (* close, and 0 or minus the errno it failed with *) | |
| 1248 | +proc dup*(fd: INT): INT; (* a new fd for the same file, the lowest free *) | |
| 1249 | +proc dupTo*(fd, into: INT): INT; (* into made the same file as fd, closing what it was *) | |
| 1250 | +proc dupAbove*(fd, least: INT): INT; (* a new fd for the same file, the lowest free from least on, closed on exec *) | |
| 1251 | +proc keepOnExec*(fd: INT; yes: BOOL): INT; (* fd left open, or not (as at first for a file made by open or pipe), in the program exec runs *) | |
| 1252 | +proc isTerminal*(fd: INT): BOOL; | |
| 1253 | +proc mapRead*(fd, size: INT): ^U8; (* the first size bytes of fd, which may be open only to read, mapped read only; or nil *) | |
| 1254 | +proc protect*(p: ^U8; size: INT; read, write: BOOL): INT; (* the pages at p readable and writable as asked; neither, and touching them stops the program *) | |
| 1255 | +proc mmap*(size: INT): ^U8; (* size bytes of zeroed memory, in whole pages; or nil *) | |
| 1256 | +proc munmap*(p: ^U8; size: INT); | |
| 1257 | +proc yield*; (* the processor given to another thread *) | |
| 1258 | +proc exit*(status: INT); (* the program ended at once, without Rt's atExit *) | |
| 1259 | + | |
| 1260 | +proc rename*(old, new: []U8): INT; (* replaces what new names *) | |
| 1261 | +proc remove*(path: []U8): INT; (* a file, not a directory *) | |
| 1262 | +proc removeDir*(path: []U8): INT; (* an empty directory *) | |
| 1263 | +proc makeDir*(path: []U8): INT; (* readable by all, writable by its owner *) | |
| 1264 | +proc makeDirMode*(path: []U8; mode: INT): INT; (* makeDir, given mode *) | |
| 1265 | +proc chmod*(path: []U8; mode: INT): INT; | |
| 1266 | +proc chown*(path: []U8; uid, gid: INT): INT; (* its owner and group; -1 leaves one as it is *) | |
| 1267 | +proc makeFifo*(path: []U8; mode: INT): INT; (* a named pipe, given mode *) | |
| 1268 | +proc setTime*(path: []U8; sec: I64; nsec: INT): INT; (* its mtime, and the time it was read, made sec and nsec *) | |
| 1269 | +proc access*(path: []U8; how: Accesses): INT; (* 0 if this user may read, write or execute it *) | |
| 1270 | +proc umask*(mask: INT): INT; (* the bits taken from every file made; the mask it was *) | |
| 1271 | +proc symlink*(target, path: []U8): INT; (* path made a link to target *) | |
| 1272 | +proc readLink*(path: []U8): ([]U8, INT); (* what the link names, good until the next call *) | |
| 1273 | +proc info*(path: []U8): (Info, INT); (* following a symbolic link *) | |
| 1274 | +proc linkInfo*(path: []U8): (Info, INT); (* the link itself *) | |
| 1275 | +proc infoOf*(fd: INT): (Info, INT); (* the open file's *) | |
| 1276 | +proc space*(path: []U8): (I64, I64, INT); (* the bytes free and in all on path's file system *) | |
| 1277 | + | |
| 1278 | +proc openDir*(var d: Dir; path: []U8): INT; | |
| 1279 | +proc nextEntry*(var d: Dir): ([]U8, BOOL); (* a name, good until the next call; false at the end *) | |
| 1280 | +proc entryKind*(const d: Dir): Kind; (* what the name nextEntry gave last is *) | |
| 1281 | +proc closeDir*(var d: Dir); | |
| 1282 | + | |
| 1283 | +proc rawMode*(fd: INT): BOOL; (* the terminal on fd: no echo, no lines, no signals *) | |
| 1284 | +proc restoreMode*(fd: INT); (* as rawMode found it *) | |
| 1285 | +proc getMode*(fd: INT): (Mode, INT); (* the terminal's modes, to set again *) | |
| 1286 | +proc setMode*(fd: INT; m: Mode): INT; (* once what was written to it is sent *) | |
| 1287 | +proc termSize*(fd: INT): (INT, INT); (* columns and rows; 80 and 24 if unknown *) | |
| 1288 | +proc ready*(fd, ms: INT): BOOL; (* something to read within ms, or ever if ms < 0 *) | |
| 1289 | +proc readyOf*(fds: []INT; ms: INT): INT; (* the first of fds with something to read within ms, or -1 *) | |
| 1290 | +proc readyFor*(reads, writes: []INT; ms: INT): INT; (* readyOf, and the first of writes with room to write *) | |
| 1291 | +proc poll*(var fds: []Poll; ms: INT): INT; (* sets each fd's ready, as each read and write say; the number ready, 0 on a timeout, or minus an errno *) | |
| 1292 | +proc setBlocking*(fd: INT; yes: BOOL): INT; (* if not yes, a read or write that would wait is -11 at once *) | |
| 1293 | +proc blocking*(fd: INT): INT; (* 1 if reads and writes wait, 0 if they are -11 at once, or minus an errno *) | |
| 1294 | + | |
| 1295 | +proc errorText*(err: INT): []U8; (* what errno err, or minus it, means, as C's strerror says *) | |
| 1296 | + | |
| 1297 | +proc env*(name: []U8): []U8; (* the environment variable's value; "" if unset *) | |
| 1298 | +proc findEnv*(name: []U8): ([]U8, BOOL); (* the value and true; "" and false if unset, "" and true if empty *) | |
| 1299 | +proc envAt*(i: INT): ([]U8, BOOL); (* the environment's ith NAME=value, from 0; false past the last *) | |
| 1300 | +proc setEnv*(name, value: []U8): INT; (* name set to value, for env and the programs started *) | |
| 1301 | +proc workDir*: ([]U8, INT); (* the working directory, good until the next call *) | |
| 1302 | +proc setWorkDir*(path: []U8): INT; | |
| 1303 | + | |
| 1304 | +proc pipe*: (INT, INT); (* the fd to read and the fd to write; or minus an errno and -1 *) | |
| 1305 | +proc openPty*: INT; (* a pseudo-terminal: the fd of its controlling side *) | |
| 1306 | +proc setTermSize*(fd, cols, rows: INT): INT; (* the size its programs are told of *) | |
| 1307 | +proc spawn*(p: Program): INT; (* a program started: its process id *) | |
| 1308 | +proc exec*(p: Program): INT; (* p run in this program's place; returns only if it can't *) | |
| 1309 | +proc execve*(path: []U8; args, env: [][]U8): INT; (* as the kernel's execve: no search *) | |
| 1310 | +proc fork*: INT; (* this program copied: 0 in the copy, its process id in this one *) | |
| 1311 | +proc setsid*: INT; (* a session of its own, led by this program: its process id, or minus an errno *) | |
| 1312 | +proc wait*(pid: INT; block: BOOL): (INT, Status, INT); (* which program, how, and its code *) | |
| 1313 | +proc waitExit*(pid: INT): (INT, Status, INT); (* as wait, but only for a program to end *) | |
| 1314 | +proc kill*(pid, signal: INT): INT; | |
| 1315 | +proc pid*: INT; (* this program's process id *) | |
| 1316 | +proc group*: INT; (* the process group this program is in *) | |
| 1317 | +proc setGroup*(pid, group: INT): INT; (* pid 0 is this program; group 0 a new one pid leads *) | |
| 1318 | +proc foreground*(fd, group: INT): INT; (* the terminal on fd gives its keys to group *) | |
| 1319 | +proc foregroundOf*(fd: INT): INT; (* the group the terminal on fd gives its keys to *) | |
| 1320 | +proc uid*: INT; (* the user this program runs as *) | |
| 1321 | +proc euid*: INT; (* the user whose rights it has: 0 is root *) | |
| 1322 | +proc hostName*: ([]U8, INT); (* this machine's name, good until the next call *) | |
| 1323 | +proc processors*: INT; (* the processors this program may run on, at least 1 *) | |
| 1324 | +proc cpuTime*(children: BOOL): (I64, I64); (* ns used in the program and in the system; or by its children *) | |
| 1325 | +proc limit*(which: INT): (I64, I64, INT); (* the soft limit and the hard; -1 for none *) | |
| 1326 | +proc setLimit*(which: INT; soft, hard: I64): INT; | |
| 1327 | + | |
| 1328 | +proc catch*(sigs: []INT): INT; (* sigs caught: an fd to wait on *) | |
| 1329 | +proc caught*(fd: INT): INT; (* the next signal caught, or 0 if none is waiting *) | |
| 1330 | +proc ignore*(sig: INT; yes: BOOL): INT; (* sig ignored; or, if not yes, back to what it does at first *) | |
| 1331 | +proc ignored*(sig: INT): BOOL; (* whether sig does nothing now *) | |
| 1332 | +proc handle*(sig: INT): INT; (* sig noted, for came; a system call it comes during is -4 *) | |
| 1333 | +proc came*(sig: INT): BOOL; (* whether sig came since the last time it was asked *) | |
| 1334 | + | |
| 1335 | +proc clock*: I64; (* nanoseconds, on a clock that only goes forward *) | |
| 1336 | +proc now*: I64; (* nanoseconds since 1970-01-01, UTC *) | |
| 1337 | +proc sleep*(ms: INT); | |
| 1338 | +proc random*(b: []U8); (* b filled with random bytes; stops the program if it can't be *) | |
| 1339 | + | |
| 1340 | +proc connect*(path: []U8): INT; (* a stream socket, connected to the Unix socket at path: its fd *) | |
| 1341 | +proc connectTcp*(addr: []U8; port: INT): INT; (* addr an IPv4 or IPv6 address, as numbers *) | |
| 1342 | +proc connectUdp*(addr: []U8; port: INT): INT; | |
| 1343 | +proc listen*(path: []U8): INT; (* a Unix socket made at path, taking connections *) | |
| 1344 | +proc listenTcp*(addr: []U8; port: INT): INT; | |
| 1345 | +proc accept*(fd: INT): INT; (* the next connection, waiting for one *) | |
| 1346 | +proc send*(fd: INT; s: []U8): INT; (* write, to a socket: -32 (EPIPE), not a signal, if it is closed *) | |
| 1347 | +proc sendNow*(fd: INT; s: []U8): INT; (* send, but -11 (EAGAIN) where it would wait *) | |
| 1348 | +proc connectTcpWithin*(addr: []U8; port, ms: INT): INT; (* connectTcp, or -110 (ETIMEDOUT) after ms *) | |
| 1349 | +proc listenUdp*(addr: []U8; port: INT): INT; (* a socket of datagrams on port at addr *) | |
| 1350 | +proc receive*(fd: INT; buf: []U8): (INT, Peer); (* the next datagram, in buf, and who sent it *) | |
| 1351 | +proc reply*(fd: INT; peer: Peer; s: []U8): INT; (* s, as one datagram, to peer *) | |
| 1352 | +proc localPort*(fd: INT): INT; (* the port the socket fd is bound to *) | |
| 1353 | +proc closeWrite*(fd: INT): INT; (* no more writing to the socket fd; the other end reads an end *) | |
| 1354 | +proc peer*(fd: INT): (Remote, INT); (* who is at the other end of the connected socket fd *) | |
| 1355 | +proc socketPair*: (INT, INT, INT); (* two connected stream sockets, and 0 *) | |
| 1356 | +proc sendFds*(fd: INT; s: []U8; fds: []INT): INT; (* send, and with it fds, to a Unix socket *) | |
| 1357 | +proc receiveFds*(fd: INT; buf: []U8; fds: []INT): (INT, INT); (* read, and the fds that came with it *) | |
| 1358 | + | |
| 1359 | +proc memFile*(size: INT): INT; (* a file of size zero bytes, in memory, with no name: its fd *) | |
| 1360 | +proc mapFile*(fd, size: INT): ^U8; (* the first size bytes of fd, shared; munmap gives them back; or nil *)</code></pre> | |
| 1361 | +<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> | |
| 1362 | +<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> | |
| 1363 | +<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> | |
| 1364 | +<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> | |
| 1365 | +<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<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> | |
| 1366 | +<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> | |
| 1367 | +<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> | |
| 1368 | +<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> | |
| 1369 | +<p>A shell moves its own files with <code>dup</code> and <code>dupTo</code>, for <code>2>&1</code> and <code>exec >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>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> | |
| 1370 | +<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> | |
| 1371 | +<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> | |
| 1372 | +<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> | |
| 1373 | +<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> | |
| 1374 | +<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> | |
| 1375 | +<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> | |
| 1376 | +<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> | |
| 1377 | +<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> | |
| 1378 | +<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> | |
| 1379 | +<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> | |
| 1380 | +<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 < 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> | |
| 1381 | +<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> | |
| 1382 | +<p><strong>Strings, buffers and collections.</strong></p> | |
| 1383 | +<pre><code>module Str; | |
| 1384 | +proc cmp*(a, b: []U8): INT; (* -1, 0 or 1 as a sorts before, with or after b, byte by byte *) | |
| 1385 | +proc eq*(a, b: []U8): BOOL; | |
| 1386 | +proc eqFold*(a, b: []U8): BOOL; (* eq, an ASCII letter's capital and small the same *) | |
| 1387 | +proc copy*(a: ^Mem.Allocator; s: []U8): ([]U8, BOOL); (* s's bytes in memory from a; false if a has none *) | |
| 1388 | +proc free*(a: ^Mem.Allocator; s: []U8); (* what copy gave from a, given back; "" is none *) | |
| 1389 | +proc hash*(s: []U8): U64; (* FNV-1a, 64 bits *) | |
| 1390 | +proc find*(s, sub: []U8): INT; (* where sub first starts in s, or -1 *) | |
| 1391 | +proc findFrom*(s, sub: []U8; from: INT): INT; (* where sub first starts in s at or after from, or -1 *) | |
| 1392 | +proc findLast*(s, sub: []U8): INT; (* where sub last starts in s, or -1 *) | |
| 1393 | +proc hasPrefix*(s, p: []U8): BOOL; | |
| 1394 | +proc hasSuffix*(s, x: []U8): BOOL; | |
| 1395 | +proc trim*(s: []U8): []U8; (* s without the spaces at either end *) | |
| 1396 | +proc trimLeft*(s: []U8): []U8; (* s without the spaces at its start *) | |
| 1397 | +proc trimRight*(s: []U8): []U8; (* s without the spaces at its end *) | |
| 1398 | +proc cut*(s, sep: []U8): ([]U8, []U8, BOOL); (* what comes before the first sep, and after it *) | |
| 1399 | +proc field*(s: []U8): ([]U8, []U8); (* the first run of bytes in s that aren't spaces, and what follows it *) | |
| 1400 | +proc isDigit*(c: U8): BOOL; (* 0 to 9 *) | |
| 1401 | +proc isLetter*(c: U8): BOOL; (* A to Z, a to z *) | |
| 1402 | +proc isSpace*(c: U8): BOOL; (* a space, as trim takes it *) | |
| 1403 | +proc isPunct*(c: U8): BOOL; (* printable, and neither a letter, a digit nor the blank *) | |
| 1404 | +proc hexVal*(c: U8): INT; (* c's value as a hexadecimal digit, or -1 *) | |
| 1405 | +proc lower*(s: []U8); (* s's ASCII capitals made small, in place *) | |
| 1406 | +proc upper*(s: []U8); (* s's ASCII small letters made capitals, in place *) | |
| 1407 | +proc join*(var b: Buf.Buf; parts: [][]U8; sep: []U8); (* the parts added to b, sep between each two *) | |
| 1408 | +proc replace*(var b: Buf.Buf; s, old, new: []U8); (* s added to b, with new for each old in it *) | |
| 1409 | +proc encode*(c: I32): ([4]U8, INT); (* c in UTF-8: its bytes, and how many *) | |
| 1410 | +proc decode*(s: []U8): (I32, INT); (* the character s starts with, and its length in bytes *) | |
| 1411 | +proc decodeLast*(s: []U8): (I32, INT); (* the character s ends with, and its length in bytes *) | |
| 1412 | +proc next*(s: []U8; i: INT): (I32, INT); (* the character at i, and where the next starts; -1 at the end *) | |
| 1413 | +proc valid*(s: []U8): BOOL; (* s is UTF-8, every character rightly spelled *) | |
| 1414 | +proc chars*(s: []U8): INT; (* the characters in s, as decode reads them *) | |
| 1415 | +proc toInt*(s: []U8): (I64, BOOL); (* s, in decimal; false if it isn't a number an I64 holds *) | |
| 1416 | +proc toHex*(s: []U8): (U64, BOOL); (* s, in hexadecimal; false if it isn't a number a U64 holds *) | |
| 1417 | +proc toU64*(s: []U8): (U64, BOOL); (* s, decimal digits only; false if it isn't one, or a U64 can't hold it *) | |
| 1418 | +proc fromC*(p: ^U8): []U8; (* the bytes at p up to its zero byte, not copied; "" for nil *) | |
| 1419 | +proc toC*(s, out: []U8): ^U8; (* s copied into out with a zero byte after it, which holds LEN(s) + 1 bytes at least: PTR(out) *) | |
| 1420 | +const Base64*, Base64Url*; (* the digits of RFC 4648, sections 4 and 5 *) | |
| 1421 | +proc base64With*(s, out, alphabet: []U8; pad: BOOL): INT; (* s in base64 with alphabet's 64 digits into out, which holds base64Size(LEN(s)) bytes at least, padded with = if pad: the bytes written *) | |
| 1422 | +proc unbase64With*(s, out, alphabet: []U8; pad: BOOL): (INT, BOOL); (* s, base64 as base64With wrote it, into out, which holds (LEN(s) + 3) div 4 * 3 bytes at least: the bytes written; false if s is not that *) | |
| 1423 | +proc base64Size*(n: INT): INT; (* the bytes base64 makes of n bytes: 4 for each 3, or part of 3 *) | |
| 1424 | +proc base64*(s, out: []U8): INT; (* s in base64 into out, which holds base64Size(LEN(s)) bytes at least: the bytes written *) | |
| 1425 | +proc unbase64*(s, out: []U8): (INT, BOOL); (* s, base64, into out, which holds LEN(s) div 4 * 3 bytes at least: the bytes written; false if s is not base64 *) | |
| 1426 | +proc fromInt*(n: I64): ([20]U8, INT); (* n in decimal: its bytes, and how many *) | |
| 1427 | +proc le*(s: []U8): U64; (* s, at most 8 bytes, the first the lowest *) | |
| 1428 | +proc be*(s: []U8): U64; (* s, at most 8 bytes, the first the highest *) | |
| 1429 | +proc putLE*(s: []U8; v: U64); (* v into s, the lowest byte first *) | |
| 1430 | +proc putBE*(s: []U8; v: U64); (* v into s, the highest byte first *) | |
| 1431 | + | |
| 1432 | +module Buf; | |
| 1433 | +type Buf* = record len*: INT; ... end; | |
| 1434 | +proc init*(var b: Buf; a: ^Mem.Allocator); | |
| 1435 | +proc room*(var b: Buf; n: INT): BOOL; (* room for n more bytes; false if the allocator has none *) | |
| 1436 | +proc add*(var b: Buf; c: U8); | |
| 1437 | +proc str*(var b: Buf; s: []U8); | |
| 1438 | +proc spare*(var b: Buf; n: INT): []U8; (* room for n more bytes, and those bytes, to fill *) | |
| 1439 | +proc bytes*(const b: Buf): []U8; (* what it holds, until it next grows *) | |
| 1440 | +proc cut*(var b: Buf; n: INT); (* only the first n bytes kept, its memory kept *) | |
| 1441 | +proc reset*(var b: Buf); (* emptied, its memory kept *) | |
| 1442 | +proc done*(var b: Buf); (* its memory given back *) | |
| 1443 | + | |
| 1444 | +module Fmt; | |
| 1445 | +type Arg* = variant | |
| 1446 | + int(i: I64); | |
| 1447 | + uint(u: U64); | |
| 1448 | + hex(h: U64); | |
| 1449 | + lowHex(h: U64); | |
| 1450 | + str(s: []U8); | |
| 1451 | + char(c: U8); | |
| 1452 | + bool(b: BOOL); | |
| 1453 | + real(r: F64; places: INT); | |
| 1454 | +end; | |
| 1455 | +const ShortMost* = 24; (* the longest Fmt.short *) | |
| 1456 | +proc short*(x: F64; var out: [ShortMost]U8): []U8; (* x in the fewest digits that read back, in out *) | |
| 1457 | +proc print*(f: []U8; args: []Arg); (* to standard output *) | |
| 1458 | +proc eprint*(f: []U8; args: []Arg); (* to standard error, once Out is flushed *) | |
| 1459 | +proc write*(var b: Buf.Buf; f: []U8; args: []Arg); (* added to b *) | |
| 1460 | +proc into*(out: []U8; f: []U8; args: []Arg): (INT, BOOL); (* into out: the bytes, and false if cut short *) | |
| 1461 | + | |
| 1462 | +module List(T); | |
| 1463 | +type | |
| 1464 | + Node* = record next*: ^Node; val*: T; end; | |
| 1465 | + List* = record head*: ^Node; len*: INT; ... end; | |
| 1466 | +proc init*(var l: List; a: ^Mem.Allocator); | |
| 1467 | +proc push*(var l: List; v: T): BOOL; (* v at the front; false if the allocator has no room *) | |
| 1468 | +proc pop*(var l: List): (T, BOOL); (* the front value, taken off; false if the list is empty *) | |
| 1469 | +proc reverse*(var l: List); | |
| 1470 | +proc clear*(var l: List); | |
| 1471 | + | |
| 1472 | +module Map(K, V; hash: proc(k: K): U64; eq: proc(a, b: K): BOOL); | |
| 1473 | +type Map* = record len*: INT; ... end; | |
| 1474 | +proc init*(var m: Map; a: ^Mem.Allocator); | |
| 1475 | +proc put*(var m: Map; k: K; v: V): BOOL; (* k now maps to v; false if there was no room *) | |
| 1476 | +proc remove*(var m: Map; k: K): BOOL; (* false if k wasn't there *) | |
| 1477 | +proc get*(const m: Map; k: K): (V, BOOL); (* what k maps to, and whether it maps to anything *) | |
| 1478 | +proc next*(const m: Map; i: INT): (INT, K, V); (* the entry after i *) | |
| 1479 | +proc done*(var m: Map); (* its memory given back, leaving it empty *) | |
| 1480 | + | |
| 1481 | +module Vec(T); | |
| 1482 | +type Vec* = record len*: INT; ... end; | |
| 1483 | +proc init*(var v: Vec; a: ^Mem.Allocator); | |
| 1484 | +proc room*(var v: Vec; n: INT): BOOL; (* room for n more; false if the allocator has none *) | |
| 1485 | +proc push*(var v: Vec; x: T); (* x added at the end *) | |
| 1486 | +proc pop*(var v: Vec): (T, BOOL); (* the last element, taken off; false if the array is empty *) | |
| 1487 | +proc add*(var v: Vec): ^T; (* a new element at the end, zero, to fill in place *) | |
| 1488 | +proc tryPush*(var v: Vec; x: T): BOOL; (* push; false, and v as it was, if there is no room *) | |
| 1489 | +proc tryAdd*(var v: Vec): (^T, BOOL); (* add; nil and false, and v as it was, if there is no room *) | |
| 1490 | +proc resize*(var v: Vec; n: INT); (* n elements: cut short, or the new ones zero *) | |
| 1491 | +proc insert*(var v: Vec; i, n: INT); (* n zero elements opened at i; stops the program if there is no room *) | |
| 1492 | +proc remove*(var v: Vec; i, n: INT); (* the n elements from i taken out, those after moved down *) | |
| 1493 | +proc all*(const v: Vec): []T; (* the elements, until it next grows *) | |
| 1494 | +proc reset*(var v: Vec); (* emptied, its memory kept *) | |
| 1495 | +proc done*(var v: Vec); (* its memory given back *) | |
| 1496 | + | |
| 1497 | +module Sort(T; less: proc(a, b: T): BOOL); | |
| 1498 | +proc sort*(s: []T); | |
| 1499 | + | |
| 1500 | +module Math; | |
| 1501 | +const pi* = 3.141592653589793; | |
| 1502 | +proc sqrt*(x: F64): F64; | |
| 1503 | +proc pow*(x, y: F64): F64; (* x to the power y *) | |
| 1504 | +proc floor*(x: F64): F64; | |
| 1505 | +proc ceil*(x: F64): F64; | |
| 1506 | +proc round*(x: F64): F64; (* to the nearest whole number; a half away from 0 *) | |
| 1507 | +proc roundEven*(x: F64): F64; (* to the nearest whole number; a half to the even one *) | |
| 1508 | +proc exp*(x: F64): F64; | |
| 1509 | +proc ln*(x: F64): F64; | |
| 1510 | +proc log2*(x: F64): F64; | |
| 1511 | +proc log10*(x: F64): F64; | |
| 1512 | +proc sin*(x: F64): F64; | |
| 1513 | +proc cos*(x: F64): F64; | |
| 1514 | +proc tan*(x: F64): F64; | |
| 1515 | +proc tanh*(x: F64): F64; (* from -1 to 1 *) | |
| 1516 | +proc asin*(x: F64): F64; (* from -pi/2 to pi/2 *) | |
| 1517 | +proc acos*(x: F64): F64; (* from 0 to pi *) | |
| 1518 | +proc atan*(x: F64): F64; (* from -pi/2 to pi/2 *) | |
| 1519 | +proc atan2*(y, x: F64): F64; (* the angle of (x, y) from the x axis, from -pi to pi *) | |
| 1520 | +proc bits*(x: F64): U64; (* the bits of x, as IEEE 754 lays them out *) | |
| 1521 | +proc fromBits*(u: U64): F64; (* the F64 whose bits are u *) | |
| 1522 | +proc mul*(a, b: U64): (U64, U64); (* a times b: the low 64 bits of the product, and the high *) | |
| 1523 | +proc divMod*(hi, lo, d: U64): (U64, U64); (* hi, lo divided by d: the quotient and the remainder; hi < d *) | |
| 1524 | +proc toReal*(s: []U8): (F64, BOOL); (* s as a real, the F64 nearest it; false if it isn't one *)</code></pre> | |
| 1525 | +<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 > 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([]U8, INT, Str.hash, Str.eq);</code>.</p> | |
| 1526 | +<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> | |
| 1527 | +<pre><code>c, i := Str.next(s, 0); | |
| 1528 | +while i >= 0 do | |
| 1529 | + ... (* c is a character of s *) | |
| 1530 | + c, i := Str.next(s, i); | |
| 1531 | +end;</code></pre> | |
| 1532 | +<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> | |
| 1533 | +<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> | |
| 1534 | +<pre><code>line, rest, more := Str.cut(text, "\n"); (* the first line, and the others *) | |
| 1535 | +key, val, ok := Str.cut(line, "="); | |
| 1536 | +w, rest := Str.field(line); (* the words of a line *) | |
| 1537 | +while LEN(w) > 0 do | |
| 1538 | + Out.str(w); Out.ln; | |
| 1539 | + w, rest := Str.field(rest); | |
| 1540 | +end;</code></pre> | |
| 1541 | +<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> | |
| 1542 | +<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> | |
| 1543 | +<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> | |
| 1544 | +<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> | |
| 1545 | +<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> | |
| 1546 | +<pre><code>len := U32(Str.le(header[4..8])); | |
| 1547 | +Str.putBE(packet[0..2], U64(port));</code></pre> | |
| 1548 | +<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> | |
| 1549 | +<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> | |
| 1550 | +<pre><code>i, k, v := Names.next(names, 0); | |
| 1551 | +while i >= 0 do | |
| 1552 | + Fmt.print("{} is {}\n", [Fmt.str(k), Fmt.int(v)]); | |
| 1553 | + i, k, v := Names.next(names, i); | |
| 1554 | +end;</code></pre> | |
| 1555 | +<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> | |
| 1556 | +<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> | |
| 1557 | +<pre><code>module Files; | |
| 1558 | +proc arg*(i: INT): []U8; (* argument i; 0 is the program's name; "" if there is none *) | |
| 1559 | +proc read*(path: []U8; var b: Buf.Buf): BOOL; (* the whole file added to b *) | |
| 1560 | +proc load*(path: []U8; var b: Buf.Buf): INT; (* as read: 0, or minus the errno that stopped it *) | |
| 1561 | +proc write*(path, data: []U8): BOOL; (* the file made to hold data; false if it or its close failed *) | |
| 1562 | +proc writeAll*(fd: INT; s: []U8): INT; (* all of s written to fd; 0, or minus the errno *) | |
| 1563 | +proc realPath*(path: []U8; var b: Buf.Buf): INT; (* the absolute path of path, plain, added to b; 0, or minus an errno *) | |
| 1564 | +proc removeTree*(path: []U8): INT; (* the file, or the directory and all in it, removed; 0, or minus the first errno *) | |
| 1565 | + | |
| 1566 | +module Opt; | |
| 1567 | +type | |
| 1568 | + Row* = variant | |
| 1569 | + usage(scope, line: []U8); (* a synopsis line, without "usage: " *) | |
| 1570 | + sub(scope, name, help: []U8); (* a subcommand *) | |
| 1571 | + option(scope: []U8; letter: U8; long, value, help: []U8); | |
| 1572 | + end; | |
| 1573 | + Parser* = record | |
| 1574 | + letter*: U8; (* the option just read *) | |
| 1575 | + value*: []U8; (* its value; "" for a flag *) | |
| 1576 | + long*: BOOL; (* it was written by its long name *) | |
| 1577 | + spelt*: []U8; (* as it was written, no dashes: "b" or "bar"; to read only *) | |
| 1578 | + ... | |
| 1579 | + end; | |
| 1580 | +proc init*(var p: Parser; name: []U8; table: []Row); (* the arguments from 1 on, by table *) | |
| 1581 | +proc next*(var p: Parser): BOOL; (* the next option; false when they end *) | |
| 1582 | +proc operand*(var p: Parser): ([]U8, BOOL); (* the next operand; false when there are no more *) | |
| 1583 | +proc at*(var p: Parser): INT; (* the argument operand would give next *) | |
| 1584 | +proc scope*(var p: Parser; name: []U8); (* subcommand name's options, from the word after it *) | |
| 1585 | +proc number*(const p: Parser; lo, hi: I64): I64; (* the value just read, a number from lo to hi *) | |
| 1586 | +proc refuse*(const p: Parser; wants: []U8); (* the value just read refused, as number refuses one *) | |
| 1587 | +proc fail*(const p: Parser; text: []U8); (* the program's own mistake *) | |
| 1588 | +proc misuse*(const p: Parser; text: []U8); (* the program's own mistake, with the synopsis *)</code></pre> | |
| 1589 | +<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> | |
| 1590 | +<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> | |
| 1591 | +<pre><code>const wait = 1; (* the key of --wait, which has no letter *) | |
| 1592 | +... | |
| 1593 | +Opt.init(p, "keep", [ | |
| 1594 | + Opt.usage("", "keep [-v] [--wait secs] start ..."), | |
| 1595 | + Opt.sub("", "start", "start a job"), | |
| 1596 | + Opt.option("", 'v', "verbose", "", "say more"), | |
| 1597 | + Opt.option("", wait, "wait", "secs", "give the job secs to start"), | |
| 1598 | + Opt.usage("start", "keep start [-b label] name command [argument ...]"), | |
| 1599 | + Opt.option("start", 'b', "bar", "label", "show the job in the bar as label")]); | |
| 1600 | +while Opt.next(p) do | |
| 1601 | + if p.letter = 'v' then verbose := true; | |
| 1602 | + elsif p.letter = wait then secs := Opt.number(p, 1, 600); | |
| 1603 | + end; | |
| 1604 | +end; | |
| 1605 | +w, ok := Opt.operand(p); | |
| 1606 | +if not ok or (w # "start") then Opt.fail(p, "no command; see keep -h"); end; | |
| 1607 | +Opt.scope(p, "start"); | |
| 1608 | +while Opt.next(p) do | |
| 1609 | + if p.letter = 'b' then bar := p.value; end; | |
| 1610 | +end; | |
| 1611 | +job, ok := Opt.operand(p);</code></pre> | |
| 1612 | +<p>The rules are <code>getopt</code>’s:</p> | |
| 1613 | +<ul> | |
| 1614 | +<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> | |
| 1615 | +<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> | |
| 1616 | +<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> | |
| 1617 | +<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> | |
| 1618 | +<li>Each scope has its own options. An option given twice is read twice.</li> | |
| 1619 | +</ul> | |
| 1620 | +<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> | |
| 1621 | +<pre><code>script, ok := Opt.operand(p); (* tery file arg ... *) | |
| 1622 | +first := Opt.at(p); (* file's own arguments, from here on *)</code></pre> | |
| 1623 | +<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> | |
| 1624 | +<pre><code>usage: keep start [-b label] name command [argument ...] | |
| 1625 | + | |
| 1626 | + -b, --bar label show the job in the bar as label | |
| 1627 | + -h, --help print this and exit</code></pre> | |
| 1628 | +<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> | |
| 1629 | +<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> | |
| 1630 | +<pre><code>keep: unknown option -x | |
| 1631 | +usage: keep start [-b label] name command [argument ...]</code></pre> | |
| 1632 | +<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> | |
| 1633 | +<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> | |
| 1634 | +<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> | |
| 1635 | +<pre><code>module Width; | |
| 1636 | +proc width*(c: I32): INT; (* the columns the character c takes: 0, 1 or 2 *) | |
| 1637 | +proc columns*(s: []U8): INT; (* the columns the UTF-8 text s takes *)</code></pre> | |
| 1638 | +<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> | |
| 1639 | +<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> | |
| 1640 | +<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> | |
| 1641 | +<pre><code>module Rand; | |
| 1642 | +type Rand* = record ... end; | |
| 1643 | +proc init*(var r: Rand; seed: U64); (* starts r at seed; any seed, 0 too *) | |
| 1644 | +proc next*(var r: Rand): U64; (* the next number, all 64 bits of it *) | |
| 1645 | +proc below*(var r: Rand; n: U64): U64; (* 0 to n - 1, each as likely as another; n = 0 stops the program *) | |
| 1646 | +proc range*(var r: Rand; lo, hi: I64): I64; (* lo to hi, both included; lo must not exceed hi *) | |
| 1647 | +proc seed*(): U64; (* a fresh seed from the kernel, to print and give back to init *)</code></pre> | |
| 1648 | +<pre><code>module Dice; | |
| 1649 | +import Rand, Check; | |
| 1650 | + | |
| 1651 | +(* Five rolls of a die from seed, as the digits of a number. *) | |
| 1652 | +proc rolls(seed: U64): INT; | |
| 1653 | +var r: Rand.Rand; i, v: INT; | |
| 1654 | +begin | |
| 1655 | + Rand.init(r, seed); | |
| 1656 | + for i := 1 to 5 do v := v * 10 + INT(Rand.range(r, 1, 6)); end; | |
| 1657 | + return v; | |
| 1658 | +end; | |
| 1659 | + | |
| 1660 | +proc main*; | |
| 1661 | +begin | |
| 1662 | + Check.int("the same seed, the same rolls", rolls(7), rolls(7)); | |
| 1663 | + Check.ok(rolls(7) >= 11111, "every die shows 1 or more"); | |
| 1664 | + Check.ok(rolls(7) <= 66666, "every die shows 6 or less"); | |
| 1665 | +end; | |
| 1666 | + | |
| 1667 | +end Dice.</code></pre> | |
| 1668 | +<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> | |
| 1669 | +<pre><code>module Check; | |
| 1670 | +proc ok*(cond: BOOL; what: []U8); (* fails, saying what, when cond is false *) | |
| 1671 | +proc str*(what, got, want: []U8); (* fails when got is not want; shows both, escaped, and the byte where they differ *) | |
| 1672 | +proc int*(what: []U8; got, want: I64); (* fails when got is not want; shows both *) | |
| 1673 | +proc mute*(on: BOOL); (* while on, checks say nothing and are not counted *) | |
| 1674 | +proc mutedFailures*(): INT; (* how many failed since mute was turned on *)</code></pre> | |
| 1675 | +<pre><code>module Digits; | |
| 1676 | +import Check; | |
| 1677 | + | |
| 1678 | +(* How many decimal digits n, not negative, takes. *) | |
| 1679 | +proc count(n: INT): INT; | |
| 1680 | +var d: INT; | |
| 1681 | +begin | |
| 1682 | + d := 1; | |
| 1683 | + while n >= 10 do n := n div 10; INC(d); end; | |
| 1684 | + return d; | |
| 1685 | +end; | |
| 1686 | + | |
| 1687 | +proc main*; | |
| 1688 | +begin | |
| 1689 | + Check.int("0 is one digit", count(0), 1); | |
| 1690 | + Check.int("9 is one digit", count(9), 1); | |
| 1691 | + Check.int("10 is two digits", count(10), 2); | |
| 1692 | + Check.ok(count(1000000) = 7, "a million is seven digits"); | |
| 1693 | +end; | |
| 1694 | + | |
| 1695 | +end Digits.</code></pre> | |
| 1696 | +<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> | |
| 1697 | +<pre><code>module Prop; | |
| 1698 | +type Source* = record ... end; | |
| 1699 | +type Property* = proc(var s: Source); (* draws from s, checks with Check *) | |
| 1700 | +proc bits*(var s: Source): U64; (* 64 bits, from 8 bytes, the first the highest *) | |
| 1701 | +proc int*(var s: Source; lo, hi: I64): I64; (* lo to hi, both included; zeros give lo *) | |
| 1702 | +proc pick*(var s: Source; n: INT): INT; (* 0 to n - 1; n at least 1 *) | |
| 1703 | +proc bool*(var s: Source): BOOL; | |
| 1704 | +proc bytes*(var s: Source; max: INT; var b: Buf.Buf); (* b, emptied, then given at most max bytes *) | |
| 1705 | +proc check*(name: []U8; p: Property); (* runs p on the saved cases, then on fresh ones *)</code></pre> | |
| 1706 | +<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> | |
| 1707 | +<pre><code>module Reverse; | |
| 1708 | +import Prop, Check, Buf, Heap; | |
| 1709 | + | |
| 1710 | +var | |
| 1711 | + b, was: Buf.Buf; (* the bytes drawn, and a copy of them *) | |
| 1712 | + | |
| 1713 | +(* Turns s round, in place. *) | |
| 1714 | +proc reverse(s: []U8); | |
| 1715 | +var i: INT; c: U8; | |
| 1716 | +begin | |
| 1717 | + for i := 0 to LEN(s) div 2 - 1 do | |
| 1718 | + c := s[i]; s[i] := s[LEN(s) - 1 - i]; s[LEN(s) - 1 - i] := c; | |
| 1719 | + end; | |
| 1720 | +end; | |
| 1721 | + | |
| 1722 | +(* Reversing any string twice gives it back. *) | |
| 1723 | +proc twice(var s: Prop.Source); | |
| 1724 | +begin | |
| 1725 | + Prop.bytes(s, 64, b); | |
| 1726 | + Buf.reset(was); | |
| 1727 | + Buf.str(was, Buf.bytes(b)); | |
| 1728 | + reverse(Buf.bytes(b)); | |
| 1729 | + reverse(Buf.bytes(b)); | |
| 1730 | + Check.str("reversed twice", Buf.bytes(b), Buf.bytes(was)); | |
| 1731 | +end; | |
| 1732 | + | |
| 1733 | +proc main*; | |
| 1734 | +begin | |
| 1735 | + Buf.init(b, Heap.heap); | |
| 1736 | + Buf.init(was, Heap.heap); | |
| 1737 | + Prop.check("reverse", twice); | |
| 1738 | +end; | |
| 1739 | + | |
| 1740 | +end Reverse.</code></pre> | |
| 1741 | +</div> | |
| 1742 | +</main> | |
| 1743 | +<footer>raz is under the ISC license. <a href="source/index.html">Source</a></footer> | |
| 1744 | +</body> | |
| 1745 | +</html> |
| @@ -0,0 +1,153 @@ | ||
| 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>Talking to C - Raz, Set, Go</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="Talking to C - Raz, Set, Go"> | |
| 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.lucelad.workers.dev/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" aria-current="page">Raz, Set, Go</a><a href="../advanced/index.html">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<div class="tour"><aside><h2>Raz, Set, Go</h2><h3>Raz</h3><ol start='1'> | |
| 22 | +<li><a href="hello.html">Hello, world</a></li> | |
| 23 | +<li><a href="modules.html">Modules</a></li> | |
| 24 | +<li><a href="integers.html">Integers</a></li> | |
| 25 | +<li><a href="values.html">Values and conversions</a></li> | |
| 26 | +<li><a href="procedures.html">Procedures and several results</a></li> | |
| 27 | +</ol> | |
| 28 | +<h3>Set</h3><ol start='6'> | |
| 29 | +<li><a href="slices.html">Arrays, slices and strings</a></li> | |
| 30 | +<li><a href="records.html">Records and pointers</a></li> | |
| 31 | +<li><a href="variants.html">Enumerations, sets, variants and match</a></li> | |
| 32 | +<li><a href="memory.html">Memory and allocators</a></li> | |
| 33 | +</ol> | |
| 34 | +<h3>Go</h3><ol start='10'> | |
| 35 | +<li><a href="errors.html">Errors</a></li> | |
| 36 | +<li><a href="defer.html">Defer</a></li> | |
| 37 | +<li><a href="checks.html">When it goes wrong</a></li> | |
| 38 | +<li><a href="generics.html">Generic modules</a></li> | |
| 39 | +<li><a href="c.html" aria-current="page">Talking to C</a></li> | |
| 40 | +<li><a href="threads.html">Threads</a></li> | |
| 41 | +</ol></aside><article><p class="kicker">Go · lesson 14 of 15</p><h1>Talking to C</h1> | |
| 42 | +<div class="file"><span>Qsort.raz</span></div><pre class="code"><code><span class="kw">module</span> Qsort; | |
| 43 | +<span class="kw">import</span> Out, Fmt, SYSTEM; | |
| 44 | + | |
| 45 | +<span class="kw">link</span> <span class="string">"libm.so.6"</span>; | |
| 46 | + | |
| 47 | +<span class="kw">extern</span> <span class="kw">proc</span> qsort(base: ^<span class="ty">U8</span>; n, size: <span class="ty">UINT</span>; | |
| 48 | + less: <span class="kw">proc</span>(a, b: ^<span class="ty">U8</span>): <span class="ty">I32</span>); | |
| 49 | +<span class="kw">extern</span> <span class="kw">proc</span> cbrt(x: <span class="ty">F64</span>): <span class="ty">F64</span>; | |
| 50 | + | |
| 51 | +<span class="comment">(* the order of two INTs, as C's qsort wants it *)</span> | |
| 52 | +<span class="kw">proc</span> order(a, b: ^<span class="ty">U8</span>): <span class="ty">I32</span>; | |
| 53 | +<span class="kw">var</span> x, y: ^<span class="ty">INT</span>; | |
| 54 | +<span class="kw">begin</span> | |
| 55 | + x := ^<span class="ty">INT</span>(a); | |
| 56 | + y := ^<span class="ty">INT</span>(b); | |
| 57 | + <span class="kw">if</span> x^ < y^ <span class="kw">then</span> <span class="kw">return</span> -<span class="number">1</span>; <span class="kw">elsif</span> x^ > y^ <span class="kw">then</span> <span class="kw">return</span> <span class="number">1</span>; <span class="kw">end</span>; | |
| 58 | + <span class="kw">return</span> <span class="number">0</span>; | |
| 59 | +<span class="kw">end</span>; | |
| 60 | + | |
| 61 | +<span class="kw">proc</span> main*; | |
| 62 | +<span class="kw">var</span> a: [<span class="number">5</span>]<span class="ty">INT</span>; i: <span class="ty">INT</span>; | |
| 63 | +<span class="kw">begin</span> | |
| 64 | + a := [<span class="number">30</span>, <span class="number">10</span>, <span class="number">50</span>, <span class="number">20</span>, <span class="number">40</span>]; | |
| 65 | + qsort(^<span class="ty">U8</span>(SYSTEM.<span class="ty">ADR</span>(a)), <span class="ty">LEN</span>(a), <span class="ty">SIZE</span>(<span class="ty">INT</span>), order); | |
| 66 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">4</span> <span class="kw">do</span> Out.int(a[i]); Out.char(<span class="string">' '</span>); <span class="kw">end</span>; | |
| 67 | + Out.ln; | |
| 68 | + Fmt.print(<span class="string">"{}\n"</span>, [Fmt.real(cbrt(<span class="number">27.0</span>), <span class="number">3</span>)]); | |
| 69 | +<span class="kw">end</span>; | |
| 70 | + | |
| 71 | +<span class="kw">end</span> Qsort.</code></pre> | |
| 72 | +<pre class="output"><code>10 20 30 40 50 | |
| 73 | +3.000 | |
| 74 | +</code></pre> | |
| 75 | +<p>An <code>extern</code> procedure is found by its name in the C library, or in a library a <code>link</code> line names. Its parameters are integers, reals, pointers and procedures, as C declares them; a raz procedure of such types can be given to C to call back, as <code>order</code> is. A record goes to C by pointer, never by value.</p> | |
| 76 | +<h2>What using C costs</h2> | |
| 77 | +<p>A program that uses C is linked against it dynamically and starts through it, so that C's own set-up and clean-up run; one that doesn't is a static executable with nothing in it but its own code. A program uses C if any module it uses has an <code>extern</code> or a <code>link</code> of a library.</p> | |
| 78 | +<h2>Varargs</h2> | |
| 79 | +<p><code>...</code> after an <code>extern</code>'s parameters takes any number of further arguments, as <code>printf</code> wants. A string literal goes as a C string, an integer constant as an <code>INT</code>, a real constant as an <code>F64</code>. An <code>F32</code> is an error there, since C promotes it; write <code>F64(x)</code>.</p> | |
| 80 | +<div class="file"><span>Say.raz</span></div><pre class="code"><code><span class="kw">module</span> Say; | |
| 81 | +<span class="kw">import</span> Out; | |
| 82 | + | |
| 83 | +<span class="kw">extern</span> <span class="kw">proc</span> printf(format: ^<span class="ty">U8</span>; ...): <span class="ty">I32</span>; | |
| 84 | +<span class="kw">extern</span> <span class="kw">proc</span> fflush(f: ^<span class="ty">U8</span>): <span class="ty">I32</span>; | |
| 85 | +<span class="kw">extern</span> <span class="kw">proc</span> puts(s: ^<span class="ty">U8</span>): <span class="ty">I32</span>; | |
| 86 | + | |
| 87 | +<span class="kw">proc</span> main*; | |
| 88 | +<span class="kw">var</span> n: <span class="ty">INT</span>; x: <span class="ty">F32</span>; | |
| 89 | +<span class="kw">begin</span> | |
| 90 | + n := <span class="number">42</span>; | |
| 91 | + x := <span class="number">2.5</span>; | |
| 92 | + Out.str(<span class="string">"raz first\n"</span>); | |
| 93 | + Out.flush; <span class="comment">(* Out has a buffer; so does C *)</span> | |
| 94 | + _ := printf(<span class="string">"C says %ld and %.2f and %s\n"</span>, n, <span class="ty">F64</span>(x), <span class="string">"hello"</span>); | |
| 95 | + _ := puts(<span class="string">"and puts"</span>); | |
| 96 | + _ := fflush(<span class="ty">nil</span>); <span class="comment">(* nil: every C stream *)</span> | |
| 97 | + Out.str(<span class="string">"raz again\n"</span>); | |
| 98 | +<span class="kw">end</span>; | |
| 99 | + | |
| 100 | +<span class="kw">end</span> Say.</code></pre> | |
| 101 | +<pre class="output"><code>raz first | |
| 102 | +C says 42 and 2.50 and hello | |
| 103 | +and puts | |
| 104 | +raz again | |
| 105 | +</code></pre> | |
| 106 | +<p><code>Out</code> and C's <code>printf</code> keep two buffers, so a program that writes with both flushes one before it writes with the other, or the text comes out of order.</p> | |
| 107 | +<h2>Libraries, and C's variables</h2> | |
| 108 | +<p><code>link "libm.so.6";</code> names a shared library to load at run time. An <code>extern var</code> is C's variable itself: reading it reads C's, assigning it writes C's.</p> | |
| 109 | +<div class="file"><span>Env.raz</span></div><pre class="code"><code><span class="kw">module</span> Env; | |
| 110 | +<span class="kw">import</span> Out; | |
| 111 | + | |
| 112 | +<span class="kw">extern</span> <span class="kw">var</span> environ: ^^<span class="ty">U8</span>; | |
| 113 | +<span class="kw">extern</span> <span class="kw">proc</span> strlen(s: ^<span class="ty">U8</span>): <span class="ty">UINT</span>; | |
| 114 | +<span class="kw">extern</span> <span class="kw">proc</span> getenv(name: ^<span class="ty">U8</span>): ^<span class="ty">U8</span>; | |
| 115 | + | |
| 116 | +<span class="kw">proc</span> main*; | |
| 117 | +<span class="kw">var</span> p: ^<span class="ty">U8</span>; n: <span class="ty">INT</span>; | |
| 118 | +<span class="kw">begin</span> | |
| 119 | + n := <span class="number">0</span>; | |
| 120 | + <span class="kw">while</span> environ[n] # <span class="ty">nil</span> <span class="kw">do</span> <span class="ty">INC</span>(n); <span class="kw">end</span>; | |
| 121 | + <span class="kw">if</span> n > <span class="number">0</span> <span class="kw">then</span> Out.str(<span class="string">"the environment is not empty\n"</span>); <span class="kw">end</span>; | |
| 122 | + p := getenv(<span class="string">"RAZ_NO_SUCH_VARIABLE"</span>); | |
| 123 | + <span class="kw">if</span> p = <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="string">"not set\n"</span>); <span class="kw">end</span>; | |
| 124 | + Out.int(<span class="ty">INT</span>(strlen(<span class="string">"six"</span>))); Out.ln; | |
| 125 | +<span class="kw">end</span>; | |
| 126 | + | |
| 127 | +<span class="kw">end</span> Env.</code></pre> | |
| 128 | +<pre class="output"><code>the environment is not empty | |
| 129 | +not set | |
| 130 | +3 | |
| 131 | +</code></pre> | |
| 132 | +<h2>Callbacks</h2> | |
| 133 | +<p>Every raz procedure uses the System V calling convention, so any with parameters and a result of C's types may be given to C to call, as <code>qsort</code> is given <code>order</code> above. The procedure may not be a closure: it has only its arguments, so state travels through the pointer C hands back or a module variable.</p> | |
| 134 | +<div class="file"><span>Roots.raz</span></div><pre class="code"><code><span class="kw">module</span> Roots; | |
| 135 | +<span class="kw">import</span> Fmt; | |
| 136 | + | |
| 137 | +<span class="kw">link</span> <span class="string">"libm.so.6"</span>; | |
| 138 | + | |
| 139 | +<span class="kw">extern</span> <span class="kw">proc</span> cbrt(x: <span class="ty">F64</span>): <span class="ty">F64</span>; | |
| 140 | +<span class="kw">extern</span> <span class="kw">proc</span> hypot(x, y: <span class="ty">F64</span>): <span class="ty">F64</span>; | |
| 141 | + | |
| 142 | +<span class="kw">proc</span> main*; | |
| 143 | +<span class="kw">begin</span> | |
| 144 | + Fmt.print(<span class="string">"{} {}\n"</span>, [Fmt.real(cbrt(<span class="number">27.0</span>), <span class="number">3</span>), Fmt.real(hypot(<span class="number">3.0</span>, <span class="number">4.0</span>), <span class="number">3</span>)]); | |
| 145 | +<span class="kw">end</span>; | |
| 146 | + | |
| 147 | +<span class="kw">end</span> Roots.</code></pre> | |
| 148 | +<pre class="output"><code>3.000 5.000 | |
| 149 | +</code></pre><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="generics.html">← Generic modules</a><a href="index.html">Contents</a><a class="next" href="threads.html">Threads →</a></div></article></div> | |
| 150 | +</main> | |
| 151 | +<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> | |
| 152 | +</body> | |
| 153 | +</html> |
| @@ -0,0 +1,187 @@ | ||
| 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>When it goes wrong - Raz, Set, Go</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="When it goes wrong - Raz, Set, Go"> | |
| 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.lucelad.workers.dev/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" aria-current="page">Raz, Set, Go</a><a href="../advanced/index.html">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<div class="tour"><aside><h2>Raz, Set, Go</h2><h3>Raz</h3><ol start='1'> | |
| 22 | +<li><a href="hello.html">Hello, world</a></li> | |
| 23 | +<li><a href="modules.html">Modules</a></li> | |
| 24 | +<li><a href="integers.html">Integers</a></li> | |
| 25 | +<li><a href="values.html">Values and conversions</a></li> | |
| 26 | +<li><a href="procedures.html">Procedures and several results</a></li> | |
| 27 | +</ol> | |
| 28 | +<h3>Set</h3><ol start='6'> | |
| 29 | +<li><a href="slices.html">Arrays, slices and strings</a></li> | |
| 30 | +<li><a href="records.html">Records and pointers</a></li> | |
| 31 | +<li><a href="variants.html">Enumerations, sets, variants and match</a></li> | |
| 32 | +<li><a href="memory.html">Memory and allocators</a></li> | |
| 33 | +</ol> | |
| 34 | +<h3>Go</h3><ol start='10'> | |
| 35 | +<li><a href="errors.html">Errors</a></li> | |
| 36 | +<li><a href="defer.html">Defer</a></li> | |
| 37 | +<li><a href="checks.html" aria-current="page">When it goes wrong</a></li> | |
| 38 | +<li><a href="generics.html">Generic modules</a></li> | |
| 39 | +<li><a href="c.html">Talking to C</a></li> | |
| 40 | +<li><a href="threads.html">Threads</a></li> | |
| 41 | +</ol></aside><article><p class="kicker">Go · lesson 12 of 15</p><h1>When it goes wrong</h1> | |
| 42 | +<div class="file"><span>Fail.raz</span></div><pre class="code"><code><span class="kw">module</span> Fail; | |
| 43 | +<span class="kw">import</span> Out; | |
| 44 | + | |
| 45 | +<span class="kw">proc</span> show(a: []<span class="ty">INT</span>; i: <span class="ty">INT</span>); | |
| 46 | +<span class="kw">begin</span> | |
| 47 | + Out.int(a[i]); | |
| 48 | + Out.ln; | |
| 49 | +<span class="kw">end</span>; | |
| 50 | + | |
| 51 | +<span class="kw">proc</span> main*; | |
| 52 | +<span class="kw">var</span> a: [<span class="number">3</span>]<span class="ty">INT</span>; i: <span class="ty">INT</span>; | |
| 53 | +<span class="kw">begin</span> | |
| 54 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> | |
| 55 | + show(a, i); | |
| 56 | + <span class="kw">end</span>; | |
| 57 | +<span class="kw">end</span>; | |
| 58 | + | |
| 59 | +<span class="kw">end</span> Fail.</code></pre> | |
| 60 | +<pre class="output"><code>0 | |
| 61 | +0 | |
| 62 | +0 | |
| 63 | +<span class="err">Fail.raz:6:15: index 3 is out of range for a length of 3 | |
| 64 | + in Fail.show at Fail.raz:6:15: i = 3 | |
| 65 | + in Fail.main at Fail.raz:14:9: i = 3 | |
| 66 | +</span></code></pre> | |
| 67 | +<p>Every index and slice is checked. A failed check says where it failed and with what values, then the calls under way with their variables, and ends the program with status 2. The three <code>0</code>s are what it printed before the fourth pass went one past the end.</p> | |
| 68 | +<h2>Reading the message</h2> | |
| 69 | +<p>The first line is the place of the offending expression: file, line and column, then what failed and the numbers involved. Each <code>in</code> line after it is a call still under way, innermost first, with the basic-typed variables it held. That is usually enough to see the bug without a debugger.</p> | |
| 70 | +<h2>Other failures</h2> | |
| 71 | +<p>The same shape of message tells of a <code>nil</code> pointer, a division by zero, a bad slice and a stack overflow. Each of them stops the program with status 2, and never runs on with a wrong value.</p> | |
| 72 | +<div class="file"><span>Nilp.raz</span></div><pre class="code"><code><span class="kw">module</span> Nilp; | |
| 73 | +<span class="kw">import</span> Out; | |
| 74 | + | |
| 75 | +<span class="kw">type</span> Node = <span class="kw">record</span> val: <span class="ty">INT</span>; next: ^Node; <span class="kw">end</span>; | |
| 76 | + | |
| 77 | +<span class="kw">proc</span> last(n: ^Node): <span class="ty">INT</span>; | |
| 78 | +<span class="kw">begin</span> | |
| 79 | + <span class="kw">while</span> n^.next # <span class="ty">nil</span> <span class="kw">do</span> n := n^.next; <span class="kw">end</span>; | |
| 80 | + <span class="kw">return</span> n^.val; | |
| 81 | +<span class="kw">end</span>; | |
| 82 | + | |
| 83 | +<span class="kw">proc</span> main*; | |
| 84 | +<span class="kw">var</span> a, b: Node; | |
| 85 | +<span class="kw">begin</span> | |
| 86 | + a.val := <span class="number">1</span>; b.val := <span class="number">2</span>; | |
| 87 | + a.next := <span class="ty">ADR</span>(b); | |
| 88 | + Out.int(last(<span class="ty">ADR</span>(a))); Out.ln; | |
| 89 | + Out.int(last(<span class="ty">nil</span>)); Out.ln; | |
| 90 | +<span class="kw">end</span>; | |
| 91 | + | |
| 92 | +<span class="kw">end</span> Nilp.</code></pre> | |
| 93 | +<pre class="output"><code>2 | |
| 94 | +<span class="err">Nilp.raz:8:11: stopped by a nil pointer | |
| 95 | + in Nilp.last at Nilp.raz:8:11: n = nil | |
| 96 | + in Nilp.main at Nilp.raz:18:5 | |
| 97 | +</span></code></pre> | |
| 98 | +<div class="file"><span>Zero.raz</span></div><pre class="code"><code><span class="kw">module</span> Zero; | |
| 99 | +<span class="kw">import</span> Out; | |
| 100 | + | |
| 101 | +<span class="kw">proc</span> ratio(a, b: <span class="ty">INT</span>): <span class="ty">INT</span>; | |
| 102 | +<span class="kw">begin</span> | |
| 103 | + <span class="kw">return</span> a <span class="kw">div</span> b; | |
| 104 | +<span class="kw">end</span>; | |
| 105 | + | |
| 106 | +<span class="kw">proc</span> main*; | |
| 107 | +<span class="kw">var</span> n: <span class="ty">INT</span>; | |
| 108 | +<span class="kw">begin</span> | |
| 109 | + Out.int(ratio(<span class="number">10</span>, <span class="number">3</span>)); Out.ln; | |
| 110 | + Out.int(ratio(<span class="number">10</span>, n)); Out.ln; <span class="comment">(* n is zero: every variable starts at zero *)</span> | |
| 111 | +<span class="kw">end</span>; | |
| 112 | + | |
| 113 | +<span class="kw">end</span> Zero.</code></pre> | |
| 114 | +<pre class="output"><code>3 | |
| 115 | +<span class="err">Zero.raz:13:5: stopped by a division fault | |
| 116 | + in Zero.main at Zero.raz:13:5: n = 0 | |
| 117 | +</span></code></pre> | |
| 118 | +<div class="file"><span>Slicing.raz</span></div><pre class="code"><code><span class="kw">module</span> Slicing; | |
| 119 | +<span class="kw">import</span> Out; | |
| 120 | + | |
| 121 | +<span class="kw">proc</span> main*; | |
| 122 | +<span class="kw">var</span> a: [<span class="number">5</span>]<span class="ty">INT</span>; s: []<span class="ty">INT</span>; hi: <span class="ty">INT</span>; | |
| 123 | +<span class="kw">begin</span> | |
| 124 | + hi := <span class="number">7</span>; | |
| 125 | + s := a[<span class="number">2</span>..<span class="number">5</span>]; | |
| 126 | + Out.int(<span class="ty">LEN</span>(s)); Out.ln; | |
| 127 | + s := a[<span class="number">2</span>..hi]; <span class="comment">(* past the end *)</span> | |
| 128 | + Out.int(<span class="ty">LEN</span>(s)); Out.ln; | |
| 129 | +<span class="kw">end</span>; | |
| 130 | + | |
| 131 | +<span class="kw">end</span> Slicing.</code></pre> | |
| 132 | +<pre class="output"><code>3 | |
| 133 | +<span class="err">Slicing.raz:10:12: slice 2..7 is out of range for a length of 5 | |
| 134 | + in Slicing.main at Slicing.raz:10:12: hi = 7 | |
| 135 | +</span></code></pre> | |
| 136 | +<p>In every case the output before the failure was written first. <code>Out</code>'s buffer is flushed by the failure, so what the program printed is never lost to the crash.</p> | |
| 137 | +<h2>A constant can fail at compile time</h2> | |
| 138 | +<p>A division by a zero constant, or a constant index out of range, is not a run-time failure at all; the compiler says it at the line, so you never ship it.</p> | |
| 139 | +<div class="file"><span>Early.raz</span></div><pre class="code"><code><span class="kw">module</span> Early; | |
| 140 | +<span class="kw">import</span> Out; | |
| 141 | + | |
| 142 | +<span class="kw">proc</span> main*; | |
| 143 | +<span class="kw">var</span> a: [<span class="number">3</span>]<span class="ty">INT</span>; | |
| 144 | +<span class="kw">begin</span> | |
| 145 | + a[<span class="number">3</span>] := <span class="number">1</span>; | |
| 146 | + Out.int(<span class="number">10</span> <span class="kw">div</span> <span class="number">0</span>); Out.ln; | |
| 147 | +<span class="kw">end</span>; | |
| 148 | + | |
| 149 | +<span class="kw">end</span> Early.</code></pre> | |
| 150 | +<pre class="output term"><code><span class="cmd">$ raz Early.raz</span> | |
| 151 | +Early.raz:7:7: error: index 3 is out of range for a length of 3 | |
| 152 | + 7 | a[3] := 1; | |
| 153 | + | ^ | |
| 154 | +Early.raz:8:13: error: division by zero | |
| 155 | + 8 | Out.int(10 div 0); Out.ln; | |
| 156 | + | ^^^^^^^^ | |
| 157 | +raz: 2 errors</code></pre> | |
| 158 | +<h2>Looking at where you are</h2> | |
| 159 | +<p><code>Rt.trace</code> prints the calls under way, as a failure does, whenever you ask. It writes to standard error and the program goes on. It is the cheapest debugging tool there is.</p> | |
| 160 | +<div class="file"><span>Where.raz</span></div><pre class="code"><code><span class="kw">module</span> Where; | |
| 161 | +<span class="kw">import</span> Rt; | |
| 162 | + | |
| 163 | +<span class="kw">proc</span> inner(depth: <span class="ty">INT</span>); | |
| 164 | +<span class="kw">begin</span> | |
| 165 | + <span class="kw">if</span> depth = <span class="number">0</span> <span class="kw">then</span> Rt.trace; <span class="kw">return</span>; <span class="kw">end</span>; | |
| 166 | + inner(depth - <span class="number">1</span>); | |
| 167 | +<span class="kw">end</span>; | |
| 168 | + | |
| 169 | +<span class="kw">proc</span> main*; | |
| 170 | +<span class="kw">begin</span> | |
| 171 | + inner(<span class="number">2</span>); | |
| 172 | +<span class="kw">end</span>; | |
| 173 | + | |
| 174 | +<span class="kw">end</span> Where.</code></pre> | |
| 175 | +<pre class="output"><code><span class="err"> in Where.inner at Where.raz:6:23: depth = 0 | |
| 176 | + in Where.inner at Where.raz:7:5: depth = 1 | |
| 177 | + and 1 more the same | |
| 178 | + in Where.main at Where.raz:12:5 | |
| 179 | +</span></code></pre> | |
| 180 | +<h2>Leaving the checks out</h2> | |
| 181 | +<p>A module that is sure of its indexes may say <code>check off;</code> after its imports and links, for speed. The module's own indexing and slicing is then unchecked, so an index out of range reads or writes whatever it reaches. Every other check stays (<code>nil</code> and division), and callers of the module keep theirs. Use it for a measured inner loop, never as a first step.</p> | |
| 182 | +<h2>For gdb and the profiler</h2> | |
| 183 | +<p>The program carries names and line numbers, so <code>gdb</code> can break at <code>Fail.raz:6</code> and show raz source. <code>RAZ_PROFILE=1</code> in the environment makes a program sample itself every millisecond and say at the end where its time went, by procedure and by line.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="defer.html">← Defer</a><a href="index.html">Contents</a><a class="next" href="generics.html">Generic modules →</a></div></article></div> | |
| 184 | +</main> | |
| 185 | +<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> | |
| 186 | +</body> | |
| 187 | +</html> |
| @@ -0,0 +1,187 @@ | ||
| 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>Defer - Raz, Set, Go</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="Defer - Raz, Set, Go"> | |
| 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.lucelad.workers.dev/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" aria-current="page">Raz, Set, Go</a><a href="../advanced/index.html">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<div class="tour"><aside><h2>Raz, Set, Go</h2><h3>Raz</h3><ol start='1'> | |
| 22 | +<li><a href="hello.html">Hello, world</a></li> | |
| 23 | +<li><a href="modules.html">Modules</a></li> | |
| 24 | +<li><a href="integers.html">Integers</a></li> | |
| 25 | +<li><a href="values.html">Values and conversions</a></li> | |
| 26 | +<li><a href="procedures.html">Procedures and several results</a></li> | |
| 27 | +</ol> | |
| 28 | +<h3>Set</h3><ol start='6'> | |
| 29 | +<li><a href="slices.html">Arrays, slices and strings</a></li> | |
| 30 | +<li><a href="records.html">Records and pointers</a></li> | |
| 31 | +<li><a href="variants.html">Enumerations, sets, variants and match</a></li> | |
| 32 | +<li><a href="memory.html">Memory and allocators</a></li> | |
| 33 | +</ol> | |
| 34 | +<h3>Go</h3><ol start='10'> | |
| 35 | +<li><a href="errors.html">Errors</a></li> | |
| 36 | +<li><a href="defer.html" aria-current="page">Defer</a></li> | |
| 37 | +<li><a href="checks.html">When it goes wrong</a></li> | |
| 38 | +<li><a href="generics.html">Generic modules</a></li> | |
| 39 | +<li><a href="c.html">Talking to C</a></li> | |
| 40 | +<li><a href="threads.html">Threads</a></li> | |
| 41 | +</ol></aside><article><p class="kicker">Go · lesson 11 of 15</p><h1>Defer</h1> | |
| 42 | +<div class="file"><span>Defers.raz</span></div><pre class="code"><code><span class="kw">module</span> Defers; | |
| 43 | +<span class="kw">import</span> Out, Sys; | |
| 44 | + | |
| 45 | +<span class="kw">proc</span> step(n: <span class="ty">INT</span>); | |
| 46 | +<span class="kw">begin</span> | |
| 47 | + Out.str(<span class="string">"in "</span>); Out.int(n); Out.ln; | |
| 48 | + <span class="kw">defer</span> Out.str(<span class="string">"out\n"</span>); | |
| 49 | + <span class="kw">if</span> n = <span class="number">2</span> <span class="kw">then</span> <span class="kw">return</span>; <span class="kw">end</span>; | |
| 50 | + <span class="kw">defer</span> Out.str(<span class="string">"done\n"</span>); | |
| 51 | + Out.str(<span class="string">"working\n"</span>); | |
| 52 | +<span class="kw">end</span>; | |
| 53 | + | |
| 54 | +<span class="comment">(* the lines of the file at path, or -1 if it can't be read *)</span> | |
| 55 | +<span class="kw">proc</span> lines(path: []<span class="ty">U8</span>): <span class="ty">INT</span>; | |
| 56 | +<span class="kw">var</span> fd, n, i, count: <span class="ty">INT</span>; buf: [<span class="number">4096</span>]<span class="ty">U8</span>; | |
| 57 | +<span class="kw">begin</span> | |
| 58 | + fd := Sys.openRead(path); | |
| 59 | + <span class="kw">if</span> fd < <span class="number">0</span> <span class="kw">then</span> <span class="kw">return</span> -<span class="number">1</span>; <span class="kw">end</span>; | |
| 60 | + <span class="kw">defer</span> Sys.close(fd); | |
| 61 | + count := <span class="number">0</span>; | |
| 62 | + n := Sys.read(fd, buf); | |
| 63 | + <span class="kw">while</span> n > <span class="number">0</span> <span class="kw">do</span> | |
| 64 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> n - <span class="number">1</span> <span class="kw">do</span> | |
| 65 | + <span class="kw">if</span> buf[i] = <span class="string">'\n'</span> <span class="kw">then</span> <span class="ty">INC</span>(count); <span class="kw">end</span>; | |
| 66 | + <span class="kw">end</span>; | |
| 67 | + n := Sys.read(fd, buf); | |
| 68 | + <span class="kw">end</span>; | |
| 69 | + <span class="kw">return</span> count; | |
| 70 | +<span class="kw">end</span>; | |
| 71 | + | |
| 72 | +<span class="kw">proc</span> main*; | |
| 73 | +<span class="kw">begin</span> | |
| 74 | + step(<span class="number">1</span>); | |
| 75 | + step(<span class="number">2</span>); | |
| 76 | + Out.int(lines(<span class="string">"/dev/null"</span>)); Out.ln; | |
| 77 | + Out.int(lines(<span class="string">"/no/such/file"</span>)); Out.ln; | |
| 78 | +<span class="kw">end</span>; | |
| 79 | + | |
| 80 | +<span class="kw">end</span> Defers.</code></pre> | |
| 81 | +<pre class="output"><code>in 1 | |
| 82 | +working | |
| 83 | +done | |
| 84 | +out | |
| 85 | +in 2 | |
| 86 | +out | |
| 87 | +0 | |
| 88 | +-1 | |
| 89 | +</code></pre> | |
| 90 | +<p><code>defer s;</code> runs <code>s</code> when the program leaves the statements the <code>defer</code> stands in: at their end, or by a <code>return</code>, a <code>break</code> or a <code>continue</code>. Deferred statements run the last first, and only those whose <code>defer</code> was reached. So a file is closed beside the line that opens it, however the procedure ends.</p> | |
| 91 | +<h2>The order, and a <code>return</code> value</h2> | |
| 92 | +<p>A <code>return e;</code> evaluates <code>e</code> before the deferred statements run, so the value is what it was at the return.</p> | |
| 93 | +<div class="file"><span>Order.raz</span></div><pre class="code"><code><span class="kw">module</span> Order; | |
| 94 | +<span class="kw">import</span> Out; | |
| 95 | + | |
| 96 | +<span class="kw">var</span> counter: <span class="ty">INT</span>; | |
| 97 | + | |
| 98 | +<span class="kw">proc</span> next(): <span class="ty">INT</span>; | |
| 99 | +<span class="kw">begin</span> | |
| 100 | + <span class="kw">defer</span> <span class="ty">INC</span>(counter); | |
| 101 | + <span class="kw">return</span> counter; <span class="comment">(* the old value is returned; then counter grows *)</span> | |
| 102 | +<span class="kw">end</span>; | |
| 103 | + | |
| 104 | +<span class="kw">proc</span> nest; | |
| 105 | +<span class="kw">begin</span> | |
| 106 | + <span class="kw">defer</span> Out.str(<span class="string">"1 "</span>); | |
| 107 | + <span class="kw">defer</span> Out.str(<span class="string">"2 "</span>); | |
| 108 | + <span class="kw">defer</span> Out.str(<span class="string">"3 "</span>); | |
| 109 | + Out.str(<span class="string">"body: "</span>); | |
| 110 | +<span class="kw">end</span>; | |
| 111 | + | |
| 112 | +<span class="kw">proc</span> main*; | |
| 113 | +<span class="kw">var</span> a, b: <span class="ty">INT</span>; | |
| 114 | +<span class="kw">begin</span> | |
| 115 | + a := next(); | |
| 116 | + b := next(); | |
| 117 | + Out.int(a); Out.char(<span class="string">' '</span>); Out.int(b); Out.char(<span class="string">' '</span>); Out.int(counter); Out.ln; | |
| 118 | + nest; | |
| 119 | + Out.ln; | |
| 120 | +<span class="kw">end</span>; | |
| 121 | + | |
| 122 | +<span class="kw">end</span> Order.</code></pre> | |
| 123 | +<pre class="output"><code>0 1 2 | |
| 124 | +body: 3 2 1 | |
| 125 | +</code></pre> | |
| 126 | +<h2>In a loop</h2> | |
| 127 | +<p>A <code>defer</code> stands in the statement list that holds it, so in a loop body it runs at the end of each pass, and on a <code>break</code> or a <code>continue</code>.</p> | |
| 128 | +<div class="file"><span>Passes.raz</span></div><pre class="code"><code><span class="kw">module</span> Passes; | |
| 129 | +<span class="kw">import</span> Out; | |
| 130 | + | |
| 131 | +<span class="kw">proc</span> main*; | |
| 132 | +<span class="kw">var</span> i: <span class="ty">INT</span>; | |
| 133 | +<span class="kw">begin</span> | |
| 134 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">4</span> <span class="kw">do</span> | |
| 135 | + Out.str(<span class="string">"pass "</span>); Out.int(i); | |
| 136 | + <span class="kw">defer</span> Out.str(<span class="string">" done\n"</span>); | |
| 137 | + <span class="kw">if</span> i = <span class="number">3</span> <span class="kw">then</span> <span class="kw">break</span>; <span class="kw">end</span>; | |
| 138 | + Out.str(<span class="string">" ..."</span>); | |
| 139 | + <span class="kw">end</span>; | |
| 140 | +<span class="kw">end</span>; | |
| 141 | + | |
| 142 | +<span class="kw">end</span> Passes.</code></pre> | |
| 143 | +<pre class="output"><code>pass 1 ... done | |
| 144 | +pass 2 ... done | |
| 145 | +pass 3 done | |
| 146 | +</code></pre> | |
| 147 | +<h2>Giving back what was taken</h2> | |
| 148 | +<p>The point is that acquiring and releasing sit next to each other, so a new early <code>return</code> added later can't leak. Here an arena and a buffer are both released on every path.</p> | |
| 149 | +<div class="file"><span>Report.raz</span></div><pre class="code"><code><span class="kw">module</span> Report; | |
| 150 | +<span class="kw">import</span> Out, Buf, Heap; | |
| 151 | + | |
| 152 | +<span class="comment">(* a line, built in a buffer; false (nothing written) if n is negative *)</span> | |
| 153 | +<span class="kw">proc</span> line(n: <span class="ty">INT</span>): <span class="ty">BOOL</span>; | |
| 154 | +<span class="kw">var</span> b: Buf.Buf; | |
| 155 | +<span class="kw">begin</span> | |
| 156 | + <span class="kw">if</span> n < <span class="number">0</span> <span class="kw">then</span> <span class="kw">return</span> <span class="ty">false</span>; <span class="kw">end</span>; | |
| 157 | + Buf.init(b, Heap.heap); | |
| 158 | + <span class="kw">defer</span> Buf.done(b); <span class="comment">(* freed on every way out below *)</span> | |
| 159 | + Buf.str(b, <span class="string">"n is "</span>); | |
| 160 | + <span class="kw">if</span> n > <span class="number">9</span> <span class="kw">then</span> | |
| 161 | + Buf.str(b, <span class="string">"large"</span>); | |
| 162 | + Out.str(Buf.bytes(b)); Out.ln; | |
| 163 | + <span class="kw">return</span> <span class="ty">true</span>; | |
| 164 | + <span class="kw">end</span>; | |
| 165 | + Buf.str(b, <span class="string">"small"</span>); | |
| 166 | + Out.str(Buf.bytes(b)); Out.ln; | |
| 167 | + <span class="kw">return</span> <span class="ty">true</span>; | |
| 168 | +<span class="kw">end</span>; | |
| 169 | + | |
| 170 | +<span class="kw">proc</span> main*; | |
| 171 | +<span class="kw">begin</span> | |
| 172 | + _ := line(<span class="number">3</span>); | |
| 173 | + _ := line(<span class="number">30</span>); | |
| 174 | + <span class="kw">if</span> <span class="kw">not</span> line(-<span class="number">1</span>) <span class="kw">then</span> Out.str(<span class="string">"rejected\n"</span>); <span class="kw">end</span>; | |
| 175 | +<span class="kw">end</span>; | |
| 176 | + | |
| 177 | +<span class="kw">end</span> Report.</code></pre> | |
| 178 | +<pre class="output"><code>n is small | |
| 179 | +n is large | |
| 180 | +rejected | |
| 181 | +</code></pre> | |
| 182 | +<h2>What defer does not do</h2> | |
| 183 | +<p>A deferred statement can't contain a <code>return</code>, <code>break</code> or <code>defer</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, so deferred cleanup is for the program's resources, not for what must happen at exit; that is what <code>Rt.atExit</code> is for.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="errors.html">← Errors</a><a href="index.html">Contents</a><a class="next" href="checks.html">When it goes wrong →</a></div></article></div> | |
| 184 | +</main> | |
| 185 | +<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> | |
| 186 | +</body> | |
| 187 | +</html> |
| @@ -0,0 +1,217 @@ | ||
| 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>Errors - Raz, Set, Go</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="Errors - Raz, Set, Go"> | |
| 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.lucelad.workers.dev/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" aria-current="page">Raz, Set, Go</a><a href="../advanced/index.html">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<div class="tour"><aside><h2>Raz, Set, Go</h2><h3>Raz</h3><ol start='1'> | |
| 22 | +<li><a href="hello.html">Hello, world</a></li> | |
| 23 | +<li><a href="modules.html">Modules</a></li> | |
| 24 | +<li><a href="integers.html">Integers</a></li> | |
| 25 | +<li><a href="values.html">Values and conversions</a></li> | |
| 26 | +<li><a href="procedures.html">Procedures and several results</a></li> | |
| 27 | +</ol> | |
| 28 | +<h3>Set</h3><ol start='6'> | |
| 29 | +<li><a href="slices.html">Arrays, slices and strings</a></li> | |
| 30 | +<li><a href="records.html">Records and pointers</a></li> | |
| 31 | +<li><a href="variants.html">Enumerations, sets, variants and match</a></li> | |
| 32 | +<li><a href="memory.html">Memory and allocators</a></li> | |
| 33 | +</ol> | |
| 34 | +<h3>Go</h3><ol start='10'> | |
| 35 | +<li><a href="errors.html" aria-current="page">Errors</a></li> | |
| 36 | +<li><a href="defer.html">Defer</a></li> | |
| 37 | +<li><a href="checks.html">When it goes wrong</a></li> | |
| 38 | +<li><a href="generics.html">Generic modules</a></li> | |
| 39 | +<li><a href="c.html">Talking to C</a></li> | |
| 40 | +<li><a href="threads.html">Threads</a></li> | |
| 41 | +</ol></aside><article><p class="kicker">Go · lesson 10 of 15</p><h1>Errors</h1> | |
| 42 | +<div class="file"><span>Errors.raz</span></div><pre class="code"><code><span class="kw">module</span> Errors; | |
| 43 | +<span class="kw">import</span> Out, Str; | |
| 44 | + | |
| 45 | +<span class="kw">const</span> | |
| 46 | + Empty*: <span class="ty">ERROR</span> = <span class="string">"nothing to read"</span>; | |
| 47 | + TooBig*: <span class="ty">ERROR</span> = <span class="string">"not a number up to 1000"</span>; | |
| 48 | + | |
| 49 | +<span class="comment">(* the number s holds, up to 1000 *)</span> | |
| 50 | +<span class="kw">proc</span> number(s: []<span class="ty">U8</span>): (<span class="ty">INT</span>, <span class="ty">ERROR</span>); | |
| 51 | +<span class="kw">var</span> n: <span class="ty">I64</span>; ok: <span class="ty">BOOL</span>; | |
| 52 | +<span class="kw">begin</span> | |
| 53 | + <span class="kw">if</span> <span class="ty">LEN</span>(s) = <span class="number">0</span> <span class="kw">then</span> <span class="kw">return</span> <span class="number">0</span>, Empty; <span class="kw">end</span>; | |
| 54 | + n, ok := Str.toInt(s); | |
| 55 | + <span class="kw">if</span> <span class="kw">not</span> ok <span class="kw">or</span> (n > <span class="number">1000</span>) <span class="kw">then</span> <span class="kw">return</span> <span class="number">0</span>, TooBig; <span class="kw">end</span>; | |
| 56 | + <span class="kw">return</span> <span class="ty">INT</span>(n), <span class="ty">nil</span>; | |
| 57 | +<span class="kw">end</span>; | |
| 58 | + | |
| 59 | +<span class="comment">(* the sum of the numbers in words: the first error ends it *)</span> | |
| 60 | +<span class="kw">proc</span> total(words: [][]<span class="ty">U8</span>): (<span class="ty">INT</span>, <span class="ty">ERROR</span>); | |
| 61 | +<span class="kw">var</span> i, sum: <span class="ty">INT</span>; | |
| 62 | +<span class="kw">begin</span> | |
| 63 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="ty">LEN</span>(words) - <span class="number">1</span> <span class="kw">do</span> | |
| 64 | + sum := sum + <span class="kw">try</span> number(words[i]); | |
| 65 | + <span class="kw">end</span>; | |
| 66 | + <span class="kw">return</span> sum, <span class="ty">nil</span>; | |
| 67 | +<span class="kw">end</span>; | |
| 68 | + | |
| 69 | +<span class="kw">proc</span> main*; | |
| 70 | +<span class="kw">var</span> words: [<span class="number">3</span>][]<span class="ty">U8</span>; i, n: <span class="ty">INT</span>; err: <span class="ty">ERROR</span>; | |
| 71 | +<span class="kw">begin</span> | |
| 72 | + words := [<span class="string">"42"</span>, <span class="string">""</span>, <span class="string">"12345"</span>]; | |
| 73 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">2</span> <span class="kw">do</span> | |
| 74 | + n, err := number(words[i]); | |
| 75 | + <span class="kw">if</span> err = <span class="ty">nil</span> <span class="kw">then</span> Out.int(n); | |
| 76 | + <span class="kw">elsif</span> err = Empty <span class="kw">then</span> Out.str(<span class="string">"empty"</span>); | |
| 77 | + <span class="kw">else</span> Out.str(<span class="ty">MSG</span>(err)); | |
| 78 | + <span class="kw">end</span>; | |
| 79 | + Out.ln; | |
| 80 | + <span class="kw">end</span>; | |
| 81 | + n, err := total([<span class="string">"1"</span>, <span class="string">"2"</span>, <span class="string">"3"</span>]); | |
| 82 | + Out.int(n); Out.ln; | |
| 83 | + n, err := total(words); | |
| 84 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">end</span>; | |
| 85 | +<span class="kw">end</span>; | |
| 86 | + | |
| 87 | +<span class="kw">end</span> Errors.</code></pre> | |
| 88 | +<pre class="output"><code>42 | |
| 89 | +empty | |
| 90 | +not a number up to 1000 | |
| 91 | +6 | |
| 92 | +nothing to read | |
| 93 | +</code></pre> | |
| 94 | +<p>A procedure that can fail returns an <code>ERROR</code> beside its result, and <code>nil</code> when it didn't. Each <code>ERROR</code> constant is an error of its own, compared with <code>=</code> by which declaration made it, never by its message; <code>MSG(err)</code> is the message. An exported one, as <code>Empty</code> is here, lets the callers tell it from the others. raz has no exceptions, so every failure is visible in the signature and handled where the call is written.</p> | |
| 95 | +<h2>Handling them by kind</h2> | |
| 96 | +<p>Because an error is compared by identity, a caller can handle the cases it knows and pass on the rest.</p> | |
| 97 | +<div class="file"><span>Parse.raz</span></div><pre class="code"><code><span class="kw">module</span> Parse; | |
| 98 | +<span class="kw">import</span> Out, Str; | |
| 99 | + | |
| 100 | +<span class="kw">const</span> | |
| 101 | + Empty*: <span class="ty">ERROR</span> = <span class="string">"nothing to read"</span>; | |
| 102 | + Bad*: <span class="ty">ERROR</span> = <span class="string">"not a number"</span>; | |
| 103 | + Range*: <span class="ty">ERROR</span> = <span class="string">"out of range"</span>; | |
| 104 | + | |
| 105 | +<span class="comment">(* a percentage, 0 to 100 *)</span> | |
| 106 | +<span class="kw">proc</span> percent(s: []<span class="ty">U8</span>): (<span class="ty">INT</span>, <span class="ty">ERROR</span>); | |
| 107 | +<span class="kw">var</span> n: <span class="ty">I64</span>; ok: <span class="ty">BOOL</span>; | |
| 108 | +<span class="kw">begin</span> | |
| 109 | + <span class="kw">if</span> <span class="ty">LEN</span>(s) = <span class="number">0</span> <span class="kw">then</span> <span class="kw">return</span> <span class="number">0</span>, Empty; <span class="kw">end</span>; | |
| 110 | + n, ok := Str.toInt(s); | |
| 111 | + <span class="kw">if</span> <span class="kw">not</span> ok <span class="kw">then</span> <span class="kw">return</span> <span class="number">0</span>, Bad; <span class="kw">end</span>; | |
| 112 | + <span class="kw">if</span> (n < <span class="number">0</span>) <span class="kw">or</span> (n > <span class="number">100</span>) <span class="kw">then</span> <span class="kw">return</span> <span class="number">0</span>, Range; <span class="kw">end</span>; | |
| 113 | + <span class="kw">return</span> <span class="ty">INT</span>(n), <span class="ty">nil</span>; | |
| 114 | +<span class="kw">end</span>; | |
| 115 | + | |
| 116 | +<span class="kw">proc</span> main*; | |
| 117 | +<span class="kw">var</span> inputs: [<span class="number">4</span>][]<span class="ty">U8</span>; i, n: <span class="ty">INT</span>; err: <span class="ty">ERROR</span>; | |
| 118 | +<span class="kw">begin</span> | |
| 119 | + inputs := [<span class="string">"42"</span>, <span class="string">""</span>, <span class="string">"forty"</span>, <span class="string">"140"</span>]; | |
| 120 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> | |
| 121 | + n, err := percent(inputs[i]); | |
| 122 | + <span class="kw">if</span> err = <span class="ty">nil</span> <span class="kw">then</span> | |
| 123 | + Out.int(n); Out.str(<span class="string">"%"</span>); | |
| 124 | + <span class="kw">elsif</span> err = Empty <span class="kw">then</span> | |
| 125 | + Out.str(<span class="string">"(skipped)"</span>); | |
| 126 | + <span class="kw">else</span> | |
| 127 | + Out.str(<span class="string">"error: "</span>); Out.str(<span class="ty">MSG</span>(err)); | |
| 128 | + <span class="kw">end</span>; | |
| 129 | + Out.ln; | |
| 130 | + <span class="kw">end</span>; | |
| 131 | +<span class="kw">end</span>; | |
| 132 | + | |
| 133 | +<span class="kw">end</span> Parse.</code></pre> | |
| 134 | +<pre class="output"><code>42% | |
| 135 | +(skipped) | |
| 136 | +error: not a number | |
| 137 | +error: out of range | |
| 138 | +</code></pre> | |
| 139 | +<h2>Passing errors up</h2> | |
| 140 | +<p>When a procedure can't do anything useful with an error, it returns it, so the first caller that can decide gets it. Written out, that is a test and a <code>return</code> after each call:</p> | |
| 141 | +<p>``<code>raz x, err := value(a); if err # nil then return 0, err; end; </code>``</p> | |
| 142 | +<p><code>try</code> says the same in a word. <code>x := try value(a)</code> calls <code>value</code> and, if the error it returned isn't <code>nil</code>, returns that error from the procedure it stands in, with zero for that procedure's other results; otherwise it is <code>value</code>'s number. There is no hidden unwinding and no handler: <code>try</code> is a <code>return</code>, written where the call is, and a procedure that uses it must end in an <code>ERROR</code> itself, so its signature says it can fail. <code>main</code> returns none, so it tests its errors and deals with them.</p> | |
| 143 | +<div class="file"><span>Layers.raz</span></div><pre class="code"><code><span class="kw">module</span> Layers; | |
| 144 | +<span class="kw">import</span> Out, Str; | |
| 145 | + | |
| 146 | +<span class="kw">const</span> Missing*: <span class="ty">ERROR</span> = <span class="string">"key missing"</span>; | |
| 147 | + | |
| 148 | +<span class="comment">(* the number after "n=" in a line like "n=17" *)</span> | |
| 149 | +<span class="kw">proc</span> value(line: []<span class="ty">U8</span>): (<span class="ty">INT</span>, <span class="ty">ERROR</span>); | |
| 150 | +<span class="kw">var</span> n: <span class="ty">I64</span>; ok: <span class="ty">BOOL</span>; | |
| 151 | +<span class="kw">begin</span> | |
| 152 | + <span class="kw">if</span> <span class="kw">not</span> Str.hasPrefix(line, <span class="string">"n="</span>) <span class="kw">then</span> <span class="kw">return</span> <span class="number">0</span>, Missing; <span class="kw">end</span>; | |
| 153 | + n, ok := Str.toInt(line[<span class="number">2</span>..<span class="ty">LEN</span>(line)]); | |
| 154 | + <span class="kw">if</span> <span class="kw">not</span> ok <span class="kw">then</span> <span class="kw">return</span> <span class="number">0</span>, Missing; <span class="kw">end</span>; | |
| 155 | + <span class="kw">return</span> <span class="ty">INT</span>(n), <span class="ty">nil</span>; | |
| 156 | +<span class="kw">end</span>; | |
| 157 | + | |
| 158 | +<span class="comment">(* the sum of the values of two lines: the first error ends it *)</span> | |
| 159 | +<span class="kw">proc</span> sum(a, b: []<span class="ty">U8</span>): (<span class="ty">INT</span>, <span class="ty">ERROR</span>); | |
| 160 | +<span class="kw">begin</span> | |
| 161 | + <span class="kw">return</span> <span class="kw">try</span> value(a) + <span class="kw">try</span> value(b), <span class="ty">nil</span>; | |
| 162 | +<span class="kw">end</span>; | |
| 163 | + | |
| 164 | +<span class="kw">proc</span> main*; | |
| 165 | +<span class="kw">var</span> n: <span class="ty">INT</span>; err: <span class="ty">ERROR</span>; | |
| 166 | +<span class="kw">begin</span> | |
| 167 | + n, err := sum(<span class="string">"n=40"</span>, <span class="string">"n=2"</span>); | |
| 168 | + <span class="kw">if</span> err = <span class="ty">nil</span> <span class="kw">then</span> Out.int(n); Out.ln; <span class="kw">end</span>; | |
| 169 | + n, err := sum(<span class="string">"n=40"</span>, <span class="string">"x=2"</span>); | |
| 170 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="string">"sum failed: "</span>); Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">end</span>; | |
| 171 | +<span class="kw">end</span>; | |
| 172 | + | |
| 173 | +<span class="kw">end</span> Layers.</code></pre> | |
| 174 | +<pre class="output"><code>42 | |
| 175 | +sum failed: key missing | |
| 176 | +</code></pre> | |
| 177 | +<h2>When the library reports errors</h2> | |
| 178 | +<p>Library procedures that can fail say so in the same way: <code>Thread.spawn</code> returns an <code>ERROR</code>; <code>Sys</code> calls return a negative <code>errno</code> as an <code>INT</code>, with <code>0</code> or a positive count for success; <code>Files.read</code> returns a <code>BOOL</code>. The first is the language's way; the others are the system's, left as they are.</p> | |
| 179 | +<div class="file"><span>Probe.raz</span></div><pre class="code"><code><span class="kw">module</span> Probe; | |
| 180 | +<span class="kw">import</span> Out, Sys; | |
| 181 | + | |
| 182 | +<span class="kw">proc</span> main*; | |
| 183 | +<span class="kw">var</span> fd: <span class="ty">INT</span>; | |
| 184 | +<span class="kw">begin</span> | |
| 185 | + fd := Sys.openRead(<span class="string">"/no/such/file"</span>); | |
| 186 | + <span class="kw">if</span> fd < <span class="number">0</span> <span class="kw">then</span> | |
| 187 | + Out.str(<span class="string">"open failed, errno "</span>); Out.int(-fd); Out.ln; <span class="comment">(* 2: ENOENT *)</span> | |
| 188 | + <span class="kw">end</span>; | |
| 189 | + fd := Sys.openRead(<span class="string">"/dev/null"</span>); | |
| 190 | + <span class="kw">if</span> fd >= <span class="number">0</span> <span class="kw">then</span> | |
| 191 | + Out.str(<span class="string">"open worked\n"</span>); | |
| 192 | + Sys.close(fd); | |
| 193 | + <span class="kw">end</span>; | |
| 194 | +<span class="kw">end</span>; | |
| 195 | + | |
| 196 | +<span class="kw">end</span> Probe.</code></pre> | |
| 197 | +<pre class="output"><code>open failed, errno 2 | |
| 198 | +open worked | |
| 199 | +</code></pre> | |
| 200 | +<h2>When there is nothing to do but stop</h2> | |
| 201 | +<p>A program that has found a state it can't carry on from, such as a broken invariant, says so and ends with <code>Rt.stop</code>: the message goes to standard error and the status is 2, the same as a failed check.</p> | |
| 202 | +<div class="file"><span>Giveup.raz</span></div><pre class="code"><code><span class="kw">module</span> Giveup; | |
| 203 | +<span class="kw">import</span> Rt; | |
| 204 | + | |
| 205 | +<span class="kw">proc</span> main*; | |
| 206 | +<span class="kw">begin</span> | |
| 207 | + Rt.stop(<span class="string">"the table is corrupt"</span>); | |
| 208 | +<span class="kw">end</span>; | |
| 209 | + | |
| 210 | +<span class="kw">end</span> Giveup.</code></pre> | |
| 211 | +<pre class="output term"><code><span class="cmd">$ raz run Giveup.raz; echo "status $?"</span> | |
| 212 | +the table is corrupt | |
| 213 | +status 2</code></pre><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="memory.html">← Memory and allocators</a><a href="index.html">Contents</a><a class="next" href="defer.html">Defer →</a></div></article></div> | |
| 214 | +</main> | |
| 215 | +<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> | |
| 216 | +</body> | |
| 217 | +</html> |
| @@ -0,0 +1,174 @@ | ||
| 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>Generic modules - Raz, Set, Go</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="Generic modules - Raz, Set, Go"> | |
| 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.lucelad.workers.dev/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" aria-current="page">Raz, Set, Go</a><a href="../advanced/index.html">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<div class="tour"><aside><h2>Raz, Set, Go</h2><h3>Raz</h3><ol start='1'> | |
| 22 | +<li><a href="hello.html">Hello, world</a></li> | |
| 23 | +<li><a href="modules.html">Modules</a></li> | |
| 24 | +<li><a href="integers.html">Integers</a></li> | |
| 25 | +<li><a href="values.html">Values and conversions</a></li> | |
| 26 | +<li><a href="procedures.html">Procedures and several results</a></li> | |
| 27 | +</ol> | |
| 28 | +<h3>Set</h3><ol start='6'> | |
| 29 | +<li><a href="slices.html">Arrays, slices and strings</a></li> | |
| 30 | +<li><a href="records.html">Records and pointers</a></li> | |
| 31 | +<li><a href="variants.html">Enumerations, sets, variants and match</a></li> | |
| 32 | +<li><a href="memory.html">Memory and allocators</a></li> | |
| 33 | +</ol> | |
| 34 | +<h3>Go</h3><ol start='10'> | |
| 35 | +<li><a href="errors.html">Errors</a></li> | |
| 36 | +<li><a href="defer.html">Defer</a></li> | |
| 37 | +<li><a href="checks.html">When it goes wrong</a></li> | |
| 38 | +<li><a href="generics.html" aria-current="page">Generic modules</a></li> | |
| 39 | +<li><a href="c.html">Talking to C</a></li> | |
| 40 | +<li><a href="threads.html">Threads</a></li> | |
| 41 | +</ol></aside><article><p class="kicker">Go · lesson 13 of 15</p><h1>Generic modules</h1> | |
| 42 | +<p>A module may take types, and the procedures it needs on them, as parameters. <code>Biggest.raz</code>:</p> | |
| 43 | +<div class="file"><span>Biggest.raz</span></div><pre class="code"><code><span class="kw">module</span> Biggest(T; less: <span class="kw">proc</span>(a, b: T): <span class="ty">BOOL</span>); | |
| 44 | + | |
| 45 | +<span class="comment">(* the biggest of s, which mustn't be empty *)</span> | |
| 46 | +<span class="kw">proc</span> max*(s: []T): T; | |
| 47 | +<span class="kw">var</span> i: <span class="ty">INT</span>; m: T; | |
| 48 | +<span class="kw">begin</span> | |
| 49 | + m := s[<span class="number">0</span>]; | |
| 50 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="ty">LEN</span>(s) - <span class="number">1</span> <span class="kw">do</span> | |
| 51 | + <span class="kw">if</span> less(m, s[i]) <span class="kw">then</span> m := s[i]; <span class="kw">end</span>; | |
| 52 | + <span class="kw">end</span>; | |
| 53 | + <span class="kw">return</span> m; | |
| 54 | +<span class="kw">end</span>; | |
| 55 | + | |
| 56 | +<span class="kw">end</span> Biggest.</code></pre> | |
| 57 | +<p>and a program that uses it:</p> | |
| 58 | +<div class="file"><span>Generics.raz</span></div><pre class="code"><code><span class="kw">module</span> Generics; | |
| 59 | +<span class="kw">import</span> Out, Ints := Biggest(<span class="ty">INT</span>, before), | |
| 60 | + Words := Biggest([]<span class="ty">U8</span>, shorter), Order := Sort(<span class="ty">INT</span>, before); | |
| 61 | + | |
| 62 | +<span class="kw">proc</span> before(a, b: <span class="ty">INT</span>): <span class="ty">BOOL</span>; | |
| 63 | +<span class="kw">begin</span> | |
| 64 | + <span class="kw">return</span> a < b; | |
| 65 | +<span class="kw">end</span>; | |
| 66 | + | |
| 67 | +<span class="kw">proc</span> shorter(a, b: []<span class="ty">U8</span>): <span class="ty">BOOL</span>; | |
| 68 | +<span class="kw">begin</span> | |
| 69 | + <span class="kw">return</span> <span class="ty">LEN</span>(a) < <span class="ty">LEN</span>(b); | |
| 70 | +<span class="kw">end</span>; | |
| 71 | + | |
| 72 | +<span class="kw">proc</span> main*; | |
| 73 | +<span class="kw">var</span> a: [<span class="number">5</span>]<span class="ty">INT</span>; i: <span class="ty">INT</span>; | |
| 74 | +<span class="kw">begin</span> | |
| 75 | + a := [<span class="number">3</span>, <span class="number">1</span>, <span class="number">4</span>, <span class="number">1</span>, <span class="number">5</span>]; | |
| 76 | + Out.int(Ints.max(a)); Out.ln; | |
| 77 | + Out.str(Words.max([<span class="string">"a"</span>, <span class="string">"tree"</span>, <span class="string">"is"</span>])); Out.ln; | |
| 78 | + Order.sort(a); | |
| 79 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">4</span> <span class="kw">do</span> Out.int(a[i]); Out.char(<span class="string">' '</span>); <span class="kw">end</span>; | |
| 80 | + Out.ln; | |
| 81 | +<span class="kw">end</span>; | |
| 82 | + | |
| 83 | +<span class="kw">end</span> Generics.</code></pre> | |
| 84 | +<pre class="output"><code>5 | |
| 85 | +tree | |
| 86 | +1 1 3 4 5 | |
| 87 | +</code></pre> | |
| 88 | +<p>Each import with its own arguments makes an instance: the module compiled again, with <code>T</code> standing for the type given, and <code>less</code> calling the procedure given. The arguments may name what the importing module declares later, as <code>before</code> is here. There is no run-time cost for being generic, and no boxing: <code>Ints.max</code> is exactly the code you would write by hand for <code>INT</code>.</p> | |
| 89 | +<h2>Writing your own</h2> | |
| 90 | +<p>A generic module is an ordinary module with parameters in its header. Here is a stack of anything, which takes the allocator it grows from.</p> | |
| 91 | +<div class="file"><span>Stk.raz</span></div><pre class="code"><code><span class="kw">module</span> Stk(T); | |
| 92 | +<span class="kw">import</span> Mem; | |
| 93 | + | |
| 94 | +<span class="kw">type</span> | |
| 95 | + Stack* = <span class="kw">record</span> | |
| 96 | + items: ^T; <span class="comment">(* an array of cap Ts *)</span> | |
| 97 | + cap*, len*: <span class="ty">INT</span>; | |
| 98 | + a: ^Mem.Allocator; | |
| 99 | + <span class="kw">end</span>; | |
| 100 | + | |
| 101 | +<span class="kw">proc</span> init*(s: ^Stack; a: ^Mem.Allocator); | |
| 102 | +<span class="kw">begin</span> | |
| 103 | + s^.a := a; | |
| 104 | + s^.items := <span class="ty">nil</span>; | |
| 105 | + s^.cap := <span class="number">0</span>; | |
| 106 | + s^.len := <span class="number">0</span>; | |
| 107 | +<span class="kw">end</span>; | |
| 108 | + | |
| 109 | +<span class="comment">(* v on top; false if the allocator has no room *)</span> | |
| 110 | +<span class="kw">proc</span> push*(s: ^Stack; v: T): <span class="ty">BOOL</span>; | |
| 111 | +<span class="kw">var</span> bigger: ^T; i, cap: <span class="ty">INT</span>; src, dst: ^T; | |
| 112 | +<span class="kw">begin</span> | |
| 113 | + <span class="kw">if</span> s^.len = s^.cap <span class="kw">then</span> | |
| 114 | + <span class="kw">if</span> s^.cap = <span class="number">0</span> <span class="kw">then</span> cap := <span class="number">4</span>; <span class="kw">else</span> cap := s^.cap * <span class="number">2</span>; <span class="kw">end</span>; | |
| 115 | + bigger := ^T(Mem.alloc(s^.a, cap * <span class="ty">SIZE</span>(T), <span class="number">8</span>)); | |
| 116 | + <span class="kw">if</span> bigger = <span class="ty">nil</span> <span class="kw">then</span> <span class="kw">return</span> <span class="ty">false</span>; <span class="kw">end</span>; | |
| 117 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> s^.len - <span class="number">1</span> <span class="kw">do</span> | |
| 118 | + src := ^T(<span class="ty">INT</span>(s^.items) + i * <span class="ty">SIZE</span>(T)); | |
| 119 | + dst := ^T(<span class="ty">INT</span>(bigger) + i * <span class="ty">SIZE</span>(T)); | |
| 120 | + dst^ := src^; | |
| 121 | + <span class="kw">end</span>; | |
| 122 | + <span class="kw">if</span> s^.items # <span class="ty">nil</span> <span class="kw">then</span> Mem.free(s^.a, ^<span class="ty">U8</span>(s^.items)); <span class="kw">end</span>; | |
| 123 | + s^.items := bigger; | |
| 124 | + s^.cap := cap; | |
| 125 | + <span class="kw">end</span>; | |
| 126 | + dst := ^T(<span class="ty">INT</span>(s^.items) + s^.len * <span class="ty">SIZE</span>(T)); | |
| 127 | + dst^ := v; | |
| 128 | + <span class="ty">INC</span>(s^.len); | |
| 129 | + <span class="kw">return</span> <span class="ty">true</span>; | |
| 130 | +<span class="kw">end</span>; | |
| 131 | + | |
| 132 | +<span class="comment">(* the top value, taken off; false if empty *)</span> | |
| 133 | +<span class="kw">proc</span> pop*(s: ^Stack): (T, <span class="ty">BOOL</span>); | |
| 134 | +<span class="kw">var</span> z: T; p: ^T; | |
| 135 | +<span class="kw">begin</span> | |
| 136 | + <span class="kw">if</span> s^.len = <span class="number">0</span> <span class="kw">then</span> <span class="kw">return</span> z, <span class="ty">false</span>; <span class="kw">end</span>; | |
| 137 | + <span class="ty">DEC</span>(s^.len); | |
| 138 | + p := ^T(<span class="ty">INT</span>(s^.items) + s^.len * <span class="ty">SIZE</span>(T)); | |
| 139 | + <span class="kw">return</span> p^, <span class="ty">true</span>; | |
| 140 | +<span class="kw">end</span>; | |
| 141 | + | |
| 142 | +<span class="kw">end</span> Stk.</code></pre> | |
| 143 | +<div class="file"><span>Uses.raz</span></div><pre class="code"><code><span class="kw">module</span> Uses; | |
| 144 | +<span class="kw">import</span> Out, Heap, Nums := Stk(<span class="ty">INT</span>), Pairs := Stk(Pair); | |
| 145 | + | |
| 146 | +<span class="kw">type</span> Pair = <span class="kw">record</span> a, b: <span class="ty">INT</span>; <span class="kw">end</span>; | |
| 147 | + | |
| 148 | +<span class="kw">proc</span> main*; | |
| 149 | +<span class="kw">var</span> n: Nums.Stack; p: Pairs.Stack; i, v: <span class="ty">INT</span>; ok: <span class="ty">BOOL</span>; pr: Pair; | |
| 150 | +<span class="kw">begin</span> | |
| 151 | + Nums.init(<span class="ty">ADR</span>(n), Heap.heap); | |
| 152 | + Pairs.init(<span class="ty">ADR</span>(p), Heap.heap); | |
| 153 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">10</span> <span class="kw">do</span> _ := Nums.push(<span class="ty">ADR</span>(n), i * i); <span class="kw">end</span>; | |
| 154 | + _ := Pairs.push(<span class="ty">ADR</span>(p), {a: <span class="number">3</span>, b: <span class="number">4</span>}); | |
| 155 | + v, ok := Nums.pop(<span class="ty">ADR</span>(n)); | |
| 156 | + Out.int(v); Out.str(<span class="string">" of "</span>); Out.int(n.len + <span class="number">1</span>); Out.ln; | |
| 157 | + pr, ok := Pairs.pop(<span class="ty">ADR</span>(p)); | |
| 158 | + Out.int(pr.a * pr.b); Out.ln; | |
| 159 | + _, ok := Pairs.pop(<span class="ty">ADR</span>(p)); | |
| 160 | + <span class="kw">if</span> <span class="kw">not</span> ok <span class="kw">then</span> Out.str(<span class="string">"empty\n"</span>); <span class="kw">end</span>; | |
| 161 | +<span class="kw">end</span>; | |
| 162 | + | |
| 163 | +<span class="kw">end</span> Uses.</code></pre> | |
| 164 | +<pre class="output"><code>100 of 10 | |
| 165 | +12 | |
| 166 | +empty | |
| 167 | +</code></pre> | |
| 168 | +<p>Two instances (<code>Nums</code> and <code>Pairs</code>) are two separate modules, compiled with their own <code>T</code>. Its pointer arithmetic is the one place where the program does what C does and leaves the checks behind; a library would keep that inside, as this does.</p> | |
| 169 | +<h2>The library's generics</h2> | |
| 170 | +<p>The library's <code>List</code>, <code>Map</code> and <code>Sort</code> are generic modules. A <code>Map</code> takes its key hash and equality as procedure arguments: <code>import Count := Map([]U8, INT, Str.hash, Str.eq);</code>. The advanced tour uses each of them in a real program.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="checks.html">← When it goes wrong</a><a href="index.html">Contents</a><a class="next" href="c.html">Talking to C →</a></div></article></div> | |
| 171 | +</main> | |
| 172 | +<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> | |
| 173 | +</body> | |
| 174 | +</html> |
| @@ -70,7 +70,7 @@ | ||
| 70 | 70 | <span class="cmd">$ raz run Quiet.raz</span> |
| 71 | 71 | hello, again |
| 72 | 72 | <span class="cmd">$ ls -l Quiet | awk '{print $5, "bytes"}'</span> |
| 73 | -28608 bytes</code></pre> | |
| 73 | +28680 bytes</code></pre> | |
| 74 | 74 | <p>The program is a static executable with no run time besides the code it uses, so it is a few kilobytes, and runs without any library installed.</p> |
| 75 | 75 | <h2>What <code>Out</code> can write</h2> |
| 76 | 76 | <p><code>Out</code> is the library's buffered output. It writes strings, single characters, numbers in decimal or hexadecimal, and a line feed. A string is written as it is, with <code>\n</code> for a line feed, <code>\t</code> for a tab, <code>\"</code> and <code>\\</code>; or between backquotes, as a raw string with no escapes at all, which may run over lines (lesson 6).</p> |
| @@ -136,20 +136,9 @@ | ||
| 136 | 136 | |
| 137 | 137 | <span class="kw">end</span> Args.</code></pre> |
| 138 | 138 | <pre class="output term"><code><span class="cmd">$ raz run Args.raz one "two words"; echo "status $?"</span> |
| 139 | -Args.raz:9:11: error: indexing through a pointer needs import SYSTEM | |
| 140 | - 9 | while s[n] # 0 do n := n + 1; end; | |
| 141 | - | ^^^ | |
| 142 | -help: it reaches memory other than through a variable: say import SYSTEM after the module's imports | |
| 143 | -Args.raz:17:14: error: ARGV is SYSTEM's, and written SYSTEM.ARGV | |
| 144 | - 17 | s := ARGV()[i]; | |
| 145 | - | ^^^^ | |
| 146 | -help: say import SYSTEM after the module's imports, and write the name after SYSTEM. | |
| 147 | -Args.raz:18:17: error: a slice of a pointer needs import SYSTEM | |
| 148 | - 18 | Out.str(s[0..len(s)]); | |
| 149 | - | ^ | |
| 150 | -help: it reaches memory other than through a variable: say import SYSTEM after the module's imports | |
| 151 | -raz: 3 errors | |
| 152 | -status 1</code></pre><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="index.html">Contents</a><a class="next" href="modules.html">Modules →</a></div></article></div> | |
| 139 | +one | |
| 140 | +two words | |
| 141 | +status 2</code></pre><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="index.html">Contents</a><a class="next" href="modules.html">Modules →</a></div></article></div> | |
| 153 | 142 | </main> |
| 154 | 143 | <footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> |
| 155 | 144 | </body> |
| @@ -0,0 +1,54 @@ | ||
| 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>Raz, Set, Go</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="Raz, Set, Go"> | |
| 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.lucelad.workers.dev/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" aria-current="page">Raz, Set, Go</a><a href="../advanced/index.html">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<div class="contents"><h1>Raz, Set, Go</h1> | |
| 22 | +<p>A tour of raz, in the spirit of <em>A Tour of Go</em>. Each lesson is one | |
| 23 | +idea and a whole program, and the output shown is what the program printed | |
| 24 | +when this page was made.</p> | |
| 25 | +<p>It is in three parts, as one counts off: <strong>Raz</strong> (one), the | |
| 26 | +first steps; <strong>Set</strong>, how data is laid out; and | |
| 27 | +<strong>Go</strong>, making programs that run, fail and finish well. To follow | |
| 28 | +along, <a href="../index.html#download">get raz</a> and run any program with | |
| 29 | +<code>raz run Name.raz</code>. When you finish, <a href="../advanced/index.html">More Raz</a> goes down to the machine.</p> | |
| 30 | +<h2>Raz</h2><ol start='1'> | |
| 31 | +<li><a href="hello.html">Hello, world</a> <span>A module, an import, a procedure; running, printing, exit status and arguments.</span></li> | |
| 32 | +<li><a href="modules.html">Modules</a> <span>Exports, renaming, the order bodies run in, and what the compiler refuses.</span></li> | |
| 33 | +<li><a href="integers.html">Integers</a> <span>The ten integer types, literals, wrapping, signed and unsigned, division, shifts and bits.</span></li> | |
| 34 | +<li><a href="values.html">Values and conversions</a> <span>Nothing converts unasked; what converts to what; booleans and reals.</span></li> | |
| 35 | +<li><a href="procedures.html">Procedures and several results</a> <span>Value and var parameters, several results, forward, and procedures as values.</span></li> | |
| 36 | +</ol> | |
| 37 | +<h2>Set</h2><ol start='6'> | |
| 38 | +<li><a href="slices.html">Arrays, slices and strings</a> <span>Five in a row, a window onto them, bytes in UTF-8, raw strings over lines, and checks on every index.</span></li> | |
| 39 | +<li><a href="records.html">Records and pointers</a> <span>Laid out as C lays out a struct, packed records, pointers and nil.</span></li> | |
| 40 | +<li><a href="variants.html">Enumerations, sets, variants and match</a> <span>Names in order, sets as bits, and cases the compiler makes you handle.</span></li> | |
| 41 | +<li><a href="memory.html">Memory and allocators</a> <span>No garbage collector; you choose where memory comes from, and what happens when it runs out.</span></li> | |
| 42 | +</ol> | |
| 43 | +<h2>Go</h2><ol start='10'> | |
| 44 | +<li><a href="errors.html">Errors</a> <span>A second result, compared by identity; passing errors up; and no exceptions.</span></li> | |
| 45 | +<li><a href="defer.html">Defer</a> <span>Clean up beside the line that needs it, in the right order, on every way out.</span></li> | |
| 46 | +<li><a href="checks.html">When it goes wrong</a> <span>Every index is checked, a failure says where and with what values, and how to read it.</span></li> | |
| 47 | +<li><a href="generics.html">Generic modules</a> <span>A module that takes types and procedures; the library's List, Map and Sort.</span></li> | |
| 48 | +<li><a href="c.html">Talking to C</a> <span>Call a C library, be called back, share variables, and mind the two buffers.</span></li> | |
| 49 | +<li><a href="threads.html">Threads</a> <span>Native threads without C, atomics, a mutex, and why the counter needs both.</span></li> | |
| 50 | +</ol></div> | |
| 51 | +</main> | |
| 52 | +<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> | |
| 53 | +</body> | |
| 54 | +</html> |
| @@ -0,0 +1,286 @@ | ||
| 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>Integers - Raz, Set, Go</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="Integers - Raz, Set, Go"> | |
| 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.lucelad.workers.dev/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" aria-current="page">Raz, Set, Go</a><a href="../advanced/index.html">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<div class="tour"><aside><h2>Raz, Set, Go</h2><h3>Raz</h3><ol start='1'> | |
| 22 | +<li><a href="hello.html">Hello, world</a></li> | |
| 23 | +<li><a href="modules.html">Modules</a></li> | |
| 24 | +<li><a href="integers.html" aria-current="page">Integers</a></li> | |
| 25 | +<li><a href="values.html">Values and conversions</a></li> | |
| 26 | +<li><a href="procedures.html">Procedures and several results</a></li> | |
| 27 | +</ol> | |
| 28 | +<h3>Set</h3><ol start='6'> | |
| 29 | +<li><a href="slices.html">Arrays, slices and strings</a></li> | |
| 30 | +<li><a href="records.html">Records and pointers</a></li> | |
| 31 | +<li><a href="variants.html">Enumerations, sets, variants and match</a></li> | |
| 32 | +<li><a href="memory.html">Memory and allocators</a></li> | |
| 33 | +</ol> | |
| 34 | +<h3>Go</h3><ol start='10'> | |
| 35 | +<li><a href="errors.html">Errors</a></li> | |
| 36 | +<li><a href="defer.html">Defer</a></li> | |
| 37 | +<li><a href="checks.html">When it goes wrong</a></li> | |
| 38 | +<li><a href="generics.html">Generic modules</a></li> | |
| 39 | +<li><a href="c.html">Talking to C</a></li> | |
| 40 | +<li><a href="threads.html">Threads</a></li> | |
| 41 | +</ol></aside><article><p class="kicker">Raz · lesson 3 of 15</p><h1>Integers</h1> | |
| 42 | +<p>raz has ten integer types, and a program that works with bytes, addresses, hashes and file offsets uses most of them. Each is a different type, so each has rules, and the rules are the same everywhere: that is the point of having them.</p> | |
| 43 | +<table><thead><tr><th>Type</th><th>Size</th><th>Values</th></tr></thead><tbody><tr><td data-label="Type"><code>I8</code> <code>I16</code> <code>I32</code> <code>I64</code></td><td data-label="Size">1, 2, 4, 8 bytes</td><td data-label="Values">signed, two's complement</td></tr><tr><td data-label="Type"><code>U8</code> <code>U16</code> <code>U32</code> <code>U64</code></td><td data-label="Size">1, 2, 4, 8 bytes</td><td data-label="Values">unsigned</td></tr><tr><td data-label="Type"><code>INT</code></td><td data-label="Size">an address's: 8 on x86-64</td><td data-label="Values">signed, as big as an address</td></tr><tr><td data-label="Type"><code>UINT</code></td><td data-label="Size">an address's</td><td data-label="Values">unsigned, as big as an address</td></tr></tbody></table> | |
| 44 | +<p><code>SIZE(T)</code> says how many bytes a type takes, and an unsigned type's largest value is what you get by taking one from zero. This program asks each type.</p> | |
| 45 | +<div class="file"><span>Family.raz</span></div><pre class="code"><code><span class="kw">module</span> Family; | |
| 46 | +<span class="kw">import</span> Out; | |
| 47 | + | |
| 48 | +<span class="kw">proc</span> main*; | |
| 49 | +<span class="kw">var</span> a: <span class="ty">U8</span>; b: <span class="ty">U16</span>; c: <span class="ty">U32</span>; d: <span class="ty">U64</span>; | |
| 50 | +<span class="kw">begin</span> | |
| 51 | + a := <span class="number">0</span>; a := a - <span class="number">1</span>; | |
| 52 | + b := <span class="number">0</span>; b := b - <span class="number">1</span>; | |
| 53 | + c := <span class="number">0</span>; c := c - <span class="number">1</span>; | |
| 54 | + d := <span class="number">0</span>; d := d - <span class="number">1</span>; | |
| 55 | + Out.str(<span class="string">"U8 "</span>); Out.int(<span class="ty">SIZE</span>(<span class="ty">U8</span>)); Out.str(<span class="string">" byte, largest "</span>); Out.int(<span class="ty">I64</span>(a)); Out.ln; | |
| 56 | + Out.str(<span class="string">"U16 "</span>); Out.int(<span class="ty">SIZE</span>(<span class="ty">U16</span>)); Out.str(<span class="string">" bytes, largest "</span>); Out.int(<span class="ty">I64</span>(b)); Out.ln; | |
| 57 | + Out.str(<span class="string">"U32 "</span>); Out.int(<span class="ty">SIZE</span>(<span class="ty">U32</span>)); Out.str(<span class="string">" bytes, largest "</span>); Out.int(<span class="ty">I64</span>(c)); Out.ln; | |
| 58 | + Out.str(<span class="string">"U64 "</span>); Out.int(<span class="ty">SIZE</span>(<span class="ty">U64</span>)); Out.str(<span class="string">" bytes, largest 0x"</span>); Out.hex(d, <span class="number">16</span>); Out.ln; | |
| 59 | + Out.str(<span class="string">"INT "</span>); Out.int(<span class="ty">SIZE</span>(<span class="ty">INT</span>)); Out.str(<span class="string">" bytes, as big as an address\n"</span>); | |
| 60 | + Out.str(<span class="string">"I8 "</span>); Out.int(<span class="ty">SIZE</span>(<span class="ty">I8</span>)); Out.str(<span class="string">" byte, from -128 to 127\n"</span>); | |
| 61 | +<span class="kw">end</span>; | |
| 62 | + | |
| 63 | +<span class="kw">end</span> Family.</code></pre> | |
| 64 | +<pre class="output"><code>U8 1 byte, largest 255 | |
| 65 | +U16 2 bytes, largest 65535 | |
| 66 | +U32 4 bytes, largest 4294967295 | |
| 67 | +U64 8 bytes, largest 0xFFFFFFFFFFFFFFFF | |
| 68 | +INT 8 bytes, as big as an address | |
| 69 | +I8 1 byte, from -128 to 127 | |
| 70 | +</code></pre> | |
| 71 | +<h2>INT is the everyday one</h2> | |
| 72 | +<p>Lengths, indexes, counts and sizes are <code>INT</code>s. <code>LEN(s)</code> of a slice is an <code>INT</code>, and so is the loop variable that walks it. It is as big as an address, so it is the integer a pointer converts to, and the word the atomics work on. Reach for <code>INT</code> unless you have a reason: a byte is a <code>U8</code>, a character an <code>I32</code>, a file's size an <code>I64</code>, a hash a <code>U64</code>.</p> | |
| 73 | +<p><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> (and a <code>UINT</code> into a <code>U64</code>) wherever it meets one, in <code>pos + LEN(s)</code> as in a call, which is why <code>Out.int(n)</code> and <code>Fmt.int(n)</code> take an <code>I64</code> and accept any <code>INT</code>. The other way is written, <code>INT(pos)</code>, since an <code>INT</code> may be smaller on another machine. An <code>INT</code> holds every <code>U8</code>, <code>I8</code> and <code>I16</code> on any machine, so those go silently into an <code>INT</code> too (and a <code>U8</code> or <code>U16</code> into a <code>UINT</code>): <code>n := s[i]</code>, and <code>n * 10 + s[i] - '0'</code> for a digit. Not what an operator made of them, which was computed in the small type and may have wrapped there: with <code>a, b: U8</code>, <code>n := a + b</code> is an error, and <code>INT(a) + b</code> the sum. And only one step: a <code>U8</code> goes into an <code>INT</code>, not on into an <code>I64</code>, so <code>Out.int(I64(b))</code> still says it. Nothing else converts unasked.</p> | |
| 74 | +<h2>A number written in the program</h2> | |
| 75 | +<p>A number in the program text is untyped until it meets a type, and then it must fit. <code>0FFH</code> is hexadecimal (it starts with a digit and ends in <code>H</code>), a character in quotes is its code point, and <code>'\u{E9}'</code> is a code point written by number. A hexadecimal literal too big for an <code>I64</code> is a <code>U64</code>.</p> | |
| 76 | +<div class="file"><span>Literals.raz</span></div><pre class="code"><code><span class="kw">module</span> Literals; | |
| 77 | +<span class="kw">import</span> Out; | |
| 78 | + | |
| 79 | +<span class="kw">proc</span> main*; | |
| 80 | +<span class="kw">var</span> b: <span class="ty">U8</span>; w: <span class="ty">I16</span>; big: <span class="ty">U64</span>; | |
| 81 | +<span class="kw">begin</span> | |
| 82 | + b := <span class="number">0FFH</span>; <span class="comment">(* fits a U8 *)</span> | |
| 83 | + w := -<span class="number">300</span>; | |
| 84 | + big := <span class="number">0FFFFFFFFFFFFFFFFH</span>; <span class="comment">(* above the largest I64: a U64 *)</span> | |
| 85 | + Out.int(<span class="ty">I64</span>(b)); Out.char(<span class="string">' '</span>); | |
| 86 | + Out.int(<span class="ty">I64</span>(w)); Out.char(<span class="string">' '</span>); | |
| 87 | + Out.int(<span class="ty">I64</span>(<span class="string">'a'</span>)); Out.char(<span class="string">' '</span>); | |
| 88 | + Out.int(<span class="ty">I64</span>(<span class="string">'\u{E9}'</span>)); Out.char(<span class="string">' '</span>); | |
| 89 | + Out.hex(big, <span class="number">16</span>); Out.ln; | |
| 90 | +<span class="kw">end</span>; | |
| 91 | + | |
| 92 | +<span class="kw">end</span> Literals.</code></pre> | |
| 93 | +<pre class="output"><code>255 -300 97 233 FFFFFFFFFFFFFFFF | |
| 94 | +</code></pre> | |
| 95 | +<p>A constant that doesn't fit is an error, not a quiet cut. A conversion of a constant, which says you mean it, is allowed: <code>U8(300)</code> is 44.</p> | |
| 96 | +<div class="file"><span>Fits.raz</span></div><pre class="code"><code><span class="kw">module</span> Fits; | |
| 97 | + | |
| 98 | +<span class="kw">proc</span> main*; | |
| 99 | +<span class="kw">var</span> b: <span class="ty">U8</span>; c: <span class="ty">U8</span>; | |
| 100 | +<span class="kw">begin</span> | |
| 101 | + b := <span class="number">300</span>; | |
| 102 | + c := <span class="ty">U8</span>(<span class="number">300</span>); | |
| 103 | +<span class="kw">end</span>; | |
| 104 | + | |
| 105 | +<span class="kw">end</span> Fits.</code></pre> | |
| 106 | +<pre class="output term"><code><span class="cmd">$ raz Fits.raz</span> | |
| 107 | +Fits.raz:6:10: error: 300 doesn't fit U8 | |
| 108 | + 6 | b := 300; | |
| 109 | + | ^^^ | |
| 110 | +raz: 1 error</code></pre> | |
| 111 | +<h2>Wrapping</h2> | |
| 112 | +<p>Arithmetic wraps at the type's width and never stops the program. <code>250 + 10</code> in a <code>U8</code> is 4; one more than the largest <code>I8</code> is the smallest. A unary minus wraps too: for an unsigned <code>x</code>, <code>-x</code> is <code>0 - x</code>. This is not undefined behaviour, as in C; it is what the report says, in every program, on every target, so a hash function can rely on it.</p> | |
| 113 | +<div class="file"><span>Wrap.raz</span></div><pre class="code"><code><span class="kw">module</span> Wrap; | |
| 114 | +<span class="kw">import</span> Out; | |
| 115 | + | |
| 116 | +<span class="kw">proc</span> main*; | |
| 117 | +<span class="kw">var</span> a: <span class="ty">U8</span>; b: <span class="ty">I8</span>; c: <span class="ty">U32</span>; d: <span class="ty">U8</span>; | |
| 118 | +<span class="kw">begin</span> | |
| 119 | + a := <span class="number">250</span>; a := a + <span class="number">10</span>; | |
| 120 | + Out.int(<span class="ty">I64</span>(a)); Out.ln; <span class="comment">(* 4 *)</span> | |
| 121 | + b := <span class="number">127</span>; b := b + <span class="number">1</span>; | |
| 122 | + Out.int(<span class="ty">I64</span>(b)); Out.ln; <span class="comment">(* -128 *)</span> | |
| 123 | + c := <span class="number">0</span>; c := c - <span class="number">1</span>; | |
| 124 | + Out.int(<span class="ty">I64</span>(c)); Out.ln; <span class="comment">(* 4294967295 *)</span> | |
| 125 | + d := <span class="number">1</span>; d := -d; | |
| 126 | + Out.int(<span class="ty">I64</span>(d)); Out.ln; <span class="comment">(* 255: 0 - 1 *)</span> | |
| 127 | +<span class="kw">end</span>; | |
| 128 | + | |
| 129 | +<span class="kw">end</span> Wrap.</code></pre> | |
| 130 | +<pre class="output"><code>4 | |
| 131 | +-128 | |
| 132 | +4294967295 | |
| 133 | +255 | |
| 134 | +</code></pre> | |
| 135 | +<p>Because wrapping is defined, a hash that depends on it is portable. Here is the FNV-1a hash that <code>Str.hash</code> uses, written in a few lines; the multiplication overflows a <code>U64</code> on every byte, on purpose.</p> | |
| 136 | +<div class="file"><span>Fnv.raz</span></div><pre class="code"><code><span class="kw">module</span> Fnv; | |
| 137 | +<span class="kw">import</span> Out, Str; | |
| 138 | + | |
| 139 | +<span class="kw">const</span> Offset = <span class="number">0CBF29CE484222325H</span>; | |
| 140 | +<span class="kw">const</span> Prime = <span class="number">100000001B3H</span>; | |
| 141 | + | |
| 142 | +<span class="comment">(* FNV-1a: xor each byte in, then multiply, all modulo 2^64 *)</span> | |
| 143 | +<span class="kw">proc</span> fnv(s: []<span class="ty">U8</span>): <span class="ty">U64</span>; | |
| 144 | +<span class="kw">var</span> h: <span class="ty">U64</span>; i: <span class="ty">INT</span>; | |
| 145 | +<span class="kw">begin</span> | |
| 146 | + h := Offset; | |
| 147 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="ty">LEN</span>(s) - <span class="number">1</span> <span class="kw">do</span> | |
| 148 | + h := (h <span class="kw">xor</span> <span class="ty">U64</span>(s[i])) * Prime; | |
| 149 | + <span class="kw">end</span>; | |
| 150 | + <span class="kw">return</span> h; | |
| 151 | +<span class="kw">end</span>; | |
| 152 | + | |
| 153 | +<span class="kw">proc</span> main*; | |
| 154 | +<span class="kw">begin</span> | |
| 155 | + Out.hex(fnv(<span class="string">"raz"</span>), <span class="number">16</span>); Out.ln; | |
| 156 | + Out.hex(Str.hash(<span class="string">"raz"</span>), <span class="number">16</span>); Out.ln; | |
| 157 | + <span class="kw">if</span> fnv(<span class="string">"raz"</span>) = Str.hash(<span class="string">"raz"</span>) <span class="kw">then</span> Out.str(<span class="string">"the same\n"</span>); <span class="kw">end</span>; | |
| 158 | +<span class="kw">end</span>; | |
| 159 | + | |
| 160 | +<span class="kw">end</span> Fnv.</code></pre> | |
| 161 | +<pre class="output"><code>89F6BC1960FF4912 | |
| 162 | +89F6BC1960FF4912 | |
| 163 | +the same | |
| 164 | +</code></pre> | |
| 165 | +<h2>Widening, narrowing, and sign</h2> | |
| 166 | +<p>A conversion to a narrower integer cuts the value to the new width. To a wider one it extends by the sign for a signed source and with zeros for an unsigned one. That difference is the whole story of "why did my byte come out negative".</p> | |
| 167 | +<div class="file"><span>Widths.raz</span></div><pre class="code"><code><span class="kw">module</span> Widths; | |
| 168 | +<span class="kw">import</span> Out; | |
| 169 | + | |
| 170 | +<span class="kw">proc</span> main*; | |
| 171 | +<span class="kw">var</span> s: <span class="ty">I8</span>; u: <span class="ty">U8</span>; | |
| 172 | +<span class="kw">begin</span> | |
| 173 | + s := -<span class="number">1</span>; | |
| 174 | + u := <span class="number">255</span>; <span class="comment">(* the same eight bits *)</span> | |
| 175 | + Out.int(<span class="ty">I64</span>(s)); Out.char(<span class="string">' '</span>); <span class="comment">(* sign-extended: -1 *)</span> | |
| 176 | + Out.int(<span class="ty">I64</span>(u)); Out.char(<span class="string">' '</span>); <span class="comment">(* zero-extended: 255 *)</span> | |
| 177 | + Out.int(<span class="ty">I64</span>(<span class="ty">U8</span>(s))); Out.char(<span class="string">' '</span>); <span class="comment">(* the bits, read as unsigned: 255 *)</span> | |
| 178 | + Out.int(<span class="ty">I64</span>(<span class="ty">I8</span>(u))); Out.char(<span class="string">' '</span>); <span class="comment">(* and back: -1 *)</span> | |
| 179 | + Out.int(<span class="ty">I64</span>(<span class="ty">U8</span>(<span class="number">300</span> + <span class="ty">INT</span>(u)))); Out.ln; <span class="comment">(* 555 cut to 8 bits: 43 *)</span> | |
| 180 | +<span class="kw">end</span>; | |
| 181 | + | |
| 182 | +<span class="kw">end</span> Widths.</code></pre> | |
| 183 | +<pre class="output"><code>-1 255 255 -1 43 | |
| 184 | +</code></pre> | |
| 185 | +<p>Relations compare as signed or unsigned according to the type, so the same bits order differently:</p> | |
| 186 | +<div class="file"><span>Order.raz</span></div><pre class="code"><code><span class="kw">module</span> Order; | |
| 187 | +<span class="kw">import</span> Out; | |
| 188 | + | |
| 189 | +<span class="kw">proc</span> main*; | |
| 190 | +<span class="kw">var</span> s: <span class="ty">I8</span>; u: <span class="ty">U8</span>; | |
| 191 | +<span class="kw">begin</span> | |
| 192 | + s := -<span class="number">1</span>; | |
| 193 | + u := <span class="ty">U8</span>(s); <span class="comment">(* 255 *)</span> | |
| 194 | + <span class="kw">if</span> s < <span class="number">0</span> <span class="kw">then</span> Out.str(<span class="string">"s is below zero\n"</span>); <span class="kw">end</span>; | |
| 195 | + <span class="kw">if</span> u > <span class="number">100</span> <span class="kw">then</span> Out.str(<span class="string">"u is above 100\n"</span>); <span class="kw">end</span>; | |
| 196 | + <span class="kw">if</span> <span class="ty">U8</span>(s) = u <span class="kw">then</span> Out.str(<span class="string">"but they are the same bits\n"</span>); <span class="kw">end</span>; | |
| 197 | +<span class="kw">end</span>; | |
| 198 | + | |
| 199 | +<span class="kw">end</span> Order.</code></pre> | |
| 200 | +<pre class="output"><code>s is below zero | |
| 201 | +u is above 100 | |
| 202 | +but they are the same bits | |
| 203 | +</code></pre> | |
| 204 | +<h2>Division</h2> | |
| 205 | +<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 -3 and <code>-7 mod 2</code> is -1. Dividing by zero stops the program, and so does dividing the smallest value of a signed type by -1, whose result can't be represented. Neither is a silent wrong answer.</p> | |
| 206 | +<div class="file"><span>Divide.raz</span></div><pre class="code"><code><span class="kw">module</span> Divide; | |
| 207 | +<span class="kw">import</span> Out; | |
| 208 | + | |
| 209 | +<span class="kw">proc</span> main*; | |
| 210 | +<span class="kw">var</span> n, d: <span class="ty">INT</span>; | |
| 211 | +<span class="kw">begin</span> | |
| 212 | + n := -<span class="number">7</span>; d := <span class="number">2</span>; | |
| 213 | + Out.int(n <span class="kw">div</span> d); Out.char(<span class="string">' '</span>); Out.int(n <span class="kw">mod</span> d); Out.char(<span class="string">' '</span>); <span class="comment">(* -3 -1 *)</span> | |
| 214 | + n := <span class="number">7</span>; d := -<span class="number">2</span>; | |
| 215 | + Out.int(n <span class="kw">div</span> d); Out.char(<span class="string">' '</span>); Out.int(n <span class="kw">mod</span> d); Out.ln; <span class="comment">(* -3 1 *)</span> | |
| 216 | +<span class="kw">end</span>; | |
| 217 | + | |
| 218 | +<span class="kw">end</span> Divide.</code></pre> | |
| 219 | +<pre class="output"><code>-3 -1 -3 1 | |
| 220 | +</code></pre> | |
| 221 | +<h2>Shifts and bits</h2> | |
| 222 | +<p><code>&</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: for a <code>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, so it divides by two keeping the sign, and zeros for unsigned ones. The result has <code>x</code>'s type, cut to its width: in a <code>U8</code>, <code>0C0H shl 1</code> is <code>80H</code>.</p> | |
| 223 | +<div class="file"><span>Shifts.raz</span></div><pre class="code"><code><span class="kw">module</span> Shifts; | |
| 224 | +<span class="kw">import</span> Out; | |
| 225 | + | |
| 226 | +<span class="kw">proc</span> main*; | |
| 227 | +<span class="kw">var</span> u: <span class="ty">U8</span>; s: <span class="ty">I8</span>; | |
| 228 | +<span class="kw">begin</span> | |
| 229 | + u := <span class="number">0C0H</span>; | |
| 230 | + Out.hex(<span class="ty">U64</span>(u <span class="kw">shl</span> <span class="number">1</span>), <span class="number">2</span>); Out.char(<span class="string">' '</span>); <span class="comment">(* 80: cut to 8 bits *)</span> | |
| 231 | + Out.hex(<span class="ty">U64</span>(u <span class="kw">shr</span> <span class="number">4</span>), <span class="number">2</span>); Out.char(<span class="string">' '</span>); <span class="comment">(* 0C: zeros come in *)</span> | |
| 232 | + Out.hex(<span class="ty">U64</span>(u <span class="kw">shl</span> <span class="number">9</span>), <span class="number">2</span>); Out.ln; <span class="comment">(* 9 mod 8 = 1: 80 *)</span> | |
| 233 | + s := -<span class="number">64</span>; | |
| 234 | + Out.int(<span class="ty">I64</span>(s <span class="kw">shr</span> <span class="number">2</span>)); Out.char(<span class="string">' '</span>); <span class="comment">(* -16: the sign comes in *)</span> | |
| 235 | + Out.int(<span class="ty">I64</span>(s <span class="kw">shr</span> <span class="number">7</span>)); Out.ln; <span class="comment">(* -1 *)</span> | |
| 236 | +<span class="kw">end</span>; | |
| 237 | + | |
| 238 | +<span class="kw">end</span> Shifts.</code></pre> | |
| 239 | +<pre class="output"><code>80 0C 80 | |
| 240 | +-16 -1 | |
| 241 | +</code></pre> | |
| 242 | +<p>A packed value is the usual use of all this: several small numbers in one word. This puts a colour in the bytes of a <code>U32</code> and takes it out again.</p> | |
| 243 | +<div class="file"><span>Colour.raz</span></div><pre class="code"><code><span class="kw">module</span> Colour; | |
| 244 | +<span class="kw">import</span> Out; | |
| 245 | + | |
| 246 | +<span class="comment">(* red, green and blue, each 0 to 255, in the low 24 bits *)</span> | |
| 247 | +<span class="kw">proc</span> pack(r, g, b: <span class="ty">U8</span>): <span class="ty">U32</span>; | |
| 248 | +<span class="kw">begin</span> | |
| 249 | + <span class="kw">return</span> (<span class="ty">U32</span>(r) <span class="kw">shl</span> <span class="number">16</span>) | (<span class="ty">U32</span>(g) <span class="kw">shl</span> <span class="number">8</span>) | <span class="ty">U32</span>(b); | |
| 250 | +<span class="kw">end</span>; | |
| 251 | + | |
| 252 | +<span class="kw">proc</span> red(c: <span class="ty">U32</span>): <span class="ty">U8</span>; | |
| 253 | +<span class="kw">begin</span> | |
| 254 | + <span class="kw">return</span> <span class="ty">U8</span>(c <span class="kw">shr</span> <span class="number">16</span>); | |
| 255 | +<span class="kw">end</span>; | |
| 256 | + | |
| 257 | +<span class="kw">proc</span> green(c: <span class="ty">U32</span>): <span class="ty">U8</span>; | |
| 258 | +<span class="kw">begin</span> | |
| 259 | + <span class="kw">return</span> <span class="ty">U8</span>((c <span class="kw">shr</span> <span class="number">8</span>) & <span class="number">0FFH</span>); | |
| 260 | +<span class="kw">end</span>; | |
| 261 | + | |
| 262 | +<span class="kw">proc</span> blue(c: <span class="ty">U32</span>): <span class="ty">U8</span>; | |
| 263 | +<span class="kw">begin</span> | |
| 264 | + <span class="kw">return</span> <span class="ty">U8</span>(c & <span class="number">0FFH</span>); | |
| 265 | +<span class="kw">end</span>; | |
| 266 | + | |
| 267 | +<span class="kw">proc</span> main*; | |
| 268 | +<span class="kw">var</span> c: <span class="ty">U32</span>; | |
| 269 | +<span class="kw">begin</span> | |
| 270 | + c := pack(<span class="number">0FFH</span>, <span class="number">80H</span>, <span class="number">10H</span>); | |
| 271 | + Out.str(<span class="string">"0x"</span>); Out.hex(<span class="ty">U64</span>(c), <span class="number">6</span>); Out.ln; | |
| 272 | + Out.int(<span class="ty">I64</span>(red(c))); Out.char(<span class="string">' '</span>); | |
| 273 | + Out.int(<span class="ty">I64</span>(green(c))); Out.char(<span class="string">' '</span>); | |
| 274 | + Out.int(<span class="ty">I64</span>(blue(c))); Out.ln; | |
| 275 | +<span class="kw">end</span>; | |
| 276 | + | |
| 277 | +<span class="kw">end</span> Colour.</code></pre> | |
| 278 | +<pre class="output"><code>0xFF8010 | |
| 279 | +255 128 16 | |
| 280 | +</code></pre> | |
| 281 | +<h2>Which one to use</h2> | |
| 282 | +<ul><li><strong><code>INT</code></strong> for lengths, indexes, counts, loop variables, and anything you'd write <code>int</code> for in C.</li><li><strong><code>U8</code></strong> for bytes, and for a string's elements (<code>[]U8</code>). <strong><code>I32</code></strong> for a character, a code point.</li><li><strong><code>U32</code>, <code>U64</code></strong> for hashes, bit sets, masks and addresses you do arithmetic on.</li><li><strong><code>I64</code></strong> for what must not shrink on a smaller target: a file's size or position, a time in nanoseconds, a number read from text.</li><li><strong><code>I8</code>, <code>I16</code>, <code>U16</code></strong> when a format or a layout says so, in a record or an array, to save space or match a protocol. Convert at the edge and compute in <code>INT</code>.</li><li><strong><code>UINT</code></strong> rarely: for a count that must use the whole address range, or an address.</li></ul><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="modules.html">← Modules</a><a href="index.html">Contents</a><a class="next" href="values.html">Values and conversions →</a></div></article></div> | |
| 283 | +</main> | |
| 284 | +<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> | |
| 285 | +</body> | |
| 286 | +</html> |
| @@ -0,0 +1,196 @@ | ||
| 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>Memory and allocators - Raz, Set, Go</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="Memory and allocators - Raz, Set, Go"> | |
| 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.lucelad.workers.dev/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" aria-current="page">Raz, Set, Go</a><a href="../advanced/index.html">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<div class="tour"><aside><h2>Raz, Set, Go</h2><h3>Raz</h3><ol start='1'> | |
| 22 | +<li><a href="hello.html">Hello, world</a></li> | |
| 23 | +<li><a href="modules.html">Modules</a></li> | |
| 24 | +<li><a href="integers.html">Integers</a></li> | |
| 25 | +<li><a href="values.html">Values and conversions</a></li> | |
| 26 | +<li><a href="procedures.html">Procedures and several results</a></li> | |
| 27 | +</ol> | |
| 28 | +<h3>Set</h3><ol start='6'> | |
| 29 | +<li><a href="slices.html">Arrays, slices and strings</a></li> | |
| 30 | +<li><a href="records.html">Records and pointers</a></li> | |
| 31 | +<li><a href="variants.html">Enumerations, sets, variants and match</a></li> | |
| 32 | +<li><a href="memory.html" aria-current="page">Memory and allocators</a></li> | |
| 33 | +</ol> | |
| 34 | +<h3>Go</h3><ol start='10'> | |
| 35 | +<li><a href="errors.html">Errors</a></li> | |
| 36 | +<li><a href="defer.html">Defer</a></li> | |
| 37 | +<li><a href="checks.html">When it goes wrong</a></li> | |
| 38 | +<li><a href="generics.html">Generic modules</a></li> | |
| 39 | +<li><a href="c.html">Talking to C</a></li> | |
| 40 | +<li><a href="threads.html">Threads</a></li> | |
| 41 | +</ol></aside><article><p class="kicker">Set · lesson 9 of 15</p><h1>Memory and allocators</h1> | |
| 42 | +<div class="file"><span>Stack.raz</span></div><pre class="code"><code><span class="kw">module</span> Stack; | |
| 43 | +<span class="kw">import</span> Out, Mem, Heap, Arena, SYSTEM; | |
| 44 | + | |
| 45 | +<span class="kw">type</span> Node = <span class="kw">record</span> next: ^Node; val: <span class="ty">INT</span>; <span class="kw">end</span>; | |
| 46 | + | |
| 47 | +<span class="comment">(* a node holding v on top of top, from the allocator a; | |
| 48 | + nil if a has no room *)</span> | |
| 49 | +<span class="kw">proc</span> push(top: ^Node; v: <span class="ty">INT</span>; a: ^Mem.Allocator): ^Node; | |
| 50 | +<span class="kw">var</span> n: ^Node; | |
| 51 | +<span class="kw">begin</span> | |
| 52 | + <span class="ty">NEW</span>(n, a); | |
| 53 | + <span class="kw">if</span> n # <span class="ty">nil</span> <span class="kw">then</span> | |
| 54 | + n^.next := top; | |
| 55 | + n^.val := v; | |
| 56 | + <span class="kw">end</span>; | |
| 57 | + <span class="kw">return</span> n; | |
| 58 | +<span class="kw">end</span>; | |
| 59 | + | |
| 60 | +<span class="kw">proc</span> main*; | |
| 61 | +<span class="kw">var</span> top, n: ^Node; i: <span class="ty">INT</span>; ar: Arena.Arena; | |
| 62 | +<span class="kw">begin</span> | |
| 63 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> top := push(top, i, Heap.heap); <span class="kw">end</span>; | |
| 64 | + <span class="kw">while</span> top # <span class="ty">nil</span> <span class="kw">do</span> | |
| 65 | + Out.int(top^.val); Out.char(<span class="string">' '</span>); | |
| 66 | + n := top; | |
| 67 | + top := top^.next; | |
| 68 | + Mem.free(Heap.heap, ^<span class="ty">U8</span>(n)); | |
| 69 | + <span class="kw">end</span>; | |
| 70 | + Out.ln; | |
| 71 | + <span class="kw">if</span> <span class="kw">not</span> Arena.init(ar, <span class="number">100000</span>) <span class="kw">then</span> <span class="kw">return</span>; <span class="kw">end</span>; | |
| 72 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">1000</span> <span class="kw">do</span> top := push(top, i, SYSTEM.<span class="ty">ADR</span>(ar.base)); <span class="kw">end</span>; | |
| 73 | + Out.int(top^.val); Out.ln; | |
| 74 | + Arena.done(ar); <span class="comment">(* every node at once *)</span> | |
| 75 | +<span class="kw">end</span>; | |
| 76 | + | |
| 77 | +<span class="kw">end</span> Stack.</code></pre> | |
| 78 | +<pre class="output"><code>3 2 1 | |
| 79 | +1000 | |
| 80 | +</code></pre> | |
| 81 | +<p>raz has no garbage collector, and no allocator of its own: memory comes from an allocator, a <code>Mem.Allocator</code>, which the program chooses and passes. <code>NEW(n, a)</code> sets <code>n</code> to a fresh, zeroed <code>Node</code> from <code>a</code>, or to <code>nil</code> if <code>a</code> has no room. <code>Heap.heap</code> is the general one, which <code>Mem.free</code> gives memory back to. An <code>Arena</code> hands out memory from one block and frees it all at once, as the last lines above do.</p> | |
| 82 | +<h2>Why an allocator is a parameter</h2> | |
| 83 | +<p>A procedure that allocates takes the allocator it uses, so its caller decides where the memory comes from and when it goes: the heap for something that lives long, an arena for everything one request needs. Nothing in the library allocates behind your back.</p> | |
| 84 | +<div class="file"><span>Pool.raz</span></div><pre class="code"><code><span class="kw">module</span> Pool; | |
| 85 | +<span class="kw">import</span> Out, Mem, Arena; | |
| 86 | + | |
| 87 | +<span class="kw">type</span> Item = <span class="kw">record</span> id: <span class="ty">INT</span>; next: ^Item; <span class="kw">end</span>; | |
| 88 | + | |
| 89 | +<span class="comment">(* n items, linked; or nil if the allocator ran dry (what came is lost with it) *)</span> | |
| 90 | +<span class="kw">proc</span> make(n: <span class="ty">INT</span>; a: ^Mem.Allocator): ^Item; | |
| 91 | +<span class="kw">var</span> head, it: ^Item; i: <span class="ty">INT</span>; | |
| 92 | +<span class="kw">begin</span> | |
| 93 | + head := <span class="ty">nil</span>; | |
| 94 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> n <span class="kw">do</span> | |
| 95 | + <span class="ty">NEW</span>(it, a); | |
| 96 | + <span class="kw">if</span> it = <span class="ty">nil</span> <span class="kw">then</span> <span class="kw">return</span> <span class="ty">nil</span>; <span class="kw">end</span>; | |
| 97 | + it^.id := i; | |
| 98 | + it^.next := head; | |
| 99 | + head := it; | |
| 100 | + <span class="kw">end</span>; | |
| 101 | + <span class="kw">return</span> head; | |
| 102 | +<span class="kw">end</span>; | |
| 103 | + | |
| 104 | +<span class="kw">proc</span> count(it: ^Item): <span class="ty">INT</span>; | |
| 105 | +<span class="kw">var</span> n: <span class="ty">INT</span>; | |
| 106 | +<span class="kw">begin</span> | |
| 107 | + n := <span class="number">0</span>; | |
| 108 | + <span class="kw">while</span> it # <span class="ty">nil</span> <span class="kw">do</span> <span class="ty">INC</span>(n); it := it^.next; <span class="kw">end</span>; | |
| 109 | + <span class="kw">return</span> n; | |
| 110 | +<span class="kw">end</span>; | |
| 111 | + | |
| 112 | +<span class="kw">proc</span> main*; | |
| 113 | +<span class="kw">var</span> ar: Arena.Arena; small: Arena.Arena; list: ^Item; | |
| 114 | +<span class="kw">begin</span> | |
| 115 | + <span class="kw">if</span> <span class="kw">not</span> Arena.init(ar, <span class="number">1000000</span>) <span class="kw">then</span> <span class="kw">return</span>; <span class="kw">end</span>; | |
| 116 | + list := make(<span class="number">1000</span>, <span class="ty">ADR</span>(ar.base)); | |
| 117 | + Out.int(count(list)); Out.str(<span class="string">" items from a big arena\n"</span>); | |
| 118 | + Arena.reset(ar); <span class="comment">(* every allocation forgotten *)</span> | |
| 119 | + list := make(<span class="number">10</span>, <span class="ty">ADR</span>(ar.base)); | |
| 120 | + Out.int(count(list)); Out.str(<span class="string">" after a reset\n"</span>); | |
| 121 | + Arena.done(ar); | |
| 122 | + | |
| 123 | + <span class="kw">if</span> <span class="kw">not</span> Arena.init(small, <span class="number">4096</span>) <span class="kw">then</span> <span class="kw">return</span>; <span class="kw">end</span>; | |
| 124 | + list := make(<span class="number">1000</span>, <span class="ty">ADR</span>(small.base)); | |
| 125 | + <span class="kw">if</span> list = <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="string">"a small arena ran out, and said so\n"</span>); <span class="kw">end</span>; | |
| 126 | + Arena.done(small); | |
| 127 | +<span class="kw">end</span>; | |
| 128 | + | |
| 129 | +<span class="kw">end</span> Pool.</code></pre> | |
| 130 | +<pre class="output"><code>1000 items from a big arena | |
| 131 | +10 after a reset | |
| 132 | +a small arena ran out, and said so | |
| 133 | +</code></pre> | |
| 134 | +<p>The run-out case is an ordinary <code>nil</code> to test, not an exception that unwinds past your code.</p> | |
| 135 | +<h2>The heap</h2> | |
| 136 | +<p><code>Heap.heap</code> serves any size and takes memory back with <code>Mem.free</code>. Freeing a block twice, or one that was never given out, stops the program with a message instead of corrupting the heap. It is safe to call from several threads.</p> | |
| 137 | +<div class="file"><span>Free.raz</span></div><pre class="code"><code><span class="kw">module</span> Free; | |
| 138 | +<span class="kw">import</span> Out, Mem, Heap; | |
| 139 | + | |
| 140 | +<span class="kw">type</span> Cell = <span class="kw">record</span> val: <span class="ty">INT</span>; <span class="kw">end</span>; | |
| 141 | + | |
| 142 | +<span class="kw">proc</span> main*; | |
| 143 | +<span class="kw">var</span> a, b: ^Cell; i, total: <span class="ty">INT</span>; | |
| 144 | +<span class="kw">begin</span> | |
| 145 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">5</span> <span class="kw">do</span> | |
| 146 | + <span class="ty">NEW</span>(a, Heap.heap); | |
| 147 | + a^.val := i * i; | |
| 148 | + total := total + a^.val; | |
| 149 | + Mem.free(Heap.heap, ^<span class="ty">U8</span>(a)); <span class="comment">(* freed at once: its block is reused *)</span> | |
| 150 | + <span class="kw">end</span>; | |
| 151 | + <span class="ty">NEW</span>(b, Heap.heap); | |
| 152 | + Out.int(total); Out.char(<span class="string">' '</span>); Out.int(b^.val); Out.ln; <span class="comment">(* a new block is zeroed *)</span> | |
| 153 | + Mem.free(Heap.heap, ^<span class="ty">U8</span>(b)); | |
| 154 | +<span class="kw">end</span>; | |
| 155 | + | |
| 156 | +<span class="kw">end</span> Free.</code></pre> | |
| 157 | +<pre class="output"><code>55 0 | |
| 158 | +</code></pre> | |
| 159 | +<h2>Buffers that grow</h2> | |
| 160 | +<p><code>Buf</code> is a growable byte buffer; like everything else it takes the allocator it grows from. It is what the program uses to build a string of unknown length.</p> | |
| 161 | +<div class="file"><span>Build.raz</span></div><pre class="code"><code><span class="kw">module</span> Build; | |
| 162 | +<span class="kw">import</span> Out, Buf, Heap, Str; | |
| 163 | + | |
| 164 | +<span class="kw">proc</span> main*; | |
| 165 | +<span class="kw">var</span> b: Buf.Buf; i: <span class="ty">INT</span>; | |
| 166 | +<span class="kw">begin</span> | |
| 167 | + Buf.init(b, Heap.heap); | |
| 168 | + <span class="kw">defer</span> Buf.done(b); | |
| 169 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">5</span> <span class="kw">do</span> | |
| 170 | + Buf.str(b, <span class="string">"item "</span>); | |
| 171 | + Buf.add(b, <span class="ty">U8</span>(<span class="string">'0'</span> + i)); | |
| 172 | + Buf.add(b, <span class="string">','</span>); | |
| 173 | + <span class="kw">end</span>; | |
| 174 | + Out.str(Buf.bytes(b)); Out.ln; | |
| 175 | + Out.int(b.len); Out.str(<span class="string">" bytes\n"</span>); | |
| 176 | + Buf.reset(b); | |
| 177 | + Str.join(b, [<span class="string">"red"</span>, <span class="string">"green"</span>, <span class="string">"blue"</span>], <span class="string">", "</span>); | |
| 178 | + Out.str(Buf.bytes(b)); Out.ln; | |
| 179 | + Buf.reset(b); | |
| 180 | + Str.replace(b, <span class="string">"a-b-c"</span>, <span class="string">"-"</span>, <span class="string">" and "</span>); | |
| 181 | + Out.str(Buf.bytes(b)); Out.ln; | |
| 182 | +<span class="kw">end</span>; | |
| 183 | + | |
| 184 | +<span class="kw">end</span> Build.</code></pre> | |
| 185 | +<pre class="output"><code>item 1,item 2,item 3,item 4,item 5, | |
| 186 | +35 bytes | |
| 187 | +red, green, blue | |
| 188 | +a and b and c | |
| 189 | +</code></pre> | |
| 190 | +<p><code>Str.join</code> and <code>Str.replace</code> build into a <code>Buf</code> too: the parts with a separator between them, or a string with one text replaced by another wherever it is.</p> | |
| 191 | +<h2>Pages</h2> | |
| 192 | +<p>Under the allocators are pages from the system: <code>Mem.pages(size)</code> gives zeroed memory in whole pages, or <code>nil</code>, and <code>Mem.unmap</code> gives it back. Most programs never need to call it directly.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="variants.html">← Enumerations, sets, variants and match</a><a href="index.html">Contents</a><a class="next" href="errors.html">Errors →</a></div></article></div> | |
| 193 | +</main> | |
| 194 | +<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> | |
| 195 | +</body> | |
| 196 | +</html> |
| @@ -45,7 +45,7 @@ | ||
| 45 | 45 | |
| 46 | 46 | <span class="kw">var</span> count*: <span class="ty">INT</span>; <span class="comment">(* the greetings so far *)</span> |
| 47 | 47 | |
| 48 | -<span class="kw">proc</span> hello*(name: []<span class="kw">const</span> <span class="ty">U8</span>); | |
| 48 | +<span class="kw">proc</span> hello*(name: []<span class="ty">U8</span>); | |
| 49 | 49 | <span class="kw">begin</span> |
| 50 | 50 | Out.str(<span class="string">"hello, "</span>); |
| 51 | 51 | Out.str(name); |
| @@ -0,0 +1,237 @@ | ||
| 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>Procedures and several results - Raz, Set, Go</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="Procedures and several results - Raz, Set, Go"> | |
| 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.lucelad.workers.dev/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" aria-current="page">Raz, Set, Go</a><a href="../advanced/index.html">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<div class="tour"><aside><h2>Raz, Set, Go</h2><h3>Raz</h3><ol start='1'> | |
| 22 | +<li><a href="hello.html">Hello, world</a></li> | |
| 23 | +<li><a href="modules.html">Modules</a></li> | |
| 24 | +<li><a href="integers.html">Integers</a></li> | |
| 25 | +<li><a href="values.html">Values and conversions</a></li> | |
| 26 | +<li><a href="procedures.html" aria-current="page">Procedures and several results</a></li> | |
| 27 | +</ol> | |
| 28 | +<h3>Set</h3><ol start='6'> | |
| 29 | +<li><a href="slices.html">Arrays, slices and strings</a></li> | |
| 30 | +<li><a href="records.html">Records and pointers</a></li> | |
| 31 | +<li><a href="variants.html">Enumerations, sets, variants and match</a></li> | |
| 32 | +<li><a href="memory.html">Memory and allocators</a></li> | |
| 33 | +</ol> | |
| 34 | +<h3>Go</h3><ol start='10'> | |
| 35 | +<li><a href="errors.html">Errors</a></li> | |
| 36 | +<li><a href="defer.html">Defer</a></li> | |
| 37 | +<li><a href="checks.html">When it goes wrong</a></li> | |
| 38 | +<li><a href="generics.html">Generic modules</a></li> | |
| 39 | +<li><a href="c.html">Talking to C</a></li> | |
| 40 | +<li><a href="threads.html">Threads</a></li> | |
| 41 | +</ol></aside><article><p class="kicker">Raz · lesson 5 of 15</p><h1>Procedures and several results</h1> | |
| 42 | +<div class="file"><span>Procs.raz</span></div><pre class="code"><code><span class="kw">module</span> Procs; | |
| 43 | +<span class="kw">import</span> Out; | |
| 44 | + | |
| 45 | +<span class="kw">proc</span> divmod(a, b: <span class="ty">INT</span>): (<span class="ty">INT</span>, <span class="ty">INT</span>); | |
| 46 | +<span class="kw">begin</span> | |
| 47 | + <span class="kw">return</span> a <span class="kw">div</span> b, a <span class="kw">mod</span> b; | |
| 48 | +<span class="kw">end</span>; | |
| 49 | + | |
| 50 | +<span class="kw">proc</span> swap(<span class="kw">var</span> a, b: <span class="ty">INT</span>); | |
| 51 | +<span class="kw">var</span> t: <span class="ty">INT</span>; | |
| 52 | +<span class="kw">begin</span> | |
| 53 | + t := a; | |
| 54 | + a := b; | |
| 55 | + b := t; | |
| 56 | +<span class="kw">end</span>; | |
| 57 | + | |
| 58 | +<span class="kw">proc</span> square(n: <span class="ty">INT</span>): <span class="ty">INT</span>; | |
| 59 | +<span class="kw">begin</span> | |
| 60 | + <span class="kw">return</span> n * n; | |
| 61 | +<span class="kw">end</span>; | |
| 62 | + | |
| 63 | +<span class="kw">proc</span> twice(f: <span class="kw">proc</span>(n: <span class="ty">INT</span>): <span class="ty">INT</span>; n: <span class="ty">INT</span>): <span class="ty">INT</span>; | |
| 64 | +<span class="kw">begin</span> | |
| 65 | + <span class="kw">return</span> f(f(n)); | |
| 66 | +<span class="kw">end</span>; | |
| 67 | + | |
| 68 | +<span class="kw">proc</span> main*; | |
| 69 | +<span class="kw">var</span> q, r, x, y: <span class="ty">INT</span>; | |
| 70 | +<span class="kw">begin</span> | |
| 71 | + q, r := divmod(<span class="number">17</span>, <span class="number">5</span>); | |
| 72 | + x := <span class="number">1</span>; | |
| 73 | + y := <span class="number">2</span>; | |
| 74 | + swap(x, y); | |
| 75 | + Out.int(q); Out.char(<span class="string">' '</span>); Out.int(r); Out.ln; | |
| 76 | + Out.int(x); Out.char(<span class="string">' '</span>); Out.int(y); Out.ln; | |
| 77 | + Out.int(twice(square, <span class="number">3</span>)); Out.ln; | |
| 78 | + _, r := divmod(-<span class="number">7</span>, <span class="number">2</span>); | |
| 79 | + Out.int(r); Out.ln; | |
| 80 | +<span class="kw">end</span>; | |
| 81 | + | |
| 82 | +<span class="kw">end</span> Procs.</code></pre> | |
| 83 | +<pre class="output"><code>3 2 | |
| 84 | +2 1 | |
| 85 | +81 | |
| 86 | +-1 | |
| 87 | +</code></pre> | |
| 88 | +<p>A parameter is a copy, unless it is <code>var</code>, when it is the caller's variable itself. A procedure may return several results, which a multiple assignment takes apart; the blank, <code>_</code>, drops one.</p> | |
| 89 | +<h2>Value and <code>var</code> parameters</h2> | |
| 90 | +<p>A value parameter is the procedure's own: it may change it, and the caller's variable stays as it was. A <code>var</code> parameter is the caller's variable, and its argument must be a variable of exactly that type.</p> | |
| 91 | +<div class="file"><span>Params.raz</span></div><pre class="code"><code><span class="kw">module</span> Params; | |
| 92 | +<span class="kw">import</span> Out; | |
| 93 | + | |
| 94 | +<span class="kw">proc</span> bump(n: <span class="ty">INT</span>); <span class="comment">(* changes its own copy *)</span> | |
| 95 | +<span class="kw">begin</span> | |
| 96 | + n := n + <span class="number">1</span>; | |
| 97 | +<span class="kw">end</span>; | |
| 98 | + | |
| 99 | +<span class="kw">proc</span> bumpIn(<span class="kw">var</span> n: <span class="ty">INT</span>); <span class="comment">(* changes the caller's *)</span> | |
| 100 | +<span class="kw">begin</span> | |
| 101 | + n := n + <span class="number">1</span>; | |
| 102 | +<span class="kw">end</span>; | |
| 103 | + | |
| 104 | +<span class="kw">proc</span> fill(<span class="kw">var</span> a: [<span class="number">4</span>]<span class="ty">INT</span>; v: <span class="ty">INT</span>); <span class="comment">(* an array is copied unless var *)</span> | |
| 105 | +<span class="kw">var</span> i: <span class="ty">INT</span>; | |
| 106 | +<span class="kw">begin</span> | |
| 107 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> a[i] := v; <span class="kw">end</span>; | |
| 108 | +<span class="kw">end</span>; | |
| 109 | + | |
| 110 | +<span class="kw">proc</span> main*; | |
| 111 | +<span class="kw">var</span> x: <span class="ty">INT</span>; a: [<span class="number">4</span>]<span class="ty">INT</span>; | |
| 112 | +<span class="kw">begin</span> | |
| 113 | + x := <span class="number">10</span>; | |
| 114 | + bump(x); | |
| 115 | + Out.int(x); Out.ln; <span class="comment">(* 10 *)</span> | |
| 116 | + bumpIn(x); | |
| 117 | + Out.int(x); Out.ln; <span class="comment">(* 11 *)</span> | |
| 118 | + fill(a, <span class="number">7</span>); | |
| 119 | + Out.int(a[<span class="number">0</span>] + a[<span class="number">3</span>]); Out.ln; <span class="comment">(* 14 *)</span> | |
| 120 | +<span class="kw">end</span>; | |
| 121 | + | |
| 122 | +<span class="kw">end</span> Params.</code></pre> | |
| 123 | +<pre class="output"><code>10 | |
| 124 | +11 | |
| 125 | +14 | |
| 126 | +</code></pre> | |
| 127 | +<h2>Several results</h2> | |
| 128 | +<p>Instead of an output parameter, a procedure says what it returns: <code>(INT, INT)</code>, or any list of types. The caller takes them apart with a multiple assignment. A call that returns several values may stand on the right of one, alone as a statement, or alone after <code>return</code>, which passes them on as they are.</p> | |
| 129 | +<div class="file"><span>Several.raz</span></div><pre class="code"><code><span class="kw">module</span> Several; | |
| 130 | +<span class="kw">import</span> Out; | |
| 131 | + | |
| 132 | +<span class="kw">proc</span> divmod(a, b: <span class="ty">INT</span>): (<span class="ty">INT</span>, <span class="ty">INT</span>); | |
| 133 | +<span class="kw">begin</span> | |
| 134 | + <span class="kw">return</span> a <span class="kw">div</span> b, a <span class="kw">mod</span> b; | |
| 135 | +<span class="kw">end</span>; | |
| 136 | + | |
| 137 | +<span class="kw">proc</span> minmax(a, b: <span class="ty">INT</span>): (<span class="ty">INT</span>, <span class="ty">INT</span>); | |
| 138 | +<span class="kw">begin</span> | |
| 139 | + <span class="kw">if</span> a < b <span class="kw">then</span> <span class="kw">return</span> a, b; <span class="kw">end</span>; | |
| 140 | + <span class="kw">return</span> b, a; | |
| 141 | +<span class="kw">end</span>; | |
| 142 | + | |
| 143 | +<span class="kw">proc</span> spread(a, b: <span class="ty">INT</span>): (<span class="ty">INT</span>, <span class="ty">INT</span>); | |
| 144 | +<span class="kw">begin</span> | |
| 145 | + <span class="kw">return</span> minmax(a, b); <span class="comment">(* passes both results on *)</span> | |
| 146 | +<span class="kw">end</span>; | |
| 147 | + | |
| 148 | +<span class="kw">proc</span> main*; | |
| 149 | +<span class="kw">var</span> q, r, lo, hi: <span class="ty">INT</span>; | |
| 150 | +<span class="kw">begin</span> | |
| 151 | + q, r := divmod(<span class="number">100</span>, <span class="number">7</span>); | |
| 152 | + Out.int(q); Out.str(<span class="string">" rest "</span>); Out.int(r); Out.ln; | |
| 153 | + lo, hi := spread(<span class="number">9</span>, <span class="number">4</span>); | |
| 154 | + Out.int(lo); Out.str(<span class="string">" .. "</span>); Out.int(hi); Out.ln; | |
| 155 | + _, r := divmod(-<span class="number">7</span>, <span class="number">2</span>); <span class="comment">(* drop the quotient *)</span> | |
| 156 | + Out.int(r); Out.ln; | |
| 157 | +<span class="kw">end</span>; | |
| 158 | + | |
| 159 | +<span class="kw">end</span> Several.</code></pre> | |
| 160 | +<pre class="output"><code>14 rest 2 | |
| 161 | +4 .. 9 | |
| 162 | +-1 | |
| 163 | +</code></pre> | |
| 164 | +<h2>Recursion, and <code>forward</code></h2> | |
| 165 | +<p>A name is declared before it is used, and procedures don't nest. When two procedures need each other, <code>forward</code> declares the first so that its body can come later.</p> | |
| 166 | +<div class="file"><span>Recur.raz</span></div><pre class="code"><code><span class="kw">module</span> Recur; | |
| 167 | +<span class="kw">import</span> Out; | |
| 168 | + | |
| 169 | +<span class="kw">proc</span> gcd(a, b: <span class="ty">INT</span>): <span class="ty">INT</span>; | |
| 170 | +<span class="kw">begin</span> | |
| 171 | + <span class="kw">if</span> b = <span class="number">0</span> <span class="kw">then</span> <span class="kw">return</span> a; <span class="kw">end</span>; | |
| 172 | + <span class="kw">return</span> gcd(b, a <span class="kw">mod</span> b); | |
| 173 | +<span class="kw">end</span>; | |
| 174 | + | |
| 175 | +<span class="kw">proc</span> isOdd(n: <span class="ty">INT</span>): <span class="ty">BOOL</span>; <span class="kw">forward</span>; | |
| 176 | + | |
| 177 | +<span class="kw">proc</span> isEven(n: <span class="ty">INT</span>): <span class="ty">BOOL</span>; | |
| 178 | +<span class="kw">begin</span> | |
| 179 | + <span class="kw">if</span> n = <span class="number">0</span> <span class="kw">then</span> <span class="kw">return</span> <span class="ty">true</span>; <span class="kw">end</span>; | |
| 180 | + <span class="kw">return</span> isOdd(n - <span class="number">1</span>); | |
| 181 | +<span class="kw">end</span>; | |
| 182 | + | |
| 183 | +<span class="kw">proc</span> isOdd(n: <span class="ty">INT</span>): <span class="ty">BOOL</span>; | |
| 184 | +<span class="kw">begin</span> | |
| 185 | + <span class="kw">if</span> n = <span class="number">0</span> <span class="kw">then</span> <span class="kw">return</span> <span class="ty">false</span>; <span class="kw">end</span>; | |
| 186 | + <span class="kw">return</span> isEven(n - <span class="number">1</span>); | |
| 187 | +<span class="kw">end</span>; | |
| 188 | + | |
| 189 | +<span class="kw">proc</span> main*; | |
| 190 | +<span class="kw">begin</span> | |
| 191 | + Out.int(gcd(<span class="number">84</span>, <span class="number">36</span>)); Out.ln; | |
| 192 | + <span class="kw">if</span> isEven(<span class="number">10</span>) <span class="kw">and</span> isOdd(<span class="number">7</span>) <span class="kw">then</span> Out.str(<span class="string">"parity works\n"</span>); <span class="kw">end</span>; | |
| 193 | +<span class="kw">end</span>; | |
| 194 | + | |
| 195 | +<span class="kw">end</span> Recur.</code></pre> | |
| 196 | +<pre class="output"><code>12 | |
| 197 | +parity works | |
| 198 | +</code></pre> | |
| 199 | +<h2>Procedures are values</h2> | |
| 200 | +<p>A procedure used without parentheses is a procedure value, of a procedure type such as <code>proc(a, b: INT): INT</code>. It can be passed, stored in a variable or a record, and called. This is raz's only dynamic dispatch, and it is as plain as it looks.</p> | |
| 201 | +<div class="file"><span>Table.raz</span></div><pre class="code"><code><span class="kw">module</span> Table; | |
| 202 | +<span class="kw">import</span> Out; | |
| 203 | + | |
| 204 | +<span class="kw">type</span> Op = <span class="kw">proc</span>(a, b: <span class="ty">INT</span>): <span class="ty">INT</span>; | |
| 205 | + | |
| 206 | +<span class="kw">proc</span> add(a, b: <span class="ty">INT</span>): <span class="ty">INT</span>; <span class="kw">begin</span> <span class="kw">return</span> a + b; <span class="kw">end</span>; | |
| 207 | +<span class="kw">proc</span> sub(a, b: <span class="ty">INT</span>): <span class="ty">INT</span>; <span class="kw">begin</span> <span class="kw">return</span> a - b; <span class="kw">end</span>; | |
| 208 | +<span class="kw">proc</span> mul(a, b: <span class="ty">INT</span>): <span class="ty">INT</span>; <span class="kw">begin</span> <span class="kw">return</span> a * b; <span class="kw">end</span>; | |
| 209 | + | |
| 210 | +<span class="kw">proc</span> apply(f: Op; a, b: <span class="ty">INT</span>): <span class="ty">INT</span>; | |
| 211 | +<span class="kw">begin</span> | |
| 212 | + <span class="kw">return</span> f(a, b); | |
| 213 | +<span class="kw">end</span>; | |
| 214 | + | |
| 215 | +<span class="kw">proc</span> main*; | |
| 216 | +<span class="kw">var</span> ops: [<span class="number">3</span>]Op; names: [<span class="number">3</span>][]<span class="ty">U8</span>; i: <span class="ty">INT</span>; | |
| 217 | +<span class="kw">begin</span> | |
| 218 | + ops := [add, sub, mul]; | |
| 219 | + names := [<span class="string">"add"</span>, <span class="string">"sub"</span>, <span class="string">"mul"</span>]; | |
| 220 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">2</span> <span class="kw">do</span> | |
| 221 | + Out.str(names[i]); Out.str(<span class="string">": "</span>); | |
| 222 | + Out.int(apply(ops[i], <span class="number">12</span>, <span class="number">5</span>)); Out.ln; | |
| 223 | + <span class="kw">end</span>; | |
| 224 | +<span class="kw">end</span>; | |
| 225 | + | |
| 226 | +<span class="kw">end</span> Table.</code></pre> | |
| 227 | +<pre class="output"><code>add: 17 | |
| 228 | +sub: 7 | |
| 229 | +mul: 60 | |
| 230 | +</code></pre> | |
| 231 | +<p>A procedure without parameters leaves out the parentheses where it is called, as <code>Out.ln</code> does. That means <code>f</code> alone is the procedure and <code>f()</code> would not be a call, so be careful when passing one around.</p> | |
| 232 | +<h2>Dropped results</h2> | |
| 233 | +<p>A call that drops a result, as <code>Sys.write(fd, s);</code> does, is warned of; <code>_ := Sys.write(fd, s);</code> says it is meant. The compiler also warns of a variable that is assigned and never read, and of a name declared and never used, unless it starts with <code>_</code>.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="values.html">← Values and conversions</a><a href="index.html">Contents</a><a class="next" href="slices.html">Arrays, slices and strings →</a></div></article></div> | |
| 234 | +</main> | |
| 235 | +<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> | |
| 236 | +</body> | |
| 237 | +</html> |
| @@ -0,0 +1,350 @@ | ||
| 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>Records and pointers - Raz, Set, Go</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="Records and pointers - Raz, Set, Go"> | |
| 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.lucelad.workers.dev/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" aria-current="page">Raz, Set, Go</a><a href="../advanced/index.html">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<div class="tour"><aside><h2>Raz, Set, Go</h2><h3>Raz</h3><ol start='1'> | |
| 22 | +<li><a href="hello.html">Hello, world</a></li> | |
| 23 | +<li><a href="modules.html">Modules</a></li> | |
| 24 | +<li><a href="integers.html">Integers</a></li> | |
| 25 | +<li><a href="values.html">Values and conversions</a></li> | |
| 26 | +<li><a href="procedures.html">Procedures and several results</a></li> | |
| 27 | +</ol> | |
| 28 | +<h3>Set</h3><ol start='6'> | |
| 29 | +<li><a href="slices.html">Arrays, slices and strings</a></li> | |
| 30 | +<li><a href="records.html" aria-current="page">Records and pointers</a></li> | |
| 31 | +<li><a href="variants.html">Enumerations, sets, variants and match</a></li> | |
| 32 | +<li><a href="memory.html">Memory and allocators</a></li> | |
| 33 | +</ol> | |
| 34 | +<h3>Go</h3><ol start='10'> | |
| 35 | +<li><a href="errors.html">Errors</a></li> | |
| 36 | +<li><a href="defer.html">Defer</a></li> | |
| 37 | +<li><a href="checks.html">When it goes wrong</a></li> | |
| 38 | +<li><a href="generics.html">Generic modules</a></li> | |
| 39 | +<li><a href="c.html">Talking to C</a></li> | |
| 40 | +<li><a href="threads.html">Threads</a></li> | |
| 41 | +</ol></aside><article><p class="kicker">Set · lesson 7 of 15</p><h1>Records and pointers</h1> | |
| 42 | +<div class="file"><span>Boxes.raz</span></div><pre class="code"><code><span class="kw">module</span> Boxes; | |
| 43 | +<span class="kw">import</span> Fmt, SYSTEM; | |
| 44 | + | |
| 45 | +<span class="kw">type</span> | |
| 46 | + Point = <span class="kw">record</span> x, y: <span class="ty">INT</span>; <span class="kw">end</span>; | |
| 47 | + Box = <span class="kw">record</span> lo, hi: Point; <span class="kw">end</span>; | |
| 48 | + | |
| 49 | +<span class="kw">proc</span> area(b: Box): <span class="ty">INT</span>; | |
| 50 | +<span class="kw">begin</span> | |
| 51 | + <span class="kw">return</span> (b.hi.x - b.lo.x) * (b.hi.y - b.lo.y); | |
| 52 | +<span class="kw">end</span>; | |
| 53 | + | |
| 54 | +<span class="kw">proc</span> grow(b: ^Box; n: <span class="ty">INT</span>); | |
| 55 | +<span class="kw">begin</span> | |
| 56 | + <span class="ty">DEC</span>(b^.lo.x, n); | |
| 57 | + <span class="ty">DEC</span>(b^.lo.y, n); | |
| 58 | + <span class="ty">INC</span>(b^.hi.x, n); | |
| 59 | + <span class="ty">INC</span>(b^.hi.y, n); | |
| 60 | +<span class="kw">end</span>; | |
| 61 | + | |
| 62 | +<span class="kw">proc</span> main*; | |
| 63 | +<span class="kw">var</span> b: Box; p: ^Point; | |
| 64 | +<span class="kw">begin</span> | |
| 65 | + b := {lo: {x: <span class="number">1</span>, y: <span class="number">1</span>}, hi: {x: <span class="number">4</span>, y: <span class="number">3</span>}}; | |
| 66 | + Fmt.print(<span class="string">"{}\n"</span>, [Fmt.int(area(b))]); | |
| 67 | + grow(SYSTEM.<span class="ty">ADR</span>(b), <span class="number">1</span>); | |
| 68 | + p := SYSTEM.<span class="ty">ADR</span>(b.hi); | |
| 69 | + p^.x := <span class="number">10</span>; | |
| 70 | + Fmt.print(<span class="string">"{} {}\n"</span>, [Fmt.int(area(b)), Fmt.int(b.hi.x)]); | |
| 71 | +<span class="kw">end</span>; | |
| 72 | + | |
| 73 | +<span class="kw">end</span> Boxes.</code></pre> | |
| 74 | +<pre class="output"><code>6 | |
| 75 | +40 10 | |
| 76 | +</code></pre> | |
| 77 | +<p>A record is laid out as C lays out a struct. <code>{lo: ..., hi: ...}</code> builds one, naming its fields; the ones it leaves out are zero. <code>^Box</code> is a pointer to a <code>Box</code>, <code>ADR(b)</code> the address of <code>b</code>, and <code>b^</code> what a pointer points at. A pointer is never the record: it is <code>b^.lo</code>, never <code>b.lo</code>, so you always see where the memory is reached through an address.</p> | |
| 78 | +<h2>Copies and literals</h2> | |
| 79 | +<p>Assigning a record copies it whole, as with an array. A record is compared field by field by writing the comparison, not by <code>=</code>.</p> | |
| 80 | +<div class="file"><span>Points.raz</span></div><pre class="code"><code><span class="kw">module</span> Points; | |
| 81 | +<span class="kw">import</span> Out; | |
| 82 | + | |
| 83 | +<span class="kw">type</span> Point = <span class="kw">record</span> x, y: <span class="ty">INT</span>; <span class="kw">end</span>; | |
| 84 | + | |
| 85 | +<span class="kw">proc</span> show(p: Point); | |
| 86 | +<span class="kw">begin</span> | |
| 87 | + Out.char(<span class="string">'('</span>); Out.int(p.x); Out.str(<span class="string">", "</span>); Out.int(p.y); Out.char(<span class="string">')'</span>); | |
| 88 | +<span class="kw">end</span>; | |
| 89 | + | |
| 90 | +<span class="kw">proc</span> mirror(p: Point): Point; | |
| 91 | +<span class="kw">begin</span> | |
| 92 | + <span class="kw">return</span> {x: p.y, y: p.x}; | |
| 93 | +<span class="kw">end</span>; | |
| 94 | + | |
| 95 | +<span class="kw">proc</span> main*; | |
| 96 | +<span class="kw">var</span> a, b: Point; | |
| 97 | +<span class="kw">begin</span> | |
| 98 | + a := {x: <span class="number">3</span>, y: <span class="number">4</span>}; | |
| 99 | + b := a; <span class="comment">(* a copy *)</span> | |
| 100 | + b.x := <span class="number">30</span>; | |
| 101 | + show(a); show(b); show(mirror(a)); Out.ln; | |
| 102 | + a := {y: <span class="number">9</span>}; <span class="comment">(* x is zero *)</span> | |
| 103 | + show(a); Out.ln; | |
| 104 | +<span class="kw">end</span>; | |
| 105 | + | |
| 106 | +<span class="kw">end</span> Points.</code></pre> | |
| 107 | +<pre class="output"><code>(3, 4)(30, 4)(4, 3) | |
| 108 | +(0, 9) | |
| 109 | +</code></pre> | |
| 110 | +<h2>Tables of constants</h2> | |
| 111 | +<p>A constant may be a record, or an array of them: a table the program reads but can't change. Its fields are integers, reals, <code>BOOL</code>s, strings, procedures and the like, and arrays and records of these.</p> | |
| 112 | +<div class="file"><span>Planets.raz</span></div><pre class="code"><code><span class="kw">module</span> Planets; | |
| 113 | +<span class="kw">import</span> Fmt; | |
| 114 | + | |
| 115 | +<span class="kw">type</span> Planet = <span class="kw">record</span> name: []<span class="ty">U8</span>; moons: <span class="ty">INT</span>; water: <span class="ty">BOOL</span>; <span class="kw">end</span>; | |
| 116 | + | |
| 117 | +<span class="kw">const</span> Inner: []Planet = [ | |
| 118 | + {name: <span class="string">"Mercury"</span>}, | |
| 119 | + {name: <span class="string">"Venus"</span>}, | |
| 120 | + {name: <span class="string">"Earth"</span>, moons: <span class="number">1</span>, water: <span class="ty">true</span>}, | |
| 121 | + {name: <span class="string">"Mars"</span>, moons: <span class="number">2</span>}]; | |
| 122 | + | |
| 123 | +<span class="kw">proc</span> main*; | |
| 124 | +<span class="kw">var</span> i, total: <span class="ty">INT</span>; | |
| 125 | +<span class="kw">begin</span> | |
| 126 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="ty">LEN</span>(Inner) - <span class="number">1</span> <span class="kw">do</span> | |
| 127 | + total := total + Inner[i].moons; | |
| 128 | + <span class="kw">if</span> Inner[i].moons = <span class="number">0</span> <span class="kw">then</span> Fmt.print(<span class="string">"{} has no moon\n"</span>, [Fmt.str(Inner[i].name)]); <span class="kw">end</span>; | |
| 129 | + <span class="kw">end</span>; | |
| 130 | + Fmt.print(<span class="string">"{} moons in all\n"</span>, [Fmt.int(total)]); | |
| 131 | +<span class="kw">end</span>; | |
| 132 | + | |
| 133 | +<span class="kw">end</span> Planets.</code></pre> | |
| 134 | +<pre class="output"><code>Mercury has no moon | |
| 135 | +Venus has no moon | |
| 136 | +3 moons in all | |
| 137 | +</code></pre> | |
| 138 | +<p>Fields left out are zero, as in any literal: Mercury's <code>moons</code> is 0 and its <code>water</code> is <code>false</code>. A constant typed <code>[]Planet</code> takes its length from its literal, here 4, so a planet added to the list needs no count changed.</p> | |
| 139 | +<h2>Layout</h2> | |
| 140 | +<p>A record's layout is C's: each field at the next multiple of its own alignment, and the whole padded to a multiple of its largest alignment. <code>SIZE(T)</code> says how many bytes. A <code>packed record</code> has no padding, which is what a file format or a wire protocol wants.</p> | |
| 141 | +<div class="file"><span>Layout.raz</span></div><pre class="code"><code><span class="kw">module</span> Layout; | |
| 142 | +<span class="kw">import</span> Out; | |
| 143 | + | |
| 144 | +<span class="kw">type</span> | |
| 145 | + Loose = <span class="kw">record</span> a: <span class="ty">U8</span>; b: <span class="ty">U32</span>; c: <span class="ty">U8</span>; <span class="kw">end</span>; | |
| 146 | + Tight = <span class="kw">packed</span> <span class="kw">record</span> a: <span class="ty">U8</span>; b: <span class="ty">U32</span>; c: <span class="ty">U8</span>; <span class="kw">end</span>; | |
| 147 | + | |
| 148 | +<span class="kw">proc</span> main*; | |
| 149 | +<span class="kw">begin</span> | |
| 150 | + Out.str(<span class="string">"loose: "</span>); Out.int(<span class="ty">SIZE</span>(Loose)); Out.ln; <span class="comment">(* 12 *)</span> | |
| 151 | + Out.str(<span class="string">"tight: "</span>); Out.int(<span class="ty">SIZE</span>(Tight)); Out.ln; <span class="comment">(* 6 *)</span> | |
| 152 | + Out.str(<span class="string">"INT: "</span>); Out.int(<span class="ty">SIZE</span>(<span class="ty">INT</span>)); Out.ln; | |
| 153 | + Out.str(<span class="string">"[5]I16: "</span>); Out.int(<span class="ty">SIZE</span>([<span class="number">5</span>]<span class="ty">I16</span>)); Out.ln; | |
| 154 | +<span class="kw">end</span>; | |
| 155 | + | |
| 156 | +<span class="kw">end</span> Layout.</code></pre> | |
| 157 | +<pre class="output"><code>loose: 12 | |
| 158 | +tight: 6 | |
| 159 | +INT: 8 | |
| 160 | +[5]I16: 10 | |
| 161 | +</code></pre> | |
| 162 | +<p>A field of a packed record may sit at any address, and is read and written like any other; but it has no address of its own to take with <code>ADR</code>.</p> | |
| 163 | +<h2>Bytes as numbers and records: views</h2> | |
| 164 | +<p>A file, a socket or a device hands a program bytes. A view reads and writes them as another type: <code>msg[3].(U32)</code> is the <code>U32</code> whose four bytes start at <code>msg[3]</code>, and <code>msg[0].(Head)</code> the <code>Head</code> whose bytes start at <code>msg[0]</code>.</p> | |
| 165 | +<div class="file"><span>Wire.raz</span></div><pre class="code"><code><span class="kw">module</span> Wire; | |
| 166 | +<span class="kw">import</span> Out; | |
| 167 | + | |
| 168 | +<span class="kw">type</span> Head = <span class="kw">packed</span> <span class="kw">record</span> magic: <span class="ty">U16</span>; kind: <span class="ty">U8</span>; len: <span class="ty">U32</span>; <span class="kw">end</span>; <span class="comment">(* 7 bytes, as sent *)</span> | |
| 169 | + | |
| 170 | +<span class="kw">var</span> msg: [<span class="number">32</span>]<span class="ty">U8</span>; | |
| 171 | + | |
| 172 | +<span class="kw">proc</span> main*; | |
| 173 | +<span class="kw">var</span> h: Head; i: <span class="ty">INT</span>; sum: <span class="ty">I64</span>; | |
| 174 | +<span class="kw">begin</span> | |
| 175 | + <span class="comment">(* what a socket might have handed us *)</span> | |
| 176 | + msg[<span class="number">0</span>] := <span class="number">52H</span>; msg[<span class="number">1</span>] := <span class="number">5AH</span>; | |
| 177 | + msg[<span class="number">2</span>] := <span class="number">1</span>; | |
| 178 | + msg[<span class="number">3</span>].(<span class="ty">U32</span>) := <span class="number">8</span>; | |
| 179 | + msg[<span class="number">7</span>].(<span class="ty">I32</span>) := <span class="number">100</span>; | |
| 180 | + msg[<span class="number">11</span>].(<span class="ty">I32</span>) := <span class="number">200</span>; | |
| 181 | + | |
| 182 | + h := msg[<span class="number">0</span>].(Head); | |
| 183 | + Out.hex(<span class="ty">U64</span>(h.magic), <span class="number">4</span>); Out.char(<span class="string">' '</span>); | |
| 184 | + Out.int(<span class="ty">I64</span>(h.kind)); Out.char(<span class="string">' '</span>); | |
| 185 | + Out.int(<span class="ty">I64</span>(h.len)); Out.ln; | |
| 186 | + sum := <span class="number">0</span>; | |
| 187 | + i := <span class="number">7</span>; | |
| 188 | + <span class="kw">while</span> i < <span class="number">7</span> + <span class="ty">INT</span>(h.len) <span class="kw">do</span> | |
| 189 | + sum := sum + <span class="ty">I64</span>(msg[i].(<span class="ty">I32</span>)); | |
| 190 | + i := i + <span class="number">4</span>; | |
| 191 | + <span class="kw">end</span>; | |
| 192 | + Out.int(sum); Out.ln; | |
| 193 | +<span class="kw">end</span>; | |
| 194 | + | |
| 195 | +<span class="kw">end</span> Wire.</code></pre> | |
| 196 | +<pre class="output"><code>5A52 1 8 | |
| 197 | +300 | |
| 198 | +</code></pre> | |
| 199 | +<p>A view isn't a copy: it *is* those bytes, so <code>msg[3].(U32) := 8</code> writes <code>msg[3]</code> to <code>msg[6]</code>, and a view goes wherever a variable does, with a field after it, in <code>INC</code>, on the left of <code>:=</code>. Nor is it a conversion: <code>I64(x)</code> is a real's number, <code>x.(U64)</code> its bits. The magic number reads <code>5A52</code>, its bytes backwards, because x86-64 keeps a number's low byte first; a format with an order of its own is read with <code>Str.le</code> or <code>Str.be</code>.</p> | |
| 200 | +<p>A view of an element must end inside the array, and the program checks it as it checks an index:</p> | |
| 201 | +<div class="file"><span>Short.raz</span></div><pre class="code"><code><span class="kw">module</span> Short; | |
| 202 | +<span class="kw">import</span> Out; | |
| 203 | + | |
| 204 | +<span class="kw">var</span> msg: [<span class="number">10</span>]<span class="ty">U8</span>; | |
| 205 | + | |
| 206 | +<span class="kw">proc</span> main*; | |
| 207 | +<span class="kw">var</span> i: <span class="ty">INT</span>; | |
| 208 | +<span class="kw">begin</span> | |
| 209 | + i := <span class="number">0</span>; | |
| 210 | + <span class="kw">while</span> i < <span class="ty">LEN</span>(msg) <span class="kw">do</span> | |
| 211 | + Out.int(<span class="ty">I64</span>(msg[i].(<span class="ty">U32</span>))); Out.char(<span class="string">' '</span>); | |
| 212 | + i := i + <span class="number">4</span>; | |
| 213 | + <span class="kw">end</span>; | |
| 214 | +<span class="kw">end</span>; | |
| 215 | + | |
| 216 | +<span class="kw">end</span> Short.</code></pre> | |
| 217 | +<pre class="output"><code>0 0 <span class="err">Short.raz:11:25: a view at index 8 runs past a length of 10 | |
| 218 | + in Short.main at Short.raz:11:25: i = 8 | |
| 219 | +</span></code></pre> | |
| 220 | +<p>The type of a view is an integer, a real or a pointer, or a record or array made of them: types any bytes are a value of, which a <code>BOOL</code> or an enumeration isn't. A view may start at any byte, so, as a packed record's field, it has no address of its own.</p> | |
| 221 | +<h2>Pointers</h2> | |
| 222 | +<p><code>ADR(x)</code> takes the address of a variable, <code>^T</code> is a pointer to a <code>T</code>, and <code>p^</code> is what it points at. A pointer that points nowhere is <code>nil</code>, and following it stops the program with a message that names the place, so a forgotten check is found at once instead of corrupting memory.</p> | |
| 223 | +<div class="file"><span>Pointers.raz</span></div><pre class="code"><code><span class="kw">module</span> Pointers; | |
| 224 | +<span class="kw">import</span> Out; | |
| 225 | + | |
| 226 | +<span class="kw">type</span> Counter = <span class="kw">record</span> hits: <span class="ty">INT</span>; name: []<span class="ty">U8</span>; <span class="kw">end</span>; | |
| 227 | + | |
| 228 | +<span class="kw">proc</span> hit(c: ^Counter); | |
| 229 | +<span class="kw">begin</span> | |
| 230 | + <span class="kw">if</span> c = <span class="ty">nil</span> <span class="kw">then</span> <span class="kw">return</span>; <span class="kw">end</span>; | |
| 231 | + <span class="ty">INC</span>(c^.hits); | |
| 232 | +<span class="kw">end</span>; | |
| 233 | + | |
| 234 | +<span class="kw">proc</span> swap(a, b: ^<span class="ty">INT</span>); | |
| 235 | +<span class="kw">var</span> t: <span class="ty">INT</span>; | |
| 236 | +<span class="kw">begin</span> | |
| 237 | + t := a^; | |
| 238 | + a^ := b^; | |
| 239 | + b^ := t; | |
| 240 | +<span class="kw">end</span>; | |
| 241 | + | |
| 242 | +<span class="kw">proc</span> main*; | |
| 243 | +<span class="kw">var</span> c: Counter; x, y: <span class="ty">INT</span>; p: ^<span class="ty">INT</span>; | |
| 244 | +<span class="kw">begin</span> | |
| 245 | + c.name := <span class="string">"front door"</span>; | |
| 246 | + hit(<span class="ty">ADR</span>(c)); hit(<span class="ty">ADR</span>(c)); hit(<span class="ty">nil</span>); | |
| 247 | + Out.str(c.name); Out.str(<span class="string">": "</span>); Out.int(c.hits); Out.ln; | |
| 248 | + x := <span class="number">1</span>; y := <span class="number">2</span>; | |
| 249 | + swap(<span class="ty">ADR</span>(x), <span class="ty">ADR</span>(y)); | |
| 250 | + Out.int(x); Out.char(<span class="string">' '</span>); Out.int(y); Out.ln; | |
| 251 | + p := <span class="ty">ADR</span>(x); | |
| 252 | + p^ := p^ + <span class="number">40</span>; | |
| 253 | + Out.int(x); Out.ln; | |
| 254 | +<span class="kw">end</span>; | |
| 255 | + | |
| 256 | +<span class="kw">end</span> Pointers.</code></pre> | |
| 257 | +<pre class="output"><code>front door: 2 | |
| 258 | +2 1 | |
| 259 | +42 | |
| 260 | +</code></pre> | |
| 261 | +<h2>Pointers that link</h2> | |
| 262 | +<p>A record may hold a pointer to its own type, which is how lists and trees are made. Memory for them comes from an allocator, which is the next lesson; here the nodes simply live in an array.</p> | |
| 263 | +<div class="file"><span>Chain.raz</span></div><pre class="code"><code><span class="kw">module</span> Chain; | |
| 264 | +<span class="kw">import</span> Out; | |
| 265 | + | |
| 266 | +<span class="kw">type</span> Node = <span class="kw">record</span> next: ^Node; val: <span class="ty">INT</span>; <span class="kw">end</span>; | |
| 267 | + | |
| 268 | +<span class="kw">proc</span> main*; | |
| 269 | +<span class="kw">var</span> nodes: [<span class="number">4</span>]Node; head, n: ^Node; i: <span class="ty">INT</span>; | |
| 270 | +<span class="kw">begin</span> | |
| 271 | + head := <span class="ty">nil</span>; | |
| 272 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> | |
| 273 | + nodes[i].val := (i + <span class="number">1</span>) * <span class="number">10</span>; | |
| 274 | + nodes[i].next := head; <span class="comment">(* each new one in front *)</span> | |
| 275 | + head := <span class="ty">ADR</span>(nodes[i]); | |
| 276 | + <span class="kw">end</span>; | |
| 277 | + n := head; | |
| 278 | + <span class="kw">while</span> n # <span class="ty">nil</span> <span class="kw">do</span> | |
| 279 | + Out.int(n^.val); Out.char(<span class="string">' '</span>); | |
| 280 | + n := n^.next; | |
| 281 | + <span class="kw">end</span>; | |
| 282 | + Out.ln; | |
| 283 | +<span class="kw">end</span>; | |
| 284 | + | |
| 285 | +<span class="kw">end</span> Chain.</code></pre> | |
| 286 | +<pre class="output"><code>40 30 20 10 | |
| 287 | +</code></pre> | |
| 288 | +<h2>A slice's pointer</h2> | |
| 289 | +<p>A slice is a pointer and a length, and a record can keep the two apart: an interpreter keeps a string so, and C takes one so. <code>LEN(s)</code> is the length. The pointer looks like <code>ADR(s[0])</code>, the address of the first element, and that works until the slice is empty: then there is no first element, <code>s[0]</code> is out of range, and the program stops.</p> | |
| 290 | +<div class="file"><span>Empty.raz</span></div><pre class="code"><code><span class="kw">module</span> Empty; | |
| 291 | +<span class="kw">import</span> Out; | |
| 292 | + | |
| 293 | +<span class="kw">type</span> Span = <span class="kw">record</span> p: ^<span class="ty">U8</span>; n: <span class="ty">INT</span>; <span class="kw">end</span>; | |
| 294 | + | |
| 295 | +<span class="kw">proc</span> spanOf(s: []<span class="ty">U8</span>): Span; | |
| 296 | +<span class="kw">begin</span> | |
| 297 | + <span class="kw">return</span> {p: <span class="ty">ADR</span>(s[<span class="number">0</span>]), n: <span class="ty">LEN</span>(s)}; | |
| 298 | +<span class="kw">end</span>; | |
| 299 | + | |
| 300 | +<span class="kw">proc</span> main*; | |
| 301 | +<span class="kw">var</span> a, b: Span; | |
| 302 | +<span class="kw">begin</span> | |
| 303 | + a := spanOf(<span class="string">"one"</span>); | |
| 304 | + Out.int(a.n); Out.ln; | |
| 305 | + b := spanOf(<span class="string">""</span>); | |
| 306 | + Out.int(b.n); Out.ln; | |
| 307 | +<span class="kw">end</span>; | |
| 308 | + | |
| 309 | +<span class="kw">end</span> Empty.</code></pre> | |
| 310 | +<pre class="output"><code>3 | |
| 311 | +<span class="err">Empty.raz:8:22: index 0 is out of range for a length of 0 | |
| 312 | + in Empty.spanOf at Empty.raz:8:22 | |
| 313 | + in Empty.main at Empty.raz:16:5 | |
| 314 | +</span></code></pre> | |
| 315 | +<p><code>PTR(s)</code> is the pointer itself, a <code>^U8</code> for a <code>[]U8</code>, with no check. For a slice that isn't empty it is <code>ADR(s[0])</code>; for an empty one it is what the slice holds, <code>nil</code> for one never set. So nothing needs testing first, and <code>sp.p[0..sp.n]</code> makes the slice again, empty when <code>sp.n</code> is 0, whatever <code>sp.p</code> is:</p> | |
| 316 | +<div class="file"><span>Spans.raz</span></div><pre class="code"><code><span class="kw">module</span> Spans; | |
| 317 | +<span class="kw">import</span> Out, SYSTEM; | |
| 318 | + | |
| 319 | +<span class="kw">type</span> Span = <span class="kw">record</span> p: ^<span class="ty">U8</span>; n: <span class="ty">INT</span>; <span class="kw">end</span>; | |
| 320 | + | |
| 321 | +<span class="kw">proc</span> spanOf(s: []<span class="ty">U8</span>): Span; | |
| 322 | +<span class="kw">begin</span> | |
| 323 | + <span class="kw">return</span> {p: SYSTEM.PTR(s), n: <span class="ty">LEN</span>(s)}; | |
| 324 | +<span class="kw">end</span>; | |
| 325 | + | |
| 326 | +<span class="kw">proc</span> text(sp: Span): []<span class="ty">U8</span>; | |
| 327 | +<span class="kw">begin</span> | |
| 328 | + <span class="kw">return</span> sp.p[<span class="number">0</span>..sp.n]; | |
| 329 | +<span class="kw">end</span>; | |
| 330 | + | |
| 331 | +<span class="kw">proc</span> main*; | |
| 332 | +<span class="kw">var</span> words: [<span class="number">3</span>]Span; i: <span class="ty">INT</span>; | |
| 333 | +<span class="kw">begin</span> | |
| 334 | + words := [spanOf(<span class="string">"one"</span>), spanOf(<span class="string">""</span>), spanOf(<span class="string">"three"</span>)]; | |
| 335 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">2</span> <span class="kw">do</span> | |
| 336 | + Out.int(words[i].n); Out.char(<span class="string">' '</span>); | |
| 337 | + Out.str(text(words[i])); Out.ln; | |
| 338 | + <span class="kw">end</span>; | |
| 339 | +<span class="kw">end</span>; | |
| 340 | + | |
| 341 | +<span class="kw">end</span> Spans.</code></pre> | |
| 342 | +<pre class="output"><code>3 one | |
| 343 | +0 | |
| 344 | +5 three | |
| 345 | +</code></pre> | |
| 346 | +<p>Of an array, <code>PTR(a)</code> is the address of its first element, a <code>^T</code> where <code>ADR(a)</code> is a <code>^[n]T</code>. Reading through the pointer is as unchecked as through any pointer: the length is yours to keep with it. The compiler says so when the two are mixed up: a slice given where a pointer is wanted is an error whose help says to write <code>PTR(s)</code> and <code>LEN(s)</code>, and a pointer given where a slice is, <code>p[0..n]</code>.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="slices.html">← Arrays, slices and strings</a><a href="index.html">Contents</a><a class="next" href="variants.html">Enumerations, sets, variants and match →</a></div></article></div> | |
| 347 | +</main> | |
| 348 | +<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> | |
| 349 | +</body> | |
| 350 | +</html> |
| @@ -0,0 +1,350 @@ | ||
| 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>Arrays, slices and strings - Raz, Set, Go</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="Arrays, slices and strings - Raz, Set, Go"> | |
| 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.lucelad.workers.dev/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" aria-current="page">Raz, Set, Go</a><a href="../advanced/index.html">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<div class="tour"><aside><h2>Raz, Set, Go</h2><h3>Raz</h3><ol start='1'> | |
| 22 | +<li><a href="hello.html">Hello, world</a></li> | |
| 23 | +<li><a href="modules.html">Modules</a></li> | |
| 24 | +<li><a href="integers.html">Integers</a></li> | |
| 25 | +<li><a href="values.html">Values and conversions</a></li> | |
| 26 | +<li><a href="procedures.html">Procedures and several results</a></li> | |
| 27 | +</ol> | |
| 28 | +<h3>Set</h3><ol start='6'> | |
| 29 | +<li><a href="slices.html" aria-current="page">Arrays, slices and strings</a></li> | |
| 30 | +<li><a href="records.html">Records and pointers</a></li> | |
| 31 | +<li><a href="variants.html">Enumerations, sets, variants and match</a></li> | |
| 32 | +<li><a href="memory.html">Memory and allocators</a></li> | |
| 33 | +</ol> | |
| 34 | +<h3>Go</h3><ol start='10'> | |
| 35 | +<li><a href="errors.html">Errors</a></li> | |
| 36 | +<li><a href="defer.html">Defer</a></li> | |
| 37 | +<li><a href="checks.html">When it goes wrong</a></li> | |
| 38 | +<li><a href="generics.html">Generic modules</a></li> | |
| 39 | +<li><a href="c.html">Talking to C</a></li> | |
| 40 | +<li><a href="threads.html">Threads</a></li> | |
| 41 | +</ol></aside><article><p class="kicker">Set · lesson 6 of 15</p><h1>Arrays, slices and strings</h1> | |
| 42 | +<div class="file"><span>Slices.raz</span></div><pre class="code"><code><span class="kw">module</span> Slices; | |
| 43 | +<span class="kw">import</span> Out, Str; | |
| 44 | + | |
| 45 | +<span class="kw">proc</span> sum(s: []<span class="ty">INT</span>): <span class="ty">INT</span>; | |
| 46 | +<span class="kw">var</span> i, t: <span class="ty">INT</span>; | |
| 47 | +<span class="kw">begin</span> | |
| 48 | + t := <span class="number">0</span>; | |
| 49 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="ty">LEN</span>(s) - <span class="number">1</span> <span class="kw">do</span> t := t + s[i]; <span class="kw">end</span>; | |
| 50 | + <span class="kw">return</span> t; | |
| 51 | +<span class="kw">end</span>; | |
| 52 | + | |
| 53 | +<span class="kw">proc</span> main*; | |
| 54 | +<span class="kw">var</span> a: [<span class="number">5</span>]<span class="ty">INT</span>; i: <span class="ty">INT</span>; s, val: []<span class="ty">U8</span>; name: [<span class="number">8</span>]<span class="ty">U8</span>; ok: <span class="ty">BOOL</span>; | |
| 55 | +<span class="kw">begin</span> | |
| 56 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">4</span> <span class="kw">do</span> a[i] := i * i; <span class="kw">end</span>; | |
| 57 | + Out.int(sum(a)); Out.ln; <span class="comment">(* the array, as a slice *)</span> | |
| 58 | + Out.int(sum(a[<span class="number">1</span>..<span class="number">3</span>])); Out.ln; <span class="comment">(* a[1] and a[2] *)</span> | |
| 59 | + s := <span class="string">"hello, world"</span>; | |
| 60 | + Out.str(s[<span class="number">7</span>..<span class="ty">LEN</span>(s)]); Out.ln; | |
| 61 | + <span class="kw">if</span> s[<span class="number">0</span>..<span class="number">5</span>] = <span class="string">"hello"</span> <span class="kw">then</span> Out.str(<span class="string">"it says hello\n"</span>); <span class="kw">end</span>; | |
| 62 | + Out.int(Str.find(s, <span class="string">"world"</span>)); Out.ln; | |
| 63 | + _, val, ok := Str.cut(<span class="string">" size = 42 "</span>, <span class="string">"="</span>); | |
| 64 | + <span class="kw">if</span> ok <span class="kw">then</span> Out.str(Str.trim(val)); Out.ln; <span class="kw">end</span>; | |
| 65 | + name := <span class="string">"raz"</span>; <span class="comment">(* a copy, the program's own *)</span> | |
| 66 | + name[<span class="number">0</span>] := <span class="string">'R'</span>; | |
| 67 | + Out.str(name[<span class="number">0</span>..<span class="number">3</span>]); Out.ln; | |
| 68 | + Out.str(<span class="string">` | |
| 69 | + C:\tmp\ "as it stands" | |
| 70 | + over lines | |
| 71 | + `</span>); | |
| 72 | +<span class="kw">end</span>; | |
| 73 | + | |
| 74 | +<span class="kw">end</span> Slices.</code></pre> | |
| 75 | +<pre class="output"><code>30 | |
| 76 | +5 | |
| 77 | +world | |
| 78 | +it says hello | |
| 79 | +7 | |
| 80 | +42 | |
| 81 | +Raz | |
| 82 | +C:\tmp\ "as it stands" | |
| 83 | + over lines | |
| 84 | +</code></pre> | |
| 85 | +<h2>Arrays</h2> | |
| 86 | +<p><code>[5]INT</code> is an array: five <code>INT</code>s in a row, copied when it is assigned or passed. Its length is part of its type, so <code>[5]INT</code> and <code>[6]INT</code> are different types, and <code>LEN(a)</code> of an array is a constant. Array literals are written in brackets, and need a type from the place they are used.</p> | |
| 87 | +<div class="file"><span>Arrays.raz</span></div><pre class="code"><code><span class="kw">module</span> Arrays; | |
| 88 | +<span class="kw">import</span> Out; | |
| 89 | + | |
| 90 | +<span class="kw">proc</span> main*; | |
| 91 | +<span class="kw">var</span> a, b: [<span class="number">4</span>]<span class="ty">INT</span>; grid: [<span class="number">3</span>][<span class="number">3</span>]<span class="ty">INT</span>; i, j: <span class="ty">INT</span>; | |
| 92 | +<span class="kw">begin</span> | |
| 93 | + a := [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>]; | |
| 94 | + b := a; <span class="comment">(* a copy *)</span> | |
| 95 | + b[<span class="number">0</span>] := <span class="number">99</span>; | |
| 96 | + Out.int(a[<span class="number">0</span>]); Out.char(<span class="string">' '</span>); Out.int(b[<span class="number">0</span>]); Out.ln; | |
| 97 | + <span class="kw">if</span> a # b <span class="kw">then</span> Out.str(<span class="string">"they differ now\n"</span>); <span class="kw">end</span>; | |
| 98 | + | |
| 99 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">2</span> <span class="kw">do</span> | |
| 100 | + <span class="kw">for</span> j := <span class="number">0</span> <span class="kw">to</span> <span class="number">2</span> <span class="kw">do</span> grid[i][j] := i * <span class="number">3</span> + j; <span class="kw">end</span>; | |
| 101 | + <span class="kw">end</span>; | |
| 102 | + Out.int(grid[<span class="number">2</span>][<span class="number">1</span>]); Out.ln; <span class="comment">(* 7 *)</span> | |
| 103 | + Out.int(<span class="ty">LEN</span>(grid)); Out.char(<span class="string">'x'</span>); Out.int(<span class="ty">LEN</span>(grid[<span class="number">0</span>])); Out.ln; | |
| 104 | +<span class="kw">end</span>; | |
| 105 | + | |
| 106 | +<span class="kw">end</span> Arrays.</code></pre> | |
| 107 | +<pre class="output"><code>1 99 | |
| 108 | +they differ now | |
| 109 | +7 | |
| 110 | +3x3 | |
| 111 | +</code></pre> | |
| 112 | +<h2>Slices</h2> | |
| 113 | +<p><code>[]INT</code> is a slice: a pointer to elements that live elsewhere, and their number, <code>LEN(s)</code>. <code>a[lo..hi]</code> is the slice of the elements from <code>lo</code> up to, but not including, <code>hi</code>, and an array goes silently where a slice is wanted. A slice doesn't copy anything: changing an element of it changes the array it looks at.</p> | |
| 114 | +<div class="file"><span>Windows.raz</span></div><pre class="code"><code><span class="kw">module</span> Windows; | |
| 115 | +<span class="kw">import</span> Out; | |
| 116 | + | |
| 117 | +<span class="kw">proc</span> zero(s: []<span class="ty">INT</span>); | |
| 118 | +<span class="kw">var</span> i: <span class="ty">INT</span>; | |
| 119 | +<span class="kw">begin</span> | |
| 120 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="ty">LEN</span>(s) - <span class="number">1</span> <span class="kw">do</span> s[i] := <span class="number">0</span>; <span class="kw">end</span>; | |
| 121 | +<span class="kw">end</span>; | |
| 122 | + | |
| 123 | +<span class="kw">proc</span> show(s: []<span class="ty">INT</span>); | |
| 124 | +<span class="kw">var</span> i: <span class="ty">INT</span>; | |
| 125 | +<span class="kw">begin</span> | |
| 126 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="ty">LEN</span>(s) - <span class="number">1</span> <span class="kw">do</span> Out.int(s[i]); Out.char(<span class="string">' '</span>); <span class="kw">end</span>; | |
| 127 | + Out.ln; | |
| 128 | +<span class="kw">end</span>; | |
| 129 | + | |
| 130 | +<span class="kw">proc</span> main*; | |
| 131 | +<span class="kw">var</span> a: [<span class="number">8</span>]<span class="ty">INT</span>; i: <span class="ty">INT</span>; | |
| 132 | +<span class="kw">begin</span> | |
| 133 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">7</span> <span class="kw">do</span> a[i] := i + <span class="number">1</span>; <span class="kw">end</span>; | |
| 134 | + zero(a[<span class="number">2</span>..<span class="number">5</span>]); <span class="comment">(* a window onto a *)</span> | |
| 135 | + show(a); <span class="comment">(* 1 2 0 0 0 6 7 8 *)</span> | |
| 136 | + show(a[<span class="number">6</span>..<span class="number">8</span>]); | |
| 137 | + show(a[<span class="number">3</span>..<span class="number">3</span>]); <span class="comment">(* empty: prints just a line feed *)</span> | |
| 138 | +<span class="kw">end</span>; | |
| 139 | + | |
| 140 | +<span class="kw">end</span> Windows.</code></pre> | |
| 141 | +<pre class="output"><code>1 2 0 0 0 6 7 8 | |
| 142 | +7 8 | |
| 143 | + | |
| 144 | +</code></pre> | |
| 145 | +<p>Every index and every slice bound is checked, so a slice can never reach past what it was made from; the lesson on failures shows what that looks like.</p> | |
| 146 | +<p>A slice of a local array is good only while its procedure runs: the array is gone once it returns. So returning one is an error, <code>return a[0..n]</code> or <code>return a</code> with <code>a</code> a local, a value parameter or an array literal. Take the array as a <code>var</code> parameter instead, and the slice is of the caller's array; or fill a buffer the caller gives.</p> | |
| 147 | +<h2><code>COPY</code></h2> | |
| 148 | +<p><code>COPY(d, s)</code> copies the elements of <code>s</code> to the start of <code>d</code>, as one block, and is right when they overlap. <code>LEN(s)</code> must be at most <code>LEN(d)</code>.</p> | |
| 149 | +<div class="file"><span>Moves.raz</span></div><pre class="code"><code><span class="kw">module</span> Moves; | |
| 150 | +<span class="kw">import</span> Out; | |
| 151 | + | |
| 152 | +<span class="kw">proc</span> main*; | |
| 153 | +<span class="kw">var</span> a: [<span class="number">6</span>]<span class="ty">INT</span>; i: <span class="ty">INT</span>; | |
| 154 | +<span class="kw">begin</span> | |
| 155 | + a := [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">0</span>]; | |
| 156 | + COPY(a[<span class="number">1</span>..<span class="number">6</span>], a[<span class="number">0</span>..<span class="number">5</span>]); <span class="comment">(* shift everything one place up *)</span> | |
| 157 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">5</span> <span class="kw">do</span> Out.int(a[i]); Out.char(<span class="string">' '</span>); <span class="kw">end</span>; | |
| 158 | + Out.ln; | |
| 159 | +<span class="kw">end</span>; | |
| 160 | + | |
| 161 | +<span class="kw">end</span> Moves.</code></pre> | |
| 162 | +<pre class="output"><code>1 1 2 3 4 5 | |
| 163 | +</code></pre> | |
| 164 | +<h2>Strings</h2> | |
| 165 | +<p>A string is a slice of bytes, <code>[]U8</code>, in UTF-8, and a string constant's bytes are constant. A <code>[8]U8</code> made from one is a copy you can change. Arrays and slices of integers compare with <code>=</code> and <code>#</code>, so strings do too. <code>Str</code> has the rest: ordering, finding, hashing, prefixes and suffixes, trimming, taking apart, ASCII case and kinds of character, UTF-8, and numbers to and from text.</p> | |
| 166 | +<div class="file"><span>Words.raz</span></div><pre class="code"><code><span class="kw">module</span> Words; | |
| 167 | +<span class="kw">import</span> Out, Str; | |
| 168 | + | |
| 169 | +<span class="kw">proc</span> main*; | |
| 170 | +<span class="kw">var</span> s: []<span class="ty">U8</span>; n: <span class="ty">I64</span>; ok: <span class="ty">BOOL</span>; name: [<span class="number">8</span>]<span class="ty">U8</span>; | |
| 171 | +<span class="kw">begin</span> | |
| 172 | + s := <span class="string">"hello, world"</span>; | |
| 173 | + Out.str(s[<span class="number">7</span>..<span class="ty">LEN</span>(s)]); Out.ln; | |
| 174 | + <span class="kw">if</span> s[<span class="number">0</span>..<span class="number">5</span>] = <span class="string">"hello"</span> <span class="kw">then</span> Out.str(<span class="string">"it says hello\n"</span>); <span class="kw">end</span>; | |
| 175 | + Out.int(Str.find(s, <span class="string">"world"</span>)); Out.ln; <span class="comment">(* 7 *)</span> | |
| 176 | + Out.int(Str.find(s, <span class="string">"xyz"</span>)); Out.ln; <span class="comment">(* -1 *)</span> | |
| 177 | + Out.int(Str.findLast(<span class="string">"abcabc"</span>, <span class="string">"bc"</span>)); Out.ln; <span class="comment">(* 4 *)</span> | |
| 178 | + Out.int(Str.findFrom(s, <span class="string">"o"</span>, <span class="number">5</span>)); Out.ln; <span class="comment">(* 8: the first o from 5 on *)</span> | |
| 179 | + <span class="kw">if</span> Str.isDigit(<span class="string">'7'</span>) <span class="kw">and</span> <span class="kw">not</span> Str.isLetter(<span class="string">'7'</span>) <span class="kw">then</span> Out.str(<span class="string">"a digit\n"</span>); <span class="kw">end</span>; | |
| 180 | + <span class="kw">if</span> Str.hasPrefix(s, <span class="string">"hell"</span>) <span class="kw">then</span> Out.str(<span class="string">"prefix\n"</span>); <span class="kw">end</span>; | |
| 181 | + <span class="kw">if</span> Str.hasSuffix(s, <span class="string">"world"</span>) <span class="kw">then</span> Out.str(<span class="string">"suffix\n"</span>); <span class="kw">end</span>; | |
| 182 | + Out.int(Str.cmp(<span class="string">"apple"</span>, <span class="string">"banana"</span>)); Out.ln; <span class="comment">(* -1 *)</span> | |
| 183 | + <span class="kw">if</span> Str.eqFold(<span class="string">"RAZ"</span>, <span class="string">"raz"</span>) <span class="kw">then</span> Out.str(<span class="string">"the same, but for case\n"</span>); <span class="kw">end</span>; | |
| 184 | + Out.str(<span class="string">"["</span>); Out.str(Str.trim(<span class="string">" padded \t\n"</span>)); Out.str(<span class="string">"]\n"</span>); | |
| 185 | + | |
| 186 | + n, ok := Str.toInt(<span class="string">"-1234"</span>); | |
| 187 | + <span class="kw">if</span> ok <span class="kw">then</span> Out.int(n + <span class="number">1</span>); Out.ln; <span class="kw">end</span>; | |
| 188 | + n, ok := Str.toInt(<span class="string">"12x"</span>); | |
| 189 | + <span class="kw">if</span> <span class="kw">not</span> ok <span class="kw">then</span> Out.str(<span class="string">"not a number\n"</span>); <span class="kw">end</span>; | |
| 190 | + | |
| 191 | + name := <span class="string">"raz"</span>; <span class="comment">(* a copy, the program's own *)</span> | |
| 192 | + name[<span class="number">0</span>] := <span class="string">'R'</span>; | |
| 193 | + Out.str(name[<span class="number">0</span>..<span class="number">3</span>]); Out.ln; | |
| 194 | + Str.upper(name[<span class="number">0</span>..<span class="number">3</span>]); <span class="comment">(* in place: name is a variable *)</span> | |
| 195 | + Out.str(name[<span class="number">0</span>..<span class="number">3</span>]); Out.ln; | |
| 196 | +<span class="kw">end</span>; | |
| 197 | + | |
| 198 | +<span class="kw">end</span> Words.</code></pre> | |
| 199 | +<pre class="output"><code>world | |
| 200 | +it says hello | |
| 201 | +7 | |
| 202 | +-1 | |
| 203 | +4 | |
| 204 | +8 | |
| 205 | +a digit | |
| 206 | +prefix | |
| 207 | +suffix | |
| 208 | +-1 | |
| 209 | +the same, but for case | |
| 210 | +[padded] | |
| 211 | +-1233 | |
| 212 | +not a number | |
| 213 | +Raz | |
| 214 | +RAZ | |
| 215 | +</code></pre> | |
| 216 | +<h2>Taking a string apart</h2> | |
| 217 | +<p><code>Str.cut</code> splits a string at the first place a separator is: what comes before it, what comes after, and whether it was there at all. <code>Str.field</code> gives the first word, past any spaces, and the rest. Neither copies anything: every part is a slice of the string it came from, so taking a line or a file apart costs no memory.</p> | |
| 218 | +<div class="file"><span>Parts.raz</span></div><pre class="code"><code><span class="kw">module</span> Parts; | |
| 219 | +<span class="kw">import</span> Out, Str; | |
| 220 | + | |
| 221 | +<span class="kw">const</span> Text = <span class="string">"name = raz\nkind = language\nyear = 2026\n"</span>; | |
| 222 | + | |
| 223 | +<span class="kw">proc</span> main*; | |
| 224 | +<span class="kw">var</span> line, rest, key, val, w: []<span class="ty">U8</span>; more, ok: <span class="ty">BOOL</span>; | |
| 225 | +<span class="kw">begin</span> | |
| 226 | + <span class="comment">(* line by line, then each line at its = *)</span> | |
| 227 | + line, rest, more := Str.cut(Text, <span class="string">"\n"</span>); | |
| 228 | + <span class="kw">while</span> more <span class="kw">do</span> | |
| 229 | + key, val, ok := Str.cut(line, <span class="string">"="</span>); | |
| 230 | + <span class="kw">if</span> ok <span class="kw">then</span> | |
| 231 | + Out.str(Str.trim(key)); Out.str(<span class="string">" is "</span>); Out.str(Str.trim(val)); Out.ln; | |
| 232 | + <span class="kw">end</span>; | |
| 233 | + line, rest, more := Str.cut(rest, <span class="string">"\n"</span>); | |
| 234 | + <span class="kw">end</span>; | |
| 235 | + | |
| 236 | + <span class="comment">(* word by word *)</span> | |
| 237 | + w, rest := Str.field(<span class="string">" the quick brown fox "</span>); | |
| 238 | + <span class="kw">while</span> <span class="ty">LEN</span>(w) > <span class="number">0</span> <span class="kw">do</span> | |
| 239 | + Out.str(<span class="string">"<"</span>); Out.str(w); Out.str(<span class="string">">"</span>); | |
| 240 | + w, rest := Str.field(rest); | |
| 241 | + <span class="kw">end</span>; | |
| 242 | + Out.ln; | |
| 243 | +<span class="kw">end</span>; | |
| 244 | + | |
| 245 | +<span class="kw">end</span> Parts.</code></pre> | |
| 246 | +<pre class="output"><code>name is raz | |
| 247 | +kind is language | |
| 248 | +year is 2026 | |
| 249 | +<the><quick><brown><fox> | |
| 250 | +</code></pre> | |
| 251 | +<p>When <code>Str.cut</code> finds no separator it gives the whole string, an empty one and <code>false</code>, so the loop above ends after the last line that has a line feed. Building a string goes the other way, in a <code>Buf</code>: <code>Str.join</code> adds parts with a separator between them, and <code>Str.replace</code> adds a string with every match of one text replaced by another (lesson 9 shows <code>Buf</code>).</p> | |
| 252 | +<h2>Raw strings</h2> | |
| 253 | +<p>A string between backquotes is raw: its bytes are the text as it stands, with no escapes, so a backslash or a double quote is itself, and it may run over lines. When the opening backquote ends its line and the closing one has only spaces and tabs before it, those blanks come off the start of every line between, and the text keeps the indent of the code it sits in. Each line ends in a line feed, the last one too.</p> | |
| 254 | +<div class="file"><span>Raw.raz</span></div><pre class="code"><code><span class="kw">module</span> Raw; | |
| 255 | +<span class="kw">import</span> Out; | |
| 256 | + | |
| 257 | +<span class="kw">const</span> Path = <span class="string">`C:\Users\raz\"notes".txt`</span>; | |
| 258 | + | |
| 259 | +<span class="kw">proc</span> usage; | |
| 260 | +<span class="kw">begin</span> | |
| 261 | + Out.str(<span class="string">` | |
| 262 | + usage: tool [-v] file ... | |
| 263 | + -v say what is done | |
| 264 | + file read this, not standard input | |
| 265 | + `</span>); | |
| 266 | +<span class="kw">end</span>; | |
| 267 | + | |
| 268 | +<span class="kw">proc</span> main*; | |
| 269 | +<span class="kw">begin</span> | |
| 270 | + Out.str(Path); Out.ln; | |
| 271 | + usage; | |
| 272 | + Out.str(<span class="string">`a raw string on one line, \n and all`</span>); Out.ln; | |
| 273 | +<span class="kw">end</span>; | |
| 274 | + | |
| 275 | +<span class="kw">end</span> Raw.</code></pre> | |
| 276 | +<pre class="output"><code>C:\Users\raz\"notes".txt | |
| 277 | +usage: tool [-v] file ... | |
| 278 | + -v say what is done | |
| 279 | + file read this, not standard input | |
| 280 | +a raw string on one line, \n and all | |
| 281 | +</code></pre> | |
| 282 | +<p>A line of an indented raw string that doesn't start with the closing line's blanks is an error, so a slip in the indent is caught where it is made, not printed. A raw string can't hold a backquote; join one in with <code>+</code> and an ordinary string that holds it.</p> | |
| 283 | +<h2>UTF-8</h2> | |
| 284 | +<p>A character is an <code>I32</code>, its code point. A string stays bytes; UTF-8 is how <code>Str</code> reads them. <code>Str.next</code> walks a string a character at a time, giving each one and where the next starts, -1 at the end. <code>Str.decode</code> reads the first character of a string and says how many bytes it took, <code>Str.decodeLast</code> the last, and <code>Str.encode</code> goes the other way. <code>Str.chars</code> counts characters and <code>Str.valid</code> says whether a string is UTF-8 at all; a byte that doesn't start a character rightly reads as FFFDH, the character that stands for a wrong one. Byte length and character count are different things, and the program is the one that says which it wants. On a terminal there is a third: a character takes 0, 1 or 2 columns, a combining accent none and an ideograph two, and <code>Width.columns</code> counts those.</p> | |
| 285 | +<div class="file"><span>Runes.raz</span></div><pre class="code"><code><span class="kw">module</span> Runes; | |
| 286 | +<span class="kw">import</span> Out, Str, Width; | |
| 287 | + | |
| 288 | +<span class="kw">proc</span> main*; | |
| 289 | +<span class="kw">var</span> s: []<span class="ty">U8</span>; c: <span class="ty">I32</span>; i, size: <span class="ty">INT</span>; bytes: [<span class="number">4</span>]<span class="ty">U8</span>; k: <span class="ty">INT</span>; | |
| 290 | +<span class="kw">begin</span> | |
| 291 | + s := <span class="string">"caf\u{E9} \u{3BB}"</span>; | |
| 292 | + Out.int(<span class="ty">LEN</span>(s)); Out.str(<span class="string">" bytes, "</span>); | |
| 293 | + Out.int(Str.chars(s)); Out.str(<span class="string">" characters, "</span>); | |
| 294 | + Out.int(Width.columns(<span class="string">"\u{4E2D}\u{6587}"</span>)); Out.str(<span class="string">" columns for two ideographs\n"</span>); | |
| 295 | + | |
| 296 | + <span class="comment">(* each character, as its code point *)</span> | |
| 297 | + c, i := Str.next(s, <span class="number">0</span>); | |
| 298 | + <span class="kw">while</span> i >= <span class="number">0</span> <span class="kw">do</span> | |
| 299 | + Out.int(<span class="ty">I64</span>(c)); Out.str(<span class="string">" "</span>); | |
| 300 | + c, i := Str.next(s, i); | |
| 301 | + <span class="kw">end</span>; | |
| 302 | + Out.ln; | |
| 303 | + | |
| 304 | + c, size := Str.decodeLast(s); | |
| 305 | + Out.int(<span class="ty">I64</span>(c)); Out.str(<span class="string">" is last, in "</span>); Out.int(size); Out.str(<span class="string">" bytes\n"</span>); | |
| 306 | + bytes, k := Str.encode(<span class="number">955</span>); | |
| 307 | + Out.str(bytes[<span class="number">0</span>..k]); Out.ln; | |
| 308 | + <span class="kw">if</span> <span class="kw">not</span> Str.valid(s[<span class="number">0</span>..<span class="number">4</span>]) <span class="kw">then</span> Out.str(<span class="string">"cut in the middle of a character\n"</span>); <span class="kw">end</span>; | |
| 309 | +<span class="kw">end</span>; | |
| 310 | + | |
| 311 | +<span class="kw">end</span> Runes.</code></pre> | |
| 312 | +<pre class="output"><code>8 bytes, 6 characters, 4 columns for two ideographs | |
| 313 | +99 97 102 233 32 955 | |
| 314 | +955 is last, in 2 bytes | |
| 315 | +λ | |
| 316 | +cut in the middle of a character | |
| 317 | +</code></pre> | |
| 318 | +<p><code>Str</code> knows UTF-8 and no more of Unicode: its case is ASCII's, and it doesn't say how wide a character is on a terminal or which spellings of a text are the same. Those need tables bigger than the rest of the library.</p> | |
| 319 | +<h2>Loops over lengths</h2> | |
| 320 | +<p>A <code>for</code> loop takes its bounds once, and never steps past the last: with an empty slice, <code>0 to LEN(s) - 1</code> doesn't run at all, and the variable can't wrap. <code>for</code> takes a constant step with <code>by</code>, and <code>while</code> and <code>repeat ... until</code> do the rest. <code>break</code> leaves a loop, and <code>continue</code> ends its round: a <code>for</code> steps, a <code>while</code> or a <code>repeat</code> tests again. So a <code>while</code> moves on before any <code>continue</code>, or it never moves at all.</p> | |
| 321 | +<div class="file"><span>Loops.raz</span></div><pre class="code"><code><span class="kw">module</span> Loops; | |
| 322 | +<span class="kw">import</span> Out; | |
| 323 | + | |
| 324 | +<span class="kw">proc</span> main*; | |
| 325 | +<span class="kw">var</span> i: <span class="ty">INT</span>; | |
| 326 | +<span class="kw">begin</span> | |
| 327 | + <span class="kw">for</span> i := <span class="number">10</span> <span class="kw">to</span> <span class="number">0</span> <span class="kw">by</span> -<span class="number">5</span> <span class="kw">do</span> Out.int(i); Out.char(<span class="string">' '</span>); <span class="kw">end</span>; | |
| 328 | + Out.ln; | |
| 329 | + i := <span class="number">1</span>; | |
| 330 | + <span class="kw">while</span> i < <span class="number">100</span> <span class="kw">do</span> i := i * <span class="number">3</span>; <span class="kw">end</span>; | |
| 331 | + Out.int(i); Out.ln; | |
| 332 | + <span class="kw">repeat</span> <span class="ty">DEC</span>(i, <span class="number">30</span>); <span class="kw">until</span> i < <span class="number">0</span>; | |
| 333 | + Out.int(i); Out.ln; | |
| 334 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">10</span> <span class="kw">do</span> | |
| 335 | + <span class="kw">if</span> i <span class="kw">mod</span> <span class="number">3</span> = <span class="number">0</span> <span class="kw">then</span> continue; <span class="kw">end</span>; <span class="comment">(* 3, 6 and 9 passed over *)</span> | |
| 336 | + Out.int(i); Out.char(<span class="string">' '</span>); | |
| 337 | + <span class="kw">end</span>; | |
| 338 | + Out.ln; | |
| 339 | +<span class="kw">end</span>; | |
| 340 | + | |
| 341 | +<span class="kw">end</span> Loops.</code></pre> | |
| 342 | +<pre class="output"><code>10 5 0 | |
| 343 | +243 | |
| 344 | +-27 | |
| 345 | +1 2 4 5 7 8 10 | |
| 346 | +</code></pre><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="procedures.html">← Procedures and several results</a><a href="index.html">Contents</a><a class="next" href="records.html">Records and pointers →</a></div></article></div> | |
| 347 | +</main> | |
| 348 | +<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> | |
| 349 | +</body> | |
| 350 | +</html> |
| @@ -0,0 +1,185 @@ | ||
| 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>Threads - Raz, Set, Go</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="Threads - Raz, Set, Go"> | |
| 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.lucelad.workers.dev/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" aria-current="page">Raz, Set, Go</a><a href="../advanced/index.html">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<div class="tour"><aside><h2>Raz, Set, Go</h2><h3>Raz</h3><ol start='1'> | |
| 22 | +<li><a href="hello.html">Hello, world</a></li> | |
| 23 | +<li><a href="modules.html">Modules</a></li> | |
| 24 | +<li><a href="integers.html">Integers</a></li> | |
| 25 | +<li><a href="values.html">Values and conversions</a></li> | |
| 26 | +<li><a href="procedures.html">Procedures and several results</a></li> | |
| 27 | +</ol> | |
| 28 | +<h3>Set</h3><ol start='6'> | |
| 29 | +<li><a href="slices.html">Arrays, slices and strings</a></li> | |
| 30 | +<li><a href="records.html">Records and pointers</a></li> | |
| 31 | +<li><a href="variants.html">Enumerations, sets, variants and match</a></li> | |
| 32 | +<li><a href="memory.html">Memory and allocators</a></li> | |
| 33 | +</ol> | |
| 34 | +<h3>Go</h3><ol start='10'> | |
| 35 | +<li><a href="errors.html">Errors</a></li> | |
| 36 | +<li><a href="defer.html">Defer</a></li> | |
| 37 | +<li><a href="checks.html">When it goes wrong</a></li> | |
| 38 | +<li><a href="generics.html">Generic modules</a></li> | |
| 39 | +<li><a href="c.html">Talking to C</a></li> | |
| 40 | +<li><a href="threads.html" aria-current="page">Threads</a></li> | |
| 41 | +</ol></aside><article><p class="kicker">Go · lesson 15 of 15</p><h1>Threads</h1> | |
| 42 | +<div class="file"><span>Hits.raz</span></div><pre class="code"><code><span class="kw">module</span> Hits; | |
| 43 | +<span class="kw">import</span> Out, Thread, SYSTEM; | |
| 44 | + | |
| 45 | +<span class="kw">const</span> Workers = <span class="number">4</span>; | |
| 46 | + | |
| 47 | +<span class="kw">var</span> | |
| 48 | + hits: <span class="ty">INT</span>; <span class="comment">(* added to by every thread at once, by XADD *)</span> | |
| 49 | + m: Thread.Mutex; | |
| 50 | + total: <span class="ty">INT</span>; <span class="comment">(* added to under m *)</span> | |
| 51 | + | |
| 52 | +<span class="kw">proc</span> work(arg: ^<span class="ty">U8</span>); | |
| 53 | +<span class="kw">var</span> i, n, sum: <span class="ty">INT</span>; | |
| 54 | +<span class="kw">begin</span> | |
| 55 | + n := <span class="ty">INT</span>(arg); | |
| 56 | + sum := <span class="number">0</span>; | |
| 57 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> n <span class="kw">do</span> | |
| 58 | + sum := sum + i; | |
| 59 | + _ := <span class="ty">XADD</span>(hits, <span class="number">1</span>); | |
| 60 | + <span class="kw">end</span>; | |
| 61 | + Thread.lock(m); | |
| 62 | + total := total + sum; | |
| 63 | + Thread.unlock(m); | |
| 64 | +<span class="kw">end</span>; | |
| 65 | + | |
| 66 | +<span class="kw">proc</span> main*; | |
| 67 | +<span class="kw">var</span> t: [Workers]^Thread.Thread; i: <span class="ty">INT</span>; err: <span class="ty">ERROR</span>; | |
| 68 | +<span class="kw">begin</span> | |
| 69 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> Workers - <span class="number">1</span> <span class="kw">do</span> | |
| 70 | + t[i], err := Thread.spawn(work, ^<span class="ty">U8</span>(<span class="number">1000</span> * (i + <span class="number">1</span>))); | |
| 71 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">return</span>; <span class="kw">end</span>; | |
| 72 | + <span class="kw">end</span>; | |
| 73 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> Workers - <span class="number">1</span> <span class="kw">do</span> Thread.join(t[i]); <span class="kw">end</span>; | |
| 74 | + Out.int(hits); Out.char(<span class="string">' '</span>); Out.int(total); Out.ln; | |
| 75 | +<span class="kw">end</span>; | |
| 76 | + | |
| 77 | +<span class="kw">end</span> Hits.</code></pre> | |
| 78 | +<pre class="output"><code>10000 15005000 | |
| 79 | +</code></pre> | |
| 80 | +<p><code>Thread.spawn</code> runs a procedure in a thread of its own, with a stack of its own, and <code>Thread.join</code> waits for it to end. <code>XADD</code>, <code>CAS</code> and <code>XCHG</code> change a word atomically; a <code>Thread.Mutex</code> keeps a longer section to one thread at a time. <code>Out</code> and <code>Heap</code> lock themselves.</p> | |
| 81 | +<h2>What goes wrong without them</h2> | |
| 82 | +<p>Two threads that each read a variable, add one and write it back can lose one of the additions. A plain <code>INC</code> on a variable shared by threads has no particular value afterwards; the report says so. <code>XADD</code> is the atomic add: it returns the old value and adds in one indivisible step.</p> | |
| 83 | +<div class="file"><span>Race.raz</span></div><pre class="code"><code><span class="kw">module</span> Race; | |
| 84 | +<span class="kw">import</span> Out, Thread; | |
| 85 | + | |
| 86 | +<span class="kw">var</span> | |
| 87 | + safe: <span class="ty">INT</span>; <span class="comment">(* added to by XADD *)</span> | |
| 88 | + plain: <span class="ty">INT</span>; <span class="comment">(* added to by INC: unsafe, never printed *)</span> | |
| 89 | + | |
| 90 | +<span class="kw">proc</span> work(_arg: ^<span class="ty">U8</span>); | |
| 91 | +<span class="kw">var</span> i: <span class="ty">INT</span>; | |
| 92 | +<span class="kw">begin</span> | |
| 93 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">100000</span> <span class="kw">do</span> | |
| 94 | + _ := <span class="ty">XADD</span>(<span class="ty">ADR</span>(safe), <span class="number">1</span>); | |
| 95 | + <span class="ty">INC</span>(plain); <span class="comment">(* unsafe: lost additions *)</span> | |
| 96 | + <span class="kw">end</span>; | |
| 97 | +<span class="kw">end</span>; | |
| 98 | + | |
| 99 | +<span class="kw">proc</span> main*; | |
| 100 | +<span class="kw">var</span> t: [<span class="number">4</span>]^Thread.Thread; i: <span class="ty">INT</span>; err: <span class="ty">ERROR</span>; | |
| 101 | +<span class="kw">begin</span> | |
| 102 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> | |
| 103 | + t[i], err := Thread.spawn(work, <span class="ty">nil</span>); | |
| 104 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">return</span>; <span class="kw">end</span>; | |
| 105 | + <span class="kw">end</span>; | |
| 106 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> Thread.join(t[i]); <span class="kw">end</span>; | |
| 107 | + Out.str(<span class="string">"safe "</span>); Out.int(safe); Out.ln; | |
| 108 | +<span class="kw">end</span>; | |
| 109 | + | |
| 110 | +<span class="kw">end</span> Race.</code></pre> | |
| 111 | +<pre class="output"><code>safe 400000 | |
| 112 | +</code></pre> | |
| 113 | +<p>The atomic count is always 400000. The plain one is usually lower, and different from run to run, which is why this page doesn't print it.</p> | |
| 114 | +<h2>A mutex for longer sections</h2> | |
| 115 | +<p>An atomic is one word. When several variables must change together, take a <code>Thread.Mutex</code>; it sleeps while it waits, so it suits sections that take a while. Declare it as a module variable, since zero is free.</p> | |
| 116 | +<div class="file"><span>Bank.raz</span></div><pre class="code"><code><span class="kw">module</span> Bank; | |
| 117 | +<span class="kw">import</span> Out, Thread; | |
| 118 | + | |
| 119 | +<span class="kw">var</span> | |
| 120 | + m: Thread.Mutex; | |
| 121 | + balance, deposits: <span class="ty">INT</span>; <span class="comment">(* kept in step, under m *)</span> | |
| 122 | + | |
| 123 | +<span class="kw">proc</span> deposit(_arg: ^<span class="ty">U8</span>); | |
| 124 | +<span class="kw">var</span> i: <span class="ty">INT</span>; | |
| 125 | +<span class="kw">begin</span> | |
| 126 | + <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">10000</span> <span class="kw">do</span> | |
| 127 | + Thread.lock(m); | |
| 128 | + balance := balance + <span class="number">5</span>; | |
| 129 | + <span class="ty">INC</span>(deposits); | |
| 130 | + Thread.unlock(m); | |
| 131 | + <span class="kw">end</span>; | |
| 132 | +<span class="kw">end</span>; | |
| 133 | + | |
| 134 | +<span class="kw">proc</span> main*; | |
| 135 | +<span class="kw">var</span> t: [<span class="number">3</span>]^Thread.Thread; i: <span class="ty">INT</span>; err: <span class="ty">ERROR</span>; | |
| 136 | +<span class="kw">begin</span> | |
| 137 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">2</span> <span class="kw">do</span> | |
| 138 | + t[i], err := Thread.spawn(deposit, <span class="ty">nil</span>); | |
| 139 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">return</span>; <span class="kw">end</span>; | |
| 140 | + <span class="kw">end</span>; | |
| 141 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">2</span> <span class="kw">do</span> Thread.join(t[i]); <span class="kw">end</span>; | |
| 142 | + Out.int(deposits); Out.char(<span class="string">' '</span>); Out.int(balance); Out.ln; | |
| 143 | +<span class="kw">end</span>; | |
| 144 | + | |
| 145 | +<span class="kw">end</span> Bank.</code></pre> | |
| 146 | +<pre class="output"><code>30000 150000 | |
| 147 | +</code></pre> | |
| 148 | +<h2>Handing work out</h2> | |
| 149 | +<p>A thread's procedure takes one pointer argument. Pass a record's address to give each thread its own job and its own place to put the answer; then no one shares anything.</p> | |
| 150 | +<div class="file"><span>Jobs.raz</span></div><pre class="code"><code><span class="kw">module</span> Jobs; | |
| 151 | +<span class="kw">import</span> Out, Thread; | |
| 152 | + | |
| 153 | +<span class="kw">type</span> Job = <span class="kw">record</span> lo, hi: <span class="ty">INT</span>; sum: <span class="ty">INT</span>; <span class="kw">end</span>; | |
| 154 | + | |
| 155 | +<span class="kw">proc</span> work(arg: ^<span class="ty">U8</span>); | |
| 156 | +<span class="kw">var</span> j: ^Job; i: <span class="ty">INT</span>; | |
| 157 | +<span class="kw">begin</span> | |
| 158 | + j := ^Job(arg); | |
| 159 | + <span class="kw">for</span> i := j^.lo <span class="kw">to</span> j^.hi - <span class="number">1</span> <span class="kw">do</span> j^.sum := j^.sum + i; <span class="kw">end</span>; | |
| 160 | +<span class="kw">end</span>; | |
| 161 | + | |
| 162 | +<span class="kw">proc</span> main*; | |
| 163 | +<span class="kw">var</span> jobs: [<span class="number">4</span>]Job; t: [<span class="number">4</span>]^Thread.Thread; i, total: <span class="ty">INT</span>; err: <span class="ty">ERROR</span>; | |
| 164 | +<span class="kw">begin</span> | |
| 165 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> | |
| 166 | + jobs[i].lo := i * <span class="number">250000</span>; | |
| 167 | + jobs[i].hi := (i + <span class="number">1</span>) * <span class="number">250000</span>; | |
| 168 | + t[i], err := Thread.spawn(work, ^<span class="ty">U8</span>(<span class="ty">ADR</span>(jobs[i]))); | |
| 169 | + <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">return</span>; <span class="kw">end</span>; | |
| 170 | + <span class="kw">end</span>; | |
| 171 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> | |
| 172 | + Thread.join(t[i]); | |
| 173 | + total := total + jobs[i].sum; | |
| 174 | + <span class="kw">end</span>; | |
| 175 | + Out.int(total); Out.ln; | |
| 176 | +<span class="kw">end</span>; | |
| 177 | + | |
| 178 | +<span class="kw">end</span> Jobs.</code></pre> | |
| 179 | +<pre class="output"><code>499999500000 | |
| 180 | +</code></pre> | |
| 181 | +<p><code>Thread</code> makes its own threads, without C, so a program that uses it can't use C; one that does makes its threads with C's <code>pthread_create</code> instead. The advanced tour goes further into atomics, memory ordering and lock-free code.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="c.html">← Talking to C</a><a href="index.html">Contents</a><a class="next" href="../advanced/index.html">More Raz →</a></div></article></div> | |
| 182 | +</main> | |
| 183 | +<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> | |
| 184 | +</body> | |
| 185 | +</html> |
| @@ -0,0 +1,146 @@ | ||
| 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>Values and conversions - Raz, Set, Go</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="Values and conversions - Raz, Set, Go"> | |
| 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.lucelad.workers.dev/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" aria-current="page">Raz, Set, Go</a><a href="../advanced/index.html">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<div class="tour"><aside><h2>Raz, Set, Go</h2><h3>Raz</h3><ol start='1'> | |
| 22 | +<li><a href="hello.html">Hello, world</a></li> | |
| 23 | +<li><a href="modules.html">Modules</a></li> | |
| 24 | +<li><a href="integers.html">Integers</a></li> | |
| 25 | +<li><a href="values.html" aria-current="page">Values and conversions</a></li> | |
| 26 | +<li><a href="procedures.html">Procedures and several results</a></li> | |
| 27 | +</ol> | |
| 28 | +<h3>Set</h3><ol start='6'> | |
| 29 | +<li><a href="slices.html">Arrays, slices and strings</a></li> | |
| 30 | +<li><a href="records.html">Records and pointers</a></li> | |
| 31 | +<li><a href="variants.html">Enumerations, sets, variants and match</a></li> | |
| 32 | +<li><a href="memory.html">Memory and allocators</a></li> | |
| 33 | +</ol> | |
| 34 | +<h3>Go</h3><ol start='10'> | |
| 35 | +<li><a href="errors.html">Errors</a></li> | |
| 36 | +<li><a href="defer.html">Defer</a></li> | |
| 37 | +<li><a href="checks.html">When it goes wrong</a></li> | |
| 38 | +<li><a href="generics.html">Generic modules</a></li> | |
| 39 | +<li><a href="c.html">Talking to C</a></li> | |
| 40 | +<li><a href="threads.html">Threads</a></li> | |
| 41 | +</ol></aside><article><p class="kicker">Raz · lesson 4 of 15</p><h1>Values and conversions</h1> | |
| 42 | +<p>This program uses several of the basic types at once, with each conversion written where it happens.</p> | |
| 43 | +<div class="file"><span>Values.raz</span></div><pre class="code"><code><span class="kw">module</span> Values; | |
| 44 | +<span class="kw">import</span> Fmt; | |
| 45 | + | |
| 46 | +<span class="kw">const</span> Max = <span class="number">100</span>; <span class="comment">(* untyped: it takes the type it meets *)</span> | |
| 47 | + | |
| 48 | +<span class="kw">proc</span> main*; | |
| 49 | +<span class="kw">var</span> n: <span class="ty">INT</span>; b: <span class="ty">U8</span>; big: <span class="ty">I64</span>; x: <span class="ty">F64</span>; c: <span class="ty">I32</span>; ok: <span class="ty">BOOL</span>; | |
| 50 | +<span class="kw">begin</span> | |
| 51 | + n := Max * <span class="number">3</span>; | |
| 52 | + b := <span class="number">250</span>; | |
| 53 | + b := b + <span class="number">10</span>; <span class="comment">(* wraps, in a U8: 4 *)</span> | |
| 54 | + big := n; <span class="comment">(* an INT goes into an I64 *)</span> | |
| 55 | + x := <span class="ty">F64</span>(n) / <span class="number">7.0</span>; <span class="comment">(* nothing else converts unasked *)</span> | |
| 56 | + c := <span class="string">'\u{E9}'</span>; <span class="comment">(* a character is its code point *)</span> | |
| 57 | + ok := (n > Max) <span class="kw">and</span> (b # <span class="number">0</span>); | |
| 58 | + Fmt.print(<span class="string">"{} {} {} {} {} {}\n"</span>, [Fmt.int(n), Fmt.int(<span class="ty">I64</span>(b)), | |
| 59 | + Fmt.int(big), Fmt.real(x, <span class="number">3</span>), Fmt.int(<span class="ty">I64</span>(c)), | |
| 60 | + Fmt.bool(ok)]); | |
| 61 | +<span class="kw">end</span>; | |
| 62 | + | |
| 63 | +<span class="kw">end</span> Values.</code></pre> | |
| 64 | +<pre class="output"><code>300 4 300 42.857 233 true | |
| 65 | +</code></pre> | |
| 66 | +<h2>Conversions are written</h2> | |
| 67 | +<p>Two types never mix but where nothing can be lost: an <code>INT</code> goes into an <code>I64</code> wherever it meets one, so with <code>pos: I64</code>, <code>pos + LEN(s)</code> is an <code>I64</code>; and a <code>U8</code>, <code>I8</code> or <code>I16</code> into an <code>INT</code>, unless an operator made it, so <code>n := s[i]</code> needs no conversion. With <code>i: I32</code> and a slice <code>s</code>, <code>i < LEN(s)</code> is an error. A type's name converts: <code>F64(n)</code>, <code>I64(b)</code>, <code>U8(x)</code>; an <code>I64</code> becomes an <code>INT</code> only so, <code>INT(pos)</code>, since an <code>INT</code> may be smaller on another machine. The <a href="integers.html">lesson on integers</a> says what each width conversion does.</p> | |
| 68 | +<p>A number written in the program is untyped until it meets a type, and <code>1.5</code> is a real, which an integer never becomes without a conversion.</p> | |
| 69 | +<div class="file"><span>Mix.raz</span></div><pre class="code"><code><span class="kw">module</span> Mix; | |
| 70 | +<span class="kw">import</span> Out; | |
| 71 | + | |
| 72 | +<span class="kw">proc</span> main*; | |
| 73 | +<span class="kw">var</span> i: <span class="ty">I32</span>; s: []<span class="ty">U8</span>; | |
| 74 | +<span class="kw">begin</span> | |
| 75 | + s := <span class="string">"four"</span>; | |
| 76 | + i := <span class="number">3</span>; | |
| 77 | + <span class="kw">if</span> i < <span class="ty">LEN</span>(s) <span class="kw">then</span> Out.str(<span class="string">"smaller\n"</span>); <span class="kw">end</span>; | |
| 78 | +<span class="kw">end</span>; | |
| 79 | + | |
| 80 | +<span class="kw">end</span> Mix.</code></pre> | |
| 81 | +<pre class="output term"><code><span class="cmd">$ raz Mix.raz</span> | |
| 82 | +Mix.raz:9:8: error: I32 and INT are different types | |
| 83 | + 9 | if i < LEN(s) then Out.str("smaller\n"); end; | |
| 84 | + | ^^^^^^^^^^ | |
| 85 | +help: convert one to the other's type, as in INT(i) | |
| 86 | +raz: 1 error</code></pre> | |
| 87 | +<p>The fix is the conversion, written where it happens: <code>if INT(i) < LEN(s)</code>. It costs nothing at run time and says what is meant.</p> | |
| 88 | +<h2>What converts to what</h2> | |
| 89 | +<p>Everything else that converts does so with the type's name, and the rules are short:</p> | |
| 90 | +<table><thead><tr><th>From</th><th>To</th><th>Result</th></tr></thead><tbody><tr><td data-label="From">integer</td><td data-label="To">integer</td><td data-label="Result">cut to the new width, or extended by the sign (signed) or zeros (unsigned)</td></tr><tr><td data-label="From">integer</td><td data-label="To"><code>F32</code>, <code>F64</code></td><td data-label="Result">the nearest real</td></tr><tr><td data-label="From"><code>F32</code>, <code>F64</code></td><td data-label="To">integer</td><td data-label="Result">rounded toward zero</td></tr><tr><td data-label="From"><code>F32</code></td><td data-label="To"><code>F64</code></td><td data-label="Result">the same value; the other way, the nearest <code>F32</code></td></tr><tr><td data-label="From">enumeration</td><td data-label="To">integer</td><td data-label="Result">its position; and back, if there is a name at that position</td></tr><tr><td data-label="From">set</td><td data-label="To">integer</td><td data-label="Result">its bits; and back</td></tr><tr><td data-label="From"><code>INT</code>, <code>UINT</code></td><td data-label="To">pointer</td><td data-label="Result">the address; and back</td></tr></tbody></table> | |
| 91 | +<p>There is no conversion between <code>BOOL</code> and an integer: say what you mean with <code>if</code>. A <code>BOOL</code> is <code>true</code> or <code>false</code>, and <code>and</code>, <code>or</code> and <code>not</code> are for <code>BOOL</code>s: they bind below the relations, so <code>i < n and a[i] # 0</code> needs no parentheses, and <code>and</code> and <code>or</code> evaluate their right operand only when it decides the result. <code>#</code>, not <code><></code>, is "different".</p> | |
| 92 | +<div class="file"><span>Truth.raz</span></div><pre class="code"><code><span class="kw">module</span> Truth; | |
| 93 | +<span class="kw">import</span> Out; | |
| 94 | + | |
| 95 | +<span class="kw">proc</span> positive(n: <span class="ty">INT</span>): <span class="ty">BOOL</span>; | |
| 96 | +<span class="kw">begin</span> | |
| 97 | + <span class="kw">return</span> n > <span class="number">0</span>; | |
| 98 | +<span class="kw">end</span>; | |
| 99 | + | |
| 100 | +<span class="kw">proc</span> main*; | |
| 101 | +<span class="kw">var</span> a: [<span class="number">3</span>]<span class="ty">INT</span>; i: <span class="ty">INT</span>; found: <span class="ty">BOOL</span>; | |
| 102 | +<span class="kw">begin</span> | |
| 103 | + a := [<span class="number">4</span>, <span class="number">0</span>, <span class="number">9</span>]; | |
| 104 | + i := <span class="number">0</span>; | |
| 105 | + <span class="kw">while</span> (i < <span class="ty">LEN</span>(a)) <span class="kw">and</span> (a[i] # <span class="number">0</span>) <span class="kw">do</span> <span class="ty">INC</span>(i); <span class="kw">end</span>; <span class="comment">(* never reads a[3] *)</span> | |
| 106 | + Out.int(i); Out.ln; | |
| 107 | + found := positive(i) <span class="kw">or</span> positive(-<span class="number">1</span>); | |
| 108 | + <span class="kw">if</span> found <span class="kw">and</span> <span class="kw">not</span> positive(<span class="number">0</span>) <span class="kw">then</span> Out.str(<span class="string">"true and true\n"</span>); <span class="kw">end</span>; | |
| 109 | +<span class="kw">end</span>; | |
| 110 | + | |
| 111 | +<span class="kw">end</span> Truth.</code></pre> | |
| 112 | +<pre class="output"><code>1 | |
| 113 | +true and true | |
| 114 | +</code></pre> | |
| 115 | +<h2>Reals</h2> | |
| 116 | +<p><code>F32</code> and <code>F64</code> are the reals. A real constant is written with a point, <code>1.5</code> or <code>2.0E-3</code>. <code>Fmt.real(x, places)</code> writes one with that many digits after the point, and <code>Math</code> has the functions.</p> | |
| 117 | +<div class="file"><span>Reals.raz</span></div><pre class="code"><code><span class="kw">module</span> Reals; | |
| 118 | +<span class="kw">import</span> Fmt, Math; | |
| 119 | + | |
| 120 | +<span class="kw">proc</span> main*; | |
| 121 | +<span class="kw">var</span> n: <span class="ty">INT</span>; x: <span class="ty">F64</span>; y: <span class="ty">F32</span>; | |
| 122 | +<span class="kw">begin</span> | |
| 123 | + n := <span class="number">22</span>; | |
| 124 | + x := <span class="ty">F64</span>(n) / <span class="number">7.0</span>; | |
| 125 | + y := <span class="ty">F32</span>(x); | |
| 126 | + Fmt.print(<span class="string">"22/7 = {}\n"</span>, [Fmt.real(x, <span class="number">6</span>)]); | |
| 127 | + Fmt.print(<span class="string">"as F32 = {}\n"</span>, [Fmt.real(<span class="ty">F64</span>(y), <span class="number">6</span>)]); | |
| 128 | + Fmt.print(<span class="string">"sqrt 2 = {}, pi = {}\n"</span>, [Fmt.real(Math.sqrt(<span class="number">2.0</span>), <span class="number">5</span>), Fmt.real(Math.pi, <span class="number">5</span>)]); | |
| 129 | + Fmt.print(<span class="string">"2^10 = {}, log2 of that = {}\n"</span>, [Fmt.real(Math.pow(<span class="number">2.0</span>, <span class="number">10.0</span>), <span class="number">1</span>), Fmt.real(Math.log2(<span class="number">1024.0</span>), <span class="number">1</span>)]); | |
| 130 | + Fmt.print(<span class="string">"rounded: {} {}\n"</span>, [Fmt.real(Math.round(<span class="number">2.5</span>), <span class="number">1</span>), Fmt.real(Math.round(-<span class="number">2.5</span>), <span class="number">1</span>)]); | |
| 131 | + Fmt.print(<span class="string">"truncated: {} {}\n"</span>, [Fmt.int(<span class="ty">I64</span>(<span class="number">2.9</span>)), Fmt.int(<span class="ty">I64</span>(-<span class="number">2.9</span>))]); | |
| 132 | +<span class="kw">end</span>; | |
| 133 | + | |
| 134 | +<span class="kw">end</span> Reals.</code></pre> | |
| 135 | +<pre class="output"><code>22/7 = 3.142857 | |
| 136 | +as F32 = 3.142857 | |
| 137 | +sqrt 2 = 1.41421, pi = 3.14159 | |
| 138 | +2^10 = 1024.0, log2 of that = 10.0 | |
| 139 | +rounded: 3.0 -3.0 | |
| 140 | +truncated: 2 -2 | |
| 141 | +</code></pre> | |
| 142 | +<p>A real converts to an integer by rounding toward zero. Every variable starts at zero, a real's <code>0.0</code> and a <code>BOOL</code>'s <code>false</code> included, so there is no uninitialised value to be surprised by.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="integers.html">← Integers</a><a href="index.html">Contents</a><a class="next" href="procedures.html">Procedures and several results →</a></div></article></div> | |
| 143 | +</main> | |
| 144 | +<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> | |
| 145 | +</body> | |
| 146 | +</html> |
| @@ -0,0 +1,318 @@ | ||
| 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>Enumerations, sets, variants and match - Raz, Set, Go</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="Enumerations, sets, variants and match - Raz, Set, Go"> | |
| 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.lucelad.workers.dev/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" aria-current="page">Raz, Set, Go</a><a href="../advanced/index.html">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> | |
| 20 | +<main> | |
| 21 | +<div class="tour"><aside><h2>Raz, Set, Go</h2><h3>Raz</h3><ol start='1'> | |
| 22 | +<li><a href="hello.html">Hello, world</a></li> | |
| 23 | +<li><a href="modules.html">Modules</a></li> | |
| 24 | +<li><a href="integers.html">Integers</a></li> | |
| 25 | +<li><a href="values.html">Values and conversions</a></li> | |
| 26 | +<li><a href="procedures.html">Procedures and several results</a></li> | |
| 27 | +</ol> | |
| 28 | +<h3>Set</h3><ol start='6'> | |
| 29 | +<li><a href="slices.html">Arrays, slices and strings</a></li> | |
| 30 | +<li><a href="records.html">Records and pointers</a></li> | |
| 31 | +<li><a href="variants.html" aria-current="page">Enumerations, sets, variants and match</a></li> | |
| 32 | +<li><a href="memory.html">Memory and allocators</a></li> | |
| 33 | +</ol> | |
| 34 | +<h3>Go</h3><ol start='10'> | |
| 35 | +<li><a href="errors.html">Errors</a></li> | |
| 36 | +<li><a href="defer.html">Defer</a></li> | |
| 37 | +<li><a href="checks.html">When it goes wrong</a></li> | |
| 38 | +<li><a href="generics.html">Generic modules</a></li> | |
| 39 | +<li><a href="c.html">Talking to C</a></li> | |
| 40 | +<li><a href="threads.html">Threads</a></li> | |
| 41 | +</ol></aside><article><p class="kicker">Set · lesson 8 of 15</p><h1>Enumerations, sets, variants and match</h1> | |
| 42 | +<div class="file"><span>Shapes.raz</span></div><pre class="code"><code><span class="kw">module</span> Shapes; | |
| 43 | +<span class="kw">import</span> Out, Fmt, Math; | |
| 44 | + | |
| 45 | +<span class="kw">type</span> | |
| 46 | + Colour = (red, green, blue); | |
| 47 | + Colours = <span class="kw">set</span> <span class="kw">of</span> Colour; | |
| 48 | + Shape = <span class="kw">variant</span> | |
| 49 | + circle(r: <span class="ty">F64</span>); | |
| 50 | + rect(w, h: <span class="ty">F64</span>); | |
| 51 | + dot; | |
| 52 | + <span class="kw">end</span>; | |
| 53 | + | |
| 54 | +<span class="kw">const</span> Some: []Shape = [circle(<span class="number">1.0</span>), rect(<span class="number">2.0</span>, <span class="number">3.5</span>), dot]; | |
| 55 | + | |
| 56 | +<span class="kw">proc</span> area(<span class="kw">const</span> s: Shape): <span class="ty">F64</span>; | |
| 57 | +<span class="kw">begin</span> | |
| 58 | + <span class="kw">match</span> s <span class="kw">of</span> | |
| 59 | + | circle(r): <span class="kw">return</span> Math.pi * r * r; | |
| 60 | + | rect(w, h): <span class="kw">return</span> w * h; | |
| 61 | + | dot: <span class="kw">return</span> <span class="number">0.0</span>; | |
| 62 | + <span class="kw">end</span>; | |
| 63 | +<span class="kw">end</span>; | |
| 64 | + | |
| 65 | +<span class="kw">proc</span> kind(c: <span class="ty">I32</span>): []<span class="ty">U8</span>; | |
| 66 | +<span class="kw">begin</span> | |
| 67 | + <span class="kw">match</span> c <span class="kw">of</span> | |
| 68 | + | <span class="string">' '</span>, <span class="string">'\t'</span>, <span class="string">'\n'</span>: <span class="kw">return</span> <span class="string">"space"</span>; | |
| 69 | + | <span class="string">'0'</span> .. <span class="string">'9'</span>: <span class="kw">return</span> <span class="string">"digit"</span>; | |
| 70 | + | <span class="string">'a'</span> .. <span class="string">'z'</span>, <span class="string">'A'</span> .. <span class="string">'Z'</span>: <span class="kw">return</span> <span class="string">"letter"</span>; | |
| 71 | + | <span class="kw">else</span>: <span class="kw">return</span> <span class="string">"other"</span>; | |
| 72 | + <span class="kw">end</span>; | |
| 73 | +<span class="kw">end</span>; | |
| 74 | + | |
| 75 | +<span class="kw">proc</span> colour(name: []<span class="ty">U8</span>): Colour; | |
| 76 | +<span class="kw">begin</span> | |
| 77 | + <span class="kw">match</span> name <span class="kw">of</span> | |
| 78 | + | <span class="string">"red"</span>, <span class="string">"rose"</span>: <span class="kw">return</span> red; | |
| 79 | + | <span class="string">"green"</span>: <span class="kw">return</span> green; | |
| 80 | + | <span class="kw">else</span>: <span class="kw">return</span> blue; | |
| 81 | + <span class="kw">end</span>; | |
| 82 | +<span class="kw">end</span>; | |
| 83 | + | |
| 84 | +<span class="kw">proc</span> main*; | |
| 85 | +<span class="kw">var</span> i: <span class="ty">INT</span>; warm: Colours; c: Colour; | |
| 86 | +<span class="kw">begin</span> | |
| 87 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="ty">LEN</span>(Some) - <span class="number">1</span> <span class="kw">do</span> | |
| 88 | + Fmt.print(<span class="string">"{}\n"</span>, [Fmt.real(area(Some[i]), <span class="number">2</span>)]); | |
| 89 | + <span class="kw">end</span>; | |
| 90 | + Fmt.print(<span class="string">"{} {} {}\n"</span>, [Fmt.str(kind(<span class="string">'7'</span>)), Fmt.str(kind(<span class="string">'x'</span>)), | |
| 91 | + Fmt.str(kind(<span class="string">'+'</span>))]); | |
| 92 | + warm := {red, blue} - {blue} + {green}; | |
| 93 | + <span class="kw">for</span> c := red <span class="kw">to</span> blue <span class="kw">do</span> | |
| 94 | + <span class="kw">if</span> c <span class="kw">in</span> warm <span class="kw">then</span> Out.int(<span class="ty">I64</span>(c)); Out.ln; <span class="kw">end</span>; | |
| 95 | + <span class="kw">end</span>; | |
| 96 | + Out.int(<span class="ty">I64</span>(colour(<span class="string">"rose"</span>))); Out.int(<span class="ty">I64</span>(colour(<span class="string">"green"</span>))); Out.ln; | |
| 97 | +<span class="kw">end</span>; | |
| 98 | + | |
| 99 | +<span class="kw">end</span> Shapes.</code></pre> | |
| 100 | +<pre class="output"><code>3.14 | |
| 101 | +7.00 | |
| 102 | +0.00 | |
| 103 | +digit letter other | |
| 104 | +0 | |
| 105 | +1 | |
| 106 | +01 | |
| 107 | +</code></pre> | |
| 108 | +<h2>Enumerations</h2> | |
| 109 | +<p>An enumeration is a list of names, in order. They convert to their position and back, and a <code>for</code> loop can run over them. A name may be written with its type, <code>Day.mon</code>, and two enumerations of a module may share a name, <code>Style.bold</code> and <code>Elem.bold</code>, which is then always written so. An integer that has no name at its position is a failed check, never a silent wrong value.</p> | |
| 110 | +<div class="file"><span>Days.raz</span></div><pre class="code"><code><span class="kw">module</span> Days; | |
| 111 | +<span class="kw">import</span> Out; | |
| 112 | + | |
| 113 | +<span class="kw">type</span> Day = (mon, tue, wed, thu, fri, sat, sun); | |
| 114 | + | |
| 115 | +<span class="kw">proc</span> name(d: Day): []<span class="ty">U8</span>; | |
| 116 | +<span class="kw">begin</span> | |
| 117 | + <span class="kw">match</span> d <span class="kw">of</span> | |
| 118 | + | mon: <span class="kw">return</span> <span class="string">"Monday"</span>; | |
| 119 | + | tue: <span class="kw">return</span> <span class="string">"Tuesday"</span>; | |
| 120 | + | wed: <span class="kw">return</span> <span class="string">"Wednesday"</span>; | |
| 121 | + | thu: <span class="kw">return</span> <span class="string">"Thursday"</span>; | |
| 122 | + | fri: <span class="kw">return</span> <span class="string">"Friday"</span>; | |
| 123 | + | sat: <span class="kw">return</span> <span class="string">"Saturday"</span>; | |
| 124 | + | sun: <span class="kw">return</span> <span class="string">"Sunday"</span>; | |
| 125 | + <span class="kw">end</span>; | |
| 126 | +<span class="kw">end</span>; | |
| 127 | + | |
| 128 | +<span class="kw">proc</span> main*; | |
| 129 | +<span class="kw">var</span> d: Day; | |
| 130 | +<span class="kw">begin</span> | |
| 131 | + <span class="kw">for</span> d := mon <span class="kw">to</span> sun <span class="kw">do</span> | |
| 132 | + Out.int(<span class="ty">I64</span>(d)); Out.str(<span class="string">" "</span>); Out.str(name(d)); | |
| 133 | + <span class="kw">if</span> d >= sat <span class="kw">then</span> Out.str(<span class="string">" (weekend)"</span>); <span class="kw">end</span>; | |
| 134 | + Out.ln; | |
| 135 | + <span class="kw">end</span>; | |
| 136 | + d := Day(<span class="number">4</span>); | |
| 137 | + Out.str(name(d)); Out.ln; | |
| 138 | +<span class="kw">end</span>; | |
| 139 | + | |
| 140 | +<span class="kw">end</span> Days.</code></pre> | |
| 141 | +<pre class="output"><code>0 Monday | |
| 142 | +1 Tuesday | |
| 143 | +2 Wednesday | |
| 144 | +3 Thursday | |
| 145 | +4 Friday | |
| 146 | +5 Saturday (weekend) | |
| 147 | +6 Sunday (weekend) | |
| 148 | +Friday | |
| 149 | +</code></pre> | |
| 150 | +<h2>Sets</h2> | |
| 151 | +<p>A <code>set of</code> an enumeration holds any choice of its names, in the bits of a word. <code>in</code> tests membership; <code>+</code> is union, <code>*</code> intersection and <code>-</code> difference; <code>{}</code> is the empty set. Sets are how Unix permissions, option flags and key modifiers are best written.</p> | |
| 152 | +<div class="file"><span>Perms.raz</span></div><pre class="code"><code><span class="kw">module</span> Perms; | |
| 153 | +<span class="kw">import</span> Out; | |
| 154 | + | |
| 155 | +<span class="kw">type</span> | |
| 156 | + Perm = (x, w, r); <span class="comment">(* bits 0, 1, 2, as chmod has them *)</span> | |
| 157 | + Perms = <span class="kw">set</span> <span class="kw">of</span> Perm; | |
| 158 | + | |
| 159 | +<span class="kw">proc</span> show(p: Perms); | |
| 160 | +<span class="kw">begin</span> | |
| 161 | + <span class="kw">if</span> r <span class="kw">in</span> p <span class="kw">then</span> Out.char(<span class="string">'r'</span>); <span class="kw">else</span> Out.char(<span class="string">'-'</span>); <span class="kw">end</span>; | |
| 162 | + <span class="kw">if</span> w <span class="kw">in</span> p <span class="kw">then</span> Out.char(<span class="string">'w'</span>); <span class="kw">else</span> Out.char(<span class="string">'-'</span>); <span class="kw">end</span>; | |
| 163 | + <span class="kw">if</span> x <span class="kw">in</span> p <span class="kw">then</span> Out.char(<span class="string">'x'</span>); <span class="kw">else</span> Out.char(<span class="string">'-'</span>); <span class="kw">end</span>; | |
| 164 | +<span class="kw">end</span>; | |
| 165 | + | |
| 166 | +<span class="kw">proc</span> main*; | |
| 167 | +<span class="kw">var</span> user, group, mine: Perms; | |
| 168 | +<span class="kw">begin</span> | |
| 169 | + user := {r, w, x}; | |
| 170 | + group := {r, x}; | |
| 171 | + show(user); Out.char(<span class="string">' '</span>); show(group); Out.ln; | |
| 172 | + show(user * group); Out.char(<span class="string">' '</span>); <span class="comment">(* both: r-x *)</span> | |
| 173 | + show(user - group); Out.char(<span class="string">' '</span>); <span class="comment">(* only user: -w- *)</span> | |
| 174 | + show(user - {w}); Out.ln; <span class="comment">(* r-x *)</span> | |
| 175 | + mine := group; | |
| 176 | + <span class="kw">if</span> mine = {r, x} <span class="kw">then</span> Out.str(<span class="string">"same as group\n"</span>); <span class="kw">end</span>; | |
| 177 | + Out.int(<span class="ty">I64</span>(<span class="ty">U8</span>(user))); Out.ln; <span class="comment">(* 7: a set is its bits *)</span> | |
| 178 | +<span class="kw">end</span>; | |
| 179 | + | |
| 180 | +<span class="kw">end</span> Perms.</code></pre> | |
| 181 | +<pre class="output"><code>rwx r-x | |
| 182 | +r-x -w- r-x | |
| 183 | +same as group | |
| 184 | +7 | |
| 185 | +</code></pre> | |
| 186 | +<h2>Variants</h2> | |
| 187 | +<p>A variant holds one of its cases, each with fields of its own, and <code>match</code> is the only way to read them: it runs the arm of the case the variant holds, naming its fields. Every case has an arm, unless an <code>| else:</code> comes last, so adding a case to the type makes every <code>match</code> that forgot it a compile error.</p> | |
| 188 | +<div class="file"><span>Tokens.raz</span></div><pre class="code"><code><span class="kw">module</span> Tokens; | |
| 189 | +<span class="kw">import</span> Out; | |
| 190 | + | |
| 191 | +<span class="kw">type</span> | |
| 192 | + Token = <span class="kw">variant</span> | |
| 193 | + number(n: <span class="ty">INT</span>); | |
| 194 | + plus; | |
| 195 | + times; | |
| 196 | + word(s: []<span class="ty">U8</span>); | |
| 197 | + <span class="kw">end</span>; | |
| 198 | + | |
| 199 | +<span class="kw">proc</span> describe(t: Token); | |
| 200 | +<span class="kw">begin</span> | |
| 201 | + <span class="kw">match</span> t <span class="kw">of</span> | |
| 202 | + | number(n): Out.str(<span class="string">"number "</span>); Out.int(n); | |
| 203 | + | plus: Out.str(<span class="string">"plus"</span>); | |
| 204 | + | times: Out.str(<span class="string">"times"</span>); | |
| 205 | + | word(s): Out.str(<span class="string">"word '"</span>); Out.str(s); Out.char(<span class="string">'\''</span>); | |
| 206 | + <span class="kw">end</span>; | |
| 207 | + Out.ln; | |
| 208 | +<span class="kw">end</span>; | |
| 209 | + | |
| 210 | +<span class="comment">(* evaluates tokens in reverse Polish; assumes the input is well formed *)</span> | |
| 211 | +<span class="kw">proc</span> eval(ts: []Token): <span class="ty">INT</span>; | |
| 212 | +<span class="kw">var</span> stack: [<span class="number">16</span>]<span class="ty">INT</span>; top, i, b: <span class="ty">INT</span>; | |
| 213 | +<span class="kw">begin</span> | |
| 214 | + top := <span class="number">0</span>; | |
| 215 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="ty">LEN</span>(ts) - <span class="number">1</span> <span class="kw">do</span> | |
| 216 | + <span class="kw">match</span> ts[i] <span class="kw">of</span> | |
| 217 | + | number(n): stack[top] := n; <span class="ty">INC</span>(top); | |
| 218 | + | plus: b := stack[top - <span class="number">1</span>]; <span class="ty">DEC</span>(top); stack[top - <span class="number">1</span>] := stack[top - <span class="number">1</span>] + b; | |
| 219 | + | times: b := stack[top - <span class="number">1</span>]; <span class="ty">DEC</span>(top); stack[top - <span class="number">1</span>] := stack[top - <span class="number">1</span>] * b; | |
| 220 | + | <span class="kw">else</span>: | |
| 221 | + <span class="kw">end</span>; | |
| 222 | + <span class="kw">end</span>; | |
| 223 | + <span class="kw">return</span> stack[<span class="number">0</span>]; | |
| 224 | +<span class="kw">end</span>; | |
| 225 | + | |
| 226 | +<span class="kw">proc</span> main*; | |
| 227 | +<span class="kw">var</span> ts: [<span class="number">5</span>]Token; i: <span class="ty">INT</span>; | |
| 228 | +<span class="kw">begin</span> | |
| 229 | + ts := [number(<span class="number">3</span>), number(<span class="number">4</span>), plus, number(<span class="number">5</span>), times]; <span class="comment">(* (3 + 4) * 5 *)</span> | |
| 230 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">4</span> <span class="kw">do</span> describe(ts[i]); <span class="kw">end</span>; | |
| 231 | + Out.int(eval(ts)); Out.ln; | |
| 232 | + describe(word(<span class="string">"hello"</span>)); | |
| 233 | +<span class="kw">end</span>; | |
| 234 | + | |
| 235 | +<span class="kw">end</span> Tokens.</code></pre> | |
| 236 | +<pre class="output"><code>number 3 | |
| 237 | +number 4 | |
| 238 | +plus | |
| 239 | +number 5 | |
| 240 | +times | |
| 241 | +35 | |
| 242 | +word 'hello' | |
| 243 | +</code></pre> | |
| 244 | +<h2>Matching integers</h2> | |
| 245 | +<p>On an integer, <code>match</code> takes constants and ranges, and must have an <code>| else:</code>. Characters are integers, so it is also how a scanner is written.</p> | |
| 246 | +<div class="file"><span>Classify.raz</span></div><pre class="code"><code><span class="kw">module</span> Classify; | |
| 247 | +<span class="kw">import</span> Out; | |
| 248 | + | |
| 249 | +<span class="kw">proc</span> kind(c: <span class="ty">I32</span>): []<span class="ty">U8</span>; | |
| 250 | +<span class="kw">begin</span> | |
| 251 | + <span class="kw">match</span> c <span class="kw">of</span> | |
| 252 | + | <span class="string">' '</span>, <span class="string">'\t'</span>, <span class="string">'\n'</span>: <span class="kw">return</span> <span class="string">"space"</span>; | |
| 253 | + | <span class="string">'0'</span> .. <span class="string">'9'</span>: <span class="kw">return</span> <span class="string">"digit"</span>; | |
| 254 | + | <span class="string">'a'</span> .. <span class="string">'z'</span>, <span class="string">'A'</span> .. <span class="string">'Z'</span>, <span class="string">'_'</span>: <span class="kw">return</span> <span class="string">"letter"</span>; | |
| 255 | + | <span class="kw">else</span>: <span class="kw">return</span> <span class="string">"other"</span>; | |
| 256 | + <span class="kw">end</span>; | |
| 257 | +<span class="kw">end</span>; | |
| 258 | + | |
| 259 | +<span class="kw">proc</span> main*; | |
| 260 | +<span class="kw">var</span> s: []<span class="ty">U8</span>; i: <span class="ty">INT</span>; | |
| 261 | +<span class="kw">begin</span> | |
| 262 | + s := <span class="string">"x1 + _y"</span>; | |
| 263 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="ty">LEN</span>(s) - <span class="number">1</span> <span class="kw">do</span> | |
| 264 | + Out.char(s[i]); Out.str(<span class="string">" is "</span>); Out.str(kind(<span class="ty">I32</span>(s[i]))); Out.ln; | |
| 265 | + <span class="kw">end</span>; | |
| 266 | +<span class="kw">end</span>; | |
| 267 | + | |
| 268 | +<span class="kw">end</span> Classify.</code></pre> | |
| 269 | +<pre class="output"><code>x is letter | |
| 270 | +1 is digit | |
| 271 | + is space | |
| 272 | ++ is other | |
| 273 | + is space | |
| 274 | +_ is letter | |
| 275 | +y is letter | |
| 276 | +</code></pre> | |
| 277 | +<h2>Matching strings</h2> | |
| 278 | +<p>On a string, <code>match</code> takes string constants, several to an arm if need be, and compares them as <code>=</code> does. It too must have an <code>| else:</code>. It is how a program reads a command, an option or a keyword without a chain of <code>elsif</code>s.</p> | |
| 279 | +<div class="file"><span>Commands.raz</span></div><pre class="code"><code><span class="kw">module</span> Commands; | |
| 280 | +<span class="kw">import</span> Out; | |
| 281 | + | |
| 282 | +<span class="kw">type</span> Op = (none, add, sub, show); | |
| 283 | + | |
| 284 | +<span class="kw">proc</span> op(word: []<span class="ty">U8</span>): Op; | |
| 285 | +<span class="kw">begin</span> | |
| 286 | + <span class="kw">match</span> word <span class="kw">of</span> | |
| 287 | + | <span class="string">"add"</span>, <span class="string">"plus"</span>, <span class="string">"+"</span>: <span class="kw">return</span> add; | |
| 288 | + | <span class="string">"sub"</span>, <span class="string">"minus"</span>, <span class="string">"-"</span>: <span class="kw">return</span> sub; | |
| 289 | + | <span class="string">"show"</span>: <span class="kw">return</span> show; | |
| 290 | + | <span class="kw">else</span>: <span class="kw">return</span> none; | |
| 291 | + <span class="kw">end</span>; | |
| 292 | +<span class="kw">end</span>; | |
| 293 | + | |
| 294 | +<span class="kw">proc</span> main*; | |
| 295 | +<span class="kw">var</span> total: <span class="ty">INT</span>; words: [<span class="number">6</span>][]<span class="ty">U8</span>; i: <span class="ty">INT</span>; | |
| 296 | +<span class="kw">begin</span> | |
| 297 | + words := [<span class="string">"add"</span>, <span class="string">"plus"</span>, <span class="string">"sub"</span>, <span class="string">"show"</span>, <span class="string">"times"</span>, <span class="string">"-"</span>]; | |
| 298 | + <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">5</span> <span class="kw">do</span> | |
| 299 | + <span class="kw">match</span> op(words[i]) <span class="kw">of</span> | |
| 300 | + | add: <span class="ty">INC</span>(total); | |
| 301 | + | sub: <span class="ty">DEC</span>(total); | |
| 302 | + | show: Out.int(total); Out.ln; | |
| 303 | + | none: Out.str(words[i]); Out.str(<span class="string">"?\n"</span>); | |
| 304 | + <span class="kw">end</span>; | |
| 305 | + <span class="kw">end</span>; | |
| 306 | + Out.int(total); Out.ln; | |
| 307 | +<span class="kw">end</span>; | |
| 308 | + | |
| 309 | +<span class="kw">end</span> Commands.</code></pre> | |
| 310 | +<pre class="output"><code>1 | |
| 311 | +times? | |
| 312 | +0 | |
| 313 | +</code></pre> | |
| 314 | +<p>Two labels that are the same string are an error, as two arms for one case are.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="records.html">← Records and pointers</a><a href="index.html">Contents</a><a class="next" href="memory.html">Memory and allocators →</a></div></article></div> | |
| 315 | +</main> | |
| 316 | +<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> | |
| 317 | +</body> | |
| 318 | +</html> |