Repository navigation
Expand file tree
/
Copy pathlibrary.html
More file actions
228 lines (226 loc) · 68.7 KB
/
Copy pathlibrary.html
File metadata and controls
228 lines (226 loc) · 68.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
<!doctype html>
<html lang="en"><head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Library reference</title>
<meta name="description" content="The standard library, rendered from spec/library.md.">
<link rel="icon" href="favicon.svg" type="image/svg+xml">
<link rel="preload" href="vendor/fonts/figtree.woff2" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="vendor/fonts/sora.woff2" as="font" type="font/woff2" crossorigin>
<link rel="stylesheet" href="style.css">
<script src="vendor/motion.js" defer></script>
<script src="vendor/lottie.js" defer></script>
<script type="module" src="app.js"></script>
</head><body data-page="library">
<header class="topbar">
<a class="brand" href="index.html"><svg viewBox="0 0 48 48" width="20" height="20" fill="none" stroke="currentColor" stroke-width="6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 6H39"/><path d="M24 14A13 13 0 1 0 37 27H26"/></svg><span>Grasm</span></a>
<span class="ver">v1.0.0</span>
<nav>
<a href="different.html">Why Grasm</a>
<a href="start.html">Docs</a>
<a href="security.html">Security</a>
<a href="achieved.html">Scorecard</a>
<a href="playground.html">Playground</a>
</nav>
<a class="cta" href="start.html">Get started</a>
</header>
<div class="frame">
<nav class="rail">
<a class="mark" href="index.html"><svg viewBox="0 0 48 48" width="18" height="18" fill="none" stroke="currentColor" stroke-width="6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 6H39"/><path d="M24 14A13 13 0 1 0 37 27H26"/></svg><b>grasm</b><span>a systems language</span></a>
<h2>Start</h2>
<a href="different.html">Why Grasm</a>
<a href="start.html">Getting started</a>
<a href="install.html">Install</a>
<a href="playground.html">Playground</a>
<h2>Learn</h2>
<a href="tutorial.html">Tutorial</a>
<a href="tour.html">Tour</a>
<a href="effects.html">Effects</a>
<a href="tiers.html">Ownership</a>
<a href="errors.html">Errors</a>
<a href="concurrency.html">Concurrency</a>
<a href="security.html">Security</a>
<h2>Reference</h2>
<a href="syntax.html">Syntax</a>
<a href="language.html">Language</a>
<a href="library.html" aria-current="page">Library</a>
<a href="packages.html">Packages</a>
<a href="spec.html">Specification</a>
<a href="architecture.html">Architecture</a>
<h2>More</h2>
<a href="examples.html">Examples</a>
<a href="achieved.html">Scorecard</a>
<a href="performance.html">Performance</a>
<a href="about.html">About</a>
<a href="status.html">Status</a>
<a href="roadmap.html">Roadmap</a>
</nav>
<main>
<p class="eyebrow">Reference</p>
<h1>Library reference</h1>
<p class="lede">The standard library, clause by clause. This page is
<code>spec/library.md</code>, rendered when the site was written — not a summary
of it.</p>
<p>Every operation the language provides, by receiver type. There are no imports: these are always available.</p>
<p>Each <code>L-</code> clause below has a conformance program under <code>spec/conformance/</code> that exercises what it claims. That is per clause, not per row: a table entry whose clause is covered elsewhere can still drift, which is how <code>read_file</code> came to be documented as returning <code>Option[str]</code> when it is fallible.</p>
<h2 id="1-free-functions">1. Free functions</h2>
<p><strong id="L-LIB-FREE">[L-LIB-FREE]</strong> Available without a receiver.</p>
<div class="scroll"><table><thead><tr><th>call</th><th>type</th><th>notes</th></tr></thead><tbody><tr><td><code>print(x)</code></td><td><code>(T)</code></td><td>writes <code>x</code> then a newline; performs <code>io</code></td></tr><tr><td><code>input()</code></td><td><code>() -> str</code></td><td>one line from stdin, without the newline; <code>io</code></td></tr><tr><td><code>args()</code></td><td><code>() -> [str]</code></td><td>the program's own arguments; performs <code>io</code></td></tr><tr><td><code>panic(msg)</code></td><td><code>(str)</code></td><td>prints <code>panic: msg</code>, exits 101</td></tr><tr><td><code>assert(c)</code></td><td><code>(bool)</code></td><td>panics when <code>c</code> is false</td></tr><tr><td><code>assert_eq(a, b)</code></td><td><code>(T, T)</code></td><td>panics when <code>a != b</code></td></tr><tr><td><code>fail(e)</code></td><td><code>(E)</code></td><td>raises the error branch of a <code>T ! E</code></td></tr><tr><td><code>map()</code></td><td><code>() -> Map[K, V]</code></td><td>a new empty map</td></tr><tr><td><code>now_millis()</code></td><td><code>() -> i64</code></td><td>milliseconds since the epoch; <code>io</code></td></tr><tr><td><code>monotonic_millis()</code></td><td><code>() -> i64</code></td><td>since an unnamed moment; only increases</td></tr><tr><td><code>monotonic_nanos()</code></td><td><code>() -> i64</code></td><td>the same clock in nanoseconds (scaled from milliseconds on wasm); <code>io</code></td></tr><tr><td><code>sleep_millis(n)</code></td><td><code>(i64) -> ()</code></td><td>waits; a replay does not; both <code>io</code></td></tr><tr><td><code>random_bytes(n)</code></td><td><code>(i64) -> bytes ! IoError</code></td><td><code>n</code> bytes from the operating system; <code>io</code></td></tr><tr><td><code>env(name)</code></td><td><code>(str) -> Option[str]</code></td><td>environment variable; <code>io</code></td></tr><tr><td><code>exit(code)</code></td><td><code>(i64)</code></td><td>ends the program with that status — its low eight bits ([L-LIB-EXIT])</td></tr><tr><td><code>read_file(p)</code></td><td><code>(str) -> str ! IoError</code></td><td>fallible, not <code>Option</code>; <code>io</code> ([L-LIB-IO])</td></tr><tr><td><code>write_file(p, s)</code></td><td><code>(str, str) -> () ! IoError</code></td><td>fallible; <code>io</code> ([L-LIB-IO])</td></tr><tr><td><code>file_exists(p)</code></td><td><code>(str) -> bool</code></td><td><code>io</code></td></tr></tbody></table></div>
<p><strong id="L-LIB-CLOCK">[L-LIB-CLOCK]</strong> <code>now_millis</code> is the <em>wall</em> clock and <strong>moves backwards</strong> — a correction, a leap second, a resumed machine — so a duration measured with it goes negative and a timeout fires wrong by that much. <code>monotonic_millis</code> only increases, and so does <code>monotonic_nanos</code>. <code>sleep_millis</code> waits; a replay does not.</p>
<p><strong id="L-LIB-EXIT">[L-LIB-EXIT]</strong> <code>exit(code)</code> ends the program with the <strong>low eight bits</strong> of <code>code</code>, as an operating system reports it and as C's <code>exit</code> does: <code>exit(-1)</code> is 255, <code>exit(256)</code> is 0. Clamping to 0..=255 was worse where it matters — it made <code>exit(-1)</code>, the commonest spelling of "fail" in a script, report <em>success</em>. <code>exit</code> performs no effect, so a dependency declaring <code>capabilities = []</code> can end the host process: deliberate, since <code>panic</code> and an endless loop already do — a ceiling bounds what a dependency can <em>reach</em>, never how long it runs. Nothing observable outside the process changes, so charging <code>io</code> for it would buy no guarantee while making every program that reports a status ask for the filesystem.</p>
<p><strong id="L-LIB-IO">[L-LIB-IO]</strong> The three ways a library call reports "no": <code>read_file</code> is <strong>fallible</strong> (<code>str ! IoError</code>) because a failure has a reason worth reading — <code>NotFound(path)</code>, and so on. <code>env</code> returns <code>Option[str]</code>, because an unset variable has no reason to give. <code>file_exists</code> returns <code>bool</code>, because the question was already yes-or-no.</p>
<h2 id="1a-how-values-are-written">1a. How values are written</h2>
<p><strong id="L-DISPLAY">[L-DISPLAY]</strong> <code>print(x)</code> and string interpolation render every type the same way, and this is normative because a program's output is what its correctness is judged on.</p>
<div class="scroll"><table><thead><tr><th>type</th><th>rendering</th><th>example</th></tr></thead><tbody><tr><td><code>i64</code></td><td>decimal</td><td><code>-7</code></td></tr><tr><td><code>f64</code></td><td>the fewest <strong>digits</strong> that round-trip, written out positionally — never exponent notation, and <strong>always with a point</strong> at every magnitude</td><td><code>1.5</code>, <code>1000000.0</code>, <code>1000000000000000.0</code>, <code>-0.0</code>; <code>1e300</code> is 303 characters</td></tr><tr><td><code>f64</code>, not finite</td><td><code>inf</code>, <code>-inf</code>, <code>NaN</code> — <code>NaN</code> is the one mixed-case rendering here</td><td><code>inf</code></td></tr><tr><td><code>()</code></td><td><code>()</code></td><td></td></tr><tr><td><code>bool</code></td><td><code>true</code> / <code>false</code></td><td></td></tr><tr><td><code>str</code></td><td>its characters, <strong>unquoted and unescaped</strong></td><td><code>b c</code></td></tr><tr><td><code>[T]</code></td><td>elements in order, <code>,</code>-separated, in brackets</td><td><code>[1, 2, 3]</code>, <code>[a, b c]</code></td></tr><tr><td><code>(A, B)</code></td><td>components in order, <code>,</code>-separated, in parentheses</td><td><code>(1, one, true)</code></td></tr><tr><td><code>Map[K, V]</code></td><td><code>key: value</code> pairs in sorted key order, in braces</td><td><code>{k: 1}</code></td></tr><tr><td>struct</td><td><code>Name{field: value, …}</code> in declaration order</td><td><code>P{x: 3, y: hi}</code></td></tr><tr><td>variant with fields</td><td><code>Name(v, …)</code></td><td><code>B(7)</code></td></tr><tr><td>variant without</td><td><code>Name</code></td><td><code>A</code></td></tr><tr><td><code>Option[T]</code></td><td><code>Some(v)</code> or <code>None</code></td><td><code>Some(1)</code></td></tr><tr><td><code>ref T</code></td><td>the slot it names and that slot's generation, never what it points at — the value may already be gone, and reading it to render would be the use-after-free the tier prevents</td><td><code>ref#0.0</code></td></tr><tr><td>a named function</td><td><code><fn module::name></code></td><td><code><fn main::dbl></code></td></tr><tr><td>a closure</td><td><code><closure></code> — it has no name to show</td><td></td></tr><tr><td>a handler</td><td>a struct with the operation names as fields</td><td><code>CHandler{now: <closure>}</code></td></tr><tr><td>a range</td><td><code>start..end</code>, as written</td><td><code>1..5</code></td></tr></tbody></table></div>
<p>Unquoted means a one-element list holding the empty string renders exactly as an empty list does: <code>[""]</code> and <code>[]</code> are both <code>[]</code>, and <code>"".split(",")</code> — one field, per the table above — looks like no fields at all. That is the price of a rendering meant to be read rather than parsed, and it is stated because the alternative is a reader concluding the library is wrong. <code>len()</code> tells them apart.</p>
<p>Strings nested inside a collection are <strong>not</strong> quoted, so <code>[a, b c]</code> is a two-element list whose second element contains a space. Rendering is for people reading output; it is not a serialisation format and does not round-trip.</p>
<h2 id="1b-calling-a-free-function-as-a-method">1b. Calling a free function as a method</h2>
<p><strong id="L-UFCS">[L-UFCS]</strong> A free function whose first parameter accepts the receiver may be called in method position: <code>f(x, y)</code> and <code>x.f(y)</code> are the same call. This applies to functions a program declares, not only to the library.</p>
<pre><code><span class="kw">fn</span> <span class="fn">double</span><span class="op">(</span>n<span class="op">:</span> <span class="ty">i64</span><span class="op">)</span> <span class="op">-></span> <span class="ty">i64</span> <span class="op">{</span> n <span class="op">*</span> <span class="nu">2</span> <span class="op">}</span>
<span class="kw">fn</span> <span class="fn">main</span><span class="op">(</span><span class="op">)</span> <span class="op">{</span>
<span class="fn">print</span><span class="op">(</span><span class="st">"{double(5)}"</span><span class="op">)</span> <span class="cm">// 10</span>
<span class="fn">print</span><span class="op">(</span><span class="st">"{5.double()}"</span><span class="op">)</span> <span class="cm">// 10 — the same call</span>
<span class="op">}</span></code></pre>
<p>Method syntax is resolved against the built-in methods for the receiver's type first, and a free function is considered only when no built-in matches. So declaring a function named <code>len</code> does not change what <code>xs.len()</code> means.</p>
<p>The language's <em>own</em> free functions — <code>print</code>, <code>read_file</code>, <code>write_file</code>, <code>file_exists</code>, <code>input</code>, <code>args</code>, <code>now_millis</code>, <code>env</code>, <code>exit</code>, <code>panic</code>, <code>assert</code>, <code>assert_eq</code> — are not reached this way. They are not methods of any type, and a second spelling for each of them buys nothing: <code>x |> print</code> already applies a free function to a value ([G-PIPE]), and it is charged the same row a call is. <code>"hi".print()</code> is refused, and the refusal says so and points at the pipeline.</p>
<h2 id="2-i64-and-f64">2. <code>i64</code> and <code>f64</code></h2>
<p><strong id="L-LIB-FIXED">[L-LIB-FIXED]</strong> <code>x.to_fixed(places)</code> is <code>f64</code> as text with exactly that many digits after the point, 0 to 17; anything else panics. Both engines format through the same code, so they agree digit for digit — which a formatter built by hand out of <code>round</code> and <code>to_str</code> cannot promise, and which is what every report with an average needs.</p>
<p>A value that is not finite answers with <code>inf</code>, <code>-inf</code> or <code>NaN</code> regardless of the requested precision, matching [L-DISPLAY].</p>
<p>Ties go <strong>away from zero</strong>, the same rule <code>round</code> uses ([L-LIB-ROUND]), so <code>(2.5).to_fixed(0)</code> is <code>"3"</code> and <code>(0.125).to_fixed(2)</code> is <code>"0.13"</code>. A tie means the <em>stored</em> value is exactly halfway, which is rarer than it looks: <code>2.675</code> is really <code>2.67499…</code>, so <code>(2.675).to_fixed(2)</code> is <code>"2.67"</code>. Nothing is scaled to decide this — scaling <code>2.675</code> by 100 lands on <code>267.5</code> and would round it the wrong way.</p>
<p><strong id="L-LIB-REMOVE">[L-LIB-REMOVE]</strong> <code>xs.remove(i)</code> takes the element at <code>i</code> out of the list and answers with it, shifting the rest down. Out of range panics, the way indexing does — <code>pop</code> is the one that answers <code>Option</code>, because "the list was empty" is a thing a caller can reasonably not know and "index 9 of 2" is not.</p>
<p>This is what draining a queue from the front <em>reads</em> like. Without it a ready queue cost <code>ready = ready.slice(1, ready.len())</code> a step, which reads like the workaround it was — but the cost is the same: <code>remove(0)</code> shifts the rest down, so both are O(n) per step and a full drain is quadratic either way. Measured at 80 000 elements, 17.2 s for <code>remove(0)</code> against 12.8 s for the slice. If a queue is what you have, reverse it once and <code>pop</code> from the end, which is O(1); this method is for taking an element out of the middle.</p>
<p><strong id="L-LIB-SUM">[L-LIB-SUM]</strong> <code>xs.sum()</code> of an empty list is the zero of the element type: <code>0</code> for <code>[i64]</code>, <code>0.0</code> for <code>[f64]</code>.</p>
<p>This held only in the compiled backend for a long time. The interpreter decides int-versus-float from the elements, and an empty list has none, so an empty float sum was <code>0</code> under <code>grasm run</code> and <code>0.0</code> from a native binary — and a float method on the result panicked with <code>no method to_fixed on 0</code>, in the engine this specification calls normative, on the empty-average case every reporting program has. It was recorded here as a known deviation on the grounds that fixing it needed the interpreter to carry element types. It did not: the checker knows the sum is an <code>f64</code> and can say so, which is the same answer it now gives for a promoted literal ([T-INT-TO-FLOAT-CARRIED]).</p>
<p><strong id="L-LIB-CMP">[L-LIB-CMP]</strong> <code>a.cmp(b)</code> answers <code>-1</code>, <code>0</code> or <code>1</code> in exactly the order <code>sort</code> uses — [L-LIB-SORT-NAN]'s total order for floats included. It exists because that order was specified, used internally, and callable by nothing: a program needing it reimplemented it from <code><</code> and <code>></code>, got NaN wrong, and scrambled a column in precisely the way that clause warns about. Naming a hazard without handing over the fix is how a specification becomes a trap.</p>
<p>It is also what makes a <em>comparator</em> sort writable — several keys with directions decided at run time, which a single <code>sort_by</code> key expression cannot express.</p>
<p><strong id="L-LIB-SORT-NAN">[L-LIB-SORT-NAN]</strong> Floats sort by a <strong>total</strong> order: <code>-NaN</code> before every number, <code>NaN</code> after every number, and <code>-0.0</code> before <code>0.0</code>. This is not IEEE comparison, where a NaN is unordered with everything — <code><</code> keeps that. A sort needs an order, and calling every NaN comparison "equal" is not one: given a non-order a sort returns a list that is not sorted <em>at all</em>, so one <code>nan</code> cell in a file scrambled a whole column rather than misplacing one value.</p>
<p><strong id="L-LIB-ROUND">[L-LIB-ROUND]</strong> <code>round</code> breaks ties <strong>away from zero</strong>: <code>2.5</code> and <code>3.5</code> round to <code>3.0</code> and <code>4.0</code>, <code>-2.5</code> to <code>-3.0</code>, <code>-0.5</code> to <code>-1.0</code>. It is not banker's rounding, and a report's figures depend on which it is. <code>(i64_min).abs()</code> is <code>i64_min</code>: there is no positive <code>i64</code> that far out, and the wrap is the same one <code>/</code> and <code>%</code> take ([E-ARITH-INT]).</p>
<p><strong id="L-LIB-NUM">[L-LIB-NUM]</strong></p>
<div class="scroll"><table><thead><tr><th>method</th><th>type</th><th>notes</th></tr></thead><tbody><tr><td><code>n.abs()</code></td><td><code>-> i64</code> / <code>-> f64</code></td><td></td></tr><tr><td><code>n.min(m)</code>, <code>n.max(m)</code></td><td><code>(T) -> T</code></td><td></td></tr><tr><td><code>x.floor()</code>, <code>x.ceil()</code>, <code>x.round()</code></td><td><code>f64 -> f64</code></td><td></td></tr><tr><td><code>x.sqrt()</code></td><td><code>f64 -> f64</code></td><td></td></tr><tr><td><code>n.to_str()</code></td><td><code>-> str</code></td><td>the same text <code>print</code> gives, [L-DISPLAY] included ([L-LIB-TO-STR])</td></tr><tr><td><code>n.as_f64()</code></td><td><code>i64 -> f64</code></td><td>widening</td></tr><tr><td><code>x.as_i64()</code></td><td><code>f64 -> i64</code></td><td>truncates toward zero, saturating ([L-LIB-AS-I64])</td></tr><tr><td><code>x.to_bits()</code>, <code>n.from_bits()</code></td><td><code>f64 -> i64</code>, <code>i64 -> f64</code></td><td>the IEEE-754 pattern, not the value ([L-LIB-AS-I64])</td></tr></tbody></table></div>
<p>Conversion is by method, not by a cast or a <code>int(...)</code>-style function. A <code>str</code> becomes a number with <code>parse_int</code> / <code>parse_float</code>, which return <code>Option</code> because the text may not be a number.</p>
<p><strong id="L-LIB-MATH">[L-LIB-MATH]</strong> Trigonometry, exponentials and logarithms, on <code>f64</code>:</p>
<div class="scroll"><table><thead><tr><th>method</th><th>type</th><th>notes</th></tr></thead><tbody><tr><td><code>x.sin()</code>, <code>x.cos()</code>, <code>x.tan()</code></td><td><code>f64 -> f64</code></td><td>radians</td></tr><tr><td><code>x.asin()</code>, <code>x.acos()</code>, <code>x.atan()</code></td><td><code>f64 -> f64</code></td><td>radians</td></tr><tr><td><code>x.atan2(y)</code></td><td><code>(f64) -> f64</code></td><td><code>x.atan2(y)</code> is <code>atan(x/y)</code> with the quadrant of <code>(y, x)</code></td></tr><tr><td><code>x.sinh()</code>, <code>x.cosh()</code>, <code>x.tanh()</code></td><td><code>f64 -> f64</code></td><td></td></tr><tr><td><code>x.exp()</code>, <code>x.ln()</code></td><td><code>f64 -> f64</code></td><td>base <em>e</em></td></tr><tr><td><code>x.log2()</code>, <code>x.log10()</code></td><td><code>f64 -> f64</code></td><td></td></tr><tr><td><code>x.log(b)</code></td><td><code>(f64) -> f64</code></td><td>base <code>b</code></td></tr><tr><td><code>x.cbrt()</code>, <code>x.hypot(y)</code></td><td><code>f64 -> f64</code></td><td></td></tr><tr><td><code>x.to_radians()</code>, <code>x.to_degrees()</code></td><td><code>f64 -> f64</code></td><td></td></tr><tr><td><code>pi()</code>, <code>e()</code></td><td><code>-> f64</code></td><td></td></tr></tbody></table></div>
<p>Every one is pure: no allocation, no error case, and <strong>no capability</strong>. That last part is the reason they are here rather than left to <code>extern fn cos</code> — a declared C function performs <code>io</code> ([T-EXTERN-VALUE]), so reaching libm for a cosine put a trigonometry helper over the ceiling of any package declaring <code>capabilities = []</code>. A pure function should not cost a capability.</p>
<p><code>pi</code> and <code>e</code> are the only two builtins that yield to a function you declare yourself: a program with its own <code>fn e()</code> keeps it. <code>e</code> is a common enough identifier that taking it outright would break working programs.</p>
<p><strong id="L-LIB-TO-STR">[L-LIB-TO-STR]</strong> <code>to_str</code> produces exactly what <code>print</code> would. In particular an <code>f64</code> keeps its point at every magnitude: <code>(1.0).to_str()</code> is <code>"1.0"</code>. The interpreter used to hand the job to its host language, which drops the point on a whole value, so it answered <code>"1"</code> where the compiled backend answered <code>"1.0"</code> — and the documented idiom <code>xs.map(|v| v.to_str()).join(", ")</code> printed a <code>[f64]</code> as a list of integers, which [L-DISPLAY] exists to prevent.</p>
<p><strong id="L-LIB-AS-I64">[L-LIB-AS-I64]</strong> <code>as_i64</code> is total: every <code>f64</code> has an answer, so it never panics. Too large gives <code>i64</code>'s maximum, too small its minimum, <code>NaN</code> gives <code>0</code> — saturation, and a <em>clamp</em> rather than a truncated bit pattern, because the two disagree and only one stays ordered. <code>to_bits</code> asks the other question, not what a float means but what it <strong>is</strong>: without it nothing can put a float in a binary format or compress a series, every such technique XORing consecutive patterns.</p>
<h2 id="3-str">3. <code>str</code></h2>
<p><strong id="L-LIB-STR">[L-LIB-STR]</strong> Lengths and offsets are in <strong>characters, not bytes</strong> ([E-STR-CHARS]). <code>s.byte_len()</code> is the one exception and is the only way to ask the other question: <code>"🙂".len()</code> is 1 and <code>"🙂".byte_len()</code> is 4. Characters are the right unit for a high-level language and the wrong one the moment a program writes a string to a socket or a file and has to say how long it is — a <code>Content-Length</code> counts bytes, and computing it from <code>len()</code> is wrong for every string that is not ASCII.</p>
<p><strong id="L-LIB-TRIM-SIDES">[L-LIB-TRIM-SIDES]</strong> <code>trim_start</code> and <code>trim_end</code> remove whitespace from one end only; <code>trim</code> removes it from both. None of the three takes an argument — whitespace is what they trim. The one-sided pair exists because a line's leading indentation usually carries meaning and its trailing newline does not, and <code>trim</code> cannot tell you that.</p>
<div class="scroll"><table><thead><tr><th>method</th><th>type</th><th>notes</th></tr></thead><tbody><tr><td><code>s.len()</code></td><td><code>-> i64</code></td><td>characters</td></tr><tr><td><code>s.byte_len()</code></td><td><code>-> i64</code></td><td>bytes, for a length that goes on the wire ([L-LIB-STR])</td></tr><tr><td><code>s.is_empty()</code></td><td><code>-> bool</code></td><td></td></tr><tr><td><code>s.substr(start, len)</code></td><td><code>(i64, i64) -> str</code></td><td><strong>start and length</strong>, not start and end; clamps past the end rather than panicking, unlike indexing</td></tr><tr><td><code>s.chars()</code></td><td><code>-> [str]</code></td><td>one single-character string per element</td></tr><tr><td><code>s.lines()</code></td><td><code>-> [str]</code></td><td>splits on newlines; no trailing empty line</td></tr><tr><td><code>s.split(sep)</code></td><td><code>(str) -> [str]</code></td><td>on an exact separator; adjacent separators give empty elements</td></tr><tr><td><code>s.words()</code></td><td><code>-> [str]</code></td><td>on runs of whitespace, with no empties ([L-LIB-WORDS])</td></tr><tr><td><code>s.contains(t)</code>, <code>s.starts_with(t)</code>, <code>s.ends_with(t)</code></td><td><code>(str) -> bool</code></td><td></td></tr><tr><td><code>s.index_of(t)</code></td><td><code>(str) -> Option[i64]</code></td><td><code>None</code> when absent</td></tr><tr><td><code>s.replace(from, to)</code></td><td><code>(str, str) -> str</code></td><td></td></tr><tr><td><code>s.trim()</code></td><td><code>-> str</code></td><td></td></tr><tr><td><code>s.trim_start()</code>, <code>s.trim_end()</code></td><td><code>-> str</code></td><td>one side only ([L-LIB-TRIM-SIDES])</td></tr><tr><td><code>s.to_upper()</code>, <code>s.to_lower()</code></td><td><code>-> str</code></td><td></td></tr><tr><td><code>s.repeat(n)</code></td><td><code>(i64) -> str</code></td><td></td></tr><tr><td><code>s.pad_start(w, fill)</code>, <code>s.pad_end(w, fill)</code></td><td><code>(i64, str) -> str</code></td><td>fill repeats and is cut to width ([E-PAD-CYCLE])</td></tr><tr><td><code>s.parse_int()</code></td><td><code>-> Option[i64]</code></td><td>surrounding space and a leading <code>+</code> are accepted; <code>1_000</code> and <code>0xFF</code> are <strong>not</strong> ([L-LIB-PARSE])</td></tr><tr><td><code>n.to_base(b)</code></td><td><code>(i64) -> str</code></td><td>digits <code>0-9a-z</code>; a base outside <code>2..36</code> panics ([L-LIB-BASE])</td></tr><tr><td><code>s.parse_int_base(b)</code></td><td><code>(i64) -> Option[i64]</code></td><td>the other direction; no prefix accepted ([L-LIB-BASE])</td></tr><tr><td><code>s.parse_float()</code></td><td><code>-> Option[f64]</code></td><td>accepts <code>inf</code>, <code>-inf</code>, <code>nan</code>; overflow gives an infinity, not <code>None</code> ([L-LIB-PARSE])</td></tr><tr><td><code>x.is_nan()</code>, <code>x.is_finite()</code></td><td><code>-> bool</code></td><td>what <code>parse_float</code> makes necessary ([L-LIB-PARSE])</td></tr><tr><td><code>s.code_at(i)</code></td><td><code>(i64) -> i64</code></td><td>Unicode code point of character <code>i</code>; panics out of range ([L-LIB-CODES])</td></tr><tr><td><code>s.codes()</code></td><td><code>-> [i64]</code></td><td>every code point, in order</td></tr><tr><td><code>n.to_char()</code></td><td><code>i64 -> str</code></td><td>a code point back to a one-character string; panics if <code>n</code> is not one</td></tr></tbody></table></div>
<p><strong id="L-LIB-CODES">[L-LIB-CODES]</strong> <code>s.code_at(i)</code> and <code>s.codes()</code> give Unicode <strong>code points</strong> (<code>char</code> scalar values), counting characters not bytes, and <code>n.to_char()</code> turns one back into text. <code>code_at</code> panics out of range, like indexing; <code>to_char</code> panics on a value that is not a code point, surrogates included. Together they are what lets a program compute <em>on</em> text — hash it, encode it, parse a number by hand — rather than only cut and compare it.</p>
<p><code>len</code>, <code>code_at</code> and <code>substr</code> all answer in constant time (<code>substr</code> in time proportional to the slice it returns), whatever the text. They count <em>characters</em>, so each used to decode the string from the start: <code>while i < s.len()</code> was quadratic in two ways at once, and 400 000 characters took 6.7 seconds where the identical loop over a list took 0.21. A string never changes once built, so its character count is computed once and kept. When that count equals the byte count the text is ASCII and an index is an index; when it does not, a character index is built once, the first time one is asked for by position. Fixing only the ASCII half left the same 6.3 seconds waiting behind a single two-byte character, and building the index for <code>code_at</code> while leaving <code>substr</code> to walk from the start left a <code>substr(i, 1)</code> scan quadratic — 39 seconds over 262 144 characters — next to a <code>code_at</code> scan of the same string costing 0.11.</p>
<p><strong id="L-LIB-WORDS">[L-LIB-WORDS]</strong> <code>s.words()</code> splits on runs of whitespace and yields no empty elements, which is what reading a line of aligned columns needs. <code>s.split(" ")</code> is the other thing — an exact separator, where two spaces in a row mean an empty element between them — and both are worth having, because a CSV wants the second and a log line wants the first.</p>
<p><strong id="L-LIB-PARSE">[L-LIB-PARSE]</strong> <code>parse_int</code> and <code>parse_float</code> answer <code>None</code> for text that is not a number, and are worth stating exactly because untrusted input reaches them:</p>
<ul><li><code>parse_int</code> accepts surrounding whitespace and a leading <code>+</code> or <code>-</code>. It does <strong>not</strong> accept the <code>1_000</code> and <code>0xFF</code> forms that [L-INT] allows in <em>source</em>: a literal in a program and a number in a data file are different things.</li><li><code>parse_float</code> accepts <code>inf</code>, <code>-inf</code> and <code>nan</code>, and a value too large to represent gives an infinity rather than <code>None</code>. So <code>"1e400"</code> parses, and the <code>inf</code> it produces then flows into arithmetic, <code>as_i64</code> ([L-LIB-NUM]) and sorting ([L-LIB-SORT-NAN]) — which is how those three came to be specified.</li></ul>
<h2 id="4-t">4. <code>[T]</code></h2>
<p><strong id="L-LIB-LIST">[L-LIB-LIST]</strong> Indexing out of bounds panics; <code>get</code> returns <code>Option</code> ([E-INDEX-BOUNDS]).</p>
<div class="scroll"><table><thead><tr><th>method</th><th>type</th><th>notes</th></tr></thead><tbody><tr><td><code>for x in xs { … }</code></td><td></td><td>iterates elements, not indices ([E-LOOP-LIST])</td></tr><tr><td><code>xs.len()</code>, <code>xs.is_empty()</code></td><td></td><td></td></tr><tr><td><code>xs[i]</code></td><td><code>-> T</code></td><td>panics when out of range</td></tr><tr><td><code>xs.get(i)</code></td><td><code>(i64) -> Option[T]</code></td><td></td></tr><tr><td><code>xs.first()</code>, <code>xs.last()</code></td><td><code>-> Option[T]</code></td><td></td></tr><tr><td><code>xs.push(v)</code></td><td><code>(T)</code></td><td>mutates; receiver must be <code>var</code></td></tr><tr><td><code>xs.pop()</code></td><td><code>-> Option[T]</code></td><td>mutates</td></tr><tr><td><code>xs.remove(i)</code></td><td><code>(i64) -> T</code></td><td>mutates; panics out of range, like indexing ([L-LIB-REMOVE])</td></tr><tr><td><code>a.cmp(b)</code></td><td><code>(T) -> i64</code></td><td><code>-1</code>, <code>0</code> or <code>1</code> in the order <code>sort</code> uses; <code>i64</code>, <code>f64</code>, <code>str</code> and tuples ([L-LIB-CMP])</td></tr><tr><td><code>xs.sort()</code></td><td></td><td>mutates; ascending. Ordered means <code>i64</code>, <code>f64</code>, <code>str</code>, and a tuple of those ([L-LIB-TUPLE]) — sorting anything else is a compile error, the same one <code><</code> gives</td></tr><tr><td><code>xs.rev()</code></td><td><code>-> [T]</code></td><td></td></tr><tr><td><code>xs.slice(a, b)</code></td><td><code>(i64, i64) -> [T]</code></td><td><code>a</code> up to but excluding <code>b</code>; clamps past either end rather than panicking, like <code>substr</code></td></tr><tr><td><code>xs.contains(v)</code></td><td><code>(T) -> bool</code></td><td></td></tr><tr><td><code>xs.join(sep)</code></td><td><code>(str) -> str</code></td><td><code>[str]</code> only — map to <code>str</code> first</td></tr><tr><td><code>xs.sum()</code></td><td><code>-> T</code></td><td>numeric elements; <code>0</code> of the element type when empty ([L-LIB-SUM])</td></tr><tr><td><code>xs.min()</code>, <code>xs.max()</code></td><td><code>-> Option[T]</code></td><td><code>None</code> when empty; not available for <code>bool</code></td></tr><tr><td><code>xs.fold(init, f)</code></td><td><code>(B, (B, T) -> B) -> B</code></td><td>left fold; the accumulator's type comes from <code>init</code>, not from <code>T</code></td></tr><tr><td><code>xs.map(f)</code></td><td><code>(T -> U) -> [U]</code></td><td></td></tr><tr><td><code>xs.par_map(f)</code></td><td><code>(T -> U) -> [U]</code></td><td>multi-core; <code>f</code> must be effect-free ([T-PAR-MAP-PURE])</td></tr><tr><td><code>xs.filter(f)</code></td><td><code>(T -> bool) -> [T]</code></td><td></td></tr><tr><td><code>xs.par_filter(f)</code></td><td><code>(T -> bool) -> [T]</code></td><td>multi-core; <code>f</code> must be effect-free; input order kept ([E-PAR-FILTER-ORDER])</td></tr><tr><td><code>xs.any(f)</code>, <code>xs.all(f)</code></td><td><code>(T -> bool) -> bool</code></td><td>short-circuit ([E-SEARCH-SHORTCIRCUIT])</td></tr><tr><td><code>xs.find(f)</code></td><td><code>(T -> bool) -> Option[T]</code></td><td>first match</td></tr><tr><td><code>xs + ys</code></td><td><code>([T], [T]) -> [T]</code></td><td>concatenation, the way <code>+</code> joins strings ([E-LIST-CONCAT])</td></tr><tr><td><code>xs.sort_by(key)</code></td><td><code>(T -> K)</code></td><td>mutates; sorts by an extracted <code>i64</code>/<code>f64</code>/<code>str</code> key, stably ([L-LIB-SORT-BY])</td></tr><tr><td><code>xs.enumerate()</code></td><td><code>-> [(i64, T)]</code></td><td>pair each element with its index</td></tr><tr><td><code>xs.zip(ys)</code></td><td><code>([U]) -> [(T, U)]</code></td><td>pairs up to the shorter of the two</td></tr><tr><td><code>pair.0</code>, <code>pair.1</code>, …</td><td><code>-> T</code></td><td>a tuple's components are named by position ([L-LIB-TUPLE])</td></tr></tbody></table></div>
<p><strong id="L-LIB-SORT-BY">[L-LIB-SORT-BY]</strong> <code>xs.sort_by(key)</code> sorts by what <code>key</code> returns for each element, which is where a list of structs gets its order from — <code>sort</code> needs the <em>elements</em> ordered, and a struct is not. The key is <code>i64</code>, <code>f64</code>, <code>str</code>, or a <strong>tuple</strong> of those, which is what makes <code>xs.sort_by(|p| (p.dept, p.age, p.name))</code> a multi-key sort rather than an error ([L-LIB-TUPLE]). This clause said "must be <code>i64</code>, <code>f64</code> or <code>str</code>" while tuple keys worked in all three engines — two clauses of one document disagreeing, and the one that was wrong was the one a reader would find first. The sort is stable: elements with equal keys stay in the order they were written. It sorts <strong>ascending</strong>, always; descending is <code>xs.sort_by(k)</code> followed by <code>xs = xs.rev()</code>. Negating the key works for a number and has no counterpart for a <code>str</code>, so the reversal is the general answer and the one to reach for. The assignment is the whole point: <code>sort_by</code> mutates and <code>rev</code> answers with a new list, so the clause's earlier wording — <code>xs.rev()</code> on its own line — left the list ascending and said nothing.</p>
<p><strong id="L-LIB-PAIRS">[L-LIB-PAIRS]</strong> <code>xs.enumerate()</code> pairs each element with its index and <code>xs.zip(ys)</code> pairs the two lists positionally, stopping at the shorter — there is no element to invent past the end of one. Both give <code>[(A, B)]</code>, which <code>for (a, b) in …</code> binds by name ([G-LET-TUPLE]).</p>
<p><strong id="L-LIB-TUPLE">[L-LIB-TUPLE]</strong> A tuple's components are read by position — <code>pair.0</code>, <code>pair.1</code> — and a tuple of ordered components is itself ordered, compared component by component. That is what <code><</code> on tuples means, what <code>sort</code> on a list of them does, <code>min</code>/<code>max</code> included, and what makes <code>xs.sort_by(|p| (p.dept, p.age, p.name))</code> a multi-key sort rather than an error. <code>min</code> and <code>max</code> used to spell out the types they accepted instead of asking whether the element was ordered, so <code>xs.enumerate().min()</code> was refused on a list <code>sort</code> orders happily.</p>
<p>That example is worth spelling out, because it does <em>not</em> mean "index of the smallest": components compare left to right, so <code>enumerate().min()</code> compares indices first and always answers <code>(0, xs[0])</code>. To find the smallest and where it was, put the value first — <code>xs.enumerate().map(|p| (p.1, p.0)).min()</code>.</p>
<h2 id="5-map-k-v">5. <code>Map[K, V]</code></h2>
<p><strong id="L-LIB-MAP">[L-LIB-MAP]</strong> Keys are <code>i64</code>, <code>str</code>, or <code>bool</code>. Iteration is in sorted key order ([E-MAP-ORDER]).</p>
<div class="scroll"><table><thead><tr><th>method</th><th>type</th><th>notes</th></tr></thead><tbody><tr><td><code>m.len()</code>, <code>m.is_empty()</code></td><td></td><td></td></tr><tr><td><code>m.get(k)</code></td><td><code>(K) -> Option[V]</code></td><td></td></tr><tr><td><code>m.set(k, v)</code></td><td><code>(K, V)</code></td><td>mutates; receiver must be <code>var</code></td></tr><tr><td><code>m.has(k)</code></td><td><code>(K) -> bool</code></td><td></td></tr><tr><td><code>m.delete(k)</code></td><td><code>(K) -> bool</code></td><td>mutates; whether it was present</td></tr><tr><td><code>m.keys()</code></td><td><code>-> [K]</code></td><td>sorted</td></tr><tr><td><code>m.values()</code></td><td><code>-> [V]</code></td><td>in key order</td></tr><tr><td><code>m.entries()</code></td><td><code>-> [(K, V)]</code></td><td>pairs, in key order — the only way to reach both at once</td></tr></tbody></table></div>
<h2 id="6-option-t">6. <code>Option[T]</code></h2>
<p><strong id="L-LIB-OPTION">[L-LIB-OPTION]</strong></p>
<div class="scroll"><table><thead><tr><th>form</th><th>notes</th></tr></thead><tbody><tr><td><code>Some(v)</code>, <code>None</code></td><td>constructors</td></tr><tr><td><code>o ?? fallback</code></td><td>the value, or <code>fallback</code>; the right side is evaluated only when needed ([E-COALESCE-LAZY])</td></tr><tr><td><code>o.is_none()</code>, <code>o.is_some()</code></td><td></td></tr><tr><td><code>o.unwrap_or(d)</code></td><td>same as <code>??</code></td></tr><tr><td><code>o.expect(msg)</code></td><td>the payload, or panics with <code>msg</code> — for when absence is a bug, not a case</td></tr><tr><td><code>match o { Some(v) -> … None -> … }</code></td><td>exhaustive</td></tr></tbody></table></div>
<p><strong id="L-LIB-RANGE-OPS">[L-LIB-RANGE-OPS]</strong> A range answers <code>to_list</code>, <code>map</code>, <code>filter</code>, <code>sum</code> and <code>len</code>, producing a list of the same elements <code>for i in a..b</code> walks. There is one definition of what a range contains and not two: every engine builds that list and reuses the list method.</p>
<p>A range is also a <strong>value</strong>: <code>let r = 0..n</code> binds one, it prints as <code>0..n</code> rather than as its elements, and two compare equal when their bounds and their inclusiveness match — so <code>0..3 == 0..3</code> and <code>0..3 != 0..=3</code>. It holds three numbers and not its elements, so <code>0..2_000_000</code> costs the same as <code>0..2</code>.</p>
<p>Its type is written <strong><code>range</code></strong>: <code>fn window(n: i64) -> range</code>, <code>type W = { span: range }</code>, <code>[range]</code>. That name reached the error messages before the syntax, so a range could be bound and never declared — a value you can hold and cannot pass is stuck in one function body. It reaches its methods from any shape that produces one, not only from a name: <code>[0..3][0].len()</code> and <code>window(2).sum()</code>.</p>
<p><code>len</code> is answered from the bounds without building anything; the others build the list first. <code>for i in a..b</code> written literally never builds a range at all — it is compiled into a counted loop — and that is why the loop costs nothing and holding a range costs one allocation.</p>
<p>The clause exists because of what it replaces. Building a list from a count needed <code>var xs: [i64] = []</code>, a <code>for</code>, a <code>push</code> and two closing braces — four lines where <code>(0..n).map(f)</code> says the same thing, in every program that builds a list from a count. [G11] budgets Grasm at or below Python's token count and it measured 1.41×; this is most of the difference, and adding it moved the figure to 1.22× without adding a syntactic form — a call is a call, so the kernel's count in <code>core.md</code> does not move.</p>
<h2 id="network-the-net-capability">Network — the <code>net</code> capability</h2>
<p><strong id="L-LIB-NET">[L-LIB-NET]</strong> These builtins reach the network, and each performs <code>net</code>:</p>
<div class="scroll"><table><thead><tr><th></th><th>type</th><th></th></tr></thead><tbody><tr><td><code>tcp_listen(port)</code></td><td><code>(i64) -> i64 ! IoError</code></td><td>listens on <code>127.0.0.1:port</code>; <code>0</code> asks the system to choose</td></tr><tr><td><code>tcp_listen_on(host, port)</code></td><td><code>(str, i64) -> i64 ! IoError</code></td><td>listens on <code>host:port</code> — <code>"0.0.0.0"</code> for every interface</td></tr><tr><td><code>tcp_connect(host, port)</code></td><td><code>(str, i64) -> i64 ! IoError</code></td><td>dials <code>host:port</code>; a name is resolved</td></tr><tr><td><code>tcp_accept(h)</code></td><td><code>(i64) -> i64 ! IoError</code></td><td>waits for a connection, answering with a handle for it</td></tr><tr><td><code>tcp_read(h)</code></td><td><code>(i64) -> str ! IoError</code></td><td>what has arrived, as text</td></tr><tr><td><code>tcp_read_bytes(h)</code></td><td><code>(i64) -> bytes ! IoError</code></td><td>the same read, unconverted</td></tr><tr><td><code>tcp_write(h, text)</code></td><td><code>(i64, str) -> () ! IoError</code></td><td>writes and flushes</td></tr><tr><td><code>tcp_write_bytes(h, b)</code></td><td><code>(i64, bytes) -> () ! IoError</code></td><td>writes and flushes</td></tr><tr><td><code>net_close(h)</code></td><td><code>(i64) -> ()</code></td><td>closes a listener or a connection</td></tr><tr><td><code>net_wait(hs, ms)</code></td><td><code>([i64], i64) -> [i64] ! IoError</code></td><td>the handles that can be read without waiting</td></tr><tr><td><code>net_port(h)</code></td><td><code>(i64) -> i64 ! IoError</code></td><td>the local port a handle is bound to</td></tr><tr><td><code>tcp_peer(h)</code></td><td><code>(i64) -> (str, i64) ! IoError</code></td><td>the address and port at the other end of a connection ([L-LIB-NET-PEER])</td></tr><tr><td><code>net_workers(n, f)</code></td><td><code>(i64, fn(i64) -> T) -> [T]</code></td><td><code>f(0)</code>, …, <code>f(n - 1)</code>, a thread each ([L-LIB-NET-WORKERS])</td></tr></tbody></table></div>
<p><code>tcp_connect</code> resolves names; failing to resolve and failing to connect are the same <code>IoFailed</code>, since both mean "there is nothing to talk to", and the message carries the difference. A handle is an integer and a payload is text, so the network needed no pointer type and no byte buffer in the language.</p>
<p><code>tcp_read</code> performs <strong>one</strong> read rather than looping to end-of-stream, because an HTTP client holds the connection open after its request and reading to the end would wait forever. A caller that needs more reads again. Bytes that are not valid UTF-8 are replaced rather than refused: a socket carries bytes, a <code>str</code> carries text, and a client's mistake should not end a server.</p>
<p>That is wrong for a protocol not made of text: a JPEG in <code>multipart/form-data</code> would arrive plausibly sized and broken. <code>tcp_read_bytes</code> and <code>tcp_write_bytes</code> are the same calls without the conversion ([L-LIB-BYTES]). Both pairs stay: an HTTP header is text and its body may not be.</p>
<p><code>net_port</code> is what makes <code>tcp_listen(0)</code> usable. Letting the system choose a free port is how a program runs where the one it wanted is taken, and without reading the choice back it could not name, dial, or print the port it bound.</p>
<p><code>net_wait</code> is what lets one thread hold many conversations. Every other call here blocks, and <code>spawn</code> does not carry <code>net</code>, so without it a server serves one client at a time; several such loops at once are [L-LIB-NET-WORKERS].</p>
<p>It answers with the subset of <code>hs</code> that will not block, <strong>in the order they were asked in</strong> rather than whichever order the kernel reports, so a program that walks the result serves its connections in a fixed order ([L-DETERMINISM]). A timeout of <code>0</code> asks without waiting, a negative timeout waits indefinitely, and an empty wait set is answered immediately with an empty list rather than an error — a server that has just closed its last connection asks exactly that on its next turn. A handle that names nothing is an <code>IoFailed</code>, the same as using a connection after closing it.</p>
<p>A hung-up peer is reported as <strong>ready</strong>. The read that follows returns nothing, which is how a caller learns the conversation ended; reporting it as not-ready would leave a dead connection in the wait set forever, and the loop would never notice it should be dropped.</p>
<p><strong id="L-LIB-NET-PEER">[L-LIB-NET-PEER]</strong> <code>tcp_peer(h)</code> is the far end of an accepted or dialed stream; any other handle is an <code>IoFailed</code>. Those streams have Nagle off (<code>TCP_NODELAY</code>).</p>
<p><strong id="L-LIB-NET-WORKERS">[L-LIB-NET-WORKERS]</strong> <code>net_workers(n, f)</code> runs <code>f(0)</code>, …, <code>f(n - 1)</code>, which may run concurrently, and answers their results in index order. A compiled build gives each a thread, joined before the call returns; <code>grasm run</code>, and any recorded or replayed run, calls them one after another in index order. <code>f</code> may perform <code>net</code> and nothing else, and may not reach a <code>ref</code> or an actor handle from outside ([T-PAR-MAP-PURE]): workers share the socket table and nothing more, so the only concurrency is the network's, which no program controls anyway. <code>n <= 0</code> answers <code>[]</code>; <code>n > 256</code> panics, as does a panicking worker. A <code>tcp_accept</code> on a listener this thread's last <code>net_wait</code> reported ready does not wait: if another worker took the connection, it is an <code>IoFailed</code>.</p>
<p><strong id="L-LIB-UDP">[L-LIB-UDP]</strong> Four more reach the network as <strong>datagrams</strong>, each performing <code>net</code>:</p>
<div class="scroll"><table><thead><tr><th></th><th>type</th><th></th></tr></thead><tbody><tr><td><code>udp_bind(port)</code></td><td><code>(i64) -> i64 ! IoError</code></td><td>binds a datagram socket; <code>0</code> asks the system to choose</td></tr><tr><td><code>udp_send(h, host, port, b)</code></td><td><code>(i64, str, i64, bytes) -> i64 ! IoError</code></td><td>sends one datagram, answering with the bytes sent</td></tr><tr><td><code>udp_recv(h)</code></td><td><code>(i64) -> bytes ! IoError</code></td><td>receives <strong>one</strong> datagram, whole</td></tr><tr><td><code>udp_recv_from(h)</code></td><td><code>(i64) -> (bytes, str, i64) ! IoError</code></td><td>the same, and where it came from</td></tr></tbody></table></div>
<p>UDP is not TCP with the reliability removed but a different shape. A stream fixes both ends at connect time; a datagram is a <em>whole message</em> with <strong>no fixed peer</strong>, so <code>udp_send</code> names a destination every call and <code>udp_recv_from</code> answers the sender's — a receiver that cannot learn who wrote can only answer peers configured in advance ([L-LIB-PROC] for why a tuple).</p>
<p>Payloads are <code>bytes</code>, not <code>str</code>: the protocols that use UDP are binary, and routing a DNS query's bit-level flags through the lossy UTF-8 conversion the stream operations correctly use for text would corrupt it ([L-LIB-BYTES]).</p>
<p>A read returning half a message, or two joined, would destroy the only thing UDP guarantees. Nothing past 65535 bytes arrives over IPv4 in one piece, so the buffer cannot truncate a deliverable datagram.</p>
<p>Datagram handles share the table with stream handles, so <code>net_wait</code>, <code>net_port</code> and <code>net_close</code> work on all three kinds unchanged. A program that speaks two protocols multiplexes them in one loop, which is the ordinary case rather than an advanced one. Using a stream operation on a datagram handle is an <code>IoFailed</code> naming the operation to use instead.</p>
<p>Closing a handle twice is not an error, for the same reason releasing a <code>ref</code> twice is not ([T-REF-GENERATIONAL]) — cleanup order is not something a caller should have to track. Using a closed handle <em>is</em> an error, and an ordinary one: <code>tcp_read</code> on it answers <code>Err</code>, never a panic and never a wrong answer.</p>
<p><strong><code>net</code> is a capability of its own, not part of <code>io</code>.</strong> That distinction is the whole point. [T-CAPABILITY]'s headline example is a package permitted to read a file and forbidden to open a socket, and until there was a network to gate, that example could not be shown to anybody:</p>
<pre><code>error<span class="op">:</span> package `lib` performs `net` but its manifest only permits `io`
help<span class="op">:</span> either add the capability to that package's manifest<span class="op">,</span> <span class="kw">or</span> stop it from
performing the <span class="kw">effect</span></code></pre>
<p><strong id="L-LIB-BASE">[L-LIB-BASE]</strong> <code>n.to_base(b)</code> writes an integer in base <code>b</code> and <code>s.parse_int_base(b)</code> reads one back. Digits are <code>0-9a-z</code>, lower case, and a negative number gets a leading <code>-</code>.</p>
<p>Base ten is not the only base a systems program needs. Every protocol, hash, colour and permission mask is read and written in hex or binary — the same programs that needed [L-LIB-BITS] — and without these, printing a packet ID the way every other tool prints it means hand-writing a digit table.</p>
<p>A base outside <code>2..36</code> <strong>panics</strong> rather than answering. There is no right answer to return and a wrong one would be silently wrong, which is the same reasoning as <code>code_at</code> panicking out of range.</p>
<p>Neither side writes or accepts a prefix. The base is the argument, not something to be guessed from the text: <code>"ff".parse_int_base(16)</code> is <code>Some(255)</code> and <code>"0xff".parse_int_base(16)</code> is <code>None</code>. That keeps it consistent with <code>parse_int</code>, which refuses <code>0xFF</code> ([L-LIB-PARSE]) — the difference is now that a program can say which base it means instead of being stuck with one.</p>
<p><code>to_base(10)</code> and <code>to_str</code> agree, including at <code>i64::MIN</code>, which is converted through its unsigned magnitude because negating it overflows.</p>
<h2 id="processes-l-lib-proc">Processes — [L-LIB-PROC]</h2>
<p><strong id="L-LIB-PROC">[L-LIB-PROC]</strong> <code>proc_run(program, args)</code> runs another program to completion and answers with <code>(exit code, stdout, stderr)</code>:</p>
<div class="scroll"><table><thead><tr><th></th><th>type</th><th></th></tr></thead><tbody><tr><td><code>proc_run(prog, args)</code></td><td><code>(str, [str]) -> (i64, str, str) ! IoError</code></td><td>performs <code>proc</code></td></tr><tr><td><code>proc_pipeline(stages, input)</code></td><td><code>([(str, [str])], str) -> (i64, str, str) ! IoError</code></td><td>each stage's output feeds the next</td></tr></tbody></table></div>
<p><strong><code>proc</code> is a capability of its own, and it is strictly larger than <code>io</code> or <code>net</code>.</strong> A program that can run <code>curl</code> has the network whether or not it declared <code>net</code>; one that can run <code>rm</code> has the filesystem. Folding process execution into <code>io</code> would make every capability claim in the language weaker than it reads — a package's manifest could say <code>io</code> and mean everything.</p>
<p>The result is a <strong>tuple, not a new type</strong>. Three values with obvious positions did not need a name, and inventing one would have put a type in the prelude that nothing else uses.</p>
<p><strong>Output is captured, not inherited.</strong> A builtin that wrote to the parent's stdout would make the three engines disagree about ordering, because the child's writes and the parent's go through different buffers. A caller that wants the output shown prints it, which also means it can be examined first.</p>
<p><code>args</code> are passed as a list and never through a shell, so a filename containing a space or a <code>;</code> is one argument and not an injection. A program that genuinely wants shell semantics asks for them: <code>proc_run("sh", ["-c", line])</code>.</p>
<p><code>proc_pipeline</code> exists because a pipeline <strong>cannot be built out of <code>proc_run</code></strong>. That waits for a program to finish and hands back its output, and a pipeline needs one child's stdout to <em>be</em> another's stdin. Copying the bytes through Grasm instead would need concurrent reads and writes on pipe handles — a much larger surface for a smaller result, and the kernel already does this.</p>
<p><code>input</code> feeds the first stage's stdin, which is the other thing <code>proc_run</code> could not do: a filter with nothing to filter is not a filter. It is written on a thread, because a large input and a chatty child deadlock if the parent writes everything before it reads anything. An empty input closes stdin rather than leaving it open, so a stage reading to end-of-input does not wait for input that is never coming.</p>
<p>The result is the <strong>last stage's</strong> exit code, stdout and stderr, which is what every shell means by a pipeline's status. An earlier stage's stderr goes to the program's own stderr rather than being discarded: a diagnostic nobody sees is worse than one in the wrong place. If any stage cannot be started, everything already running is killed and the whole call is an <code>IoFailed</code> — a pipeline that failed halfway leaves nothing behind. An empty pipeline is an error, not a silent success.</p>
<p>An exit code of <strong><code>-1</code></strong> means a signal killed the process. No process can exit with <code>-1</code>, so it cannot be confused for a status the program chose. A program that could not be started at all is an <code>IoFailed</code> naming it, which is a different thing from a program that ran and failed.</p>
<h2 id="bit-manipulation-l-lib-bits">Bit manipulation — [L-LIB-BITS]</h2>
<p><strong id="L-LIB-BITS">[L-LIB-BITS]</strong> Seven methods on <code>i64</code>:</p>
<div class="scroll"><table><thead><tr><th></th><th></th><th></th></tr></thead><tbody><tr><td><code>a.bit_and(b)</code></td><td><code>(i64, i64) -> i64</code></td><td>bitwise and</td></tr><tr><td><code>a.bit_or(b)</code></td><td><code>(i64, i64) -> i64</code></td><td>bitwise or</td></tr><tr><td><code>a.bit_xor(b)</code></td><td><code>(i64, i64) -> i64</code></td><td>bitwise exclusive or</td></tr><tr><td><code>a.bit_not()</code></td><td><code>(i64) -> i64</code></td><td>ones' complement</td></tr><tr><td><code>a.shl(n)</code></td><td><code>(i64, i64) -> i64</code></td><td>shift left</td></tr><tr><td><code>a.shr(n)</code></td><td><code>(i64, i64) -> i64</code></td><td>shift right, <strong>sign-preserving</strong></td></tr><tr><td><code>a.ushr(n)</code></td><td><code>(i64, i64) -> i64</code></td><td>shift right, <strong>zero-filling</strong></td></tr></tbody></table></div>
<p><strong>Methods rather than operators</strong>, and the reason is that every symbol is already taken or ambiguous. <code>^</code> is exponentiation. <code>|</code> begins a closure and separates sum-type variants, so <code>a | b</code> cannot be told from the start of one. <code>&&</code> is already reported as "written <code>and</code>". And words would collide with the logical operators, which in this language are <code>and</code>, <code>or</code> and <code>not</code> — so <code>a and b</code> would be boolean and <code>a band b</code> bitwise, one letter apart. Methods are what <code>.abs()</code> and <code>.cmp()</code> already are, and they carry their own precedence.</p>
<p><strong>The shift count is masked to <code>0..63</code>.</strong> <code>1.shl(64)</code> is <code>1</code>, not <code>0</code> and not a trap, and <code>256.shr(-1)</code> is <code>256.shr(63)</code>, which is <code>0</code>. This is what the hardware does, and it is stated because the alternatives are worse: Rust's <code><<</code> panics in a debug build and wraps in a release one, which is the class of difference-between-builds this project refuses to ship, and Cranelift leaves an out-of-range count undefined, which would make the two engines disagree.</p>
<p><code>shr</code> preserves the sign and <code>ushr</code> does not, which is the only reason both exist: <code>(-16).shr(2)</code> is <code>-4</code> and <code>(-16).ushr(60)</code> is <code>15</code>.</p>
<p>There is no unsigned integer type, so a program working in 32 bits masks with <code>0xFFFFFFFF</code> itself. <code>spec/conformance/L-LIB-BITS.gr</code> shows the rotation that SHA-256 needs, written that way.</p>
<h2 id="the-other-stream-l-lib-eprint">The other stream — [L-LIB-EPRINT]</h2>
<p><strong id="L-LIB-EPRINT">[L-LIB-EPRINT]</strong> <code>eprint(v)</code> writes to standard error. It is <code>print</code> in every other respect: same single argument, same interpolation, same refusal to take a fallible value, same <code>io</code> effect.</p>
<p>It exists because a program that cannot separate its diagnostics from its output cannot be used in a pipeline, and being usable in a pipeline is most of what a command-line tool is for. A benchmark's timings, a compiler's warnings and a tool's progress are all diagnostics; sending them to stdout puts them in the middle of the data, which is the one place they cannot be noticed and the one place they do damage. It is the same reason a panic does not go there ([E-PANIC-EXIT]).</p>
<p>Both engines write the two streams independently and identically. The compiled build brackets the write with a flag the runtime reads, rather than carrying a second copy of the formatting code — one code path, so the two streams cannot format differently.</p>
<h2 id="files-and-directories-l-lib-fs">Files and directories — [L-LIB-FS]</h2>
<p><strong id="L-LIB-FS">[L-LIB-FS]</strong> Two additions to the file surface:</p>
<div class="scroll"><table><thead><tr><th></th><th>type</th><th></th></tr></thead><tbody><tr><td><code>make_dir(path)</code></td><td><code>(str) -> () ! IoError</code></td><td>creates the whole path; already existing is success</td></tr><tr><td><code>remove_file(path)</code></td><td><code>(str) -> () ! IoError</code></td><td>deletes; a missing path is <code>NotFound</code></td></tr><tr><td><code>list_dir(path)</code></td><td><code>(str) -> [str] ! IoError</code></td><td>entry names, <strong>sorted</strong></td></tr></tbody></table></div>
<p><code>make_dir</code> creates every missing component and treats an existing directory as success, so a program can prepare its own working directory without first asking whether one is there.</p>
<p>Without these a file could be created and truncated but never removed, a directory could not be read at all, and a program could not make one — so a program that made a temporary file could only empty it, and the next run saw a leftover.</p>
<p><strong><code>list_dir</code> sorts.</strong> A filesystem's own order differs between machines and between runs, and principle 6 makes determinism a feature: an unsorted listing would make any program that printed one untestable, and would break three-engine agreement on the first run. Both engines sort, and identically.</p>
<p>Names are returned, not paths — the caller already knows the directory it asked about, and joining is one concatenation.</p>
<h2 id="bytes-l-lib-bytes">Bytes — [L-LIB-BYTES]</h2>
<p><strong id="L-LIB-RANDOM">[L-LIB-RANDOM]</strong> <code>random_bytes(n)</code> answers <code>n</code> bytes from the operating system's entropy source, and performs <code>io</code>.</p>
<p>It is charged <code>io</code> because it reaches outside the program and two calls do not agree — the same reason the clock is. A pure function that answered differently each time would break every promise an effect row makes.</p>
<p>The primitive is bytes rather than an integer or a float because everything else is built from it and the conversions are where the mistakes are: a number in a range wants rejection sampling, not a modulo, and a language that shipped <code>random_int(lo, hi)</code> with a modulo in it would have shipped a bias.</p>
<p><code>n</code> of zero is an empty answer rather than an error. A negative count, or one past 1048576, is refused — a count is usually something a program computed, and a mistake there should be a refusal rather than a gigabyte.</p>
<p>A short read is a failure, not a short answer: a caller asking for 32 bytes of key material and receiving 12 must not proceed.</p>
<p><strong id="L-BUNDLE-SOURCE">[L-BUNDLE-SOURCE]</strong> A whole program may be written as <strong>one source file</strong>: a <em>source bundle</em>, in which each module is preceded by a line reading <code>//!module <name></code> and the entry module comes first. Nothing is renamed and nothing is rewritten, so a bundle loads exactly the modules the filesystem would have, and a single-module program is a bundle of one.</p>
<p><code>grasm build <file> --source -o <out>.gr</code> writes one. Every command that opens a program opens a bundle, because the detection is in the loader they share.</p>
<p>This exists for embedders that have no filesystem. The wasm engine takes one source string, and an <code>import</code> cannot be resolved by reading a file that is not there — so without this, a program with a single import could not run in a browser however small it was, and almost every real program has one.</p>
<p><strong id="L-LIB-BYTES">[L-LIB-BYTES]</strong> <code>bytes</code> is a contiguous run of bytes, and it is the type <code>str</code> deliberately is not.</p>
<p>A <code>str</code> is <em>text</em>: UTF-8, with anything above 127 re-encoded on the way out — correct for text, fatal otherwise. Asked for the seven bytes of <code>mov rax, 1</code> a <code>str</code> put <strong>nine</strong> on disk, and a language whose only sequence type does that cannot emit an object file.</p>
<div class="scroll"><table><thead><tr><th></th><th>type</th><th></th></tr></thead><tbody><tr><td><code>bytes_of(list)</code></td><td><code>([i64]) -> bytes</code></td><td>every element must be in <code>0..255</code></td></tr><tr><td><code>s.to_bytes()</code></td><td><code>(str) -> bytes</code></td><td>the UTF-8 encoding of the text</td></tr><tr><td><code>b.to_str()</code></td><td><code>(bytes) -> str</code></td><td>lossy, as <code>tcp_read</code> is</td></tr><tr><td><code>b.len()</code></td><td><code>(bytes) -> i64</code></td><td>count of bytes</td></tr><tr><td><code>b.is_empty()</code></td><td><code>(bytes) -> bool</code></td><td></td></tr><tr><td><code>b.at(i)</code></td><td><code>(bytes, i64) -> i64</code></td><td>one byte, <code>0..255</code>; out of range panics</td></tr><tr><td><code>b.slice(from, end)</code></td><td><code>(bytes, i64, i64) -> bytes</code></td><td><code>end</code> exclusive, as <code>list.slice</code>; out of range panics rather than clamping</td></tr><tr><td><code>b.index_of(byte, from)</code></td><td><code>(bytes, i64, i64) -> Option[i64]</code></td><td>first position <code>>= from</code> holding <code>byte</code>; <code>None</code> when absent or <code>byte</code> is outside <code>0..255</code>; <code>from</code> outside <code>0..=len</code> panics</td></tr><tr><td><code>b.concat(other)</code></td><td><code>(bytes, bytes) -> bytes</code></td><td></td></tr><tr><td><code>bytes_filled(n, byte)</code></td><td><code>(i64, i64) -> bytes</code></td><td><code>n</code> copies of <code>byte</code>; a negative <code>n</code>, or a byte outside <code>0..255</code>, panics</td></tr><tr><td><code>b.set(i, byte)</code></td><td><code>(bytes, i64, i64) -> ()</code></td><td>writes one byte; out of range panics</td></tr><tr><td><code>b.fill(byte)</code></td><td><code>(bytes, i64) -> ()</code></td><td>writes every byte</td></tr><tr><td><code>b.copy_from(at, src)</code></td><td><code>(bytes, i64, bytes) -> ()</code></td><td>writes all of <code>src</code> from <code>at</code>; past the end panics</td></tr><tr><td><code>b.to_list()</code></td><td><code>(bytes) -> [i64]</code></td><td></td></tr><tr><td><code>read_bytes(path)</code></td><td><code>(str) -> bytes ! IoError</code></td><td>the whole file</td></tr><tr><td><code>write_bytes(path, b)</code></td><td><code>(str, bytes) -> () ! IoError</code></td><td>replaces it</td></tr><tr><td><code>read_bytes_at(path, off, n)</code></td><td><code>(str, i64, i64) -> bytes ! IoError</code></td><td>a range; short at the end, empty past it</td></tr><tr><td><code>append_bytes(path, b)</code></td><td><code>(str, bytes) -> () ! IoError</code></td><td>adds to the end, creating the file</td></tr><tr><td><code>file_size(path)</code></td><td><code>(str) -> i64 ! IoError</code></td><td>without reading it</td></tr><tr><td><code>sync_file(path)</code></td><td><code>(str) -> () ! IoError</code></td><td>on the disk before answering</td></tr><tr><td><code>rename_file(a, b)</code></td><td><code>(str, str) -> () ! IoError</code></td><td>atomic where the platform allows</td></tr></tbody></table></div>
<p><strong>The last five exist because whole-file calls cannot express data</strong>: a table larger than memory is unreadable, a log rewritten per record is quadratic, and a crash-safe commit is write-beside, <code>sync_file</code>, <code>rename_file</code>.</p>
<p><strong id="L-LIB-BYTES-WRITE">[L-LIB-BYTES-WRITE]</strong> The last four write in place. A write needs a mutable binding and copies the buffer first when another value can see it ([E-COW]), so a <code>slice</code> taken before one is unaffected. <strong>The length never changes</strong>: a <code>bytes</code> may be a window on an allocation <code>slice</code> did not copy. <code>concat</code> grows one.</p>
<p><strong><code>bytes</code> is distinct from <code>[i64]</code> on purpose.</strong> A list of integers cannot promise its elements are bytes, stores eight per element, and cannot be handed to a buffer — the promise is the type. <code>at</code> gives <code>0..255</code>; one integer type is the trade. It <strong>prints as hex</strong>, and <code>to_str</code> is lossy for <code>tcp_read</code>'s reason.</p>
</main>
</div>
<footer class="sitefoot">
<div class="inner">
<div class="cols">
<div class="brandcol">
<a class="brand" href="index.html"><svg viewBox="0 0 48 48" width="20" height="20" fill="none" stroke="currentColor" stroke-width="6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 6H39"/><path d="M24 14A13 13 0 1 0 37 27H26"/></svg><span>Grasm</span></a>
<span>Four engines, one answer.</span>
</div>
<div class="links">
<div><span>Start</span><a href="different.html">Why Grasm</a><a href="start.html">Getting started</a><a href="install.html">Install</a><a href="playground.html">Playground</a></div>
<div><span>Learn</span><a href="tutorial.html">Tutorial</a><a href="tour.html">Tour</a><a href="effects.html">Effects</a><a href="tiers.html">Ownership</a><a href="errors.html">Errors</a><a href="concurrency.html">Concurrency</a><a href="security.html">Security</a></div>
<div><span>Reference</span><a href="syntax.html">Syntax</a><a href="language.html">Language</a><a href="library.html">Library</a><a href="packages.html">Packages</a><a href="spec.html">Specification</a><a href="architecture.html">Architecture</a></div>
<div><span>More</span><a href="examples.html">Examples</a><a href="achieved.html">Scorecard</a><a href="performance.html">Performance</a><a href="about.html">About</a><a href="status.html">Status</a><a href="roadmap.html">Roadmap</a></div>
</div>
</div>
<p>Counts here are computed from the repository as the page is written;
measurements are read from the document that recorded them.</p>
</div>
</footer>
</body></html>