raz / commit 3282a9a1

commit
3282a9a1c6922e90c4081a282b1c3860e91d3aad
author
Luis <42945842+ldiaz94@users.noreply.github.com>
date
parent
a5145f64
PROPOSALS.md and MEM_PROPOSAL.md gone: the Moss work's four proposals kept in PLAN.md's appendix

patch · log

8 files changed, +373 -7189

CLAUDE.md modified +15 -14

@@ -3,8 +3,8 @@
33 Read `doc/raz.md` (the language report, volume 1) and
44 `doc/compiler.md` (the guide to the compiler) first; `doc/raz-lib.md`
55 is volume 2, the library, `doc/report-history.md` what each version of
6-the report changed, and `PROPOSALS.md` what waits for a thaw. The
7-report defines the language.
6+the report changed, and `PLAN.md` what is left before 1.0. The report
7+defines the language.
88
99 ## Setup and checks
1010
@@ -103,7 +103,7 @@
103103 built-ins, what `SYSTEM` fences without it, an atomic given `ADR(x)`.
104104 `BOOT` names v0.23.0 (2026-10-26), so `src/` and the library it imports
105105 may use all of 10.37. CI couldn't run for it either; `make dist` made its tarball here.
106-v0.22.0, report 2026-10.36, before it, is the twelfth thaw, what `PROPOSALS.md`
106+v0.22.0, report 2026-10.36, before it, is the twelfth thaw, what the proposals
107107 collated: `MIN`, `MAX`, `ABS`, `CLZ`, `CTZ`, `POPCOUNT`, `INT(b)`,
108108 `OFFSET`, `SIZE(T.f)`, `BYTES` and `FILL`; a qualified case in an arm,
109109 slice and `ERROR` constants, a record's procedure field that takes the
@@ -120,7 +120,7 @@
120120 or the top 2 GB; `raz -bare` makes a program for the bare machine, which
121121 reads no arguments and runs no body of `Rt`; `BOOT` named v0.20.0, and
122122 `Sys` takes `PTR` where it had its private `bytes`. `MEM_PROPOSAL.md`
123-proposes a memory-safe raz, for a thaw.
123+proposed a memory-safe raz (the safety thaw took part of it).
124124 v0.20.0, report 2026-10.34, before it: v0.19.0 builds `src/` and the
125125 Pascal seed is gone; `Buf.bytes`, `Sys.entryKind` and `src/`'s `Item`s
126126 only read take `const`; and the tenth thaw, by the owner's word,
@@ -159,16 +159,17 @@
159159 for it. Thaws happen only by the owner's word (v0.6.0, reports
160160 2026-10.13 to 10.23, 10.25 for strings, 10.26 for `INT` and views, 10.33
161161 for `const` parameters, variants in constants and the library by `var`,
162-10.34 for `PTR`, and 10.35 and 10.36 for what `PROPOSALS.md` collated).
162+10.34 for `PTR`, and 10.35 and 10.36 for what the proposals collated).
163163
164164 **The hard freeze** (owner, 2026-10-23). raz takes no more proposals:
165-nothing new goes in `PROPOSALS.md`, and a wish, the owner's or yours,
166-isn't recorded. What is open there, the safety thaw and the Moss work
167-(`Host`, a freestanding program stated, the assembler's instructions,
168-implementation limits), is the last. `PLAN.md` gives the order: v0.22.0 for what is
169-done, the safety thaw, the Moss work, the hard freeze, a clean-up, then
170-1.0 when use shows it. Once it is done the language is in
171-a hard freeze: no more thaws. The language changes only to mend a
165+a wish, the owner's or yours, isn't recorded. `PROPOSALS.md` and
166+`MEM_PROPOSAL.md` are gone (2026-10-26; in git before). What was left
167+open, the safety thaw (done, v0.24.0) and the Moss work (`Host`, a
168+freestanding program stated, the assembler's instructions,
169+implementation limits, in `PLAN.md`'s appendix), is the last. `PLAN.md`
170+gives the order: v0.22.0 for what is done, the safety thaw, the Moss
171+work, the hard freeze, a clean-up, then 1.0 when use shows it. Once it
172+is done the language is in a hard freeze: no more thaws. The language changes only to mend a
172173 defect, the compiler or the library doing other than the report says;
173174 the library's core (appendix A) only to mend a defect or to plug a very
174175 big gap; and the rest of the library grows only conservatively, by what
@@ -312,8 +313,8 @@
312313 - A returned slice of the frame (report 2026-10.27, 7.3) is caught by
313314 `Item.frame`, which sees only the expression: a slice held first in a
314315 local slice variable or a record, stored, or come back from a call,
315- isn't, and is left undefined (10). `ret` and `keep`, in
316- PROPOSALS.md, would close it; the owner keeps it open for now.
316+ isn't, and is left undefined (10). `ret` and `keep`, once
317+ proposed, would close it; the owner keeps it open for now.
317318 - An empty slice constant, `const E: []T = [];` (report 2026-10.32),
318319 is 16 zero bytes in read-only data, read as an array constant is;
319320 `LEN` of it is no constant. A constant's slice part takes `[]`, names

HANDOVER.md modified +2 -2

@@ -53,5 +53,5 @@
5353
5454 ## What comes next
5555
56-Not started; each the owner's call. `PROPOSALS.md` and
57-`MEM_PROPOSAL.md` hold what waits for a later thaw.
56+Not started; each the owner's call. `PLAN.md` says what is left before
57+1.0.

MEM_PROPOSAL.md deleted +0 -4170

@@ -1,4170 +0,0 @@
1-# MEM_PROPOSAL: a memory-safe raz
2-
3-**Status.** A proposal, drafted 2026-10-17. Reviewed whole by the owner on 2026-10-26: `PLAN.md` §2 says what goes in (F.1, `[]const T`, G, E.4, `Task`, `Guarded`, the fence as `import SYSTEM`) and what is left out (B, C, D, the rest of E).
4-Nothing in it is built. Four adversarial reviews, made the same day,
5-are appendices 4 to 7. They find real holes in the guarantee
6-(appendix 4), wrong and imprecise claims about other languages and
7-hardware (5), wrong counts and unsupported benchmark conclusions (6),
8-and pain in real code that sections 14 and 15 understate (7). The body
9-below is as first drafted; where an appendix contradicts it, the
10-appendix stands until the body is revised. It assumes that anything may change: the
11-language, the library, the compiler, and the programs written for
12-them. It builds on two entries of `PROPOSALS.md`, "Less that is
13-undefined" and part 3 of "What a call does with its arguments" (`ret`
14-and `keep`), and goes further than either: it puts them together into
15-one promise, closes the holes they leave open, and counts the cost.
16-
17-**In one paragraph.** Raz checks where memory is (an index against a
18-length, `nil`, zeroed variables) but not when it is still there, and
19-anything that can break memory may stand in any module. This proposal
20-splits modules in two. An `unsafe;` module may do what raz allows today.
21-Every other module is safe: the compiler holds it to rules under which
22-it can't read or write memory that isn't a live variable of the right
23-type. The rules are four:
24-
25-1. Pointer arithmetic, casts, `ADR`, C and code procedures go behind
26- `unsafe;`.
27-2. A slice or pointer *lent* by a variable can't outlive that
28- variable. Most of this is checked when compiling, and it takes
29- PROPOSALS' `ret` and `keep`.
30-3. A container that hands out slices of its memory *counts* them,
31- and won't free a block while one is held.
32-4. Safe code doesn't free heap memory by hand. It keeps that memory
33- for the life of the program, or holds it in a container or a
34- `Pool` that frees it.
35-
36-The library's own unsafe modules are trusted to keep the promise, as
37-a safe program is trusted to keep its logic. The cost, measured below:
38-
39-- **Programs:** nothing for code that keeps to slices and records. 1.5
40- to 2 times for chasing a linked structure through checked handles
41- instead of raw pointers, where a program chooses handles.
42-- **Compiler:** about 5% more instructions, if its scanner checks its
43- buffer instead of reading it through a pointer.
44-- **Ergonomics:** a record can't keep a slice into a buffer that
45- belongs to someone else.
46-
47----
48-
49-## Contents
50-
51-1. Motivation
52-2. What the code we have does: a survey
53-3. The guarantee
54-4. The design, in brief
55-5. Part A: the fence, `unsafe;`
56-6. Part B: lending, `ret` and `keep`
57-7. Part C: owners that count what they lend
58-8. Part D: the heap without `free`
59-9. Part E: threads
60-10. Part F: the small mends
61-11. Part G: a debugging heap
62-12. Raz beside other languages
63-13. Performance
64-14. Ergonomics
65-15. What breaks
66-16. Changes to the report
67-17. Changes to the library
68-18. Changes to the compiler
69-19. Alternatives considered
70-20. Order of work
71-21. Open questions
72-- Appendix 1: the survey's numbers
73-- Appendix 2: the benchmarks
74-- Appendix 3: the five programs of section 1
75-- Appendix 4: adversarial review, soundness
76-- Appendix 5: adversarial review, claims about other languages and hardware
77-- Appendix 6: adversarial review, the proposal's numbers and samples
78-- Appendix 7: adversarial review, porting real code
79-
80----
81-
82-## 1. Motivation
83-
84-### 1.1 What raz promises today
85-
86-| Check | Today |
87-|---|---|
88-| Index and slice bounds | checked, unless `check off;` |
89-| `nil` dereference, `nil` procedure | stops the program |
90-| Division by zero, `low / -1` | stops the program |
91-| Stack overflow | stops the program |
92-| Variables start at zero | always |
93-| Integer overflow | wraps, defined |
94-| A variant's fields read only through `match` | always |
95-| A view's bytes stay inside its variable | checked |
96-| Integer to enumeration conversion | checked |
97-| A slice returned from its own frame | an error, but only for a direct `return` (7.3) |
98-| Use after free, after `Arena.reset`, after a `Vec` grows | nothing |
99-| A slice kept past its frame by any other route | nothing |
100-| A slice of a call's array kept past its statement | nothing |
101-| Pointer arithmetic, `p[i]` | unchecked, anywhere |
102-| Integer to pointer, pointer to pointer | allowed, anywhere |
103-| `ADR` of a local, kept | allowed, anywhere |
104-| C, code procedures, `SYSCALL` | allowed, anywhere |
105-| A race tearing a slice or a variant | the report says nothing becomes undefined (7.6); it does |
106-
107-This is close to Oberon's or Pascal's promise, without a garbage
108-collector behind it. Spatial safety (indexes, lengths, `nil`) is
109-mostly there. Temporal safety (whether memory is still there) isn't
110-there at all. Nothing marks the code that can break memory, so any
111-module may.
112-
113-### 1.2 Five programs that compile with no warning
114-
115-Each is complete, compiled by today's compiler with no warning, and run.
116-The full texts are in appendix 3.
117-
118-**Appending a buffer to itself.**
119-
120-```
121-Buf.init(b, Heap.heap);
122-for i := 1 to 64 do Buf.add(b, 'a'); end; (* full: 64 of 64 *)
123-Buf.str(b, Buf.bytes(b)); (* doubles it, or should *)
124-```
125-
126-`Buf.str` grows `b` first: it allocates a new block, copies the bytes
127-and frees the old block. It then copies from `s`, which still points at
128-the old block. It prints 24 `a`s, as it should, because the heap didn't
129-reuse the freed block in time. With another allocator, or another
130-thread using the heap, it prints garbage. Nothing tells the programmer
131-that this line is wrong. A test passes.
132-
133-**A slice kept across a `Vec`'s growth.**
134-
135-```
136-first := Vec.all(v); (* good until v next grows *)
137-p := Vec.add(v); (* grows: first now points at freed memory *)
138-...
139-p^ := -1; (* after another growth: writes into a block the heap took back *)
140-Out.int(first[0]); (* prints 1, as if nothing were wrong *)
141-```
142-
143-The library's comments say "good until the array next grows". The
144-compiler doesn't know that comment.
145-
146-**A slice of the frame, through a call.**
147-
148-```
149-proc head(var h: Hex): []U8; begin return h[0..8]; end; (* allowed *)
150-proc short: []U8; var h: Hex;
151-begin ... return head(h); end; (* not caught *)
152-```
153-
154-The caller prints `########`, the bytes the next call left in the dead
155-frame. 7.3 catches `return h[0..8]` in `short` but not the same slice
156-handed back through `head`.
157-
158-**A map keeping a slice of a frame.**
159-
160-```
161-proc remember(n: INT);
162-var buf: [8]U8;
163-begin
164- buf := "name-000"; buf[7] := U8('0' + n);
165- _ := Names.put(table, buf[0..8], n); (* the map keeps a slice of this frame *)
166-end;
167-```
168-
169-After `remember(1); remember(2);` both `name-001` and `name-002` are
170-"missing": the map's keys point at a frame that is gone. Every caller
171-of `Map([]U8, ...).put` must know, from the documentation alone, that
172-the key is kept.
173-
174-**A slice of a call's array, kept.**
175-
176-```
177-a := named('a')[0..8];
178-b := named('b')[0..8];
179-Out.str(a); Out.str(" "); Out.str(b);
180-```
181-
182-It prints `name-..b ^A^@^@^@^@^@^@^@`. Both arrays used the same
183-temporary, so `a` shows `b`'s bytes and `b` shows whatever came after.
184-Section 8 says this is undefined, and nothing catches it.
185-
186-None of these is exotic. Three are what the library's own
187-documentation warns of; two are what 7.3 and 8 warn of. Each runs to
188-the end with status 0.
189-
190-### 1.3 Why it matters for raz in particular
191-
192-- **Raz's audience.** CLAUDE.md asks that the compiler be "a model of
193- plain code that a beginner can follow". A beginner can't follow a
194- rule that lives only in a comment ("good until it next grows"). A
195- language that checks every index and then lets a slice outlive its
196- buffer teaches a false sense of safety: the checks cover the easy
197- half.
198-- **Undefined behaviour passes tests.** In four of the five programs
199- above the output is plausible, or right. The heap's free lists keep
200- freed bytes for a while; a dead frame keeps its bytes until the
201- next call. A program can carry such a bug for years.
202-- **No fence means no audit.** Today, to know whether a program can
203- corrupt memory, you read all of it. With a fence, you read the
204- modules that say `unsafe;`, and `grep` finds them. The survey
205- (section 2) shows how few modules would need to say it.
206-- **The library is growing.** Each container added (`Vec`, `Map`, `Buf`,
207- `List`, and `Svec` in sauce) adds rules of the "good until" kind. Those
208- rules should be the compiler's to check.
209-- **Threads.** `Thread` and `Lock` are in the library, and rnet and
210- rsqlite use them. A race on a slice reaches any memory today, though
211- 7.6 promises it can't.
212-
213----
214-
215-## 2. What the code we have does: a survey
216-
217-### 2.1 How it was measured
218-
219-For an exact count, not an estimate from `grep`, the compiler itself
220-was changed in a scratch copy. It printed one line for each operation
221-this proposal would fence, where it compiled one: a pointer indexed or
222-sliced, pointer arithmetic, a conversion to or from a pointer, `ADR`,
223-`PTR`, `SYSCALL`, a view, `NEW` and every dereference. Each program
224-and each library module's test was compiled with it. The places are
225-counted once each, whatever number of programs compiled them. The
226-hooks stand where most of the fence's checks would go (section 18).
227-
228-Code surveyed:
229-
230-| Code | Version | Lines | How |
231-|---|---|---|---|
232-| raz `src/` (the compiler) | main | 14,323 | compiler-counted |
233-| raz `lib/` | main | 10,291 | compiler-counted |
234-| raz `tools/`, `examples/`, `test/libc` | main | 2,207+ | compiler-counted |
235-| rnet (HTTP, DNS, TLS seams) | raz 0.15.0 | 5,111 | compiler-counted, with 0.15.0's `lib/` |
236-| rjson | raz 0.15.0 | 1,882 | compiler-counted, with 0.15.0's `lib/` |
237-| rflate (inflate) | raz 0.15.0 | 1,319 | compiler-counted, with 0.15.0's `lib/` |
238-| rsqlite (SQLite over C) | raz 0.18.0 | 705 | compiler-counted, with 0.18.0's `lib/` |
239-| rterm | raz 0.15.0 | 101 | compiler-counted |
240-| rmacs (an editor, archived) | raz v0.5.0+7 | 4,932 | `grep`: written before `INT`, today's compiler refuses it |
241-| ravite (an editor) | raz v0.5.0+7 | 2,460 | `grep`, as rmacs |
242-| rlX11 (X11 over a socket) | raz v0.3.0+52 | 7,026 | `grep`, as rmacs |
243-
244-About 50,000 lines in all. Code written for an older raz was compiled
245-by today's compiler against the library of the version it was written
246-for. The full tables are in appendix 1.
247-
248-### 2.2 What it found
249-
250-**Nobody uses `check off;`.** Not one module in 50,000 lines. Bounds
251-checks are cheap enough that no one has wanted them off.
252-
253-**Almost every `ADR` is an argument to the library.** Of rnet's 572
254-`ADR`s, 571 are arguments, and so are 556 of rmacs's 560 and all 77 of
255-rjson's. They are the library's old pointer parameters, which report
256-2026-10.33 made `var` and `const`; code written for v0.19.0 and later
257-has lost them already. `src/`, which has been ported, keeps 27, and
258-none of them needs to be an `ADR`:
259-
260-| What `src/` does with `ADR` and pointer casts | Sites | The safe form |
261-|---|---|---|
262-| a grown array: `^Chunk(Scan.regrab(^U8(chunks), ...))` | 35 | `Vec(Chunk)`, or a slice and `Mem`'s growth, in one trusted module |
263-| a real's bits: `p := ^F64(ADR(x.val))` | 6 | a view, `x.val.(F64)`, safe today |
264-| a slice passed as two words: `Scan.intern(ADR(s[0]), LEN(s))` | 7 | `Scan.intern(s)`: a slice parameter |
265-| out-parameters: `isReg(w, ADR(r), ADR(size))` | 5 | `var r, size` |
266-| a pointer to a local record: `curLoop := ADR(lp)` | 1 | a field index, or `var` |
267-| `SYSCALL(4, ...)`: `stat` | 1 | `Sys.info` |
268-
269-**Pointer indexing is buffers.** `src/` indexes a pointer 277 times
270-and slices one 30 times, nearly all in six modules: `Scan` (76), `Link`
271-(63), `Chunk` (53), `X64` (23), `Elf` (17) and `Diag` (15). Each keeps
272-a byte or record buffer that it grows by hand: `text[pc + i] := ...`,
273-`lp[lpLen] := ...`, `buf[at + i] := ...`. That is `Vec` and `Buf`
274-written out again, for speed, without checks. The scanner reads its
275-source through `buf: ^U8`, past the end to a sentinel zero.
276-
277-**Dereferences are everywhere and harmless.** 1,015 in `src/` (`Parse`
278-517, `Item` 256, `Sym` 106): `o^.typ`, `t^.base`. Every one is a pointer
279-from `NEW` on the heap, which the compiler never frees. Under part D
280-they stay as they are, unchecked and free of cost.
281-
282-**The library is where the unsafe code is.** `Sys` (287 operations,
283-129 of them `SYSCALL`), `Rt` (111), `Thread` (33), `Heap` (16) and `Map`
284-(19). It is the code that should be trusted and read twice. `Math`,
285-`Out`, `Sort` and `Width` have none; `Str`, `Fmt`, `Opt`, `Files` and
286-`Lock` have two to five each, all of them avoidable.
287-
288-**Slices held from containers.** 35 places assign `Buf.bytes`,
289-`Vec.all` or `Windows.all` to a variable and use it over several
290-statements; the rest pass it straight on. Some places store one in a
291-record:
292-
293-```
294-m^.body := Buf.bytes(ADR(m^.data)); (* rnet Http.readWhole *)
295-m^.headers[m^.n] := {name: l[0..colon], value: trim(...)}; (* l is a slice of m^.head's bytes *)
296-res^.body := Buf.bytes(ADR(text)); (* rnet's test server: a module Buf, reset per request *)
297-```
298-
299-`Http.Message` holds slices into two buffers of its own. It is right,
300-as long as nobody grows `m^.head` after the headers are read and
301-nobody uses the headers after `Http.done`. The compiler knows neither
302-condition. Section 14 shows what this pattern costs under the
303-proposal.
304-
305-**Records that hold slices** (each one is a place where something must
306-decide how long the slice lives): `src/` 10, `lib/` 22, rnet 12, rjson 8,
307-ravite 5, rmacs 4, `tools/` 4, rlX11 3, rflate 2, rsqlite 1.
308-
309-**Threads are rare.** Two of the eight other repositories spawn
310-threads (rnet's server, rsqlite's test). `src/`, the tools and the
311-editors have none.
312-
313-**Freeing is rare too.** `Mem.free`, `Heap`'s `free` or `Str.free` by
314-hand: `src/` 7 (all in grown arrays), rmacs 9, rjson 6, ravite 2,
315-rlX11 1, rnet, rflate and rsqlite 0. Programs free memory through
316-`done` on a container (rnet 30, rmacs 16) far more than by hand: 54
317-`done`s to 26 frees, outside the library.
318-
319-### 2.3 What the survey says about the design
320-
321-1. A fence costs little. Outside the library and the compiler's
322- buffers, the operations it fences are almost all `ADR`s that the
323- v0.19.0 library already removed. In `src/`, the fenced
324- operations are buffers and small habits, each with a safe form.
325-2. Leaving pointers unchecked costs nothing as long as nothing frees
326- them. The compiler's 1,015 dereferences are of heap memory that
327- lives as long as the program. Making `free` unsafe, and giving
328- containers the job of freeing (part D), keeps those dereferences
329- free of cost.
330-3. The hard case is a slice of a container's memory held while the
331- container changes. It is found in rmacs, ravite, rnet and the
332- library itself (`Fmt`, `Opt`), and nothing today checks it. Part C
333- is aimed at it.
334-4. Threads can wait for a weaker rule than Rust's (part E), since few
335- programs use them.
336-
337----
338-
339-## 3. The guarantee
340-
341-The proposal puts one paragraph into section 10 of the report, in
342-place of today's list of what isn't defined:
343-
344-> **The guarantee.** A program is *safe* if none of its modules says
345-> `unsafe;`, the library's aside, and its threads race (7.6) only on
346-> variables of a basic, pointer, procedure or slice type. A safe
347-> program reads and writes only variables that exist, each as a value
348-> of its own type, and calls only procedures. It does what this report
349-> says, or stops with status 2 and says where and why. The library's
350-> unsafe modules are trusted to keep this promise for every use a safe
351-> program can make of what they export.
352-
353-What the guarantee covers:
354-
355-- **Spatial:** no read or write outside a variable: indexes and views
356- checked, as now; pointers in safe code made only by `NEW` and by the
357- library, never by arithmetic or conversion.
358-- **Temporal:** no read or write of memory that has been freed or
359- reused: slices and pointers lent by a frame or a container can't
360- outlive it (B, C); the heap is never freed under a pointer safe code
361- holds (D).
362-- **Type:** no value read as another type: views of pointers and
363- conversions to pointers fenced; variants only through `match`; enums
364- and `BOOL` only from their values.
365-- **Initialization:** as now, every variable starts at zero.
366-- **Races:** within the bounds above (part E).
367-
368-What it doesn't cover, on purpose:
369-
370-- **Leaks.** A safe program may keep memory it no longer needs, as a
371- garbage-collected one may.
372-- **Running out of memory or stack.** These stop the program, as now.
373-- **Logic.** A stale handle into a `Pool` stops the program; it doesn't
374- fix the bug. A slice of a buffer that was cleared shows the buffer's
375- new contents, safely.
376-- **Deadlock**, and a race on a whole record, variant or container.
377- The second is undefined, as in Go, and part E says why.
378-- **The unsafe modules themselves.** They are trusted, as `unsafe`
379- code is in Rust and `UNSAFE MODULE`s are in Modula-3.
380-
381-The guarantee is stated once and is the same on every target.
382-Appendix A keeps only how it is carried out: whether the machine or
383-the code catches a fault, and how a slice is read in one access.
384-
385----
386-
387-## 4. The design, in brief
388-
389-| Part | What it does | Checked | Cost at run time |
390-|---|---|---|---|
391-| A. The fence | `unsafe;` modules alone may use `ADR`, pointer arithmetic and indexing, casts, views of pointers, `check off`, `extern`, `link`, code procedures, `SYSCALL`, `PTR`, or call an `unsafe proc` | compiling | none |
392-| B. Lending | every slice or pointer is *lasting* or *lent* by a variable of the procedure; a lent one can't be stored where it outlives its lender, nor returned unless the heading says `ret`; `keep` parameters take only lasting ones | compiling, one pass | none |
393-| C. Owners | a record with a `LENDS` field is an *owner*; what it lends is counted while a local holds it; an owner doesn't free a block while its count is above zero, and `done` with the count above zero stops; owners aren't copied | compiling, and a count at run time | an add and a subtract per lend held |
394-| D. The heap | `free` is unsafe; `NEW` gives memory that lasts; a `Pool(T)` holds what must be freed, by checked handles; containers own and free their memory | compiling, and checks in `Pool` | none, or a compare per `Pool` access |
395-| E. Threads | slices read and written in one access; containers and variants shared only under a lock, or the guarantee doesn't hold; `Task(T)` spawns safely; atomics take variables | partly | none on x86-64 with AVX |
396-| F. Small mends | an array a call returns lives to the end of its procedure; writing a string's bytes stops or changes them | compiling | a larger frame |
397-| G. Debugging | `Heap` in a mode that poisons and holds back freed blocks | at run time, when chosen | when chosen |
398-
399-A program that is safe today, which is to say every program that
400-keeps to slices, records and the library, mostly stays as it is. Section 15 counts
401-what breaks.
402-
403----
404-
405-## 5. Part A: the fence, `unsafe;`
406-
407-### 5.1 The rule
408-
409-A module that says `unsafe;`, after its imports, links and `check`
410-line, may do everything raz allows today. A module that doesn't is
411-*safe*, and it is an error for it to do any of the following:
412-
413-| Operation | Why it's fenced |
414-|---|---|
415-| `ADR(x)` | a pointer to anything, a local included, that outlives nothing |
416-| `p + i`, `p - i`, `p[i]`, `p[lo..hi]` on a pointer | no length to check against |
417-| a conversion to a pointer or procedure type, from an integer or another pointer or procedure type | makes a pointer to anything, of any type |
418-| a conversion from a pointer or procedure to an integer | not unsafe in itself, but needed only by unsafe code; fenced so `grep unsafe` finds address games |
419-| `PTR(s)` | the first word of a slice, unchecked |
420-| a view `v.(T)` whose `T` holds a pointer, procedure or slice | makes one from bytes |
421-| writing through a view of a variable that holds a pointer, procedure, slice, variant, enumeration or `BOOL` | changes those bytes behind their type |
422-| `check off;` | indexes unchecked |
423-| `extern`, `link` | C can do anything |
424-| a code procedure, `SYSCALL` | the machine can do anything |
425-| `ARGV()` | a `^^U8` from C; `Files.arg` gives a slice |
426-| a call of an `unsafe proc`, or of a value of an `unsafe proc` type | the procedure says it can break the promise |
427-
428-What stays safe, though it involves pointers: `p^`, `p^.f`, `p^[i]` (an
429-array through a pointer is indexed and checked), `nil`, comparing
430-pointers, `p - q` (an integer), `NEW`, and passing and storing a
431-pointer as any value. A pointer in safe code is only ever `nil`, from
432-`NEW`, or handed out by the library. Part B says how long each one
433-lives.
434-
435-The message names the mending:
436-
437-```
438-Window.raz:41:13: error: ADR is for unsafe modules
439- 41 | XNextEvent(dpy, ADR(ev));
440- | ^^^^^^^
441- help: say "unsafe;" after the module's imports, or pass ev as a var
442-```
443-
444-### 5.2 Unsafe procedures
445-
446-Some of the library's procedures can break the promise whatever safe
447-code does: `Mem.free`, `Heap`'s `free`, `Str.free`, `Sys.mmap`,
448-`Sys.munmap`, `Thread.spawn` with its `^U8`. They are declared
449-
450-```
451-unsafe proc free*(a: ^Allocator; p: ^U8);
452-```
453-
454-and only an unsafe module may call one. A procedure type may say
455-`unsafe proc(...)`; a value of that type may be called only from an
456-unsafe module, and a safe procedure may stand where an unsafe type is
457-wanted, not the other way. `Mem.Allocator`'s two fields are of unsafe
458-types: safe code may pass an allocator to the library but can't call
459-it.
460-
461-`unsafe`, like `static` in `link static;`, is a word only where it
462-stands: before `proc`, and as the module's line. Elsewhere it is a
463-name.
464-
465-### 5.3 The trust
466-
467-A safe module may import an unsafe one. What the unsafe module
468-exports, other than its `unsafe proc`s, it promises safe to use: for
469-any arguments a safe module can make, its procedures keep the
470-guarantee. This is Modula-3's rule for an `UNSAFE MODULE` that
471-implements a safe `INTERFACE`, and Rust's for a safe function built
472-on `unsafe` blocks. What the promise demands of an unsafe module, in
473-the report (section 16):
474-
475-1. What it returns as lasting (part B) lasts: its memory is never
476- freed or reused while the program runs.
477-2. What it returns through `ret` lives no longer than the argument it
478- says. If the argument is an owner, the module doesn't free memory
479- it lent while the owner's `LENDS` count is above zero (part C).
480-3. What it keeps (`keep` parameters) it may hold for as long as it
481- likes; what it doesn't mark `keep`, it doesn't hold past the call.
482-4. Its exported types hide whatever a safe module could misuse: a
483- container's pointer fields aren't exported.
484-5. Its procedures given to other threads, or shared by them, are safe
485- to call from several threads at once, or say otherwise.
486-
487-So `grep -l '^unsafe;'` lists every module whose bugs could corrupt
488-memory, and the library's are among them, as they are today.
489-
490-### 5.4 Which modules would say it
491-
492-From the survey, as the code stands:
493-
494-- **The library:** `Rt`, `Mem`, `Heap`, `Arena`, `Bytes`, `Sys`,
495- `Thread`, `Lock`, `C`, `CAbi`, and the containers `Buf`, `Vec`, `Map`,
496- `List`, which hold raw blocks and grow them. `Str`, `Fmt`, `Opt` and
497- `Files` can drop their two to five fenced operations and be safe.
498- `Math`, `Out`, `Sort` and `Width` are safe already.
499-- **`src/`:** all eleven modules today. Mended as section 2.2's
500- table says, with the six buffer modules' grown arrays made `Vec`s or
501- slices, `src/` keeps one unsafe module: `Scan`, for its allocator
502- (`grab`) and, if it keeps it, the pointer through its source buffer.
503- `Elf` writes the executable through `Sys.write` and needs none.
504-- **`examples/`:** `Args` (it reads `ARGV()`, which `Files.arg` does
505- for it), `Cpu` (a code procedure), `Pthreads`, `Printf`, `Window`
506- (C), `Volatile` (a device's address), `Sh` and `Workers` (`ADR` at
507- calls: mended by `var`). Five stay unsafe (`Cpu`, `Pthreads`,
508- `Printf`, `Window`, `Volatile`), as an example of each kind of
509- unsafety should be.
510-- **Elsewhere:** rsqlite's `Sqlite` (C); rlX11's three casts look like
511- work for views; rnet needs it only to keep `Http.Message` as it is
512- (section 14).
513-
514----
515-
516-## 6. Part B: lending, `ret` and `keep`
517-
518-Part B is PROPOSALS' part 3 (`ret`, `keep`) with two changes. Pointers
519-are followed, not only slices, and a third kind of lender, the owner,
520-comes from part C. What is said there of "frame-bound", "outliving the
521-call" and the checks stands. This section gives the rules in the
522-terms the guarantee needs.
523-
524-### 6.1 Lasting and lent
525-
526-Every value that holds a slice or a pointer (a *reference*) is, for
527-the compiler, either:
528-
529-- **lasting:** it points at memory that lives to the end of the
530- program: `nil`, `[]`, a string constant, a module variable or a part
531- of one, memory from `NEW` on the heap (part D), and what the library
532- returns as lasting (a result with no `ret` parameter);
533-- **lent** by one or more *lenders* of the procedure it is in:
534- - **the frame**: a slice of a local array, of a value parameter's
535- array, or of an array literal; an array a call returned (part F);
536- - **a parameter `p`**: a slice parameter's value, what a `var` or
537- `const` parameter's arrays hold or its references point at; and
538- the parameter's own variable, for `var` and `const`;
539- - **an owner `o`** (part C): what `o` lent through a `ret`.
540-
541-A value made from others is lent by every lender of its parts: a slice,
542-a field, an element of `x`; a record, variant or array literal of
543-parts; a call's result, from its arguments for `ret` parameters. A
544-local variable holding references is lent by everything assigned to
545-it anywhere in its procedure. That is PROPOSALS' rule, and the reason
546-some checks wait for the procedure's `end`.
547-
548-### 6.2 What may be done with a lent reference
549-
550-A lent reference may be:
551-
552-- read, indexed, sliced, compared, and passed to any parameter not
553- marked `keep`;
554-- held in a local variable, or in a field or element of one (owner-lent
555- values only in a local of slice or pointer type: see 7.3);
556-- returned, if each of its lenders is a parameter marked `ret`.
557-
558-It may not be:
559-
560-- stored in a module variable, through a pointer (`p^.f := s`), or into
561- a `var` parameter or part of one;
562-- given to a `keep` parameter;
563-- returned while lent by the frame, an owner, or a parameter not
564- marked `ret`;
565-- given to `Task.spawn` (part E).
566-
567-The rules are PROPOSALS' checks 1 to 3, with "frame-bound" read as
568-"lent". Every check needs only the procedure in hand and the headings
569-of what it calls, so a one-pass compiler can make it: the checks on a
570-local wait for the procedure's `end`, as PROPOSALS describes.
571-
572-### 6.3 Marks
573-
574-```
575-proc trim*(ret s: []U8): []U8; (* the result may point where s does *)
576-proc bytes*(ret const b: Buf): []U8; (* the result is lent by b, an owner *)
577-proc put*(var m: Map; keep k: K; keep v: V): BOOL; (* k and v must last *)
578-```
579-
580-`ret` and `keep` stand before `var` or `const`, and are words only
581-there. A mark that lends nothing (`keep n: INT`) is allowed, so a
582-generic module can mark `keep v: T` for every `T`. PROPOSALS covers
583-procedure values, generics, `extern` (no marks; unsafe anyway) and
584-code procedures (trusted; unsafe anyway).
585-
586-Marks at the call (PROPOSALS' part 1) are not part of this proposal:
587-the checks hold whether or not the call repeats them.
588-
589-### 6.4 Examples
590-
591-```
592-proc greet: []U8;
593-var line: [80]U8; n: INT;
594-begin
595- n := Sys.read(Sys.stdin, line);
596- Out.str(Str.trim(line[0..n])); (* fine: lent by the frame, used here *)
597- return Str.trim(line[0..n]); (* error: lent by the frame *)
598-end;
599-
600-proc first(ret s: []U8): []U8;
601-begin
602- return s[0..1]; (* fine: s is ret *)
603-end;
604-
605-proc remember(n: INT);
606-var buf: [8]U8; k: []U8; ok: BOOL;
607-begin
608- buf := "name-000"; buf[7] := U8('0' + n);
609- _ := Names.put(table, buf[0..8], n); (* error: put keeps k, and this is lent by the frame *)
610- k, ok := Str.copy(Heap.heap, buf[0..8]); (* lasting: a copy on the heap *)
611- if ok then _ := Names.put(table, k, n); end; (* fine *)
612-end;
613-```
614-
615-The messages:
616-
617-```
618-Kept.raz:10:30: error: Names.put keeps its key, and buf[0..8] is lent by this call's frame
619- 10 | _ := Names.put(table, buf[0..8], n);
620- | ^^^^^^^^^
621- help: give put a copy that lasts: Str.copy(Heap.heap, buf[0..8])
622-```
623-
624-```
625-Escape.raz:14:12: error: head(h) is lent by h, a local of short, and can't be returned
626- 14 | return head(h);
627- | ^^^^^^^
628- help: head's result points into what it is given (ret h); return a copy, or take h as a var parameter of short
629-```
630-
631-### 6.5 Pointers
632-
633-PROPOSALS' marks follow slices only and leave pointers to the promise
634-of section 10. Here pointers are references too. In a safe module the only
635-pointers are lasting (from `NEW` on the heap, or from the library) or
636-lent by an owner (`Vec.add`, `Pool.at`). `ADR` is fenced, so a safe
637-module can't make a pointer to the frame. A pointer lent by an
638-owner follows the same rules as a slice.
639-
640-### 6.6 What it closes
641-
642-- A slice of the frame returned or stored by any route (today's 7.3
643- catches one route).
644-- A slice of a parameter's array stored past the call, or returned
645- unmarked.
646-- A map, list or vector keeping a slice that doesn't last.
647-- `Opt.init` keeping a table built on the frame (it becomes `keep
648- table`, and `examples/Sh.raz` passes a constant, as PROPOSALS shows).
649-
650----
651-
652-## 7. Part C: owners that count what they lend
653-
654-### 7.1 The problem part B can't solve
655-
656-`Buf.bytes(b)` returns a slice of heap memory, so by PROPOSALS' rule it
657-points "nowhere that ends", and part B would call it lasting. It
658-isn't: the next `Buf.add` may free that memory. The slice is lent by
659-`b`, and how long it stays good depends on what happens to `b`, at run
660-time, often through a pointer: `Buf.bytes(x^.path)`.
661-
662-There are two ways to check that when compiling. One is Rust's: no
663-change to `b` while any slice of it is live, found by liveness and
664-the exclusivity of `&mut`. The other is flow analysis in one pass:
665-mark a slice stale when its lender is passed as `var`, and refuse to
666-read it after that. Both fail raz's limits. Rust's needs lifetimes in
667-types and borrow regions. The one-pass flow analysis can't see a
668-loop's second iteration before it compiles the first:
669-
670-```
671-s := Buf.bytes(b);
672-while more do
673- Out.str(s); (* compiled before the add below; but the second time round s is stale *)
674- Buf.add(b, c);
675-end;
676-```
677-
678-and through a pointer every call may change the lender, so every call
679-would make the slice stale, which is false alarms everywhere.
680-
681-So part C checks at run time, as raz checks an index. The cost is an
682-add when a lent slice is taken into a variable and a subtract when the
683-variable lets go of it.
684-
685-### 7.2 Owners
686-
687-A record type with a field of the new built-in type `LENDS` is an
688-*owner*:
689-
690-```
691-type
692- Buf* = record
693- lends: LENDS; (* how many slices of data are held *)
694- a: ^Mem.Allocator;
695- data: ^U8;
696- len*, cap: INT;
697- end;
698-```
699-
700-`LENDS` is an `INT` that only the compiler changes: the owner's own
701-module may read it, and nothing may assign it. An owner is lent from
702-only through a `ret` parameter of its type, `var` or `const`:
703-
704-```
705-proc bytes*(ret const b: Buf): []U8;
706-proc all*(ret const v: Vec): []T;
707-proc add*(ret var v: Vec): ^T;
708-proc spare*(ret var b: Buf; n: INT): []U8;
709-```
710-
711-A record that holds an owner, `Http.Message` with its two `Buf`s, is
712-not an owner itself. What its `Buf`s lend is counted on each `Buf`.
713-
714-### 7.3 Counting
715-
716-Where a call returns a reference lent by an owner `o`:
717-
718-- **Used in its statement** (`Out.str(Buf.bytes(b))`, `Buf.str(c,
719- Buf.bytes(b))`): `o.lends` is raised by one as the call returns and
720- lowered at the end of the statement.
721-- **Assigned to a local** of slice or pointer type, `s := Buf.bytes(b)`:
722- the local gets a hidden word, its *hold*, which records the address of
723- `o.lends`. Assigning the local again lowers the old count and raises
724- the new; when the procedure returns, by any path, each hold still set
725- lowers its count, as a `defer` would. `s := []` lets go.
726-- **Anywhere else**: stored in a record, an array, a module variable,
727- through a pointer, or returned. This is an error by part B, since
728- the reference is lent by an owner. A local record holding one is
729- also an error, so that each hold covers one reference:
730-
731-```
732-Fmt.raz:140:5: error: Buf.bytes(b) is lent by b, which counts what it lends: hold it in a slice variable
733-```
734-
735-A reference passed to another procedure needs no count of its own:
736-the caller holds it, by a statement's count or a local's hold, for the
737-whole call. A `ret` result lent by a lent value (`t := Str.trim(s)`,
738-with `s` lent by `b`) is lent by `b` too, and its local gets its own
739-hold.
740-
741-The owner's address is fixed while it is lent. An owner is either a
742-local, a parameter, or a variable reached through a lasting pointer,
743-and part B keeps the lent value from outliving a local or parameter
744-owner. So the hold's address stays good until it is let go.
745-
746-### 7.4 What an owner does with its count
747-
748-The owner's module, which is unsafe and trusted, reads `lends`
749-before it frees memory it has lent:
750-
751-- **Growing:** if `lends` is 0, free the old block, as now. If not,
752- keep it on a list of *retired* blocks, and free those at the next
753- growth, `reset` or `done` that finds `lends` 0. A slice held across
754- the growth keeps pointing at the old block, which stays allocated:
755- it reads what the buffer held when the slice was taken. This is Go's
756- `append`: the old slice still sees the old array.
757-- **`done`**, which gives everything back: if `lends` is above 0, the
758- program stops:
759-
760- ```
761- Buf.done while 1 slice it lent is still held
762- ```
763-
764- and the calls under way are shown, as a failed check shows them.
765- `done` can't wait, and can't leave the memory to the slice without
766- leaking it for good.
767-- **`reset`** keeps the block, so it is always safe: a slice held
768- reads the new bytes as they are written over the old.
769-
770-With this, the self-append of 1.2 is right: `Buf.str(b, Buf.bytes(b))`
771-holds a count across the call, the growth retires the old block, and
772-`COPY` reads the old block, still allocated. The `Vec` example reads
773-`1 2` because the memory is still there. The stale `p^ := -1` writes
774-into a retired block: lost, but harmless. Section 11's debugging heap
775-can say so.
776-
777-### 7.5 What it costs
778-
779-- **Run time:** two adds per lend held: on x86-64, `inc qword [r]` and
780- `dec qword [r]`, about two cycles each. In a program that uses
781- `Thread` they are `lock xadd`, about 20 cycles each (part E). Lends
782- are rare next to element accesses: `Fmt.format` lends once per call,
783- and a loop over `Buf.bytes(b)` lends once.
784-- **Memory:** a word per owner, a word per local that holds a lend,
785- and at most the retired blocks, which add up to less than the
786- current block (each was half the next).
787-- **Compiler:** the hold slots, the raise and lower code, and the
788- epilogue's let-go. The epilogue reuses the machinery `defer` already
789- has.
790-
791-### 7.6 Owners aren't copied
792-
793-Copying a `Buf` today makes two records that both own one block.
794-Freeing it twice, or growing one while the other reads, breaks
795-memory. rnet's `Http.reset` does exactly this, safely by luck:
796-`head := m^.head; ...; m^ := {..., head: head}`. In a safe module, a
797-value of an owner type, or of a type that holds one, may not be:
798-
799-- assigned from another variable, returned, passed as a value
800- parameter, or put in a literal. A literal may still leave it out, so
801- that it is zero (`{}`), the empty owner;
802-- compared, or viewed.
803-
804-It is passed as `var` or `const`, and moved by the library: `Buf.swap(var
805-a, b)`, `Buf.take(var from, to)`. The message:
806-
807-```
808-Http.raz:153:5: error: a Buf.Buf owns memory, and can't be copied
809- help: Buf.take(m^.data, data) moves it, leaving m^.data empty
810-```
811-
812-### 7.7 Who is an owner
813-
814-`Buf`, `Vec`, `Map` (it lends nothing, but owns its table; `LENDS`
815-stops a copy), `List`, `Pool`, `Arena` and the owned-string map of
816-part D. A program's own record may be an owner too, if an unsafe
817-module of the program frees what it lends.
818-
819----
820-
821-## 8. Part D: the heap without `free`
822-
823-### 8.1 The rule
824-
825-In a safe module:
826-
827-- `NEW(p, a)` with `a` lasting (`Heap.heap`) gives a lasting `p`.
828- `Heap.heap` never frees it under safe code, because only unsafe code
829- can call `free`.
830-- `NEW(p, a)` with `a` lent by an owner (an arena, part C) gives a
831- `p` lent by that owner, counted like a slice.
832-- `Mem.free`, `Heap`'s `free`, `Str.free` and `Mem.unmap` are `unsafe
833- proc`s.
834-
835-So a safe program frees memory in one of three ways:
836-
837-1. **Through a container** that owns it: `Buf.done`, `Vec.done`,
838- `Map.done`, `List.clear`, `Pool.free`. Most programs do this already:
839- outside the library, the survey's `done` calls outnumber its hand
840- frees 54 to 26.
841-2. **Through a `Pool(T)`**, for records that come and go one by one
842- (8.2).
843-3. **By ending the program.** A compiler, a tool or a short-lived
844- server process frees nothing by hand, and `src/` frees only its
845- grown arrays, which become `Vec`s.
846-
847-The 1,015 dereferences in `src/` stay as they are, with no check and
848-no cost: every pointer behind them is lasting.
849-
850-### 8.2 `Pool(T)`: handles with a generation
851-
852-```
853-module Pool(T);
854-
855-type
856- Handle* = record i, gen: INT; end; (* zero: no record *)
857- Pool* = record lends: LENDS; ... end;
858-
859-proc init*(var p: Pool; a: ^Mem.Allocator);
860-proc add*(var p: Pool; keep x: T): Handle; (* a new record, x copied in *)
861-proc get*(const p: Pool; h: Handle): T; (* a copy; stops if h is stale *)
862-proc set*(var p: Pool; h: Handle; keep x: T); (* stops if h is stale *)
863-proc at*(ret var p: Pool; h: Handle): ^T; (* in place, lent by p, counted *)
864-proc valid*(const p: Pool; h: Handle): BOOL;
865-proc free*(var p: Pool; h: Handle); (* the record gone; h, and every copy, stale *)
866-proc done*(var p: Pool);
867-```
868-
869-Each slot holds a `T` and a generation. `free` raises the slot's
870-generation and puts the slot on a free list. `get`, `set` and `at` check
871-the handle's generation against the slot's, and the index against the
872-pool's length, and stop the program if they differ:
873-
874-```
875-Pool.get: a stale handle (slot 4, generation 3; the slot is at 5)
876-```
877-
878-A slot is used only for a `T`, so even a pointer from `at` kept past
879-`free` points at a `T`: a wrong record, perhaps, but never memory
880-of another type. `at`'s count also keeps the pool from moving its slots
881-while the pointer is held (7.4).
882-
883-This is the generational arena of Rust's `slotmap` and
884-`generational-arena`, and the handle pattern Zig and game engines use;
885-Vale builds the same check into every reference. Measured cost
886-(section 13): a list chased through handles takes 1.5 times as long as
887-one chased through raw pointers when it is too big for the caches, and
888-2 times when it fits in L1. Part of the first is that each slot is 32
889-bytes, not 16.
890-
891-### 8.3 Owned strings
892-
893-`Str.copy` gives a lasting copy, which a safe program can't free. For a
894-long-running program that makes and drops strings (an editor's buffer
895-names, a server's paths), the library adds:
896-
897-- `Buf` as the string a program owns: `Buf.str(name, s)`, freed by
898- `Buf.done`;
899-- `Names(V)`, a map from strings to `V` that copies each key in on
900- `put` and frees it on `remove` and `done`: `Map([]U8, V, ...)` with
901- its keys owned, for those who would otherwise `Str.copy` and leak.
902-
903-### 8.4 Arenas
904-
905-An arena hands out memory and frees it all at once, so what it gives
906-is lent by the arena:
907-
908-```
909-var ar: Arena.Arena; t: ^Tree;
910-...
911-NEW(t, Arena.allocator(ar)); (* lent by ar *)
912-...
913-Arena.reset(ar); (* stops the program if t is still held *)
914-```
915-
916-`Arena.allocator(ret var ar): ^Mem.Allocator` gives the allocator,
917-lent by `ar`; `NEW` from it gives a `t` lent by `ar`, counted. Lent
918-values can't be stored in records (part B), so an arena in safe code
919-holds no linked structure: the pointer to a tree's root may live in
920-a local, but the tree's own links can't. A program that builds
921-linked structures in an arena does it in an unsafe module, or with
922-indexes into a `Vec`. Section 14 weighs this.
923-
924----
925-
926-## 9. Part E: threads
927-
928-### 9.1 What races can break
929-
930-7.6 says a variable that two threads touch without ordering "holds a
931-value it had or was given, or a mixture of their bytes" and that
932-"nothing else of the program becomes undefined". The second half is
933-wrong today:
934-
935-- a **slice** torn between two writes, one's address with the other's
936- length, is checked against the wrong length and reaches any memory;
937-- a **variant** torn between two cases reads one case's bytes as the
938- other's fields: an integer as a pointer;
939-- a **container** written by two threads at once (`Buf.add` in each)
940- races on its length and its block: one thread writes past the end of
941- the block the other just freed.
942-
943-Go has the same hole: its memory model says that a race on a
944-multi-word value (an interface, a slice, a string) "can lead to
945-arbitrary memory corruption". Rust closes it with `Send` and `Sync`,
946-traits that the type system checks. Java closes it by tearing only
947-`long` and `double`, never a reference.
948-
949-### 9.2 The proposal
950-
951-1. **A slice is one access.** On every target, a slice is read and
952- written in one access that can't tear, as a word is. On x86-64 a
953- slice is aligned to 16 bytes and moved with `movdqa`, which Intel
954- and AMD guarantee single-copy atomic on processors with AVX. On
955- x86-64 without AVX, the implementation uses `lock cmpxchg16b`, or
956- refuses the target, as appendix A says. ARMv8.4 has 16-byte
957- atomic `LDP`/`STP` (FEAT_LSE2). A program that hands slices from
958- thread to thread, publishing a buffer for others to read, is then
959- safe with no lock.
960-2. **The guarantee holds for races on basic, pointer, procedure and
961- slice variables, and no others.** A race on a variant, or on a
962- whole record or array copied at once, or calls of one container's
963- procedures from two threads at once without a lock, is outside
964- it: undefined, as in Go. Section 3 says so, and 7.6 is rewritten
965- to say so.
966-3. **A safe way to start a thread.** `Thread.spawn(p, arg: ^U8)` becomes
967- an `unsafe proc`. A generic `Task(T)` takes its place for safe
968- modules:
969-
970- ```
971- module Task(T);
972- proc spawn*(p: proc(var x: T); keep x: T): (^Thread.Thread, ERROR);
973- ```
974-
975- `x` is copied into the new thread's stack before `spawn` returns.
976- Its references must be lasting (`keep`), so a thread never holds
977- a slice of its spawner's frame.
978-4. **Atomics take a variable.** `CAS(x, old, new)`, `XCHG(x, v)` and
979- `XADD(x, k)` take a variable, as `INC` does; through a pointer, `XADD(p^,
980- 1)`. A safe module can then use them, with no `ADR`.
981-5. **Counts are atomic where there are threads.** Part C's raise and
982- lower are `lock xadd` in a program that imports `Thread`, so that two
983- threads lending from one locked `Buf` keep its count right. A
984- program without `Thread` gets the plain `inc` and `dec`.
985-6. **`Lock.Guarded(T)`**, a value with its lock, for sharing a
986- container:
987-
988- ```
989- g: Guarded(Names.Map);
990- Guarded.with(g, addName); (* addName(var m: Names.Map) runs under the lock *)
991- ```
992-
993- It makes the safe pattern the easy one, as Rust's `Mutex<T>` does,
994- though nothing stops a program from sharing a container without it.
995-
996-### 9.3 Why not Rust's way
997-
998-A static rule that a container can be reached from two threads only
999-under a lock needs, at the least, marks on types for what may cross
1000-threads (`Send`) and be shared (`Sync`), and a way to see that module
1001-variables are shared. Module variables are reachable from every thread,
1002-and raz has no thread-local storage to put them in instead. It would
1003-add a second type system to the language for a feature two
1004-repositories out of eight use. Section 19 keeps it as a later step.
1005-
1006----
1007-
1008-## 10. Part F: the small mends
1009-
1010-### 10.1 An array a call returns lives to the end of its procedure
1011-
1012-"Less that is undefined", piece 1. The temporary's slot in the frame is
1013-reserved for the rest of the procedure, as a deferred statement's slots
1014-already are, so `s := f('a')[0..4]` is lent by the frame, not by the
1015-statement: defined until the procedure returns, and part B keeps it
1016-from going further. In a loop the slot holds the latest call's array.
1017-1.2's last program then prints `name-..a name-..b`, since each call has
1018-a slot of its own.
1019-
1020-The same for a `const` parameter's temporary (section 8): its slot is
1021-reserved to the end of the procedure.
1022-
1023-Cost: a frame bigger by each such call's array. That is not measured
1024-here; in `src/`, arrays returned by calls are small (`Str.fromInt`'s
1025-20 bytes, `Str.encode`'s 4), so the estimate is tens of bytes per
1026-frame.
1027-
1028-### 10.2 A string's bytes
1029-
1030-"Less that is undefined", piece 2. Writing a string constant's bytes,
1031-through a slice of it, either stops the program (a bad address, as now
1032-on Linux, since constants are in read-only data) or changes the
1033-constant for the rest of the run. Which one is the target's choice
1034-(appendix A). Either is defined, and neither touches another
1035-variable. A later `[]const U8` (PROPOSALS) would make it a compile-time
1036-error.
1037-
1038-### 10.3 Views
1039-
1040-A view reading any variable's bytes as an integer type is safe: it
1041-reveals an address, but it can't make one. Writing through a view of a
1042-variable that holds a pointer, slice, procedure, variant, enumeration
1043-or `BOOL` is fenced (5.1), since it would make one of those from
1044-arbitrary bytes. Views of plain data, the survey's every use outside
1045-`Rt`, stay safe.
1046-
1047-### 10.4 `match` on a lent variant
1048-
1049-A `match` on a variant whose case holds references gives names that
1050-are lent as the variant is: a field of a local variant lent by the frame
1051-is lent by the frame. Part B's rules follow.
1052-
1053----
1054-
1055-## 11. Part G: a debugging heap
1056-
1057-Unsafe modules are trusted, and trust must be tested. `Heap` gets a
1058-second mode, chosen when the program starts (`RAZ_HEAP=debug` in the
1059-environment, or `Heap.debug(true)` before the first allocation):
1060-
1061-- every freed block is filled with `0DEH` and kept off the free lists
1062- for the next 1,024 frees (a quarantine), so a stale read sees junk
1063- and a stale write is found when the block leaves the quarantine and
1064- its bytes are checked;
1065-- each block gets eight guard bytes after it, checked when it is freed;
1066-- `Buf`, `Vec` and `Pool` fill a retired block with `0DEH` too, so a
1067- slice held across a growth reads junk in the debugging heap and the
1068- old bytes otherwise.
1069-
1070-A break is reported as a failed check is: where, and the calls under
1071-way. `make check` runs the library's tests and `test/run` in both modes.
1072-This is Zig's debug allocator, glibc's `MALLOC_PERTURB_`, and Chrome's
1073-MiraclePtr quarantine, without their reach. It costs nothing unless
1074-chosen. It is the one part that changes no rule and could come first.
1075-
1076----
1077-
1078-## 12. Raz beside other languages
1079-
1080-| Language | Spatial | Temporal | Forged pointers | Races | Fence | What it costs |
1081-|---|---|---|---|---|---|---|
1082-| C | none | none | anything | UB | none | nothing |
1083-| C++, hardened | hardened `std` containers; `-fbounds-safety` for C (clang) | none | anything | UB | none | a little |
1084-| Zig | checked in Debug and ReleaseSafe | the debug allocator finds use after free and double frees at run time; nothing in release | `@ptrCast`, `@intToPtr` anywhere | UB | none, but builtins are visible | a check per index |
1085-| Odin, Hare, C3 | checked | none | anywhere | UB | none | a check per index |
1086-| Go | checked | a garbage collector | only through `unsafe` | a race on a multi-word value corrupts memory | `import "unsafe"` | a GC, write barriers, a runtime |
1087-| Java, C# | checked | a garbage collector | none | references never tear; `long` may in Java | C#: `unsafe` blocks | a GC, a runtime |
1088-| Swift | checked | reference counting; exclusivity checked at compile and run time | only through `Unsafe*` types | Swift 6: `Sendable`, checked | `Unsafe` in names | refcounting traffic |
1089-| Rust | checked | the borrow checker, at compile time | only in `unsafe` | `Send`/`Sync`, at compile time | `unsafe` blocks and functions | lifetimes, learning, compile time |
1090-| Ada, SPARK | checked | accessibility levels: an access can't outlive its object's level; `Unchecked_Deallocation` named as unsafe; SPARK adds ownership | `Unchecked_Conversion` | protected objects | the word "unchecked" | a check per index; some dynamic accessibility checks |
1091-| Modula-3 | checked | a garbage collector for traced references; `DISPOSE` only in unsafe modules | only in `UNSAFE MODULE` | not promised | `UNSAFE MODULE`, `UNSAFE INTERFACE` | a GC |
1092-| Oberon | checked | a garbage collector | only through `SYSTEM` | n/a | `IMPORT SYSTEM` | a GC |
1093-| Vale | checked | generational references: each object carries a generation, each reference the one it expects, checked at each dereference; regions skip the check | none | regions | `unsafe` | wider references, a check per dereference |
1094-| Cyclone | fat pointers | regions, checked statically | none | n/a | none | annotations, wider pointers |
1095-| Fil-C, CHERI | every pointer carries its bounds (compiler or hardware) | Fil-C: a GC; CHERI: revocation | none | Fil-C: atomic capabilities | none | Fil-C: a few times slower; CHERI: hardware |
1096-| **raz, proposed** | checked | lending checked at compile time; owners count lends at run time; no `free` in safe code; `Pool` handles checked | only in `unsafe;` modules | slices and words atomic; containers and variants under a lock or UB | `unsafe;` modules, `unsafe proc` | an add and a subtract per lend held; a compare per `Pool` access |
1097-
1098-What raz takes from each:
1099-
1100-- **From Modula-3:** the fence by module, and the trust in an unsafe
1101- module's safe interface. The unit of review is a file, as Wirth's
1102- languages always had it.
1103-- **From Ada:** a static rule that a reference can't outlive its
1104- object's level, with no lifetime variables in types. Ada's
1105- accessibility levels are part B's frame, parameters and lasting
1106- memory, nearly exactly. Ada also names deallocation as unchecked.
1107-- **From Rust:** `ret` is lifetime elision written out; `keep` is
1108- `'static`. What raz doesn't take is lifetimes in records, which is
1109- what lets Rust check `Http.Message` and what costs Rust its
1110- learning curve.
1111-- **From Swift:** checking exclusivity at run time where the compiler
1112- can't, as part C counts lends.
1113-- **From Go:** a slice held across a growth sees the old array; and an
1114- honest statement about races.
1115-- **From Vale, `slotmap` and Zig's handle idiom:** generations,
1116- but in a container (`Pool`), not in every pointer, so that the 99% of
1117- pointers that are never freed pay nothing.
1118-- **From Zig:** the debugging allocator as the first line of defence
1119- for unsafe code.
1120-
1121-Where raz ends up: about as safe as Go or Modula-3 for a program that
1122-uses no threads, with no garbage collector and no run time beyond a
1123-count per lend; less expressive than Rust (no record may borrow); and
1124-far simpler to learn and to compile.
1125-
1126----
1127-
1128-## 13. Performance
1129-
1130-All measurements are on the session's machine, 4 cores of an x86-64
1131-virtual machine, using today's compiler. Wall-clock times are the
1132-best of several runs; on this machine they vary by 10 to 20% between
1133-runs, so where it matters instruction counts from `valgrind
1134---tool=callgrind` are given, which don't vary.
1135-
1136-### 13.1 The compiler's speed
1137-
1138-The largest cost of the proposal to `src/` itself would be checking the
1139-scanner's buffer, if `Scan` stops being unsafe. To measure it, `Scan`'s
1140-`buf: ^U8` was made a checked `[]U8` (with the sentinel inside its
1141-length) and everything else left as it was. Five lines changed:
1142-
1143-| Compile | Pointer (today) | Checked slice | More |
1144-|---|---|---|---|
1145-| `src/Raz.raz`, the compiler itself | 240,851,288 instructions | 251,595,933 | **+4.5%** |
1146-| the generated benchmark, 58,025 lines | 40,305,841 | 42,519,299 | +5.5% |
1147-
1148-`make bench`'s 348,025 lines compile in 625 to 660 ms here, about
1149-530,000 to 557,000 lines a second; 5.5% more is about 500,000 to 528,000, inside the 400,000-line
1150-floor and inside `make prev-bench`'s tenth. Most of the cost is the
1151-scanner's inner loops, `while (c = ' ') ... c := buf[p]`, checking
1152-each byte. Section 21 asks whether `Scan` stays unsafe instead,
1153-leaving the compiler as fast as it is.
1154-
1155-The other changes to `src/` (grown arrays to `Vec`, `intern(s)`, views)
1156-cost nothing measurable: `Vec`'s access through `all` is a slice index,
1157-which is the same check the hand-grown arrays don't have, on paths
1158-much cooler than the scanner's.
1159-
1160-The compiler's own checks (part B, C, the fence) are flags on items
1161-and modules and run while each expression is compiled: no measurable
1162-compile time.
1163-
1164-### 13.2 Kernels
1165-
1166-`MemBench.raz` and `GenBench.raz` (appendix 2):
1167-
1168-| Kernel | Run 1 | Run 2 | What it shows |
1169-|---|---|---|---|
1170-| chase a 1,000,000-node list (16-byte nodes), raw pointers | 8,312 ms | 7,515 ms | the baseline |
1171-| the same through `Pool`-style handles (32-byte slots, index and generation checked) | 12,336 ms | 11,992 ms | **1.5–1.6×**: half of it the larger slot |
1172-| chase a 1,000-node list (in L1), raw pointers | 857 ms | 810 ms | |
1173-| the same through handles | 1,631 ms | 1,643 ms | **1.9–2.0×**: the checks themselves |
1174-| chase 1,000,000 32-byte nodes, raw pointers | 14,001 ms | 13,725 ms | the larger node alone, against row 1: **+70–85%** |
1175-| the same through fat (address, generation) pointers, generation in the node | 8,672 ms | 10,145 ms | the check is free here: in the node's own cache line |
1176-| 1,000 32-byte nodes, raw | 870 ms | 917 ms | |
1177-| 1,000 32-byte nodes, fat pointers | 830 ms | 1,047 ms | within noise to +15% |
1178-| sum 16,000,000 bytes through `^U8`, 50 times | 305 ms | 342 ms | |
1179-| the same through a checked `[]U8` | 271 ms | 434 ms | within noise: the check hides behind the loads |
1180-| sum 4,000 bytes (in L1), 200,000 times, `^U8` | 261 ms | 265 ms | |
1181-| the same, checked `[]U8` | 256 ms | 306 ms | 0–15% |
1182-
1183-What they say:
1184-
1185-- **Bounds checks are cheap.** On sequential access the check is
1186- hidden by the loads it guards. This is why nobody uses `check off;`.
1187-- **A generation check is cheap when it is in the object's cache line**
1188- (the fat-pointer rows). **Wider references are not cheap:** doubling a
1189- node from 16 to 32 bytes costs 70 to 85% when the structure doesn't fit
1190- in the caches. This is the main argument against making every `^T`
1191- a fat generational pointer (section 19). It is also why `Pool`'s
1192- handles cost half again: the 32-byte slots, not the check.
1193-- **Handles cost 1.5–2× where pointer chasing dominates**, which is
1194- linked lists and trees. A safe program pays it only for the records
1195- it frees one by one; everything else stays a lasting `^T` with no
1196- check.
1197-
1198-### 13.3 What each part costs a program
1199-
1200-| Part | Cost | Where |
1201-|---|---|---|
1202-| A, the fence | none | compile time |
1203-| B, lending | none | compile time |
1204-| C, counts | `inc`/`dec` per lend held, or `lock xadd` with threads; a word per holding local | once per `Buf.bytes`, `Vec.all`, `Vec.add`: not per element |
1205-| C, retired blocks | memory: at most the current block again, only while a lend is held across a growth | rare |
1206-| D, no `free` | none for lasting pointers; handles where chosen, 1.5–2× on chasing | `Pool` users only |
1207-| E, atomic slices | none: two 8-byte moves become one 16-byte one; records holding slices may grow by padding to 16 | `src/` has 10 such fields |
1208-| E, atomic counts | about 20 cycles per lend, with threads only | |
1209-| F, temporaries | frame size | |
1210-| G, the debugging heap | none unless chosen | |
1211-
1212----
1213-
1214-## 14. Ergonomics
1215-
1216-### 14.1 What doesn't change
1217-
1218-Most raz is already safe under this proposal: the survey's `Parse`,
1219-`Item`, `Sym` and `Gen`, `tools/`, rjson's parser, rflate's inflater,
1220-rterm. They use records, slices, `var`, `const` and pointers from
1221-`NEW`, and they don't free. For them the change is a few `ret`s in the
1222-library's headings, which the caller never writes.
1223-
1224-### 14.2 What a programmer meets
1225-
1226-**A slice of a buffer kept in a record.** rnet's `Http.Message` keeps
1227-`headers[i].name` as slices of `m^.head`'s bytes and `body` as a slice
1228-of `m^.data`. Under part B and C these are lent by owners and can't be
1229-stored in a record. The choices:
1230-
1231-1. Offsets instead of slices:
1232-
1233- ```
1234- Header* = record name, value: Span; end; (* Span = record at, len: INT; end *)
1235- proc name*(ret const m: Message; i: INT): []U8; (* m^.head's bytes, lent by m *)
1236- ```
1237-
1238- which is safe, a little longer, and survives `m^.head` growing. It
1239- is how Rust programs without lifetimes in structs do it.
1240-2. `Http` says `unsafe;`, and keeps its invariant by hand, as it does
1241- today. It becomes one of the modules a reviewer reads twice.
1242-
1243-The proposal recommends the first for libraries, since it is what
1244-the guarantee is for.
1245-
1246-**A slice held across a call that might change its owner.** This is
1247-allowed. Part C counts it, and the owner retires instead of freeing.
1248-rmacs's `save`, with its `path := Buf.bytes(x^.path)` held across
1249-`Buf.reset(tmp)` and `Buf.str(tmp, path)`, compiles and runs as
1250-before.
1251-
1252-**`done` with a slice still held.** This stops the program at run time:
1253-
1254-```
1255-proc report(x: ^Buffer);
1256-var name: []U8;
1257-begin
1258- name := Buf.bytes(x^.name);
1259- Buf.done(x^.name); (* stops: name still holds a lend *)
1260- ...
1261-end;
1262-```
1263-
1264-The cure is `name := []` before `done`, or not holding it. It is a
1265-false alarm only when `name` is never read again. Since a stop is
1266-loud and the cure is one line, the proposal accepts it.
1267-
1268-**Owners can't be copied.** `head := m^.head` in rnet becomes
1269-`Buf.take(m^.head, head)`. The survey didn't count such copies; rnet's
1270-`Http.reset` is the one found by reading.
1271-
1272-**Records that come and go.** An editor's windows, freed when closed,
1273-become a `Pool(Window)` with `Handle`s where rmacs had `^Window` and
1274-`Mem.free`. Each access is `Windows.at(pool, h)^.field` or `get`. This is
1275-longer than `w^.field`, and 1.5–2× slower in a pointer-chasing loop,
1276-which an editor doesn't have.
1277-
1278-**An arena with links.** A tree built in an arena with `^Node` links
1279-can't be safe (8.4): links are stored in records, and lent pointers
1280-can't be. It becomes indexes into a `Vec(Node)`, which is often faster
1281-(smaller, contiguous), or stays in an unsafe module.
1282-
1283-**Strings that must be freed.** `Str.copy` and `Str.free` become
1284-`Names(V)` or a `Buf` per string (8.3).
1285-
1286-**Threads.** `Thread.spawn(work, ^U8(ADR(job)))` becomes
1287-`Jobs.spawn(work, job)`, with `import Jobs := Task(Job)`. That is
1288-shorter.
1289-
1290-### 14.3 What the compiler says
1291-
1292-Each new error names the rule and the mending, in the house style:
1293-
1294-```
1295-error: ADR is for unsafe modules
1296- help: pass x as a var parameter, or say "unsafe;" after the module's imports
1297-error: Names.put keeps its key, and buf[0..8] is lent by this call's frame
1298- help: give put a copy that lasts: Str.copy(Heap.heap, buf[0..8])
1299-error: Buf.bytes(b) is lent by b, which counts what it lends: hold it in a slice variable
1300-error: a Buf.Buf owns memory, and can't be copied
1301- help: Buf.take(from, to) moves it
1302-error: Str.trim(s) is lent by s, which isn't marked ret
1303- help: mark the parameter "ret s: []U8" to return what points into it
1304-error: Mem.free is an unsafe procedure
1305- help: free through the container that owns the memory, or say "unsafe;"
1306-```
1307-
1308-and two new run-time stops:
1309-
1310-```
1311-Buf.done while 1 slice it lent is still held
1312-Pool.get: a stale handle (slot 4, generation 3; the slot is at 5)
1313-```
1314-
1315----
1316-
1317-## 15. What breaks
1318-
1319-Everything breaks that uses a fenced operation in a module that
1320-doesn't say `unsafe;`, or stores a lent reference, or copies an
1321-owner. By codebase:
1322-
1323-| Code | What breaks | The mending |
1324-|---|---|---|
1325-| `lib/` | every module with a fenced operation: `Rt`, `Mem`, `Heap`, `Arena`, `Bytes`, `Sys`, `Thread`, `Lock`, `C`, `CAbi`, `Buf`, `Vec`, `Map`, `List` | `unsafe;` |
1326-| | `Str`, `Fmt`, `Opt`, `Files` | drop two to five operations each; they become safe |
1327-| | headings: `ret` on `Str.trim`, `trimLeft`, `trimRight`, `cut`, `field`, `Buf.bytes`, `spare`, `Vec.all`, `add`, `Sys.nextEntry`; `keep` on `Map.put`, `List.push`, `Vec.push`, `tryPush`, `Opt.init`, `scope` | marks |
1328-| | `Buf`, `Vec`, `Map`, `List`, `Arena`: a `LENDS` field, retiring, `done`'s stop, `take`, `swap` | about 15 lines each |
1329-| | new: `Pool`, `Task`, `Names`, `Lock.Guarded`, `Arena.allocator`; `Heap`'s debugging mode | about 400 lines in all |
1330-| | `unsafe proc`: `Mem.free`, `Mem.unmap`, `Heap`'s `free`, `Str.free`, `Sys.mmap`, `Sys.munmap`, `Thread.spawn`, the `Sys` calls that take a raw pointer; `Mem.Allocator`'s fields | a word each |
1331-| `src/` | all eleven modules (section 2.2) | grown arrays to `Vec` (35 sites), `intern(s)` (7), views (6), `var` (6), `Sys.info` (1); `Scan` stays `unsafe;` |
1332-| `tools/` | nothing fenced; any `Map.put` of a frame slice | none found |
1333-| `examples/` | `Args`, `Cpu`, `Pthreads`, `Printf`, `Window`, `Volatile`, `Sh`, `Workers` | `Args`, `Sh`, `Workers` mended; the other five say `unsafe;`, as examples of it |
1334-| `test/run`, `test/libc`, `conform/` | the tests of `ADR`, pointers, C | `unsafe;` in each; new tests in `conform/` for the guarantee: what is an error, and what stops |
1335-| rnet | `Http.Message` keeps lent slices; `reset` copies `Buf`s; `Thread.spawn` | spans and accessors; `take`; `Task` |
1336-| rjson | `Str.free` and `Mem.free` (6); a few casts | `Names` or `Buf`; views |
1337-| rflate | none beyond `ADR` at calls (gone with v0.19.0's library) | none |
1338-| rsqlite | C | `unsafe;` on `Sqlite` |
1339-| rmacs, ravite | `ADR` at calls (gone with v0.19.0); `Mem.free` (9 and 2) of windows and buffers | `Pool` |
1340-| rlX11 | casts on X11 replies | views; one unsafe module for the socket's bytes |
1341-| rmacs's and ravite's `Scan` use | `tools/Scan.raz` | nothing fenced |
1342-
1343-Every break is found when compiling, with a message that names its
1344-mending, except a `done` while a lend is held, which shows up at run
1345-time with a message. No program changes meaning without an error.
1346-
1347-A `raz -fix` (or `tools/Mutate.raz` taught the rewrites) can make
1348-the mechanical ones: `ADR(x)` at a `var` parameter, `^F64(ADR(x))` to
1349-a view, `intern(ADR(s[0]), LEN(s))` to `intern(s)`, `unsafe;` where a
1350-module keeps a fenced operation after those.
1351-
1352----
1353-
1354-## 16. Changes to the report
1355-
1356-The report grows by about three pages, from 32 to 35, inside its
1357-40. By section:
1358-
1359-**1. A first look.** One paragraph: what is safe, what `unsafe;`
1360-means, where to read more.
1361-
1362-**3. Modules.** The grammar takes the line:
1363-
1364-```
1365-Module = "module" ident [ "(" ModParams ")" ] ";"
1366- { Import } { Link } [ Check ] [ Unsafe ] { Declaration }
1367- [ "begin" Statements ] "end" ident "." .
1368-Unsafe = "unsafe" ";" .
1369-```
1370-
1371-A new paragraph, **`unsafe;`**, says what it allows (the table of
1372-5.1), and that `link` and `check off;` need it. **Generic modules**:
1373-an instance is safe or unsafe as its generic module is, as with
1374-`check`.
1375-
1376-**5.3 Slices.** "A slice is aligned to twice an address's
1377-alignment, and read and written in one access (7.6)."
1378-
1379-**5.4 Pointers.** A paragraph: in a safe module a pointer is `nil`,
1380-from `NEW`, or from the library; section 8.x says how long it lives.
1381-
1382-**5.5 Records.** **Owners**: a record with a `LENDS` field; it can't
1383-be copied in a safe module (7.6 of this proposal). `LENDS` joins the
1384-basic types in 5.1, as a type only a record's field may have.
1385-
1386-**5.9 Procedure types.** `unsafe proc`, and the marks `ret` and `keep`,
1387-which a procedure type carries; what may stand where (PROPOSALS).
1388-
1389-**6.4 Pointers.** `p + i`, `p - i`, `p[i]` and `p[lo..hi]`: "only in an
1390-unsafe module".
1391-
1392-**6.7 Conversions.** The pointer rows: "only in an unsafe module".
1393-
1394-**6.8 Built-in procedures.** `ADR`, `PTR`, `SYSCALL` and `ARGV`: "only in
1395-an unsafe module". `NEW` (part D): what it gives lasts, or is lent by
1396-its allocator's owner. `CAS`, `XCHG` and `XADD` take a variable.
1397-
1398-**6.9 Views.** Writing a view of a variable that holds a pointer,
1399-slice, procedure, variant, enumeration or `BOOL`, and a view as a
1400-pointer type, are for unsafe modules.
1401-
1402-**7.3 Return.** The paragraph on slices of the frame is replaced by a
1403-reference to the new section 8.x, which covers every route.
1404-
1405-**7.6 Volatile.** "Nothing else of the program becomes undefined by
1406-it" becomes: a race on a variable of a basic, pointer, procedure or
1407-slice type gives a value it had or was given, never a mixture; a race
1408-on anything else, or on a container's procedures called at once, is
1409-outside the guarantee (10).
1410-
1411-**8. Procedures.** The marks `ret` and `keep` in the grammar,
1412-`Params = [ "ret" ] [ "keep" ] [ "var" | "const" ] ...`, and
1413-`ProcDeclaration` takes `[ "unsafe" ]` before `proc`. A new section,
1414-**8.x Lending**, about two pages, with part B's rules (lasting,
1415-lent, by whom; what may be done with each) and part C's counting,
1416-and the examples of 6.4 of this proposal. An array a call returns, and a
1417-`const` parameter's temporary, live to the end of the procedure
1418-(part F). The paragraph "kept past its statement ... the exception of
1419-section 10" goes.
1420-
1421-**9. Calling C.** "`extern` and `link` only in an unsafe module."
1422-
1423-**10. Programs.** **Defined behaviour** becomes **The guarantee**
1424-(section 3), and the list of exceptions shrinks to one sentence: an
1425-unsafe module, a code procedure and C may break memory, and what
1426-follows isn't defined; a safe program can't. The stops stay as they
1427-are, and the two new run-time stops are added: an owner's `done` with
1428-lends held, and a library container's own checks (a stale handle). **Errors**: a
1429-fenced operation outside an unsafe module, a lent value where it can't
1430-go, a copied owner, a call of an `unsafe proc` from a safe module.
1431-
1432-**Appendix A.** How slices are made one access (16-byte moves, or a
1433-lock, or a refused target); whether writing a string constant stops or
1434-changes it; how the debugging heap is chosen.
1435-
1436-**Appendix B.** The grammar's new lines.
1437-
1438-**The library volume.** `unsafe proc` and `ret`/`keep` in every
1439-heading; `Pool`, `Task`, `Names`, `Lock.Guarded`; owners' `take`,
1440-`swap` and their stop; `Heap`'s debugging mode. `Mem.Allocator`
1441-described as an unsafe interface. Which modules are unsafe, and their
1442-promise.
1443-
1444-**`doc/report-history.md`**, **`doc/compiler.md`** (each rule, where in
1445-the compiler, with code before and after), **raz(7)**, the tutorial and
1446-`STANDARDS.md` ("a parameter is a value, `var`, `const`, or `keep`; a
1447-pointer only in an unsafe module or where `NEW` gave it").
1448-
1449----
1450-
1451-## 17. Changes to the library
1452-
1453-| Module | Change |
1454-|---|---|
1455-| `Mem` | `Allocator`'s fields `unsafe proc`; `free`, `unmap`, `pages` `unsafe proc`s |
1456-| `Heap` | `free` unsafe; the debugging mode (part G); big blocks' address ranges kept reserved after `free` in debugging mode |
1457-| `Arena` | an owner; `allocator(ret var ar)`; `reset` and `done` stop if lends are held |
1458-| `Buf` | an owner; `bytes`, `spare` `ret`; retiring; `done` stops; `take`, `swap` |
1459-| `Vec` | an owner; `all`, `add`, `tryAdd` `ret`; `push`, `tryPush` `keep x`; retiring; `done` stops; `take`, `swap` |
1460-| `Map` | an owner (it counts no lends, but isn't copied); `put` `keep k`, `keep v` |
1461-| `List` | an owner; `push` `keep v` |
1462-| `Str` | `trim`, `trimLeft`, `trimRight`, `cut`, `field` `ret`; `free` unsafe; `copy` documented as lasting; safe module |
1463-| `Fmt`, `Opt`, `Files` | made safe; `Opt.init`, `scope` `keep` |
1464-| `Sys` | the raw-pointer calls `unsafe proc`; `nextEntry` `ret`; the rest safe to call |
1465-| `Thread` | `spawn` unsafe; `Mutex` taken by `var`, as now |
1466-| `Lock` | `Guarded(T)` |
1467-| new `Pool(T)` | 8.2 |
1468-| new `Task(T)` | 9.2 |
1469-| new `Names(V)` | 8.3 |
1470-
1471----
1472-
1473-## 18. Changes to the compiler
1474-
1475-Where each part goes in `src/`, and about how big each is. The
1476-budget is 14,000 lines of code and the compiler is about 11,500 today.
1477-
1478-| Part | Where | Lines |
1479-|---|---|---|
1480-| A. The fence | a flag on the module, set by `unsafe;` in `Parse`; a check at each place the survey's counting build hooked (`Item.index`, `slice`, `op2`, `convert`, `view`, `indexView`; `Parse`'s `ADR`, `PTR`, `SYSCALL`) and at `ARGV`, `extern`, `link`, `check` and code procedures; `unsafe proc` on `Obj` and on procedure types | 120 |
1481-| B. Lending | PROPOSALS' estimate: a set of lenders on each `Item` in place of today's `frame: BOOL` (`Item.raz:58`), the same on each local, the checks, the list that waits for `end`; plus pointers followed as slices are | 300–450 |
1482-| C. Owners | `LENDS` as a type; `Sym`'s owner flag; the hold slots, the raise and lower in `Gen`, the let-go in the epilogue (reusing `defer`'s); the copy checks | 200 |
1483-| D. `NEW`'s provenance | lasting or lent by its allocator | 20 |
1484-| E. Atomic slices | 16-byte alignment in `Sym`, `movdqa` in `X64`'s slice moves; atomics taking variables; `lock xadd` counts when `Thread` is imported | 80 |
1485-| F. Temporaries | the slot reserved to the end, as `defer`'s are | 20 |
1486-| Messages, with help | | 100 |
1487-| **In all** | | **840–990** |
1488-
1489-So the compiler grows to about 12,400–12,500 lines, inside the budget,
1490-with room for the documentation the house style demands. The
1491-rewrite of `src/` to be safe (section 15) takes lines away: 35 grown
1492-arrays made `Vec`s.
1493-
1494-Each rule is explained in `doc/compiler.md` where it is done, with the
1495-code before and after, as CLAUDE.md asks.
1496-
1497----
1498-
1499-## 19. Alternatives considered
1500-
1501-**A garbage collector.** It would make `free` and part C unneeded, as in
1502-Go, Java and Oberon. It is rejected: raz promises "a static executable
1503-with no run time besides the code it uses" (10). A collector needs
1504-stack maps, barriers or pauses, and a heap the language owns, and it
1505-would end raz as a systems language with a C-like footprint.
1506-
1507-**Rust's borrow checker.** It closes everything, races included, at
1508-compile time. It is rejected for raz: lifetimes in types, regions
1509-inferred over whole procedures (non-lexical lifetimes are a fixpoint
1510-over the control flow, not one pass), and a learning curve that is
1511-the opposite of "a beginner can follow". The proposal takes from it
1512-`ret` (elision, written) and `keep` (`'static`), and leaves out
1513-lifetimes in records, knowing what that costs (14.2).
1514-
1515-**Fat generational pointers for every `^T`** (Vale). Every `^T` would
1516-become (address, generation), and `free` would be safe and checked at
1517-every dereference. Measured (13.2): the check costs little, since the
1518-generation sits in the object's cache line, but doubling a pointer
1519-cost 70–85% on a structure past the caches. Records with pointers grow,
1520-C interop needs a second, raw pointer type, and the 1,015 dereferences
1521-in `src/`, of memory never freed, would pay for a check they can't fail.
1522-It is kept as a fallback if part D proves too narrow: `Pool` is the
1523-same mechanism, where it is paid for only by what is freed.
1524-
1525-**Statically killing a lent slice when its owner changes.** One-pass
1526-flow analysis can't see a loop's back edge, and through a pointer
1527-every call may change the owner (7.1). It would need a second pass, or
1528-a rule so strict ("a lent slice dies at the end of its statement")
1529-that `s := Buf.bytes(b)` over several lines, 35 places in the survey,
1530-would all break.
1531-
1532-**Stop on growth while lent, instead of retiring.** It is simpler to
1533-explain, and it finds the stale-pointer bug in 1.2 at once. But it also
1534-stops `Buf.str(b, Buf.bytes(b))`, which is right and common in other
1535-languages (Go's `append(s, s...)`). Retiring keeps right programs
1536-running, and the debugging heap (part G) shows the stale ones.
1537-
1538-**Thread-local module variables, or `Send`/`Sync`.** They are needed
1539-for a static race guarantee. They are left for later (9.3): they
1540-cost a second type system for a feature little used. If they come,
1541-part E's statement grows to cover every program, and nothing else in
1542-this proposal changes.
1543-
1544-**Hardware: memory tagging (ARM MTE) and CHERI.** They catch use
1545-after free and out-of-bounds by tagging memory and pointers. They
1546-help unsafe modules and C, they aren't on x86-64, and they are
1547-probabilistic (MTE's four bits). They would make part G stronger,
1548-not replace B to D.
1549-
1550-**Only the fence (PROPOSALS' piece 4).** It is cheap and gives a list
1551-of modules to audit, but what it leaves undefined in safe code is
1552-exactly 1.2's first four programs. A fence around code that is still
1553-unsafe would mislead the reader. That is why this proposal exists.
1554-
1555----
1556-
1557-## 20. Order of work
1558-
1559-Each step is a release, and each leaves `make check` passing and every
1560-program building, with warnings where a later step will make errors.
1561-
1562-1. **The debugging heap (G).** It changes no rule, and finds bugs in
1563- today's code, the library's above all, before the rules arrive.
1564- Run `make check` under it.
1565-2. **Temporaries to the end of the procedure (F.1), strings (F.2).**
1566- No program breaks.
1567-3. **Atomic slices, and 7.6 rewritten (E.1, E.2).** No program breaks.
1568-4. **`ret` and `keep` (B), as warnings,** then errors a release later.
1569- Mark the library. This is PROPOSALS' part 3, extended to
1570- pointers.
1571-5. **Owners (C).** `LENDS` in the containers, retiring, counting,
1572- `take` and `swap`; the copy check as a warning, then an error.
1573-6. **The heap (D).** `Pool`, `Names`, `Task`; `free` an `unsafe
1574- proc`, warned of first.
1575-7. **The fence (A),** last, as a warning for one release, then an
1576- error, once everything it would flag has a safe form. `src/` comes
1577- to it, keeping `Scan` unsafe, or not, by the owner's word (21).
1578-8. **The report's guarantee (section 10),** stated when step 7 makes
1579- it true.
1580-
1581-`src/` must build with the release `BOOT` names, so it takes up each
1582-step one release after the step ships.
1583-
1584----
1585-
1586-## 21. Open questions
1587-
1588-1. **Does `Scan` stay unsafe?** Checking its buffer costs the
1589- compiler 4.5% (13.1). Leaving it unsafe keeps the speed, and the
1590- compiler then has one unsafe module, which is easy to read.
1591-2. **`LENDS` as a type, or a mark on the record** (`owner record`)?
1592- The field makes the count visible to the module that reads it, and
1593- needs no new word; a mark would be more explicit.
1594-3. **Should `done` with a lend held leak instead of stopping?** It
1595- would mean no false alarms, but a silent leak that can grow.
1596-4. **Is a local record holding an owner-lent slice worth allowing?**
1597- (7.3 forbids it.) It needs one hold per reference in the record, and
1598- a let-go when the record is reassigned. `Fmt.Arg` arrays are the
1599- case: `[Fmt.str(Buf.bytes(b))]` is fine inside a statement, but not
1600- held in a local array.
1601-5. **Is the race guarantee enough?** A cheap dynamic check would close
1602- the container case in programs with threads: each owner records
1603- the thread that last changed it, and changes from another thread
1604- without the lock stop the program, as Swift's exclusivity checks do.
1605-6. **`Pool`'s handle**: two words, or one, with 40 bits of index and 24
1606- of generation? One word fits in a register and halves `Pool`'s
1607- memory for handles, and generations would wrap after 16 million
1608- frees of one slot.
1609-7. **`unsafe` per procedure, not per module?** Rust's `unsafe` blocks
1610- are finer. A module is raz's unit of review, and a module can be
1611- split, but `Sys` would need a split into a safe and an unsafe half
1612- for readers to see the difference.
1613-
1614----
1615-
1616-## Appendix 1: the survey's numbers
1617-
1618-Places of each operation, counted once each, by the instrumented
1619-compiler. `deref` and `new` are shown for scale; they stay safe, as
1620-does `p - q`, which the module table below counts with the rest.
1621-
1622-| Code | `ADR` | deref | `p[i]` | `p[a..b]` | `p ± i` | `p - q` | ptr cast | int→ptr | ptr→int | view | `NEW` | `SYSCALL` |
1623-|---|---|---|---|---|---|---|---|---|---|---|---|---|
1624-| raz `src/` | 27 | 1,015 | 277 | 30 | 3 | 0 | 42 | 0 | 0 | 0 | 5 | 3 |
1625-| raz `lib/` | 144 | 93 | 88 | 14 | 49 | 2 | 52 | 13 | 4 | 2 | 1 | 140 |
1626-| raz `examples/` | 15 | 46 | 2 | 1 | 0 | 0 | 5 | 0 | 0 | 3 | 1 | 0 |
1627-| raz `test/libc` | 110 | 15 | 35 | 11 | 18 | 0 | 64 | 1 | 6 | 0 | 1 | 0 |
1628-| rnet | 471 | 359 | 0 | 0 | 0 | 0 | 9 | 1 | 1 | 0 | 0 | 0 |
1629-| rjson | 91 | 105 | 0 | 7 | 1 | 0 | 13 | 0 | 0 | 0 | 0 | 0 |
1630-| rflate | 61 | 102 | 0 | 0 | 0 | 0 | 7 | 0 | 0 | 0 | 2 | 0 |
1631-| rsqlite | 38 | 12 | 1 | 3 | 0 | 0 | 2 | 0 | 1 | 0 | 0 | 0 |
1632-
1633-The fenced operations of each module of `src/` and `lib/`:
1634-
1635-| Module | Fenced | Of which |
1636-|---|---|---|
1637-| `src/Scan` | 99 | `p[i]` 76, casts 12, `p[a..b]` 6, `ADR` 3, `p ± i` 2 |
1638-| `src/Link` | 71 | `p[i]` 63, `p[a..b]` 4, casts 4 |
1639-| `src/Chunk` | 65 | `p[i]` 53, casts 10, `p[a..b]` 1, `ADR` 1 |
1640-| `src/X64` | 31 | `p[i]` 23, `ADR` 5, casts 3 |
1641-| `src/Diag` | 23 | `p[i]` 15, `p[a..b]` 3, casts 3, `ADR` 2 |
1642-| `src/Elf` | 23 | `p[i]` 17, `p[a..b]` 3, `ADR` 3 |
1643-| `src/Parse` | 21 | `p[a..b]` 8, `ADR` 5, `p[i]` 5, casts 2, `SYSCALL` 1 |
1644-| `src/Sym` | 17 | `p[i]` 12, casts 3, `ADR` 2 |
1645-| `src/Item` | 16 | `p[i]` 5, `p[a..b]` 4, casts 4, `ADR` 3 |
1646-| `src/Gen` | 8 | `p[i]` 5, `ADR` 2, casts 1 |
1647-| `src/Raz` | 8 | `p[i]` 3, `SYSCALL` 2, `ADR` 1, `p[a..b]` 1, `p ± i` 1 |
1648-| `lib/Sys` | 287 | `SYSCALL` 129, `ADR` 98, `p[i]` 31, casts 12, `p ± i` 8, `p[a..b]` 6 |
1649-| `lib/Rt` | 111 | `p ± i` 32, `p[i]` 31, casts 20, `ADR` 10, int→ptr 10, `SYSCALL` 6 |
1650-| `lib/Thread` | 33 | `ADR` 16, casts 6, `SYSCALL` 5, `p[i]` 3, `p ± i` 3 |
1651-| `lib/Map` | 19 | `p[i]` 16, casts 3 |
1652-| `lib/Heap` | 16 | `p ± i` 4, casts 4, ptr→int 4, `p[i]` 2 |
1653-| `lib/Bytes` | 10 | `ADR` 5, casts 5 |
1654-| `lib/Buf` | 6 | `p[a..b]` 4, `p[i]` 1, `ADR` 1 |
1655-| `lib/Opt` | 5 | `ADR` 5 |
1656-| `lib/Arena` | 4 | `p ± i` 2, `ADR` 1, cast 1 |
1657-| `lib/Fmt` | 4 | `ADR` 4 |
1658-| `lib/Files`, `lib/Str` | 3 each | |
1659-| `lib/Lock`, `lib/Mem` | 2 each | |
1660-| `lib/List` | 1 | |
1661-| `lib/Math`, `Out`, `Sort`, `Width` | 0 | |
1662-
1663-`Vec` (generic, and instantiated by no program surveyed) has 11 by
1664-`grep`. `C` and `CAbi` are `extern` declarations (96 and 2).
1665-
1666-By `grep`, for the code today's compiler refuses (written before
1667-`INT`):
1668-
1669-| Code | Lines of code | `ADR` | at a call | casts | frees | `done` | `reset` |
1670-|---|---|---|---|---|---|---|---|
1671-| rmacs | 4,323 | 560 | 556 | 9 | 9 | 16 | 66 |
1672-| ravite | 2,185 | 202 | 200 | 3 | 2 | 1 | 15 |
1673-| rlX11 | 5,226 | 89 | 87 | 3 | 1 | 0 | 0 |
1674-
1675-## Appendix 2: the benchmarks
1676-
1677-Built with `raz -o MemBench MemBench.raz` and run as they are. Both
1678-are in the session's scratch space and can be added to `test/bench`
1679-if the proposal goes ahead.
1680-
1681-```
1682-module MemBench;
1683-import Out, Sys;
1684-
1685-const
1686- Big = 1000000; (* past the caches *)
1687- Small = 1000; (* in L1 *)
1688- Bytes = 16000000;
1689-
1690-type
1691- Node = record next: ^Node; val: INT; end;
1692- H = record i: INT; gen: INT; end;
1693- Slot = record next: H; val: INT; gen: INT; end;
1694-
1695-var
1696- nodes: [Big]Node;
1697- slots: [Big]Slot;
1698- perm: [Big]INT;
1699- bytes: [Bytes]U8;
1700- sink: INT;
1701-
1702-(* A random cycle through the first n nodes, the same in both arrays *)
1703-proc build(n: INT);
1704-var i, j, t: INT; seed: U64;
1705-begin
1706- seed := 7;
1707- for i := 0 to n - 1 do perm[i] := i; end;
1708- for i := n - 1 to 1 by -1 do
1709- seed := seed * 6364136223846793005 + 1442695040888963407;
1710- j := INT(seed shr 33) mod (i + 1);
1711- t := perm[i]; perm[i] := perm[j]; perm[j] := t;
1712- end;
1713- for i := 0 to n - 1 do
1714- j := perm[(i + 1) mod n];
1715- nodes[perm[i]] := {next: ADR(nodes[j]), val: i};
1716- slots[perm[i]] := {next: {i: j, gen: 3}, val: i, gen: 3};
1717- end;
1718-end;
1719-
1720-proc chasePtr(steps: INT): INT;
1721-var p: ^Node; s, k: INT;
1722-begin
1723- p := ADR(nodes[perm[0]]);
1724- for k := 1 to steps do s := s + p^.val; p := p^.next; end;
1725- return s;
1726-end;
1727-
1728-(* As a checked Pool.get would: the generation, and the index *)
1729-proc chaseHandle(steps: INT): INT;
1730-var h: H; s, k: INT;
1731-begin
1732- h := {i: perm[0], gen: 3};
1733- for k := 1 to steps do
1734- if slots[h.i].gen # h.gen then Sys.exit(3); end;
1735- s := s + slots[h.i].val;
1736- h := slots[h.i].next;
1737- end;
1738- return s;
1739-end;
1740-
1741-proc sumPtr(p: ^U8; n, reps: INT): INT;
1742-var s, i, r: INT;
1743-begin
1744- for r := 1 to reps do
1745- for i := 0 to n - 1 do s := s + INT(p[i]); end;
1746- end;
1747- return s;
1748-end;
1749-
1750-proc sumSlice(b: []U8; reps: INT): INT;
1751-var s, i, r: INT;
1752-begin
1753- for r := 1 to reps do
1754- for i := 0 to LEN(b) - 1 do s := s + INT(b[i]); end;
1755- end;
1756- return s;
1757-end;
1758-```
1759-
1760-`main` builds `Big`, times each chase for 100,000,000 steps, builds
1761-`Small`, times each for 500,000,000, then the sums: 16,000,000 bytes 50
1762-times and 4,000 bytes 200,000 times. `GenBench.raz` is the same chase
1763-with 32-byte records on both sides:
1764-
1765-```
1766-type
1767- Node = record next: ^Node; val, pad1, pad2: INT; end;
1768- GP = record p: ^GNode; gen: INT; end;
1769- GNode = record gen: INT; next: GP; val: INT; end;
1770-
1771-proc chaseGen(steps: INT): INT;
1772-var g: GP; s, k: INT;
1773-begin
1774- g := {p: ADR(gnodes[perm[0]]), gen: 5};
1775- for k := 1 to steps do
1776- if g.p^.gen # g.gen then Sys.exit(3); end;
1777- s := s + g.p^.val;
1778- g := g.p^.next;
1779- end;
1780- return s;
1781-end;
1782-```
1783-
1784-The compiler's instruction counts: `valgrind --tool=callgrind raz -I src
1785--I build/src -o /dev/null src/Raz.raz`, the same compiler built twice
1786-from `src/`, once with `Scan.State.buf: ^U8` and once with `[]U8`. The
1787-five lines changed were the field's type, `grab(n + 1)[0..n + 1]`,
1788-`Diag.addFile(path, PTR(cur.buf), n)`, the local `buf` in `next`, and
1789-`intern(PTR(buf) + start, p - start)`. The second compiler builds
1790-itself.
1791-
1792-## Appendix 3: the five programs of section 1
1793-
1794-```
1795-module SelfAppend;
1796-import Buf, Heap, Out;
1797-
1798-proc main*;
1799-var b: Buf.Buf; i: INT;
1800-begin
1801- Buf.init(b, Heap.heap);
1802- for i := 1 to 64 do Buf.add(b, 'a'); end; (* full: 64 of 64 *)
1803- Buf.str(b, Buf.bytes(b)); (* doubles it: or should *)
1804- Out.str(Buf.bytes(b)[56..80]); Out.ln;
1805-end;
1806-
1807-end SelfAppend.
1808-```
1809-
1810-Prints `aaaaaaaaaaaaaaaaaaaaaaaa`, status 0: right, by luck.
1811-
1812-```
1813-module Stale;
1814-import Vec := Vec(INT), Heap, Out;
1815-
1816-proc main*;
1817-var v: Vec.Vec; first: []INT; i: INT; p: ^INT;
1818-begin
1819- Vec.init(v, Heap.heap);
1820- for i := 1 to 16 do Vec.push(v, i); end;
1821- first := Vec.all(v); (* good until v next grows *)
1822- p := Vec.add(v); (* grows: first now points at freed memory *)
1823- p^ := 99;
1824- for i := 0 to 15 do Vec.push(v, 1000 + i); end; (* grows again: p is stale *)
1825- p^ := -1; (* writes into a block the heap has taken back *)
1826- Out.int(first[0]); Out.str(" "); Out.int(first[1]); Out.ln;
1827-end;
1828-
1829-end Stale.
1830-```
1831-
1832-Prints `1 2`, status 0: it read and wrote freed memory, and looks right.
1833-
1834-```
1835-module Escape;
1836-import Out;
1837-
1838-type Hex = [16]U8;
1839-
1840-proc head(var h: Hex): []U8;
1841-begin
1842- return h[0..8]; (* allowed: h is the caller's *)
1843-end;
1844-
1845-proc short: []U8;
1846-var h: Hex; i: INT;
1847-begin
1848- for i := 0 to 15 do h[i] := 'x'; end;
1849- return head(h); (* a slice of short's frame: not caught *)
1850-end;
1851-
1852-proc noise;
1853-var junk: [64]U8; i: INT;
1854-begin
1855- for i := 0 to 63 do junk[i] := '#'; end;
1856-end;
1857-
1858-proc main*;
1859-var s: []U8;
1860-begin
1861- s := short();
1862- noise;
1863- Out.str(s); Out.ln;
1864-end;
1865-
1866-end Escape.
1867-```
1868-
1869-Prints `########`, status 0: `noise`'s bytes, read through a slice of
1870-a dead frame.
1871-
1872-```
1873-module Kept;
1874-import Names := Map([]U8, INT, Str.hash, Str.eq), Str, Heap, Out;
1875-
1876-var table: Names.Map;
1877-
1878-proc remember(n: INT);
1879-var buf: [8]U8;
1880-begin
1881- buf := "name-000";
1882- buf[7] := U8('0' + n);
1883- _ := Names.put(table, buf[0..8], n); (* the map keeps a slice of this frame *)
1884-end;
1885-
1886-proc main*;
1887-var v: INT; ok: BOOL;
1888-begin
1889- Names.init(table, Heap.heap);
1890- remember(1);
1891- remember(2);
1892- v, ok := Names.get(table, "name-001");
1893- Out.str("name-001: "); if ok then Out.int(v); else Out.str("missing"); end; Out.ln;
1894- v, ok := Names.get(table, "name-002");
1895- Out.str("name-002: "); if ok then Out.int(v); else Out.str("missing"); end; Out.ln;
1896-end;
1897-
1898-end Kept.
1899-```
1900-
1901-Prints `name-001: missing` and `name-002: missing`, status 0.
1902-
1903-```
1904-module Temp;
1905-import Out;
1906-
1907-type Name = [8]U8;
1908-
1909-proc named(c: U8): Name;
1910-var n: Name;
1911-begin
1912- n := "name-..."; n[7] := c;
1913- return n;
1914-end;
1915-
1916-proc main*;
1917-var a, b: []U8;
1918-begin
1919- a := named('a')[0..8]; (* the array lives to the end of the statement *)
1920- b := named('b')[0..8];
1921- Out.str(a); Out.str(" "); Out.str(b); Out.ln;
1922-end;
1923-
1924-end Temp.
1925-```
1926-
1927-Prints `name-..b`, a space and eight bytes of junk, status 0.
1928-
1929----
1930-
1931-## Appendix 4: adversarial review, soundness
1932-
1933-This appendix tests section 3's promise against parts A to F, read as
1934-written. It finds 12 ways a program of safe modules and the library, as
1935-section 17 would change it, still breaks the guarantee; 7 ambiguities
1936-or contradictions; and 3 problems with checking or building the rules
1937-in one pass. Two of the breaks are in today's language too, and the
1938-proposal leaves them as they are: a variant changed while `match` names
1939-its fields, and an `ERROR` written through a view. Both were run with
1940-today's compiler. The rest follow from the text of the proposal.
1941-
1942-### Breaks the guarantee
1943-
1944-**1. A variant changed under its `match`.**
1945-
1946-```
1947-type V = variant ptr(p: ^INT); num(n: INT); end;
1948-var v: V; (* a module variable *)
1949-proc flip(a: INT); begin v := num(a); end;
1950-...
1951-v := ptr(q);
1952-match v of
1953-| ptr(p): flip(h.(INT) + 8); p^ := 1000000; (* p reads num's bytes as a pointer *)
1954-| num(_n):
1955-end;
1956-```
1957-
1958-Run today, this sets the length of a heap slice, `h^.s`, to 1,000,000.
1959-Every operation in it stays safe under 5.1: the view only reads a
1960-pointer's bytes as an integer (10.3), and that is allowed. 7.4 says the
1961-names stand for the fields of `s` itself, and nothing stops the arm, a
1962-call it makes, or an alias (`var` parameter, pointer) from giving `s`
1963-another case. 10.4 covers only lending. Fix: in a safe module, an arm's
1964-names are a copy of the fields whenever the arm could change the
1965-variable (any call, any store through a pointer or `var` parameter, or
1966-the variable named), or each use of a name checks the tag first. Cost:
1967-a compare per use, or a copy per `match`, and one line less of 7.4.
1968-
1969-**2. An `ERROR` written through a view.** `e.(INT) := h.(INT);
1970-Out.str(MSG(e))` printed 64 KB of memory today. `ERROR` is an address
1971-(5.8), but the list in 5.1 and 10.3 of what may not be written through
1972-a view (pointer, procedure, slice, variant, enumeration, `BOOL`) leaves
1973-it out. Fix: add `ERROR`, and better, state the rule the other way round:
1974-a view may write only a variable made wholly of the types 6.9 allows as
1975-a view's `T`. Cost: none.
1976-
1977-**3. A safe module makes its own allocator.** `Mem.Allocator`'s fields
1978-are exported. 5.2 lets a safe procedure stand where an `unsafe proc`
1979-type is wanted. So a safe module can build `{alloc: mine, free: none}`
1980-and pass it to `NEW`. Its `mine` can return the same lasting `^U8` for
1981-every call, or a 1-byte block for a large `T`. Then `NEW` zeroes and
1982-hands out memory that two pointers of different types share, or that
1983-runs past its block. The same goes for copying `Arena.allocator(ar)^`,
1984-or `ar.base`, into a heap record and passing that: Arena's `alloc`
1985-casts its argument to `^Arena`, and reads past the copy. The trust of
1986-5.3 is broken by code the trusted module calls back. Fix: a field of an
1987-`unsafe proc` type may be set only in an unsafe module, and
1988-`Mem.Allocator` becomes a type safe code can't build or copy (its
1989-fields unexported, copying refused as for an owner). Cost: a rule in
1990-5.2 and in 7.6.
1991-
1992-**4. Procedures that take an allocator report arena memory as lasting.**
1993-`Mem.alloc`, `Str.copy` and the result of `NEW` through such a call
1994-carry no `ret` on their allocator, so by 6.1 what they return is
1995-lasting. Given `Arena.allocator(ar)`, they return arena memory. After
1996-`Arena.reset`, that memory goes to the next `NEW` of another type. The
1997-same holds for `Buf.init`, `Vec.init`, `Map.init`, `List.init` and
1998-`Pool.init`, which keep the allocator in the owner without a `keep`
1999-mark, against obligation 3. Fix: `ret a` on every procedure whose
2000-result comes from `a`, and `keep a` on every `init`. Then an arena's
2001-allocator can't be kept by a container, and what `Str.copy` gives from
2002-it is lent by the arena. Cost: marks on about ten headings.
2003-
2004-**5. Storing a lent slice in an element of a slice.** 6.2 allows a
2005-lent value to be "held in a local variable, or in a field or element of
2006-one". An element of a local slice is someone else's memory:
2007-
2008-```
2009-proc stash(s: [][]U8); (* s: the caller's array, or a Vec's block *)
2010-var buf: [8]U8;
2011-begin s[0] := buf[0..8]; end; (* allowed by 6.2's words; dangles after return *)
2012-```
2013-
2014-PROPOSALS' "outliving the call" lists `p^.f` and `p^[i]` but not
2015-`s[i]`. Fix: what is reached through a slice is a place that outlives
2016-the call, as through a pointer, unless the slice is lent only by the
2017-frame. Cost: a few false alarms on local slices of local arrays.
2018-
2019-**6. Only a call's result is counted.** 7.3 counts "where a call
2020-returns a reference lent by an owner". `t := s`, `t := s[1..3]` and
2021-`u := t^[0..10]`, with `s` held, are not calls. Read as written, `t`
2022-gets no hold. Then `s := []` lets the count fall to zero while `t`
2023-still points into the block, and the next growth frees it. Fix: every
2024-assignment to a local of a value lent by an owner sets that local's
2025-holds, whatever the expression. Cost: none beyond what was meant.
2026-
2027-**7. One hold, two owners.** A value may be lent by two owners at once:
2028-`Buf.bytes(all[0])` with `all := Bufs.all(v)`; `NEW(t, al)` with `T` an
2029-owner, then `Buf.bytes(t^)`; `pick(Buf.bytes(a), Buf.bytes(b))` with
2030-two `ret` parameters. 7.3 gives a local one hidden word. Whichever owner
2031-it leaves uncounted can free or move the memory: the outer `Vec` frees
2032-the block that holds the inner `Buf`, and the hold then lowers a word of
2033-freed memory. Fix: a hold per owner a value can be lent by, which the
2034-compiler knows from the heading. Or forbid an owner reached through an
2035-owner-lent value. Cost: a word per extra owner. The second choice
2036-forbids `Vec(Buf.Buf)` and `Pool` of owners in practice.
2037-
2038-**8. Library containers copy owners.** 7.6 forbids copies only in safe
2039-modules. `Vec`, `Pool`, `Map` and `List` are unsafe and generic, so
2040-they can't know that `T` is an owner. `Pool.get` returns a copy of a
2041-slot. `Vec`'s growth copies every element into the new block, and, with
2042-a lend held, keeps the old copy alive too. `Vec.pop`, `List.pop` and
2043-`Map.get` copy out. Two `Buf`s then own one block: one grows and frees
2044-it, and the other reads it. 7.6's rule also misses the result of a call
2045-(`b := Pools.get(p, h)` isn't "assigned from another variable"). Fix: a
2046-generic module's type parameter may be an owner only if the module says
2047-it takes owners. Those modules move owners, never copy them, and
2048-`get` is refused for them. Cost: a mark on generic parameters, and
2049-`Pool` and `Vec` written for both cases.
2050-
2051-**9. Other routes that copy or overwrite an owner.** None of these is in
2052-7.6's list:
2053-
2054-- `COPY(y, x)` on arrays of owners;
2055-- `match` on another module's variable, which today names fields of a
2056- copy (confirmed by running it), and so counts on the copy;
2057-- a variant case built from an owner, `has(b)`, which isn't plainly
2058- "a literal";
2059-- `b := {}`, `x^ := {}`, and `Pool.add(p, {})`, which 7.6 allows, and
2060- `Buf.init(b, a)` on a `Buf` with a lend held. Each sets `lends` to
2061- zero under a hold. The hold's later let-go makes it -1. The next lend
2062- brings it back to 0 while that slice is held, and the next growth
2063- frees the block under it.
2064-
2065-Fix: state the rule as "a value of a type that holds an owner is never
2066-copied or overwritten in a safe module, nor by the library while its
2067-`lends` is above zero". Add `COPY`, case construction, `match` on a
2068-copy, and `{}` over a variable that isn't already empty (or make
2069-`init` and `{}` stop when `lends` isn't zero). Cost: a few rules and a
2070-test in each `init`.
2071-
2072-**10. `take`, `swap` and the count.** 7.6 names `Buf.take(var from, to)`
2073-and `Buf.swap` and says nothing of `lends`. Holds point at `from.lends`.
2074-After the move, `to` owns the block with a count of 0, and frees it at
2075-its next growth while the slices are held. Fix: `take` and `swap` stop
2076-when either owner's `lends` is above zero. Cost: a compare each. Add it
2077-to obligation 2.
2078-
2079-**11. Letting go of a hold while a `match` names its fields.**
2080-
2081-```
2082-p := Vs.add(v); p^ := a("abc");
2083-match p^ of
2084-| a(s): p := nil; grow(v); Out.str(s); (* s names a field of a freed block *)
2085-| b:
2086-end;
2087-```
2088-
2089-The names stand for the variable in place, and assigning `p` lets its
2090-hold go. Fix: a `match` on a lent variable takes its own count for the
2091-whole statement. Cost: an add and a subtract per such `match`.
2092-
2093-**12. The library breaks its own obligations.** Section 17 leaves these
2094-as they are, and each lets a safe program reach freed memory:
2095-
2096-- `List.head*` and `Node.next*` are exported, against obligation 4.
2097- `n := l.head; List.pop(l); n^.val` reads a freed node.
2098-- `Thread.join` unmaps the mapping that holds the `Thread` record. The
2099- `^Thread` that `Task.spawn` returns stays "lasting", and a second
2100- `join` or a `signal` reads, and unmaps by, whatever the address
2101- holds next.
2102-- Over C, `Sys.nextEntry`'s name points into C's `readdir` buffer,
2103- which `closeDir` frees. `Dir` is no owner, so nothing counts it. A
2104- `nextEntry` or `closeDir` after `closeDir` hands C a freed `DIR`.
2105-- Over musl, `Sys.env`'s "lasting" result can be freed by a later
2106- `setEnv` of the same name, since musl frees the strings it made.
2107-- `Names(V)`'s procedures that return a key must be `ret`, or `remove`
2108- frees what they gave. The proposal doesn't give its headings.
2109-
2110-Fix: unexport `List`'s pointers and give an iterator that lends;
2111-`Task` returns an owner handle that `join` takes by `var` and empties;
2112-`Dir` an owner; `env` copied into lasting memory over C. Cost: small,
2113-but it shows that obligations 1 to 5 need an audit of each module, not
2114-only the marks of section 17.
2115-
2116-### Ambiguities and contradictions
2117-
2118-**13. Section 3 calls a racing container program safe.** Section 3's
2119-definition counts a program as safe if its threads race "only on
2120-variables of a basic, pointer, procedure or slice type". Two threads
2121-calling `Buf.add` on one `Buf` race only on such fields (`len`,
2122-`data`), so the guarantee claims their behaviour is defined. 9.2 says
2123-it isn't. Fix: put 9.2's "a container's procedures called at once"
2124-into section 3's sentence.
2125-
2126-**14. A slice in a packed record, or in a block aligned to 8.** E.1
2127-promises one access for every slice. A slice field of a packed record
2128-is read in parts (5.5). `Vec` asks its allocator for 8-byte alignment.
2129-Either tears, or `movdqa` faults on it. Fix: no slice in a packed
2130-record; every allocator call for a type holding a slice asks for 16.
2131-
2132-**15. Returning what an owner inside a parameter lent.** 6.2 forbids
2133-returning a value "lent by an owner", even when the owner is a `ret`
2134-parameter. So `proc bytes2(ret const b: Buf): []U8 begin return
2135-Buf.bytes(b) end` is an error, and 14.2's recommended
2136-`Http.name(ret const m: Message; i): []U8` can't be written. If it is
2137-allowed, a caller of `name` sees only `m`, which is no owner (7.2), and
2138-has no count to raise. Fix: allow it when the `ret` parameter is itself
2139-the owner. For a record that holds owners, the caller raises each of
2140-their counts, or the accessor is refused.
2141-
2142-**16. When the epilogue lets go.** 7.3 says the let-go happens "as a
2143-`defer` would". If it is placed as a `defer` at the assignment, a user
2144-`defer f(b, s)` written before it runs after the let-go, and `f` can
2145-grow `b` and read `s`. Fix: holds are let go after every deferred
2146-statement has run.
2147-
2148-**17. "The end of the statement" for compound statements.** A count
2149-taken in a `while` condition, a `for` bound, an `if` condition or a
2150-`match` head: is it lowered once per evaluation or at the statement's
2151-`end`? Lowered once at `end`, a `while` raises it each round and leaks
2152-counts. Then `done` stops though nothing is held. A `try` that leaves
2153-mid-statement must lower it too. Fix: say per evaluation, and on every
2154-exit.
2155-
2156-**18. Two arms of one rule for `{}`.** 7.6 forbids passing an owner as
2157-a value parameter but allows a literal that leaves it out. So is
2158-`Pool.add(p, {})` allowed? Item 9 shows why the answer matters.
2159-
2160-**19. Writable constants beyond strings.** F.2 covers a string's bytes.
2161-An array constant of variants, enumerations or `BOOL`s may be sliced
2162-(4), and on a target where constants are writable, a compiler that
2163-folds `match Rows[0]` from the constant's case reads fields of another
2164-case. Fix: on such targets, writing any constant through a slice stops
2165-the program, or slices of non-string constants can't be written.
2166-
2167-### One-pass and implementability problems
2168-
2169-**20. A hold must be kept for every reference local.** A local may hold
2170-a lasting value at one assignment and an owner's lend at a later one
2171-(a loop's next round), and one pass doesn't know the later one when it
2172-compiles the earlier. So every assignment to every slice or pointer
2173-local must test and lower a hold, and every copy from one local to
2174-another must pass the hold on. That cost is per assignment, not "per
2175-lend held", and it falls on `src/`'s pointer loops (`o := o^.next`).
2176-Section 13 doesn't count it. Fix: measure it, or let a hold word exist
2177-only for locals declared with a mark (say `lent s: []U8`), checked at
2178-`end`.
2179-
2180-**21. Atomic counts depend on the whole program.** E.5 makes the counts
2181-`lock xadd` "in a program that imports `Thread`". A module compiled
2182-before another module's `import Thread` is read can't know which to
2183-emit, and separate compilation (10) forbids depending on it. Fix:
2184-always `lock`, or read every module's imports first. Cost: about 20
2185-cycles per lend, or a pass over the import graph.
2186-
2187-**22. Re-entry through the procedures a container is given.** `Map`
2188-calls `hash` and `eq`, `Sort` calls `less`, `Guarded.with` calls its
2189-procedure, and `Rt.atExit` procedures run after a failed check inside
2190-any of these. A safe callback can call `put`, `remove` or `done` on the
2191-same container while its own code is mid-loop: `done` inside `eq` while
2192-`get` probes leaves `slots` nil with an index still in hand. No
2193-obligation in 5.3 speaks of it, and checking the trusted code for every
2194-re-entry is not one pass of anything. Fix: obligation 6, "a module that
2195-calls a procedure given by safe code holds its own `lends` across the
2196-call", so that `done` stops; the library's containers do it.
2197-
2198-### Checked and found covered
2199-
2200-- `Pool.at` across `Pool.free`: the slot keeps its type, so a stale
2201- pointer reads the wrong record of the right type, as 8.2 says. That
2202- holds except for variants (item 1) and owners in slots (items 7 to 9).
2203-- Retired blocks and `reset`: the bytes keep their type; a held slice
2204- sees new contents, safely.
2205-- `var` parameters aliasing: `f(x, x)` with a `done` inside stops on
2206- the count; a callee assigning the caller's held local through `var`
2207- leaves the hold set, which errs on the safe side.
2208-- Holds and threads: a thread raises a count only while it already
2209- holds one, so the count can't pass through zero under another
2210- thread's test.
2211-- `Task.spawn`: `keep x` refuses lent values, and owners can't be
2212- passed by value.
2213-- `a, b := f(x)` and `return f(x)`: each target is checked as a single
2214- assignment.
2215-- A `const` parameter of another module's variable is passed in place
2216- today (run to confirm), so its count lands on the real owner.
2217-- A safe generic module instantiated with an owner: each instance is
2218- checked, so a copy inside it is refused there.
2219-
2220----
2221-
2222-## Appendix 5: adversarial review, claims about other languages and hardware
2223-
2224-This appendix checks every claim MEM_PROPOSAL.md makes about other
2225-languages, hardware, research and precedent. Of 44 claims checked, 5
2226-are wrong, 22 imprecise, 15 correct and 2 unverifiable. None of the
2227-errors breaks the design. Three of them touch it, though: 21.5 leans on
2228-Swift for a cross-thread check that Swift doesn't make; 9.2 says a
2229-slice published with no lock is safe, which fails on ARM; and 11 files
2230-Chrome's BackupRefPtr under debugging heaps, when it is the closest
2231-precedent for part C. Most of the imprecise ones are table cells that
2232-leave out a condition or a newer fact.
2233-
2234-How it was checked: through the session's proxy, which let through only
2235-GitHub-hosted sources (raw.githubusercontent.com) and web search. So
2236-primary sources were read where they live on GitHub (the Go memory
2237-model and spec, the C# standard, swift-evolution, Zig's langref and
2238-library, Fil-C, Chromium, glibc, slotmap, generational-arena,
2239-portable-atomic, GCC's libatomic, the Linux kernel's MTE document, D's
2240-DIPs, CPython). Vendor manuals (Intel SDM, AMD APM, Arm ARM) and the
2241-Modula-3, Ada and Java texts were checked through quotations that web
2242-search returned. Where a manual's section number could not be seen
2243-directly, the entry says so.
2244-
2245-### Wrong
2246-
2247-**W1. Section 21.5: "changes from another thread without the lock stop
2248-the program, as Swift's exclusivity checks do."**
2249-Wrong. Swift's run-time exclusivity checks are not required to see
2250-accesses from other threads, and by design they don't look. SE-0176
2251-says: "Dynamic enforcement is not required to detect concurrent
2252-conflicting accesses, and we propose that by default it should not
2253-make any effort to do so ... it can track accesses in a thread-local
2254-data structure." Swift leaves races to Thread Sanitizer and, since
2255-Swift 6, to `Sendable` checking at compile time.
2256-Source: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0176-enforce-exclusive-access-to-memory.md (section "Concurrency").
2257-Correct wording: "... stop the program. Swift's run-time exclusivity
2258-checks don't do this: they track accesses per thread. The nearest
2259-precedents are Go's run-time check for concurrent map writes and
2260-ThreadSanitizer."
2261-
2262-**W2. Section 12, Zig row: "`@ptrCast`, `@intToPtr` anywhere".**
2263-Wrong name. `@intToPtr` was renamed `@ptrFromInt` in Zig 0.11 (2023),
2264-and `@ptrToInt` became `@intFromPtr`. Today's langref has
2265-`@ptrFromInt` (7 uses) and `@intFromPtr` (6), and no `@intToPtr`.
2266-Source: https://raw.githubusercontent.com/ziglang/zig/master/doc/langref.html.in (Zig has since moved to Codeberg; the GitHub copy is the last one mirrored).
2267-Correct wording: "`@ptrCast`, `@ptrFromInt` anywhere".
2268-
2269-**W3. Section 12, "Java, C#" row: forged pointers "none".**
2270-Wrong for C#. C# has real pointers, pointer arithmetic and casts from
2271-integers in `unsafe` code. The same row names C#'s `unsafe` blocks as
2272-its fence, so the row contradicts itself. Also,
2273-`System.Runtime.CompilerServices.Unsafe` and `MemoryMarshal` reinterpret
2274-references with no `unsafe` keyword at all, so the fence has holes. Java
2275-can forge addresses through `sun.misc.Unsafe` (its memory methods were
2276-deprecated for removal in JDK 23, JEP 471) and through the FFM API's
2277-restricted methods, which warn unless `--enable-native-access` is given
2278-(JEP 454 and 472).
2279-Sources: https://github.com/dotnet/csharpstandard (unsafe code chapter); https://mail.openjdk.org/pipermail/jdk-dev/2024-May/008910.html (JEP 471); https://www.infoq.com/news/2024/07/jep-472-restrict-jni-jdk-24.
2280-Correct wording: split the row. Java: "none in the language;
2281-`sun.misc.Unsafe` and FFM restricted methods, behind a flag". C#: "in
2282-`unsafe` code; also the `Unsafe` and `MemoryMarshal` classes, which
2283-need no `unsafe`".
2284-
2285-**W4. Section 9.2, point 1: "A program that hands slices from thread to
2286-thread, publishing a buffer for others to read, is then safe with no
2287-lock."**
2288-Wrong on ARM, and true on x86-64 only if the compiler keeps the stores
2289-in order. Single-copy atomicity means the 16 bytes don't tear. It says
2290-nothing about the order in which other stores are seen. AArch64 is
2291-weakly ordered. A reader can see the new slice and still see old bytes
2292-in the buffer it points at, unless the store is a release (`STLR`, or
2293-`DMB` then `STP`) and the load an acquire. If the buffer was a recycled
2294-heap block, those old bytes may be another type's pointers. That breaks
2295-the type guarantee of section 3, which publication with no lock is
2296-meant to keep. x86-64's TSO keeps store order, so there it holds,
2297-provided the compiler doesn't reorder.
2298-Sources: https://raw.githubusercontent.com/taiki-e/portable-atomic/main/src/imp/atomic128/aarch64.rs (needs FEAT_LRCPC3's `LDIAPP`/`STILP`, or barriers, for acquire and release); the Arm ARM's memory model, B2.3.
2299-Correct wording: "... is then safe with no lock on x86-64. On AArch64 a
2300-slice store that publishes is a release and its load an acquire;
2301-appendix A says how."
2302-
2303-**W5. Section 12, "Java, C#" row: "references never tear; `long` may in
2304-Java".**
2305-Wrong by omission for C#, the row's other language. The C# standard
2306-(9.6) promises atomic reads and writes only for `bool`, `char`, the
2307-integer types up to 32 bits, `float` and references. It says "Reads and
2308-writes of other types, including `long`, `ulong`, `double`, and
2309-`decimal`, as well as user-defined types, need not be atomic." So C#
2310-structs tear, and that includes multi-word ones such as `ArraySegment<T>`
2311-and `Memory<T>`. C# stays memory-safe anyway because every array access
2312-is checked again against the array itself. That is worth saying, since
2313-it is the other way out of the torn-slice problem.
2314-Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/standard/variables.md#96-atomicity-of-variable-references.
2315-Correct wording: "references never tear; `long` and `double` may (in
2316-C#, structs too), but each array access is checked again".
2317-
2318-### Imprecise
2319-
2320-**I1. Section 9.2: "`movdqa`, which Intel and AMD guarantee single-copy
2321-atomic on processors with AVX"; section 4: "none on x86-64 with AVX".**
2322-Right in substance, but conditions are missing. Intel's SDM Vol. 3A,
2323-"Guaranteed Atomic Operations" (section 9.1.1 in the editions that GCC
2324-and Microsoft's STL quote; numbering shifts between editions), says:
2325-"Processors that enumerate support for Intel AVX (by setting the
2326-feature flag CPUID.01H:ECX.AVX[bit 28]) guarantee that the 16-byte
2327-memory operations performed by the following instructions will always
2328-be carried out atomically: MOVAPD, MOVAPS, and MOVDQA; VMOVAPD,
2329-VMOVAPS, and VMOVDQA when encoded with VEX.128; VMOVAPD, VMOVAPS,
2330-VMOVDQA32, and VMOVDQA64 when encoded with EVEX.128 and k0 (masking
2331-disabled)", with the operands 16-byte aligned. AMD's APM Vol. 2
2332-(Access Atomicity; I couldn't see the section number) is broader in one
2333-way and narrower in another: "Processors that report CPUID
2334-Fn0000_0001_ECX[AVX](bit 28) = 1 extend the atomicity for cacheable,
2335-naturally-aligned single loads or stores from a quadword to a double
2336-quadword." So AMD's covers any aligned 16-byte load or store, but only
2337-to cacheable memory. Neither promise belongs to "x86-64 with AVX" in
2338-general. GCC's libatomic trusts it only on Intel, AMD, Zhaoxin and
2339-newer Centaur parts, and clears AVX for other vendors: "We don't have
2340-a guarantee from vendors of other CPUs with AVX, like VIA."
2341-"Single-copy atomic" is Arm's term; Intel says "carried out
2342-atomically".
2343-Sources: https://gcc.gnu.org/pipermail/gcc-patches/2022-February/590960.html (PR104688, quoting the SDM); https://raw.githubusercontent.com/gcc-mirror/gcc/master/libatomic/config/x86/init.c; https://raw.githubusercontent.com/taiki-e/portable-atomic/main/src/imp/atomic128/x86_64.rs ("Intel, AMD, and Zhaoxin officially guarantee this behavior (VIA has not responded)"); https://github.com/microsoft/STL/issues/4480.
2344-Correct wording: "moved with `movdqa` from a 16-byte-aligned address.
2345-Intel (SDM Vol. 3A, Guaranteed Atomic Operations) and AMD (APM Vol. 2,
2346-Access Atomicity, for cacheable memory) guarantee this atomic on
2347-processors that report AVX, and so does Zhaoxin. Other vendors' AVX
2348-parts take the fallback."
2349-
2350-**I2. Section 9.2: "ARMv8.4 has 16-byte atomic `LDP`/`STP`
2351-(FEAT_LSE2)".**
2352-True, but the conditions and the reach are missing. FEAT_LSE2 is
2353-optional from Armv8.2 and mandatory from Armv8.4. The Arm ARM (DDI
2354-0487, B2.2.1.1, as quoted on LKML) makes LDP/LDNP/STP of two 64-bit
2355-registers single-copy atomic only when the access is 16-byte aligned
2356-and goes to Inner Write-Back, Outer Write-Back Normal cacheable memory.
2357-Many 64-bit Arm machines in use don't have it: Cortex-A72 (Raspberry
2358-Pi 4), Cortex-A76 (Pi 5), Neoverse N1 (AWS Graviton2, Ampere Altra).
2359-They need `LDXP`/`STXP` loops (Armv8.0) or `CASP` (FEAT_LSE, Armv8.1).
2360-Sources: https://lkml.iu.edu/2511.1/09040.html; https://raw.githubusercontent.com/taiki-e/portable-atomic/main/src/imp/atomic128/aarch64.rs ("LDP/STP: load/store (if Armv8.4 FEAT_LSE2 (optional from Armv8.2, mandatory from Armv8.4) is available)").
2361-Correct wording: "With FEAT_LSE2 (mandatory from Armv8.4) an aligned
2362-16-byte `LDP`/`STP` to normal cacheable memory is single-copy atomic.
2363-Earlier cores use `LDXP`/`STXP` or `CASP`."
2364-
2365-**I3. Section 9.2: "On x86-64 without AVX, the implementation uses
2366-`lock cmpxchg16b`".**
2367-Works, with three costs left unsaid. First, CMPXCHG16B (CPUID CX16) is
2368-not in the x86-64 baseline (x86-64-v1): the first AMD64 processors
2369-lack it. Second, a load done as `lock cmpxchg16b` writes the line. So
2370-it faults on read-only pages, needs the memory to be writable (as
2371-portable-atomic's safety comments say), and makes readers contend with
2372-one another. libatomic: "Since load and store are implemented with
2373-CAS, they are not fast." Third, a store needs a CAS loop. Raz keeps
2374-slice constants, `[]` among them, in read-only data. The compiler would
2375-have to know those are never raced and read them plainly.
2376-Sources: https://raw.githubusercontent.com/gcc-mirror/gcc/master/libatomic/config/x86/host-config.h; portable-atomic's x86_64.rs, as above.
2377-
2378-**I4. Section 13.3, row E: "none: two 8-byte moves become one 16-byte
2379-one".**
2380-Not free when the slice goes to or from general registers. That is
2381-the usual case, since raz returns a slice in rax and rdx. A 16-byte
2382-load into an XMM register then needs `movq` plus `pextrq` (or a shuffle
2383-and `movq`) to split it, and a store needs `movq` plus `pinsrq` or
2384-`punpcklqdq` to join it: two to three more uops, and a few cycles of
2385-latency. `pextrq` and `pinsrq` are SSE4.1, which is not baseline
2386-x86-64. This is the machine's cost, and it should be measured like the
2387-others.
2388-Correct wording: "a load or store of a slice through an XMM register:
2389-one or two more instructions where its words go to or from general
2390-registers; records holding slices may grow by padding to 16."
2391-
2392-**I5. Section 7.5: "`inc qword [r]` ... about two cycles each ... `lock
2393-xadd`, about 20 cycles".**
2394-Rough. On Intel, an uncontended `lock` read-modify-write measures about
2395-18 cycles (uops.info, Skylake). On recent AMD cores it is lower. It is
2396-a full barrier, and under contention, with the line bouncing between
2397-cores, it costs hundreds of cycles. That is the case that matters for
2398-two threads lending from one locked `Buf`. A memory-destination `inc`
2399-has a throughput near one a cycle, but about five to six cycles of
2400-latency when chained through store forwarding.
2401-Sources: https://uops.info/html-instr/INC_LOCK_M32.html; https://www.agner.org/optimize/instruction_tables.pdf.
2402-Correct wording: "... `lock xadd`, about 20 cycles uncontended on
2403-Intel, and far more when threads contend for one owner".
2404-
2405-**I6. Section 12, Zig row: "the debug allocator finds use after free and
2406-double frees at run time; nothing in release".**
2407-Partly. `std.heap.DebugAllocator` (renamed from `GeneralPurposeAllocator`
2408-in 0.14.0) lists "Double free detection" and "Leak detection, with
2409-stack traces". It doesn't detect use after free. It "Never reuses
2410-memory addresses" and gives freed pages back "so that it causes page
2411-faults when used", and in safe modes freed memory reads as `0xaa`. So
2412-a use after free may fault or read junk, and nothing reports it as
2413-such. The allocator is chosen by the program, not by the build mode:
2414-it works in ReleaseSafe too.
2415-Source: https://raw.githubusercontent.com/ziglang/zig/master/lib/std/heap/debug_allocator.zig (header comment).
2416-Correct wording: "the debug allocator finds double frees and leaks, and
2417-never reuses addresses, so a use after free tends to fault; a program
2418-chooses it, usually in Debug".
2419-
2420-**I7. Section 12, "C++, hardened" row: "hardened `std` containers;
2421-`-fbounds-safety` for C (clang)".**
2422-This mixes two things. `-fbounds-safety` is a C extension, not C++
2423-hardening. Apple designed it and ships it in Apple's clang. Upstream,
2424-it is "being incrementally upstreamed", behind
2425-`-fexperimental-bounds-safety`. On the C++ side, the newer fact is
2426-missing: C++26 standardizes library hardening (P3471, adopted at
2427-Hagenberg, February 2025), on top of libc++'s hardening modes and
2428-libstdc++'s `_GLIBCXX_ASSERTIONS`.
2429-Sources: https://lists.llvm.org/pipermail/cfe-commits/Week-of-Mon-20240513/579251.html; https://clang.llvm.org/docs/BoundsSafetyImplPlans.html; https://open-std.org/JTC1/SC22/WG21/docs/papers/2025/p3471r4.html.
2430-Correct wording: C row: "Spatial: none; Apple's `-fbounds-safety`
2431-extension (clang, partly upstream) adds checked bounds". C++ row:
2432-"hardened standard library (libc++, libstdc++; standard in C++26 by
2433-P3471)".
2434-
2435-**I8. Section 12, "Odin, Hare, C3" row: spatial "checked".**
2436-True by default for all three, but each can turn it off. C3 checks
2437-only in its safe (debug) mode, and in fast builds an out-of-bounds index
2438-is undefined. Hare checks every slice and array access, but its `[*]T`
2439-arrays are unchecked. Odin has `#no_bounds_check` and
2440-`-no-bounds-check`.
2441-Sources: https://c3-lang.org/language-rules/undefined-behaviour/; https://harelang.org/blog/2022-06-21-safety-features/.
2442-Correct wording: "checked by default (C3: in safe builds only); each can
2443-turn it off".
2444-
2445-**I9. Section 12, Swift row: fence "`Unsafe` in names".**
2446-Out of date. SE-0458, "Opt-in Strict Memory Safety Checking", is
2447-implemented in Swift 6.2. It adds `-strict-memory-safety`, an `@unsafe`
2448-attribute, a `@safe` attribute for a declaration that is "actually
2449-safe to use" though its signature holds unsafe types, and an `unsafe`
2450-expression "much like `try` and `await`". That is a real fence, and
2451-`@safe` is section 5.3's trust in a safe interface.
2452-Source: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0458-strict-memory-safety.md.
2453-Correct wording: "`Unsafe` in names; since Swift 6.2, an opt-in
2454-checked fence (`@unsafe`, `@safe`, `unsafe` expressions)".
2455-
2456-**I10. Section 12, Ada row: races "protected objects".**
2457-Protected objects are the tool, not the guarantee. In Ada, two
2458-unsynchronized conflicting uses of a shared variable are erroneous (RM
2459-9.10): "The execution of two concurrent actions is erroneous if the
2460-actions make conflicting uses of a shared variable." SPARK, under the
2461-Ravenscar and Jorvik profiles, proves there are no data races.
2462-Source: https://ada-lang.io/docs/arm/AA-9/AA-9.10/.
2463-Correct wording: "erroneous unless synchronized (protected objects,
2464-atomics); SPARK proves their absence".
2465-
2466-**I11. Section 12: "Ada's accessibility levels are part B's frame,
2467-parameters and lasting memory, nearly exactly."**
2468-Overstated. Ada's levels (RM 3.10.2) attach mainly to where an access
2469-type is declared. A library-level access type can't designate a
2470-deeper object. Most checks are static, but those for anonymous access
2471-parameters and some others run at run time and raise `Program_Error`.
2472-There is no notion of "lent by this parameter" for a result. The
2473-closest match to part B is C#'s ref-safety rules: their "safe-context"
2474-values are "declaration-block", "function-member" and
2475-"caller-context". Those are part B's frame, parameters and lasting
2476-nearly one for one. C# 11 adds `scoped` and `[UnscopedRef]`, which play
2477-the roles of `ret` and `keep`.
2478-Source: https://github.com/dotnet/csharplang/blob/main/proposals/csharp-11.0/low-level-struct-improvements.md.
2479-Correct wording: "Ada's accessibility levels are the idea; C#'s
2480-safe-contexts (declaration block, function member, caller) are part
2481-B's three lenders nearly exactly."
2482-
2483-**I12. Section 5.3: "This is Modula-3's rule for an `UNSAFE MODULE`
2484-that implements a safe `INTERFACE`".**
2485-Right as far as it goes, but Modula-3 also fences imports, and raz
2486-doesn't. The Modula-3 report's Safety section says: "It is a static
2487-error for a safe interface to import an unsafe one or for a safe module
2488-to import or export an unsafe interface." Raz lets any safe module
2489-import an unsafe one and fences per procedure (`unsafe proc`). That is
2490-closer to D's `@safe`/`@trusted`/`@system` per function, and to Rust's
2491-`unsafe fn`, than to Modula-3.
2492-Source: https://www.cs.purdue.edu/homes/hosking/m3/reference/safety.html.
2493-Correct wording: add "Unlike Modula-3, which forbids a safe module to
2494-import an unsafe interface, raz fences per procedure, as D's
2495-`@trusted` and Rust's `unsafe fn` do."
2496-
2497-**I13. Section 12: "The unit of review is a file, as Wirth's languages
2498-always had it."**
2499-Modula-3 isn't Wirth's. It came from DEC SRC and Olivetti, building on
2500-Modula-2+. Pascal had no modules, so "always" is wrong. Modula-2 and
2501-Oberon do mark low-level code by importing `SYSTEM` per module.
2502-Correct wording: "The unit of review is a module, as in Modula-2's and
2503-Oberon's `IMPORT SYSTEM` and Modula-3's `UNSAFE`."
2504-
2505-**I14. Section 12, Vale row: "regions skip the check"; races "regions";
2506-fence "`unsafe`".**
2507-These are mostly Vale's plans. Vale's last release is 0.2 (2022). Its
2508-own project page lists the region borrow checker and hybrid-generational
2509-memory as medium-term goals, and its `unsafe` blocks and "Fearless
2510-FFI" were proofs of concept. Generational references themselves,
2511-section 8.2's claim, are right: each object carries a current
2512-generation, each non-owning reference a remembered one, checked on
2513-dereference. Owning references aren't checked.
2514-Sources: https://vale.dev/memory-safe; https://vale.dev/project; https://vale.dev/blog/version-0.2-released.
2515-Correct wording: "generational references, checked at each
2516-dereference; regions, which would skip the check, are designed and not
2517-finished".
2518-
2519-**I15. Section 12, Cyclone row: temporal "regions, checked
2520-statically".**
2521-Leaves out that Cyclone's heap region is garbage collected
2522-(conservatively, with the Boehm collector). Grossman's PLDI 2002 paper
2523-integrates regions "with stack allocation and a garbage collector".
2524-Unique and reference-counted pointers came later (Hicks et al.).
2525-Cyclone's temporal safety for the heap is a GC, which is what raz
2526-refuses.
2527-Sources: https://www.cs.umd.edu/~mwh/papers/GrossmanMJHWC02.html; https://www.cs.washington.edu/homes/djg/slides/cyclone_pldi02.pdf.
2528-Correct wording: "regions checked statically; the heap region garbage
2529-collected".
2530-
2531-**I16. Section 12, "Fil-C, CHERI" row: "Fil-C: a few times slower";
2532-"Fil-C: atomic capabilities"; "CHERI: revocation".**
2533-Fil-C's own figures are "about 1.5x-4x slower" (README and Manifesto,
2534-version 0.686). On races, Fil-C says "Pointer races on pointers not
2535-marked `_Atomic` or `volatile` lead to Fil-C panics, at worst". Only
2536-atomic pointers get an "atomic box". CHERI's capabilities give spatial
2537-safety in hardware. Its temporal safety needs software revocation
2538-sweeps (Cornucopia, in CheriBSD), and it costs 128-bit pointers.
2539-Sources: https://raw.githubusercontent.com/pizlonator/fil-c/deluge/README.md; https://raw.githubusercontent.com/pizlonator/fil-c/deluge/Manifesto.md.
2540-Correct wording: "Fil-C: 1.5 to 4 times slower, and a concurrent GC;
2541-CHERI: 128-bit capabilities, and revocation by software sweeps".
2542-
2543-**I17. Section 19: "[MTE and CHERI] aren't on x86-64, and they are
2544-probabilistic (MTE's four bits)."**
2545-Two fixes. First, only MTE is probabilistic: a 4-bit tag per 16-byte
2546-granule (Linux's document: "a 4-bit allocation tag for each 16-byte
2547-granule"), so a stale pointer passes 1 time in 16 by chance. CHERI's
2548-bounds are exact. Second, x86 is on its way: Intel and AMD announced
2549-ChkTag, a common x86 memory-tagging specification, on 13 October 2025,
2550-with no shipping date. MTE is also not only for debugging any more.
2551-Apple's Memory Integrity Enforcement runs Enhanced MTE always on and
2552-synchronously on the iPhone 17 (September 2025).
2553-Sources: https://raw.githubusercontent.com/torvalds/linux/master/Documentation/arch/arm64/memory-tagging-extension.rst; https://www.amd.com/en/blogs/2025/amd-and-intel-celebrate-first-anniversary-of-x86-ecosys.html; https://www.phoronix.com/news/AMD-Intel-One-Year-x86-Eco; https://security.apple.com/blog/memory-integrity-enforcement.
2554-Correct wording: "They aren't on x86-64 yet (Intel and AMD announced
2555-ChkTag in 2025). MTE is probabilistic, with four bits a tag; CHERI is
2556-exact, but needs software revocation for use after free."
2557-
2558-**I18. Section 11: "This is ... Chrome's MiraclePtr quarantine".**
2559-MiraclePtr is not a debugging heap, and its quarantine isn't a fixed
2560-count. `raw_ptr<T>`, implemented by BackupRefPtr, keeps a reference
2561-count in each PartitionAlloc slot. It is "quarantining the freed memory
2562-as long as any dangling `raw_ptr<T>` pointing to it exists, and
2563-poisoning it (with 0xEF..EF pattern)". Its constructor, destructor and
2564-assignment "need to maintain BackupRefPtr's ref-count (atomic
2565-increment/decrement)". It ships in production Chrome. That makes it a
2566-precedent for part C, not part G: count the references a block has
2567-lent, and retire the block instead of freeing it while the count is
2568-above zero. Its documentation also records the cost part C should
2569-expect: "on a couple occasions it led to significant memory leaks". A
2570-fixed FIFO quarantine with guard bytes, like part G's, is
2571-AddressSanitizer's quarantine and redzones, and GWP-ASan's.
2572-Source: https://raw.githubusercontent.com/chromium/chromium/main/base/memory/raw_ptr.md.
2573-Correct wording in 11: "This is AddressSanitizer's quarantine and
2574-redzones, Zig's debug allocator and glibc's `MALLOC_PERTURB_`, without
2575-their reach." Add to section 7: "Chrome's BackupRefPtr (MiraclePtr)
2576-does the same in C++: it counts a block's references and quarantines
2577-it on free while the count is above zero."
2578-
2579-**I19. Section 3 and 9.2, point 2: a race on a whole record or variant
2580-"is undefined, as in Go".**
2581-Go doesn't call it undefined. The memory model says a racy read of a
2582-multi-word value may see "inconsistent values not corresponding to a
2583-single write". Only "when the values depend on the consistency of
2584-internal (pointer, length) or (pointer, type) pairs, as can be the case
2585-for interface values, maps, slices, and strings in most Go
2586-implementations, such races can in turn lead to arbitrary memory
2587-corruption." Go sets itself apart from C and C++, "where the meaning of
2588-any program with a race is entirely undefined". A race on a plain
2589-struct of integers just gives mixed values.
2590-Source: https://raw.githubusercontent.com/golang/go/master/doc/go_mem.html (go.dev/ref/mem).
2591-Correct wording: "undefined. Go is narrower: a race tears such a value,
2592-and corrupts memory only through its pointer and length or type pairs."
2593-
2594-**I20. Section 9.1: Go's memory model on races over multi-word values.**
2595-The quotation is right, but the list it gives is short. Go names
2596-"interface values, maps, slices, and strings", hedged "in most Go
2597-implementations", and says such races "can in turn lead to arbitrary
2598-memory corruption". The proposal's list drops maps, and its "an
2599-interface, a slice, a string" reads as Go's words when they are a
2600-paraphrase.
2601-Source: as I19.
2602-Correct wording: "Go's memory model says that races on values made of
2603-(pointer, length) or (pointer, type) pairs, 'interface values, maps,
2604-slices, and strings in most Go implementations', 'can in turn lead to
2605-arbitrary memory corruption'."
2606-
2607-**I21. Section 12: "From Swift: checking exclusivity at run time where
2608-the compiler can't, as part C counts lends."**
2609-Loose. Swift's dynamic exclusivity tracks the start and end of each
2610-access to a class property, global or escaped variable, per thread
2611-(W1). It doesn't count. Part C counts outstanding loans and refuses or
2612-defers a release while any is held. That is Rust's `RefCell` (a borrow
2613-count that panics), CPython's `bytearray` (it keeps `ob_exports` and
2614-refuses to resize: "Existing exports of data: object cannot be
2615-re-sized"), Java's and .NET's fail-fast iterators (a modification
2616-count), and Chrome's BackupRefPtr (I18).
2617-Sources: https://raw.githubusercontent.com/python/cpython/main/Objects/bytearrayobject.c; https://raw.githubusercontent.com/rust-lang/rust/master/library/core/src/cell.rs.
2618-Correct wording: "From Rust's `RefCell`, CPython's buffer exports and
2619-Chrome's BackupRefPtr: a count of what is lent, checked at run time,
2620-where the compiler can't see it."
2621-
2622-**I22. Section 8.2: "Part of the first is that each slot is 32 bytes,
2623-not 16"; and open question 6, one word or two for a handle.**
2624-The precedent the proposal cites answers the question, and the
2625-proposal doesn't use it. slotmap's key is one 64-bit word: a 32-bit
2626-index and a 32-bit version (`idx: u32, version: NonZeroU32`). A slot
2627-costs `4 + max(sizeof(T), 4)` bytes. Versions wrap after 2^31 reuses of
2628-a slot, "and in all circumstances is the behavior safe". So the 32-byte
2629-slot of the benchmark comes from the two-word `Handle` chosen here, not
2630-from generational handles as such. The 1.5x past the caches is partly
2631-an artifact of that choice.
2632-Source: https://raw.githubusercontent.com/orlp/slotmap/master/src/lib.rs.
2633-Correct wording: add to 21.6: "slotmap takes one word, 32 bits each,
2634-and lets the version wrap; with it, a slot of a 16-byte `T` is 20 or
2635-24 bytes, not 32."
2636-
2637-### Correct
2638-
2639-**C1. Section 9.1: "Java closes it by tearing only `long` and `double`,
2640-never a reference."** Correct. JLS 17.7: a non-volatile `long` or
2641-`double` write may be treated "as two separate writes, one to each
2642-32-bit half"; "Writes to and reads of references are always atomic,
2643-regardless of whether they are implemented as 32-bit or 64-bit
2644-values." Source: https://docs.oracle.com/javase/specs/jls/se21/html/jls-17.html#jls-17.7 (read through a mirror: https://www.oreilly.com/library/view/the-java-language/9780133260335/ch17lev1sec7.html).
2645-
2646-**C2. Section 7.4: "This is Go's `append`: the old slice still sees the
2647-old array."** Correct for a growing append. The spec says: "If the
2648-capacity of s is not large enough to fit the additional values, append
2649-allocates a new, sufficiently large underlying array ... Otherwise,
2650-append re-uses the underlying array." In Go the GC keeps the old array
2651-while it is referenced. Raz retires the block and frees it at a later
2652-growth once the count is 0, which matches for every slice still held.
2653-Source: https://raw.githubusercontent.com/golang/go/master/doc/go_spec.html.
2654-
2655-**C3. Section 19: `append(s, s...)` is right in Go.** Correct: append
2656-copies with memmove semantics, so overlap is safe. Source: as C2.
2657-
2658-**C4. Section 12, Go row: checked, GC, forged pointers "only through
2659-`unsafe`", fence `import "unsafe"`.** Correct. cgo is the other way
2660-out, and it is also visible in imports (`import "C"`).
2661-
2662-**C5. Section 8.2: "the generational arena of Rust's `slotmap` and
2663-`generational-arena`".** Correct. slotmap: "persistent unique keys ...
2664-The keys returned by `slotmap` are versioned." generational-arena: "A
2665-safe arena allocator that allows deletion without suffering from the
2666-ABA problem by using generational indices." Sources: https://github.com/orlp/slotmap; https://github.com/fitzgen/generational-arena.
2667-
2668-**C6. Section 8.2: "the handle pattern Zig and game engines use".**
2669-Correct as practice. The pattern's best-known write-up is Andre
2670-Weissflog's "Handles are the better pointers" (2018), worth citing:
2671-https://floooh.github.io/2018/06/17/handles-vs-pointers.html.
2672-
2673-**C7. Section 12, Rust row, and 9.1: `Send`/`Sync` checked by the type
2674-system; `unsafe` blocks and functions.** Correct.
2675-
2676-**C8. Section 19: "non-lexical lifetimes are a fixpoint over the control
2677-flow, not one pass".** Correct. NLL (RFC 2094) computes liveness and
2678-region constraints by dataflow over MIR's control-flow graph.
2679-
2680-**C9. Section 12, Swift row: "exclusivity checked at compile and run
2681-time"; "Swift 6: `Sendable`, checked".** Correct. Swift 5 enabled
2682-run-time exclusivity checks in release builds; the Swift 6 language
2683-mode makes data-race checks errors. Source: https://github.com/swiftlang/swift-org-website/blob/main/_posts/2019-02-05-swift-5-exclusivity.md.
2684-
2685-**C10. Section 12, Modula-3 row: a GC for traced references, `DISPOSE`
2686-only in unsafe modules, `UNSAFE MODULE` and `UNSAFE INTERFACE`.**
2687-Correct. The report: "An interface or module not explicitly labeled
2688-UNSAFE is called safe." SRC's compiler: `IF Module.IsSafe () THEN
2689-Error.Msg ("DISPOSE: unsafe operation")`. Untraced references (`UNTRACED
2690-REF`) aren't collected. Sources: https://www.cs.purdue.edu/homes/hosking/m3/reference/unsafe.html; https://softwarepreservation.computerhistory.org/modula3/archive/DEC_SRC/release-2.11-unpacked/compiler/src/builtinOps/Dispose.m3.
2691-
2692-**C11. Section 12, Oberon row: unsafe only through `SYSTEM`, marked by
2693-`IMPORT SYSTEM`.** Correct. The GC belongs to the Oberon system rather
2694-than the language report, which is a fine point.
2695-
2696-**C12. Section 12, Ada row: `Unchecked_Deallocation`,
2697-`Unchecked_Conversion`, "SPARK adds ownership".** Correct. SPARK's
2698-pointers follow "the Rust model": move for pool-specific access types,
2699-borrow and observe for anonymous ones (SPARK Community 2020 onward).
2700-Source: https://docs.adacore.com/spark2014-docs/html/ug/en/source/access.html.
2701-
2702-**C13. Section 12, Zig row: bounds "checked in Debug and
2703-ReleaseSafe".** Correct. The langref: "In Debug and ReleaseSafe mode
2704-... triggers a safety panic"; ReleaseFast and ReleaseSmall assume
2705-the checks away.
2706-
2707-**C14. Section 11: "Zig's debug allocator".** Correct name since Zig
2708-0.14.0 (`std.heap.DebugAllocator`; `GeneralPurposeAllocator` survives
2709-as a deprecated alias). Source: https://ziglang.org/download/0.14.0/release-notes.html.
2710-
2711-**C15. Section 11: glibc's `MALLOC_PERTURB_`.** Correct: it fills
2712-blocks "when they are allocated ... and freed". It has no quarantine
2713-and no guard bytes; the proposal's "without their reach" allows for
2714-that. Source: https://raw.githubusercontent.com/bminor/glibc/master/manual/memory.texi.
2715-
2716-### Unverifiable
2717-
2718-**U1. Section 12, Zig row: races "UB".** Zig has no written memory
2719-model. Its atomics follow LLVM's, under which a data race on a
2720-non-atomic location is undefined, so the claim is very likely right.
2721-No Zig document says so.
2722-
2723-**U2. Section 12, Modula-3 row: races "not promised".** The report
2724-doesn't speak to it in what I could read. Since Modula-3's open arrays
2725-and `TEXT`s are behind references, a race in a safe module may not
2726-break memory at all. Leave it, or write "not addressed by the report".
2727-
2728-### Precedent the proposal misses
2729-
2730-- **D: `@safe`, `@trusted`, `@system`, and DIP1000's `scope` and `return
2731- scope`.** This is the closest match to parts A and B together.
2732- `@trusted` is section 5.3's trust, per function. `return scope` is
2733- `ret`, and plain `scope` is the opposite of `keep`. PROPOSALS.md
2734- cites DIP1000; MEM_PROPOSAL.md doesn't. It should, together with D's
2735- lesson that the corners (fields, generics, delegates) took years.
2736- DIP1000 is still behind `-preview=dip1000`, and its document is marked
2737- "Superseded". Source: https://github.com/dlang/DIPs/blob/master/DIPs/other/DIP1000.md.
2738-- **C#: `ref struct`, `Span<T>`, `scoped`, ref-safety contexts.** C#
2739- checks with local, one-pass rules that a `Span<T>` never outlives what
2740- it points at, with three contexts that are part B's three lenders
2741- (I11). It is the strongest evidence that part B works in a
2742- mainstream compiler without lifetimes in types. Source: https://github.com/dotnet/csharplang/blob/main/proposals/csharp-11.0/low-level-struct-improvements.md.
2743-- **Swift: `~Escapable` types, lifetime dependencies, `Span`, and
2744- SE-0458.** Swift 6.2's non-escapable types (SE-0446) and `Span`
2745- (SE-0447) give a slice that can't outlive its source, with a
2746- dependence written on the function. That is `ret` again. SE-0458's
2747- `@safe` and `@unsafe` are the fence and the trust. Sources: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0446-non-escapable.md; .../0447-span-access-shared-contiguous-storage.md; .../0458-strict-memory-safety.md.
2748-- **Chrome's BackupRefPtr.** Counted references with quarantine on
2749- free, in production C++ (I18). It is the precedent for part C's
2750- retirement, with measured costs and recorded leaks.
2751-- **Rust's `RefCell`, CPython's buffer exports, Java's `modCount`.**
2752- Run-time counts of loans that refuse a change while one is held
2753- (I21). CPython's `bytearray` refusing to resize while exported is
2754- part C's "stop" alternative from section 19, shipped for years.
2755-- **Checked C.** Microsoft's extension of C with checked pointer types
2756- (`_Ptr`, `_Array_ptr` with bounds) and `_Checked`/`_Unchecked`
2757- scopes. It is a fence in a C-like language, at a finer grain than a
2758- module, and it shows the cost of a per-block fence.
2759- https://github.com/checkedc/checkedc.
2760-- **SafeStack (clang).** It moves address-taken locals to a separate
2761- stack. That is relevant to what an unsafe module's `ADR` of a local
2762- can reach, and to part F's frame slots. https://clang.llvm.org/docs/SafeStack.html.
2763-- **Hylo (formerly Val).** Mutable value semantics: no stored
2764- references at all, only projections that last the call. That is the
2765- extreme of section 14's "a record can't keep a slice into a buffer
2766- that belongs to someone else", and it argues that the limit is
2767- livable. https://www.hylo-lang.org.
2768-- **Austral.** Linear types with lexical borrows, kept small on purpose
2769- so that one person can hold the whole checker in their head. That
2770- matters to raz's "a beginner can follow". https://austral-lang.org.
2771-- **Mojo and Carbon.** Mojo has ownership with inferred "origins", a
2772- Rust-like model with lighter syntax. Carbon plans a safe subset
2773- reached by incremental migration from C++, as part of section 20's
2774- order of work. Both are worth a line in section 19's view of Rust's
2775- way. https://docs.modular.com/mojo/manual/values/lifetimes; https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/safety/README.md.
2776-- **Modula-2+ and Cedar.** They had safe and unsafe (Cedar: checked,
2777- trusted, unchecked) modules before Modula-3, and are where the
2778- module fence of section 12 comes from.
2779-- **AddressSanitizer and GWP-ASan.** The real models for part G's
2780- quarantine and guard bytes (I18).
2781-
2782----
2783-
2784-## Appendix 6: adversarial review, the proposal's numbers and samples
2785-
2786-**Summary.** The five demo programs compile with `-Werror`, print what
2787-the proposal says, and do the undefined thing claimed. The callgrind
2788-figures repeat to within a thousand instructions. Several other things
2789-don't hold:
2790-
2791-- The survey counts lines, not operations, and the proposal calls them
2792- operations.
2793-- Its "test/libc" row is really `lib/Sys.raz`.
2794-- rnet's TLS backends and two of its tests were never compiled.
2795-- Most `ADR`s in rnet, rjson, rlX11 and ravite are arguments to the
2796- programs' own procedures, not to the library. So the claim that
2797- v0.19.0 "removed them already" is wrong.
2798-- Every one of raz's own benchmark kernels says `check off;`.
2799-- The kernels don't run "past the caches": the machine reports a
2800- 260 MB L3.
2801-- The 16-to-32-byte and fat-pointer conclusions are confounded by node
2802- layout and by noise.
2803-- Part C's run-time rule would stop the library's own `Opt.say`, the
2804- compiler's `Parse.moduleParams` and ravite's `load`.
2805-- 7.3 forbids the accessor that 14.2 recommends.
2806-- No container's `init` is marked `keep`, so a `Buf` over an `Arena`
2807- (used by `Fmt.eprint` and `examples/Sh`) can't be written safely.
2808-- Three of the sample error messages are wrong, and one gives help that
2809- doesn't compile.
2810-- The compiler cost is likely low by 40 to 70%, judged against
2811- PROPOSALS' own revised figure.
2812-
2813-Commands below were run on 2026-10-17. The scratch data used is in
2814-`/tmp/claude-0/-home-user-raz/bab05b52-9d9d-4262-9f3e-de1807ce50a5/scratchpad/`
2815-(S below). Files made for this review are in
2816-`/tmp/claude-0/-home-user/f9bd1744-45c5-5c51-82fd-fddfc77d01cc/scratchpad/`
2817-(W below).
2818-
2819-### 1. Survey counts
2820-
2821-**1.1 "Places", counted once each, are lines (2.1, 2.2, appendix 1).**
2822-`Diag.tally` prints `path:line` with no column, and `agg.py` keys on
2823-(kind, file, line). So two operations of one kind on one line count
2824-once. I rebuilt the tally compiler to print the offset as well
2825-(`W/tc/raz`) and compiled `src/Raz.raz` with it:
2826-
2827-| kind | lines (proposal) | distinct places |
2828-|---|---|---|
2829-| `ADR` | 27 | 32 |
2830-| deref | 1,015 | 1,410 |
2831-| `p[i]` | 277 | 372 |
2832-| `p[a..b]` | 30 | 44 |
2833-| ptr cast | 42 | 48 |
2834-| `p ± i` | 3 | 4 |
2835-
2836-The distinct places are themselves a floor: nested operations at one
2837-position still merge. **Correction:** call them "lines with", or give
2838-the operation counts. The ratios between modules hold.
2839-
2840-**1.2 The `test/libc` row is library code.** `test/libc/mods/Sys.raz`
2841-is a link to `lib/Sys.raz`, the C `Sys`. It holds 108 of the row's 110
2842-`ADR`s, 63 of its 64 casts and all 35 of its `p[i]`. The tests' own
2843-files hold 2 `ADR`s, 1 cast and 1 `NEW`. **Correction:** move 242
2844-fenced operations to `lib/` (`lib/Sys`, the C one), and say so when
2845-naming the library's unsafe modules (2.2, "Sys (287 operations)" is
2846-the Linux file only).
2847-
2848-**1.3 rnet was compiled in part.** `S/out/rnet.log` shows
2849-`test/Net.raz` and `test/Https.raz` failing, because `module Tls is in
2850-.../gnutls/Tls.raz and .../openssl/Tls.raz`. So neither TLS backend
2851-was counted. Both are `extern` modules: 26 and 35 `extern`s, 27 and 24
2852-`ADR`s. **Correction:** 5.4 says "rnet needs it only to keep
2853-`Http.Message`". In fact both `tls/*/Tls.raz` must say `unsafe;`, as
2854-`Sqlite` must. Section 15's rnet row should list them.
2855-
2856-**1.4 rnet's and rjson's `ADR` totals disagree with appendix 1.** 2.2
2857-gives rnet 572 and rjson 77. Appendix 1 gives 471 and 91 (lines, from
2858-the tally). A grep outside comments finds 792 occurrences in rnet (621
2859-lines) and 110 in rjson. rlX11's 89 doesn't come out either: grep
2860-finds 108, 78 of them in `src/`. ravite's 202 and rmacs's 560 match a
2861-grep.
2862-
2863-**1.5 "Almost every ADR is ... the library's old pointer parameters"
2864-is wrong for most repositories.** I sorted each `ADR` by the call it
2865-is an argument to (`W/py/adr.py`, a textual parser):
2866-
2867-| repo | `ADR`s | to the library | to its own procedures and modules | casts and other |
2868-|---|---|---|---|---|
2869-| rnet | 792 | 226 | 525 | 41 (34 to `Tls`) |
2870-| rjson | 110 | 35 | 70 | 5 |
2871-| rflate | 67 | 48 | 16 | 3 |
2872-| rsqlite | 42 | 12 | 27 (some to C) | 3 |
2873-| rmacs | 560 | 424 | 132 | 4 |
2874-| ravite | 202 | 107 | 93 | 2 |
2875-| rlX11 | 108 | 5 | 100 | 3 |
2876-
2877-The top callees in rnet are its own `fetches`, `resolves`,
2878-`Conn.close` and `parseAnswer`. In rlX11 it is its own `expect`. Those
2879-are the programs' pointer-taking headings. They mend by `var`, but the
2880-programs have to be rewritten for it; v0.19.0's library didn't remove
2881-them. **Correction:** "Most `ADR`s are arguments; in rmacs and rflate
2882-mostly to the library, in rnet, rjson and rlX11 mostly to the
2883-programs' own pointer parameters."
2884-
2885-**1.6 "Nobody uses `check off;`" (2.2, 13.2) is wrong.** All seven
2886-kernels in `test/bench` say `check off;` (`grep -l '^check off'
2887-test/bench/*.raz` gives 7 of 7). The Makefile says so too: "the
2888-kernels of test/bench, which say check off". So does
2889-`test/run/mods/Unchecked.raz`. The survey left `test/` out, but the
2890-inference "no one has wanted them off" doesn't follow: raz's own speed
2891-comparison with FPC turns the checks off. **Correction:** "No library
2892-module or program surveyed turns them off. raz's benchmark kernels do,
2893-to match FPC -O2."
2894-
2895-**1.7 Frees and `done`s (2.2, 8.1).**
2896-
2897-- The hand frees match: `src/` 7, rmacs 9 (4 `Mem.free` plus 5
2898- `Heap.heap^.free`), rjson 6, ravite 2, rlX11 1, others 0.
2899-- rnet has 41 `done`s, not 30: `src/` has 30, its tests 11. With 41,
2900- "54 to 26" becomes 65 to 25 or 26. That still makes the point.
2901-- The mendings in section 15 misdescribe some of the frees:
2902- - rjson's 6 are all `Mem.free` of grown arrays (`nodes`, `kids`,
2903- `stack`), with no `Str.free`. They mend by `Vec`, not by `Names`
2904- or `Buf`.
2905- - ravite's 2 are `Text`'s grown `data` and `changes`, not windows.
2906- They mend by `Vec` or `Buf`, not `Pool`.
2907- - Only rmacs's 5 `Heap` frees, of windows and parts, are `Pool`
2908- material.
2909-
2910-**1.8 "35 places assign Buf.bytes, Vec.all or Windows.all"** holds.
2911-A grep finds 36 assignments to locals and 3 to fields (`m^.body`, and
2912-`res^.body` twice). The only `.all` is rmacs's `Windows.all`.
2913-
2914-**1.9 "Records that hold slices: src/ 10" isn't reproduced.** I find
2915-three slice fields in `src/`'s records: `Diag.File.path`,
2916-`Sym`'s `path*` (line 116) and `X64.Said.text`. 13.3 repeats "10".
2917-**Correction:** 3, or say how 10 was counted.
2918-
2919-**1.10 Dereferences: "Every one is a pointer from NEW on the heap,
2920-which the compiler never frees" (2.2) is false today.** Some are not:
2921-
2922-- `X64`'s `r^`, `size^` and `o^` point at locals through `ADR(r)` and
2923- `ADR(ao[an])`.
2924-- `Elf`'s `dynSize^` and `roExtra^` point at locals.
2925-- `Scan`'s `bits^` points at a local.
2926-- `Diag`'s `f^` and `Chunk`'s `c^` point into grown arrays that
2927- `regrab` frees (`Scan.raz:137`, `Diag.raz:103`).
2928-
2929-They are few (tens), and part A's mendings would remove them. But the
2930-sentence should say "nearly every".
2931-
2932-**1.11 The `src/` `ADR`-and-cast table (2.2) misses some sites and
2933-miscounts others.** The table sums to 55. There are 62 distinct lines
2934-with an `ADR` or a cast.
2935-
2936-- Grown arrays: 31 lines are `grab`/`regrab`/`free` of arrays. 3 more
2937- are single records, `^Buf.Buf(Scan.grab(SIZE(Buf.Buf)))`, which
2938- should be `NEW`, not `Vec`.
2939-- "A real's bits" are 4 lines (Item 152, 165, 364; Scan 879). 3 more
2940- are a value's bytes for data (`Gen.raz:293`, `Parse.raz:3186`,
2941- `Parse.raz:3334`). They need `setData` and the copy to take a slice,
2942- besides the view.
2943-- `intern`: 7, correct. Two `Elf.putBytes(ADR(s[0]), LEN(s))` are
2944- missing.
2945-- Out-parameters: 4 lines, 8 `ADR`s, not 5.
2946-- Not listed at all:
2947- - `ADR(chunks[n])`, `ADR(files[i])` ×2 and `ADR(ao[an])`;
2948- - `Scan.raz:119` (`return ADR(sbuf[0])`, the allocator);
2949- - `Item.raz:2155` (`^I64(p)`);
2950- - `Raz.raz`'s two `SYSCALL`s (`memfd_create`, and `execve` with
2951- `ARGV() + first`).
2952-
2953- The `SYSCALL`s mend by `Sys.memFile`, and `Sys.execve` with
2954- `Sys.envAt`, but they are not "1 SYSCALL".
2955-
2956-### 2. The five programs
2957-
2958-Each was extracted from appendix 3 and compiled with
2959-`/home/user/raz/raz -Werror`. Each is identical to `S/demo/`.
2960-
2961-| program | printed | status |
2962-|---|---|---|
2963-| SelfAppend | 24 `a` | 0 |
2964-| Stale | `1 2` | 0 |
2965-| Escape | `########` | 0 |
2966-| Kept | `name-001: missing`, `name-002: missing` | 0 |
2967-| Temp | `name-..b`, a space, then `01 00 00 00 00 00 00 00` | 0 |
2968-
2969-All as claimed.
2970-
2971-**2.1 SelfAppend's explanation (1.2) is vague where it could be
2972-exact.**
2973-
2974-- `Buf.room` copies, then frees the old block (`Buf.raz:36-37`).
2975- `Buf.str` then copies from `s`.
2976-- The old block is size class 3 and the new one class 4. `Heap.free`
2977- writes only the 16-byte header (`b := ^Block(h)`, `Heap.raz:96`).
2978- Nothing allocates between the free and the copy.
2979-- So with `Heap` in one thread the program is always right. That is
2980- not luck "in time".
2981-- A block past 4,080 bytes gets pages of its own, and `free` unmaps
2982- them. Filled to 8,192 bytes, the same line stops the program:
2983- `Buf.raz:67:5: stopped by a bad address` (`W/demo/SelfBig.raz`).
2984- That makes a stronger demonstration than the one shown.
2985-
2986-**2.2 Stale.** Holds as explained:
2987-
2988-- The class-4 block of 16 elements is freed when the `Vec` grows to 32.
2989-- `p` points into the class-5 block, which is freed at the next growth.
2990-- `free` touches only headers, so `first[0]` and `first[1]` read 1
2991- and 2.
2992-
2993-**2.3 Escape** holds.
2994-
2995-**2.4 Temp.** The listing (`raz -S`) confirms one slot,
2996-`[rbp - 40]`, for both calls.
2997-
2998-- `a` was printed before anything overwrote the slot, so it shows
2999- `b`'s bytes.
3000-- `b` points at the same slot. That slot was overwritten by the next
3001- call's argument, `Out.str(" ")`, whose length 1 lands at
3002- `[rbp - 40]`. Hence `01 00 ...`.
3003-- "Whatever came after" is right. The precise cause is the next
3004- statement's temporaries.
3005-
3006-**2.5 "Three are what the library's own documentation warns of" (1.2)
3007-is two.** `Buf` ("until it next grows") and `Vec` warn. `Map`'s
3008-documentation says nothing about keeping its keys: neither the module
3009-comment nor `put`'s "k now maps to v". The proposal itself says the
3010-caller "must know, from the documentation alone". **Correction:** "two
3011-are what the library's documentation warns of, one what it doesn't
3012-say, and two what 7.3 and 8 warn of." Or mend `Map`'s comment.
3013-
3014-### 3. Benchmarks
3015-
3016-The machine is a 4-core Xeon VM at 2.1 GHz, with AVX-512. `lscpu`
3017-reports L2 2 MiB a core and **L3 260 MiB**. THP is `madvise`.
3018-
3019-**3.1 Two runs each of MemBench and GenBench (ms):**
3020-
3021-| kernel | proposal | mine, run 1 | mine, run 2 |
3022-|---|---|---|---|
3023-| big, raw, 16-byte nodes | 8,312 / 7,515 | 5,300 | 4,859 |
3024-| big, handles, 32-byte slots | 12,336 / 11,992 | 10,665 | 10,429 |
3025-| small, raw | 857 / 810 | 864 | 876 |
3026-| small, handles | 1,631 / 1,643 | 1,829 | 1,734 |
3027-| big, raw, 32-byte nodes | 14,001 / 13,725 | 13,734 | 13,499 |
3028-| big, fat pointers | 8,672 / 10,145 | 9,232 | 10,624 |
3029-| small, raw, 32-byte | 870 / 917 | 852 | 870 |
3030-| small, fat | 830 / 1,047 | 815 | 888 |
3031-| sum, big, `^U8` / `[]U8` | 305 / 342; 271 / 434 | 296 / 279 | 318 / 370 |
3032-| sum, small, `^U8` / `[]U8` | 261 / 265; 256 / 306 | 336 / 428 | 387 / 392 |
3033-
3034-Findings:
3035-
3036-- **Big handles cost 2.0 to 2.2 times here, not 1.5 to 1.6.** The raw
3037- baseline varies by 40% between sessions.
3038-- **The working sets are not "past the caches".** The big arrays are
3039- 16 MB and 32 MB, inside a reported 260 MB L3. So "doesn't fit in
3040- the caches" and `Big = 1000000; (* past the caches *)` are wrong
3041- here. What grows with the node is the page-walk footprint and the
3042- share of L3, not a miss to DRAM.
3043-- **"Half of it the larger slot" is not supported.** Across the two
3044- programs, the 32-byte raw chase (13.5 s) is *slower* than the
3045- 32-byte handle chase (10.5 s). The two programs aren't comparable.
3046-
3047-**3.2 Why big-gen beats big-ptr.** I tested three explanations:
3048-
3049-- Run order (`W/mb/GenOrder.raz`): not it. Gen first or second, gen
3050- 11.4 to 11.6 s, ptr 13.4 s.
3051-- Array placement in bss (`W/mb/GenSwap.raz`): not it. Ptr stays
3052- slower.
3053-- Layout and code (`W/mb/GenWhy.raz`, 50M steps):
3054- - ptr 6.8 s;
3055- - gen 3.8 to 4.5 s;
3056- - gen with no check 2.7 to 3.9 s;
3057- - a raw pointer chase over the *gnodes* array 4.2 to 5.8 s.
3058-
3059- In `W/mb/Offs.raz`, the same 32-byte node chased raw takes 6.3 to
3060- 6.5 s with the link at offset 0, and 5.3 to 5.9 s with it at offset
3061- 8.
3062-
3063-So part of the gap is the node's layout (where the link and the value
3064-sit), and the rest is noise of ±20 to 30% on this VM. The generation
3065-check itself isn't what the rows measure. Its cost is within noise;
3066-calling it "free" or "the check is free here" goes further than the
3067-data. The same layout effect sits inside the "+70–85%" for doubling a
3068-node: the comparison is across two programs with different layouts.
3069-**Correction:** "On this machine, wider records and handles cost 1.5 to
3070-2.2 times in a pointer chase; the measurements can't separate the
3071-check from layout and noise." Keep the conclusion against fat
3072-pointers on other grounds: C interop, record size.
3073-
3074-**3.3 MemBench understates a real `Pool`.** `chaseHandle` indexes a
3075-fixed module array inline: no call, no copy of `T`, no heap
3076-indirection, no `LENDS` count. `Pool.get` (8.2) is a call that copies
3077-`T`, through a `const p: Pool`, into a heap block. `Pool.at` adds a
3078-counted lend. Expect more than the table's figure.
3079-
3080-**3.4 The bounds-check sums** do test the check: the listing shows
3081-`cmp r12, rsi; jae` in the loop. My figures run from -6% to +27%.
3082-"0–15%" is about right, given the noise.
3083-
3084-**3.5 The scanner experiment** repeats: `valgrind --tool=callgrind`
3085-of `S/base/raz` and `S/safe/raz` over `src/Raz.raz` gives 240,850,230
3086-and 251,594,863 instructions, +4.46%.
3087-
3088-Caveats:
3089-
3090-- The "safe" `Scan` still uses `PTR(cur.buf)` and
3091- `intern(PTR(buf) + start, ...)`, so it isn't safe. The cost of
3092- `intern(s)` taking a slice isn't measured.
3093-- `PTR` is not in v0.19.0, so this `Scan` can't be built by `BOOT`
3094- yet.
3095-- Wall-clock times of the 348,025-line bench were 688 to 891 ms for
3096- the base compiler and 723 to 858 ms for the "safe" one, interleaved
3097- six times. The "safe" one was sometimes faster. Wall clock can't
3098- show 5% here.
3099-- The proposal's "625 to 660 ms" was a quiet moment. At this
3100- session's best (688 ms, 506,000 lines a second) 5% more is about
3101- 480,000, still above the floor. On a slow run (891 ms, 390,000) the
3102- floor already fails today.
3103-
3104-**3.6 "Two 8-byte moves become one 16-byte one" (13.3)** is true only
3105-from memory to memory. Into the rax/rdx pair the ABI returns a slice
3106-in, or from it, a `movdqa` needs `movq` and `pextrq`/`pinsrq`. That is
3107-three instructions and a domain crossing, not none.
3108-
3109-### 4. Library signatures, report sections, quotations
3110-
3111-- **Exact:**
3112- - `Thread.spawn*(p: proc(arg: ^U8); arg: ^U8): (^Thread, ERROR)`;
3113- - `Str.copy*(a: ^Mem.Allocator; s: []U8): ([]U8, BOOL)`;
3114- - `Buf.spare*(var b: Buf; n: INT): []U8`;
3115- - `Buf.bytes*(const b: Buf): []U8`;
3116- - `Map.put*(var m: Map; k: K; v: V): BOOL`;
3117- - `Sys.mmap`, `Sys.munmap`, `Sys.nextEntry(var d: Dir)`,
3118- `Sys.read(fd: INT; buf: []U8): INT`;
3119- - `Item.raz:58` is `frame*: BOOL` with the comment the proposal
3120- describes;
3121- - `C` has 96 `extern`s and `CAbi` 2; `Vec` has 11 fenced lines;
3122- - `src/` is about 11,550 lines of code by a comment-stripping count
3123- (rloc isn't installed), so "about 11,500" holds.
3124-- **`Vec.all`'s comment** is "The elements, until the array next
3125- grows." "Good until the array next grows" is in `Vec`'s module
3126- comment and in `add`'s (capitalized). The quote is fair, but not
3127- `all`'s own words.
3128-- **7.6 is misquoted (9.1).** The report says a variable raced on
3129- "holds no particular value then: a read of it gives a value it had
3130- or was given, or a mixture of their bytes. Nothing else of the
3131- program becomes undefined by it." The proposal puts "holds" in
3132- front of "a value it had or was given", which the report doesn't
3133- say. **Correction:** quote "a read of it gives a value it had or was
3134- given, or a mixture of their bytes".
3135-- **Section 10's "no run time besides the code it uses" (19)** is said
3136- of "a program that doesn't [use C]". The quote is exact. It is a
3137- property of programs without C, not a promise of the language. That
3138- weakens the argument a little; line 7 of the report ("no hidden run
3139- time") supports it better.
3140-- **5.3 (16):** a slice's alignment is set in 5.1 ("a slice is aligned
3141- as an address is"), not 5.3. The sentence to change is there.
3142-- **Elf "writes the executable through `Sys.write`" (5.4):** it uses
3143- `Files.write(path, buf[0..len])` (`Elf.raz:442`). The conclusion
3144- holds.
3145-- **Zig in 12:** `@intToPtr` has been `@ptrFromInt` since Zig 0.11.
3146-- **The Go memory-model wording** in 9.1, "arbitrary memory
3147- corruption", is accurate.
3148-- **Section 15's `ret` list** leaves out `Vec.tryAdd`, which 17 marks.
3149- **Neither list marks `init`'s allocator `keep`** on `Buf`, `Vec`,
3150- `Map`, `List` or `Pool`. Every one stores `a` in its record, and
3151- 5.3(3) says "what it doesn't mark keep, it doesn't hold past the
3152- call". See 5.5 below.
3153-
3154-### 5. Code samples and the proposal's own rules
3155-
3156-**5.1 Today's-raz samples compile.**
3157-
3158-- Appendix 2 and 3 compile.
3159-- 6.4's `greet`, `first` (without `ret`) and `remember` compile.
3160-- 7.1's loop compiles (`W/demo/Samples.raz`).
3161-
3162-**5.2 The help in 6.4 and 14.3 doesn't compile.** "give put a copy
3163-that lasts: `Str.copy(Heap.heap, buf[0..8])`". `Str.copy` has two
3164-results:
3165-
3166-```
3167-Samples.raz:31:27: error: copy returns several results
3168- help: they go to variables: a, b := copy(...)
3169-```
3170-
3171-**Correction:** "copy it first: `k, ok := Str.copy(Heap.heap,
3172-buf[0..8])`".
3173-
3174-**5.3 The message positions are off.** The positions shown don't match
3175-the programs:
3176-
3177-- `Kept.raz:10:30`: the call is at line 11, column 27.
3178-- `Escape.raz:14:12`: it is at 15:12.
3179-- `Window.raz:41:13 ... XNextEvent(dpy, ADR(ev))`: the line in
3180- `examples/Window.raz` is 59, `_ := XNextEvent(d, ^U8(ADR(ev)))`.
3181-
3182-Window's help, "or pass ev as a var", is impossible. An `extern`'s
3183-parameters are integers, `BOOL`, reals, pointers or procedures (report
3184-9), and the module is unsafe for its `extern`s anyway. Pick a safe
3185-module's `ADR` for that example.
3186-
3187-**5.4 The Escape message assumes a `head` that 6.2 forbids.** It says
3188-"head's result points into what it is given (ret h)". Appendix 3's
3189-`head(var h: Hex)` has no `ret`, so under 6.2 the first error is in
3190-`head` itself: "returning what is lent by h, not marked ret".
3191-
3192-**5.5 7.3 forbids what 14.2 recommends.** 7.3 says an owner-lent
3193-reference "returned ... is an error". 14.2's option 1 is `proc
3194-name*(ret const m: Message; i: INT): []U8; (* m^.head's bytes, lent by
3195-m *)`, which returns bytes of `m.head`, a `Buf`. That is exactly an
3196-owner-lent return. 7.2 also says a `Message` is not an owner, so it
3197-can't lend through `ret` at all.
3198-
3199-The same rule refuses `tools/Widths.raz`'s `load(path; var b:
3200-Buf.Buf): []U8 ... return Buf.bytes(b)`, yet section 15 says `tools/`
3201-has "none found". It also refuses any safe wrapper over `Vec.all` or
3202-`Pool.at`.
3203-
3204-Either 7.3 allows returning through a `ret` parameter that is itself
3205-an owner, or the library's own exports, which do this, need a
3206-different rule from safe code. If returning is allowed, the hold must
3207-pass to the caller, and 7.3 doesn't say how.
3208-
3209-**5.6 Part C stops correct programs, the library's and the compiler's
3210-included.** 7.3 lets a local's hold go only when the procedure
3211-returns, and 7.4 makes `done` stop while a count is above zero. A scan
3212-for a slice held from `Buf.bytes(b)` and a later `Buf.done(b)` in one
3213-procedure (`W/py/heldone.py`) finds:
3214-
3215-- `lib/Opt.raz` `say`: `s := Buf.bytes(b)`, loop, `Buf.done(b)`;
3216-- `src/Parse.raz` `moduleParams`, lines 3696 to 3699 (every generic
3217- instance);
3218-- ravite's `load` (`Ravite.raz:1402`, done at 1411).
3219-
3220-Five more do `defer Buf.done(x)` and then hold `Buf.bytes(x)`:
3221-`examples/Elf.raz` `main`, rnet `Dns.init` and `fromHosts`, and rmacs
3222-`writeFile` and `loadInit`. Whether those stop depends on whether a
3223-hold's let-go runs before or after the deferred statements. The
3224-proposal says only "as a defer would".
3225-
3226-So the compiler itself would stop on every program with a generic
3227-import. 14.2 calls this "a false alarm only when name is never read
3228-again", and these are exactly such cases. Section 15's claim that
3229-every break is found when compiling, but `done`, should count them.
3230-**Correction:** let a hold go at the variable's last use, or at a
3231-`done` of the owner from the same procedure (both known in one pass
3232-only for straight-line code). Or count these breaks and mend them with
3233-`s := []`.
3234-
3235-**5.7 A `Buf` or `Vec` over an `Arena` has no safe form.** By 8.4,
3236-`Arena.allocator(ar)` is lent by `ar`, and a lent value can't be
3237-stored in a record (6.2) or given to `keep` (5.5 above). `Buf.init`
3238-keeps its allocator, so `Buf.init(b, Arena.allocator(ar))` is an
3239-error. This pattern appears in:
3240-
3241-- `Fmt.eprint`;
3242-- `Fmt`'s test;
3243-- `Buf`'s test;
3244-- `examples/Sh.raz`, lines 88 and 188.
3245-
3246-So "Fmt ... can be safe" (5.4, 15, 17) and "Sh ... mended by var" (5.4,
3247-15) fail. `Fmt.format` also takes `^Buf.Buf` with `nil` for standard
3248-output, which needs an interface change.
3249-
3250-**5.8 Other "can be safe" claims (5.4).**
3251-
3252-- `Files.arg` *is* `ARGV()[i]` and pointer indexing
3253- (`Files.raz:10-13`). 5.1 fences `ARGV` and names `Files.arg` as the
3254- safe form, so `Files` must stay unsafe, or `ARGV` must move into a
3255- trusted module.
3256-- `Str.copy` and `Str.free` index and free a `Mem.alloc` pointer. `Str`
3257- can be safe only if `Mem` gains a safe slice allocation. Section 17
3258- doesn't add one, and `free` is an `unsafe proc` in a module 17 calls
3259- safe.
3260-- `Lock` needs E.4 (`CAS` on a variable) first.
3261-- `examples/Workers.raz` uses `Thread.spawn(work, nil)` and
3262- `XADD(ADR(next), 1)`. It needs `Task` and E.4, not `var`.
3263-
3264-**5.9 Owners can't sit in generic containers.** 7.6 forbids passing an
3265-owner as a value parameter or copying it. `Vec.push(x: T)`,
3266-`Pool.add(keep x: T)`, `Map.put(..., v: V)` and `List.push` all copy.
3267-So `Vec(Buf.Buf)`, `Pool(Window)` where a `Window` holds a `Buf`, and
3268-`Names(Buf.Buf)` can't be used. Yet 14.2 turns rmacs's windows, which
3269-hold `Buf`s, into a `Pool(Window)`. The proposal needs an `add` that
3270-gives a zero slot in place (`Pool.at` after a zero `add`) and says
3271-that copies are refused there.
3272-
3273-### 6. The compiler's cost (section 18)
3274-
3275-- **A, 120:** about right, perhaps to 150. It needs `unsafe proc`'s
3276- rules in `Sym.same` and assignability, the two contextual places the
3277- word stands, the interface check, and a generic instance taking its
3278- module's mark.
3279-- **B, 300–450: low.** PROPOSALS' own second review (its open
3280- question 4, PROPOSALS.md line 476) revised part 3 to "400 to 600
3281- lines, not 250 to 400", for slices alone. This proposal adds
3282- pointers, owners as lenders, `match` names (10.4), literal parts and
3283- generic instances checked one by one. Likely 550 to 800.
3284-- **C, 200: low.**
3285- - Hidden hold slots per local.
3286- - A raise at each call that returns an owner-lent value.
3287- - A lower at the end of each statement. Only `const`'s temporaries
3288- have such a point today.
3289- - A let-go on every exit, `try` and early `return` included, with
3290- an order against `defer` (5.6).
3291- - The copy check at assignment, value parameters, results, literals,
3292- comparison, views and generic instances (5.9).
3293- - Likely 300 to 450.
3294-- **D, 20:** plausible.
3295-- **E, 80: low.**
3296- - 16-byte alignment of slices changes record layout in `Sym`, and
3297- frame-slot and temporary alignment in `Gen`.
3298- - Every slice load and store goes through xmm, with
3299- `movq`/`pinsrq`/`pextrq` for the rax/rdx pair. `X64` today
3300- encodes `movdqu` but not those.
3301- - Records holding slices are copied by `rep movsb` past `MaxMoves`.
3302- - `CAS`, `XCHG` and `XADD` change from pointer to variable in
3303- `Parse` and `Item`.
3304- - `lock xadd` when `Thread` is imported.
3305- - Likely 150 to 250.
3306-- **F, 20:** plausible, since `defer`'s reserved slots exist.
3307-- **Messages, 100:** plausible for about 10 new kinds with help.
3308-
3309-**In all, likely 1,250 to 1,700, not 840 to 990.** That still fits
3310-under 14,000, from about 11,550, but with much less room than 18
3311-suggests for the documentation the house style requires.
3312-
3313-The `src/` rewrite is also larger than "35 grown arrays". `Chunk.chunks`,
3314-`Chunk.text` and `Chunk.rodata` are exported and indexed from `Item`,
3315-`Parse`, `Gen`, `Raz`, `Elf`, `Link` and `X64`: about 250 lines of
3316-`p[i]` and `p[a..b]` outside `Scan`. Each would become a `Vec.all(...)`
3317-with a counted lend, often in `X64`'s emitter and `Link`'s patching,
3318-which are hot. 13.1's "cost nothing measurable" for these is
3319-unmeasured.
3320-
3321-### 7. `src/` becoming safe (2.2, 5.4, 15)
3322-
3323-The plan is plausible module by module, with three gaps:
3324-
3325-- **Elf:** its buffers are a `grab`/`regrab` byte array (a `Buf`), plus
3326- `putBytes(ADR(s[0]), LEN(s))` (a slice parameter) and
3327- `sizeTables(ADR, ADR)` (`var`). It can be safe.
3328-- **Diag:** `files` is a grown array (`Vec`), and two `^Buf.Buf(grab)`
3329- become `NEW`. `File.buf: ^U8` keeps a pointer to the scanner's
3330- source. As a slice it is lasting only if `Scan`, unsafe, promises
3331- so. It can be safe.
3332-- **Link:** four arrays sized once from `Scan.grab`, then `p[i]` 63
3333- times. They need `Vec(INT)` with `resize`, or a typed `grab` that
3334- gives a slice. Safe, at the cost of checks on the linker's paths.
3335-- **Chunk:** grown record arrays exported to every module, and
3336- `ADR(chunks[n])`. Safe as `Vec`s, but see 6 on cost and lines.
3337-- **X64:** `said` is grown, `^Buf.Buf(grab)` becomes `NEW`, and the
3338- `isReg` out-parameters and `operand(ADR(ao[an]))` become `var`. It
3339- writes `Chunk.text` per byte. Safe, with that cost.
3340-- **Gaps:**
3341- - `Raz.raz` needs its `SYSCALL`s and `ARGV() + first` replaced:
3342- `Sys.memFile`, and `Sys.execve` with an environment built from
3343- `Sys.envAt`.
3344- - `Scan.grab`'s callers outside `Scan` (`Item.raz:2154`,
3345- `Parse.raz:452`, `Parse.raz:3812`, `Raz.raz:165`) index its
3346- `^U8`. `grab` must give a slice.
3347- - `Parse.moduleParams` stops at run time under part C (5.6).
3348-
3349-"`src/` keeps one unsafe module: Scan" can be reached, but it is
3350-several hundred changed lines, not the table's 55 sites.
3351-
3352-### Confirmed
3353-
3354-- The demos' outputs and status 0, and that each does the undefined
3355- thing claimed.
3356-- The callgrind counts, +4.5%.
3357-- Appendix 1's per-module tallies, as the aggregator gives them, read
3358- as lines.
3359-- The hand-free counts.
3360-- rmacs's 560 and 556, and ravite's 202, `ADR`s.
3361-- About 36 held `Buf.bytes`/`Windows.all` slices.
3362-- `tools/` has no fenced operation.
3363-- Threads in rnet (`Http`'s server, tests) and rsqlite (`Sqlite`'s
3364- test) only.
3365-- Lines per repository, about 50,000.
3366-- `src/`'s 7 frees all in grown arrays.
3367-- The cited signatures, and `Item.raz:58`.
3368-- 7.3's and 8's text on what isn't caught.
3369-- `C` 96 and `CAbi` 2 `extern`s.
3370-- The sums' bounds check really emitted.
3371-- `src/` about 11,500 lines of code.
3372-
3373----
3374-
3375-## Appendix 7: adversarial review, porting real code
3376-
3377-Section 14 says most raz stays as it is and the pain is narrow. To
3378-test that, six pieces of real code were ported on paper under parts A
3379-to F, read as strictly as a compiler would read them: rnet's `Http`
3380-with its test servers, rmacs's buffers and windows, the compiler's
3381-name table, grown arrays, files and scopes, the library's `Fmt`, `Opt`,
3382-`Map` and the containers, `examples/Sh.raz`, and rjson's `Json`. About
3383-25,000 lines were read; about 900 of them change for parts B to F, 4%,
3384-on top of the `ADR`s the fence turns into `var`, which `STANDARDS.md`
3385-asks for anyway. By lines, then, the claim holds. By kind it doesn't.
3386-The changes gather in the one type each piece is built round
3387-(`Http.Message`, rmacs's `Text` and its accessors, `Chunk`'s arrays,
3388-`Sh`'s arena, `Json.Doc`), and each of those needs a redesign, not a
3389-mark. Three rules cause most of it: an owner's lend can't be returned
3390-by any procedure but the owner's own, can't sit in a record, and the
3391-fence has no safe form for a pointer to "the caller's state". The
3392-port also found six holes in the rules as written (A7.7): four let
3393-unsafe code through, and two leave a trap or an undecided stop. It
3394-found eight places in correct code that would stop at run time with
3395-`done` while held, and no real bug in today's code.
3396-Most of the pain goes away with seven additions that weaken nothing
3397-(A7.10).
3398-
3399-### A7.1 How it was done
3400-
3401-Each piece was first brought to today's library, so that an `ADR` at a
3402-call where the library now takes `var` doesn't count. Then each rule
3403-was applied to every line. Where the proposal is unclear, the stricter
3404-reading was taken, and noted:
3405-
3406-- **A pointer parameter is lent by its parameter** (6.1, 6.5). Storing
3407- one in a module variable or a record needs `keep`.
3408-- **Reading through a pointer gives a lasting value.** Only lasting
3409- values may be stored through a pointer (6.2), so what is read back
3410- is lasting too. The more lenient reading is taken here.
3411-- **An owner's lend may be returned only through a `ret` parameter
3412- that is the owner itself**, as `Buf.bytes` does. 7.3 says that
3413- returning one is an error. 6.2 allows it through `ret`. The middle
3414- reading is the only one under which the caller still knows whose
3415- count to raise.
3416-- **A local array or record may not hold an owner's lend** (7.3), not
3417- even one of slices.
3418-
3419-"Changed" counts lines touched, written or removed, against the
3420-source as it stands. The counts come from reading and `grep`, not from
3421-a compiler, and are good to about a fifth.
3422-
3423-### A7.2 rnet's `Http` (`src/Http.raz`, `src/Conn.raz`, `test/Webserver.raz`, `test/Server.raz`, `examples/Hello.raz`)
3424-
3425-**What the rules reject.**
3426-
3427-| Line or construct | Rule | The compiler's error |
3428-|---|---|---|
3429-| `m^.headers[m^.n] := {name: l[0..colon], value: trim(...)}` (`parseHeaders`), `l` a slice of `Buf.bytes(m^.head)` | 6.2, 7.3 | `Buf.bytes(m^.head) is lent by m^.head, which counts what it lends: hold it in a slice variable` |
3430-| `m^.raw := text`, `m^.method := l[0..i]`, `m^.target := ...`, `m^.reason := ...` | 7.3 | the same |
3431-| `m^.body := Buf.bytes(ADR(m^.data))` (`readWhole`) | 7.3 | the same |
3432-| `res^.body := Buf.bytes(ADR(text))` (Webserver, twice) | 7.3 | the same, in the program that uses `Http` |
3433-| `Http.add(res, "Location", Buf.bytes(ADR(text)))` (Webserver, twice), `add(ADR(res), "Date", Buf.bytes(ADR(when)))` (`serveConn`) | 6.2: `add` stores `name` and `value`, so it is `keep` | `Http.add keeps its value, and Buf.bytes(text) is lent by text` |
3434-| `head := m^.head; ... m^ := {..., head: head, data: data}` (`reset`) | 7.6 | `a Buf.Buf owns memory, and can't be copied` |
3435-| `out := req^` (`open`): a `Message` with two `Buf`s, copied | 7.6 | the same |
3436-| `try parseUrl(Buf.bytes(ADR(here)), ADR(u))`: `parseUrl` keeps slices of `s` in `u^` | 6.2 | `parseUrl keeps s, and Buf.bytes(here) is lent by here` |
3437-| `cl^.scheme := u^.scheme` (`connect`), always `"http"` or `"https"` | 6.2: `u`'s parts are lent as `u` is | `u.scheme is lent by u, a parameter not marked keep` |
3438-| `r^ := {conn: c, ...}` (`startBody`), `c` an `ADR` of a local `Conn` or of `cl^.conn` | 5.1, then 6.2 | `ADR is for unsafe modules`; with `var c`, `c is a var parameter and can't be kept` |
3439-| `return ADR(cl^.body), nil` (`open`) | 5.1 | `ADR is for unsafe modules` |
3440-| `Thread.spawn(work, ^U8(s))`, `s := ^Server(arg)` | 5.1, 5.2 | `a conversion to a pointer is for unsafe modules`; `Thread.spawn is an unsafe procedure` |
3441-| `Handler = proc(req, res: ^Message; arg: ^U8)`: a safe handler can't turn `arg` back into its own type | 5.1 | the same, in every program with state |
3442-| `t := ^Text(c^.state)` (`Http`'s and `Conn`'s tests); `Conn.state: ^U8` | 5.1 | the same |
3443-| `proc trim(s: []U8): []U8` returns `s` | 6.2 | `trim's result is lent by s, which isn't marked ret` |
3444-| every `^Message`, `^Conn.Conn`, `^Reader`, `^Url`, `^Client`, `^Server` parameter given `ADR(local)`: 228 `ADR`s in `Http.raz`, 37 in `Conn.raz` | 5.1 | `ADR is for unsafe modules` |
3445-
3446-The last row is what `STANDARDS.md` asks for, `var` or `const`. It
3447-changes `Http`'s whole interface, and every program that calls it.
3448-It is counted apart below.
3449-
3450-Section 14.2 offers a way out: `Http` says `unsafe;` and keeps
3451-`Message` as it is. That breaks the proposal's own rule 4 of 5.3. A
3452-safe program can read `req^.body` after `Http.done(req)`, so the
3453-exported slice fields are just what a safe module could misuse. And
3454-the programs that *write* messages (Webserver, `Hello`) are safe
3455-modules: they still can't store a `Buf`'s bytes in `res^.body`. So the
3456-spans are the only design that compiles.
3457-
3458-**Rewritten.** The text a message holds goes in its own buffers, as
3459-spans. Everything a program gives it is copied in.
3460-
3461-```
3462-(* Before *)
3463-Header* = record
3464- name*, value*: []U8;
3465-end;
3466-Message* = record
3467- method*, target*: []U8;
3468- status*: INT;
3469- reason*: []U8;
3470- minor*: INT;
3471- headers*: [MaxHeaders]Header;
3472- n*: INT;
3473- body*: []U8;
3474- maxBody*: INT;
3475- close*: BOOL;
3476- raw*: []U8;
3477- head, data: Buf.Buf;
3478-end;
3479-
3480-(* After *)
3481-Span = record at, len: INT; end; (* bytes at up to at + len of one of the buffers *)
3482-Header = record name, value: Span; end; (* in head *)
3483-Message* = record
3484- status*, minor*, n*, maxBody*: INT;
3485- close*: BOOL;
3486- method, target, reason, raw: Span; (* in head *)
3487- headers: [MaxHeaders]Header;
3488- body: Span; (* in data *)
3489- head, data: Buf.Buf; (* all of its text, read or to be written *)
3490-end;
3491-
3492-(* s added to b, and where it stands there *)
3493-proc put(var b: Buf.Buf; s: []U8): Span;
3494-begin
3495- Buf.str(b, s);
3496- return {at: b.len - LEN(s), len: LEN(s)};
3497-end;
3498-
3499-proc add*(var m: Message; name, value: []U8): ERROR;
3500-begin
3501- if m.n = MaxHeaders then return TooManyHeaders; end;
3502- m.headers[m.n] := {name: put(m.head, name), value: put(m.head, value)};
3503- INC(m.n);
3504- return nil;
3505-end;
3506-
3507-proc setBody*(var m: Message; s: []U8); (* new: s copied into the message *)
3508-begin
3509- Buf.reset(m.data);
3510- m.body := put(m.data, s);
3511-end;
3512-
3513-(* The bytes of sp in b *)
3514-proc bytesOf(ret const b: Buf.Buf; sp: Span): []U8;
3515-begin
3516- return Buf.bytes(b)[sp.at..sp.at + sp.len]; (* fine: b is the owner, and ret *)
3517-end;
3518-
3519-proc target*(ret const m: Message): []U8;
3520-begin
3521- return bytesOf(m.head, m.target); (* refused as written: lent by m.head, a part of m; see A7.7, H2 *)
3522-end;
3523-```
3524-
3525-`target`, `method`, `reason`, `raw`, `body`, `header`, `name(i)` and
3526-`value(i)` are new accessors, and the setters `setMethod`,
3527-`setTarget`, `setReason` and `setBody` are new too. They need the
3528-relaxation R1 of A7.10 to compile at all. In the programs:
3529-
3530-```
3531-(* Before (Webserver) *)
3532-path := req^.target;
3533-Fmt.write(ADR(text), "{}", [Fmt.int(conns)]);
3534-res^.body := Buf.bytes(ADR(text));
3535-
3536-(* After *)
3537-path := Http.target(req); (* held, and counted on req's head *)
3538-Fmt.write(text, "{}", [Fmt.int(conns)]);
3539-Http.setBody(res, Buf.bytes(text)); (* copied *)
3540-```
3541-
3542-`reset` keeps its buffers by moving them out and back:
3543-
3544-```
3545-proc reset*(var m: Message);
3546-var head, data: Buf.Buf; max: INT;
3547-begin
3548- Buf.take(m.head, head);
3549- Buf.take(m.data, data);
3550- max := m.maxBody;
3551- m := {minor: 1, maxBody: max}; (* the owners left out: empty *)
3552- Buf.take(head, m.head);
3553- Buf.take(data, m.data);
3554- Buf.reset(m.head);
3555- Buf.reset(m.data);
3556-end;
3557-```
3558-
3559-`m := {minor: 1, maxBody: max}` alone also compiles. It drops both
3560-buffers' memory and their allocator, so the next `Buf.add` calls a
3561-`nil` allocator and stops (A7.7, H4).
3562-
3563-A `Reader` can't hold the `Conn` it reads from, since no safe pointer
3564-to a local `Conn`, or to `cl^.conn`, exists. Either the `Conn` comes
3565-from `NEW`, and a `Client`'s 16 KB buffer can never be freed (D), or
3566-the reader takes the connection on each call:
3567-
3568-```
3569-proc read*(var r: Reader; var c: Conn.Conn; b: []U8): (INT, ERROR);
3570-proc readBody*(var cl: Client; b: []U8): (INT, ERROR); (* open no longer returns ^Reader *)
3571-```
3572-
3573-`parseUrl` fills a local `Url` with slices of a `Buf`, and the `Url`
3574-dies before the `Buf` does. That is PROPOSALS' false alarm of "a record
3575-that lives in the frame". Returning the `Url` as a result doesn't help,
3576-since a local record may not hold a lend (7.3). The cure that compiles
3577-copies the URL into a frame array, whose slices a local record *may*
3578-hold:
3579-
3580-```
3581-var here: [MaxUrl]U8; hereLen: INT; u: Url;
3582-...
3583-try parseUrl(here[0..hereLen], u); (* frame-lent: allowed in the local u; parseUrl's s is keep *)
3584-```
3585-
3586-So a URL gets a fixed limit only to get past the rule. `cl^.scheme :=
3587-u.scheme` becomes `cl.tls := u.scheme = "https"`. The server's threads
3588-become `Task(^Server)`, `Hello` makes its `Server` with `NEW`, and
3589-`arg: ^U8` goes from `Handler`. A server with state keeps it in module
3590-variables, shared by its workers with no lock unless it uses
3591-`Lock.Guarded`. The tests that cast `Conn.state` go into an unsafe
3592-module of their own.
3593-
3594-**Count.** About 2,700 lines, tests included. The fence alone
3595-(`ADR` to `Http`'s own pointer parameters, casts): about 330 lines.
3596-Parts B to F: `Message` and its accessors and setters about 120, the
3597-readers and writers that use them about 40, `reset` and `open`'s copy
3598-15, `Url` 15, `Reader` and `Client` 20, threads and the handler 10,
3599-Webserver 8, `Server` 16, `Hello` 3. About 230 lines in all, 9%.
3600-
3601-**Judgement: worse.** Every field is now a call. Each header and each
3602-body a handler makes is copied once more, and a 100,000-byte body made
3603-in a `Buf` is copied whole. Fixed limits come in only to dodge a rule
3604-(`MaxUrl`), and handlers lose their context. In return, "good until the
3605-message is read again or reset", which `Http`'s header comment asks a
3606-reader to remember, is now checked.
3607-
3608-**Contortions and false alarms:** `parseUrl` into a frame array; the
3609-scheme as a BOOL; `Reader` without its `Conn`; the accessors, which
3610-don't compile without R1. **Run-time stops in correct code:** none
3611-found. **Real bugs caught:** none. `reset`'s copy of the `Buf`s, which
3612-section 7.6 calls "safe by luck", is right: the copies are put back at
3613-once. `res^.body := req^.body` in `test/Server.raz` is right by the
3614-order `serveConn` keeps.
3615-
3616-### A7.3 rmacs (`src/Core.raz`, `Commands.raz`, `Text.raz`, `Mini.raz`, `Dired.raz`, `Windows.raz`)
3617-
3618-**What the rules reject.**
3619-
3620-| Line or construct | Rule | The compiler's error |
3621-|---|---|---|
3622-| `Text`: `data: ^U8`, `Mem.alloc`, `Mem.free`, `t^.data[i]`, `^U8(t^.changes)` | 5.1, 5.2 | `Mem.free is an unsafe procedure`, `indexing a pointer is for unsafe modules` |
3623-| `proc slice*(lo, hi: I64): []U8; ... return Text.slice(ADR(b^.t), lo, hi)` (`Core`), 12 callers | 7.3: returned, lent by the owner `b^.t`, which no parameter names | `Text.slice(b^.t, lo, hi) is lent by b^.t, which counts what it lends, and can't be returned` |
3624-| `proc text: []U8` (`Mini`), the same through `Core.mini^.t` | 7.3 | the same |
3625-| `proc nameAt(i: I64): []U8` (`Dired`), a slice of the module `Buf` `names` | 7.3 | the same |
3626-| `bufferNames(i)` returns `Buf.bytes(ADR(choices[i]^.name))`, as a `Mini.Names` procedure value | 7.3 | the same; and no mark on `Mini.Names` could allow it |
3627-| `Heap.heap^.free(Heap.heap, ^U8(x))` (`Core.kill`), four in `Windows` | 5.1, 5.2, D | `Heap's free is an unsafe procedure` |
3628-| `t := ADR(w^.buf^.t)` (`Rmacs.colours`) | 5.1 | `ADR is for unsafe modules` |
3629-| `DEC(out^.len)`, `DEC(line.len)`, `s.len := ...`, `t^.log.len := ...`: 7 writes of a `Buf`'s `len` | 5.3 rule 4 (see A7.7, H3) | nothing, as the proposal stands: a safe hole |
3630-| `selected := w`, `shown := x`, `Core.b := x`: a pointer parameter stored in a module variable (8 procedures) | 6.2, read strictly | `w is lent by the parameter w; mark it keep` |
3631-| 139 `ADR`s given to rmacs's own pointer parameters (`Text.len(ADR(b^.t))`, `Mini.read(..., ADR(answer))`) | 5.1 | `ADR is for unsafe modules` |
3632-
3633-**Rewritten.** No procedure but the owner's own can hand out what an
3634-owner lends, so `Core.slice` can't be written, and each of its twelve
3635-callers names the text itself:
3636-
3637-```
3638-(* Before *)
3639-Buf.str(ADR(Core.tmp), Core.slice(p, b));
3640-(* After *)
3641-Buf.str(Core.tmp, Text.slice(Core.b^.t, p, b));
3642-```
3643-
3644-A procedure value can't return a lend either, so `Mini.Names` changes
3645-to write the name into a buffer it is given:
3646-
3647-```
3648-(* Before *)
3649-Names* = proc(i: I64): ([]U8, BOOL);
3650-proc bufferNames(i: I64): ([]U8, BOOL);
3651-begin
3652- if i >= numChoices then return "", false; end;
3653- return Buf.bytes(ADR(choices[i]^.name)), true;
3654-end;
3655-
3656-(* After *)
3657-Names* = proc(i: I64; var name: Buf.Buf): BOOL; (* the i-th name, into name *)
3658-proc bufferNames(i: I64; var name: Buf.Buf): BOOL;
3659-begin
3660- if i >= numChoices then return false; end;
3661- Buf.reset(name);
3662- Buf.str(name, Buf.bytes(choices[i]^.name));
3663- return true;
3664-end;
3665-```
3666-
3667-`gather`'s loop and `commandNames` change to match: about 10 lines. A
3668-killed buffer and a closed window are not freed. Their contents are
3669-(`Text.done`, `Buf.done`), and the empty record, about 200 bytes, is
3670-kept to the end of the run:
3671-
3672-```
3673-Text.done(x^.t);
3674-Buf.done(x^.name);
3675-Buf.done(x^.path);
3676-(* x itself is kept, empty: part D lets no safe module free it *)
3677-```
3678-
3679-That is five lines taken out. The `Pool(Buffer)` that section 14.2
3680-offers would touch about 370 dereferences of `^Buffer` and `^Window`.
3681-`Pool` can't take a `Buffer` at all anyway: `add(var p; keep x: T)`
3682-passes `x` by value, and a `Buffer` holds owners (7.6). `Pool` would
3683-need an `alloc(var p): Handle` that hands out a zeroed slot.
3684-
3685-`Text` either says `unsafe;` and carries the owner's protocol by hand
3686-(a `LENDS` field, retiring in `room`, `ret` on `slice`: about 25
3687-lines), or is rebuilt on `Vec(U8)` and `Vec(Change)` (about 60 lines).
3688-Its gap moves under a slice that is held (`moveGap`), which the rules
3689-let pass, since it is memory-safe. That is right: today's comment,
3690-"good until the next change", stays a comment.
3691-
3692-**Count.** 4,931 lines. The fence alone: about 160 (the 139 `ADR`s,
3693-the casts, `Text`'s heading). Parts B to F: `Text` 25, the four
3694-accessors and their 20 callers 35, `Mini.Names` 10, `colours` 7, frees
3695-5, `len` writes 7: about 90, 2%.
3696-
3697-**Judgement: the same.** Twelve calls grow a little longer.
3698-`Mini.Names` copies each name once per keystroke of ido, about 256
3699-small copies, which doesn't show.
3700-
3701-**Run-time stops in correct code.** `writeFile` holds `p :=
3702-Buf.bytes(abs)` under `defer Buf.done(abs)`, and `loadInit` holds
3703-`s := Buf.bytes(b)` under `defer Buf.done(b)`. Section 7.3 lets a
3704-hold go "when the procedure returns", but doesn't say whether that is
3705-before or after its deferred statements. If after, `C-x C-w` stops
3706-the editor every time, and so does starting it with a `~/.rmacs`
3707-(A7.7, H5). **Real bugs caught:** none. No self-
3708-append or kill-while-held was found. `killBuffer` and `deleteWindow`
3709-take care with `Core.b` and `Core.selected` already.
3710-
3711-### A7.4 The compiler (`src/Scan.raz`, `Chunk.raz`, `Diag.raz`, `Sym.raz`, and their users)
3712-
3713-**Scan's name table: can be safe, and is clearer.** Today names are
3714-three hand-grown arrays and a table, all freed and copied by hand, and
3715-the bytes sit in 64 KB chunks that are never freed. Safe, the chunks
3716-come from `NEW` (lasting, so their slices last), and the arrays are
3717-`Vec`s:
3718-
3719-```
3720-var
3721- chunk: ^[PoolChunk]U8; (* from NEW, never freed: its slices last *)
3722- chunkUsed: INT;
3723- names: Strs.Vec; (* import Strs := Vec([]U8) *)
3724- hashes, table: Ints.Vec; (* import Ints := Vec(INT) *)
3725-
3726-proc intern*(s: []U8): INT; (* was intern(p: ^U8; n: INT), called with ADR(s[0]), LEN(s) *)
3727-var h, i, k: INT; t, hs: []INT; p: []U8;
3728-begin
3729- h := hash(s);
3730- t := Ints.all(table);
3731- hs := Ints.all(hashes);
3732- i := h & tableMask;
3733- while t[i] # 0 do
3734- k := t[i] - 1;
3735- if (hs[k] = h) and (Strs.get(names, k) = s) then return k; end;
3736- i := (i + 1) & tableMask;
3737- end;
3738- if (chunk = nil) or (LEN(s) > PoolChunk - chunkUsed) then NEW(chunk, Heap.heap); chunkUsed := 0; end;
3739- p := chunk^[chunkUsed..chunkUsed + LEN(s)];
3740- COPY(p, s);
3741- INC(chunkUsed, LEN(s));
3742- k := names.len;
3743- Strs.push(names, p); (* keep: p lasts *)
3744- Ints.push(hashes, h); (* may grow hashes: hs is retired, and not read again *)
3745- t[i] := k + 1;
3746- t := []; (* or grow's Ints.done(table) stops the program *)
3747- hs := [];
3748- if (k + 1) * 2 > tableMask then grow; end;
3749- return k;
3750-end;
3751-```
3752-
3753-Two things here aren't in the proposal. `Strs.get` is new: `return
3754-Strs.all(names)[n]` is refused, since an element of an owner's lend is
3755-lent (6.1), though what it holds was stored by `keep` and lasts (A7.10,
3756-R4). And `t := []` before `grow` is needed only to get past `done`'s
3757-stop. Today's `intern` checks `n > chunkLeft` and then copies `n`
3758-bytes into a 64 KB chunk: a name longer than 65,536 bytes would
3759-overrun it. That can't happen, since `MaxStr` is 65,536 and `MaxIdent`
3760-is 63, so the bound holds only by the coincidence of two constants.
3761-The safe form checks it. About 40 lines change; the scanner's buffer
3762-stays unsafe, as section 21 suggests.
3763-
3764-**Chunk's grown arrays: can be safe, and grow longer.** `text`,
3765-`rodata`, `chunks`, `fixups`, `dataFixups`, `lines` and `varNotes`
3766-become `Buf`s and `Vec`s. `put1` becomes `Buf.add(text, U8(b & 0FFH))`,
3767-which is clearer. But there are about 200 places in `Link`, `X64`,
3768-`Elf`, `Gen`, `Parse` and `Item` that read `Chunk.chunks[c].adr` or
3769-`Chunk.lines[i].at`, and each one becomes either
3770-
3771-```
3772-Chunks.all(Chunk.chunks)[c].adr := a; (* a count raised and lowered, each time *)
3773-```
3774-
3775-or a local held over the procedure, `cs := Chunks.all(Chunk.chunks)`.
3776-The obvious mending, `proc at*(c: INT): ^Chunk` in `Chunk`, can't be
3777-written, since it returns a lend of an owner that no parameter names
3778-(7.3). And a held `cs` across a `newChunk` that grows the array is a
3779-new trap. The writes through `cs` go into the retired block and are
3780-lost, with no message, even in the debugging heap, which poisons
3781-retired blocks for reads only (11). Today that is a use after free.
3782-Under the proposal it is a wrong executable, and the proposal calls it
3783-"lost, but harmless" (7.4). For a compiler it is not harmless.
3784-
3785-**Diag's files and messages.** `files: ^File` becomes `Vec(File)`, and
3786-`pathOf` needs `Vec.get` (R4). `say` keeps every message for good, in
3787-a `Buf` from `grab` that is never freed:
3788-
3789-```
3790-(* Before *)
3791-b := ^Buf.Buf(grab(SIZE(Buf.Buf)));
3792-Buf.init(b^, Heap.heap);
3793-Fmt.write(b^, f, args);
3794-return Buf.bytes(b^);
3795-
3796-(* After, with Buf.leak (R5) *)
3797-var b: Buf.Buf;
3798-Buf.init(b, Heap.heap);
3799-Fmt.write(b, f, args);
3800-return Buf.leak(b); (* b gives its block up for good: it lasts *)
3801-```
3802-
3803-Without `Buf.leak` the only safe form is a second copy, `Str.copy` of
3804-the bytes and then `Buf.done`, for every message. `Sym.typeName` is the
3805-same, and so are four `grab`-and-slice strings in `Parse`, `Item` and
3806-`Raz`.
3807-
3808-**Sym's scopes.** The hash table `hashTab: ^^Obj` becomes `Vec(^Obj)`,
3809-and `rehash` builds a new one and drops the old. `Obj`s and `Type`s
3810-come from `NEW` and are never freed, so the 1,015 dereferences stay as
3811-they are, as 8.1 says. Under the strict reading of 6.1, though, each
3812-procedure that stores a pointer it is given needs `keep`: `newObj`'s
3813-`typ`, `insert`'s `obj`, and the 17 procedures of `Item` and `Parse`
3814-that put a `^Sym.Type` or `^Sym.Obj` parameter into a `var x: Item`.
3815-That is about 40 headings across `src/`, and every argument is a
3816-pointer from `NEW` already (R3 removes them). `Parse`'s `curLoop :=
3817-ADR(lp)` becomes a stack of loops in a module array, about 10 lines.
3818-
3819-**Count.** 14,285 lines. The fence's own list (section 2.2): about 60
3820-sites. Parts B to F and what the mending entails: Scan 40, Chunk 60,
3821-the 200 accesses, Diag and the kept strings 30, Sym 20, `keep` marks
3822-40, loops 10. About 420 lines, 3%.
3823-
3824-**Judgement.** Scan's table and `Diag.say` come out clearer. `Chunk`
3825-and `Link` come out longer, and no clearer, unless R1 allows accessors.
3826-Speed: a call, a count and a bounds check where a pointer index stood,
3827-on the symbol lookup and code emission paths. That is not measured; an
3828-estimate is 1 to 3% of instructions, on top of the 4.5% of 13.1 if
3829-`Scan` goes safe as well. **Run-time stops in correct code:**
3830-`Parse.raz:3696`, `text := Buf.bytes(s)` and then `Buf.done(s)`, would
3831-stop at the first generic instance the compiler made, and so `make
3832-check` would stop in its first minute. **Real bugs caught:** none,
3833-beyond the bound in `intern` that holds by luck.
3834-
3835-### A7.5 The library (`Fmt`, `Opt`, `Map`, `Buf`, `Vec`, `List`, `Files`) and `examples/Sh.raz`
3836-
3837-**`Fmt` can't be made safe as section 5.4 says.** `format` takes
3838-`b: ^Buf.Buf`, with `nil` for standard output, and `write` and
3839-`eprint` pass `ADR(b)`. Without `ADR`, the `nil` must become a flag,
3840-and `print` has no `Buf` to pass:
3841-
3842-```
3843-(* After *)
3844-var none: Buf.Buf; (* never written: what print passes for b *)
3845-
3846-proc put(var b: Buf.Buf; out: BOOL; s: []U8);
3847-begin
3848- if out then Out.str(s); else Buf.str(b, s); end;
3849-end;
3850-
3851-proc print*(f: []U8; args: []Arg);
3852-begin
3853- format(none, true, f, args);
3854-end;
3855-```
3856-
3857-This is a contortion: an owner kept only to stand in for "none".
3858-`eprint` builds its text in a `Buf` over an arena, so that a program
3859-that doesn't call it carries no heap. Under the proposal
3860-`Buf.init(b, Arena.allocator(ar))` is refused. `init` keeps its
3861-allocator, so its parameter is `keep`, and the arena's allocator is
3862-lent by the arena (8.4). So `eprint` moves to the heap and loses the
3863-reason its comment gives. No container can take memory from an arena
3864-in safe code. About 15 lines change.
3865-
3866-**`Opt` is safe, with one stop in correct code.** `left` and
3867-`leftWidth` take `const r: Row` for `ADR(p.table[i])`, six lines.
3868-`init` is `keep name, table`, and `scope` is `keep name`. `say` would
3869-stop:
3870-
3871-```
3872-proc say(fd: INT; var b: Buf.Buf);
3873-var s: []U8; n: INT;
3874-begin
3875- s := Buf.bytes(b);
3876- while LEN(s) > 0 do
3877- n := Sys.write(fd, s);
3878- if n <= 0 then break; end;
3879- s := s[n..LEN(s)];
3880- end;
3881- s := []; (* new: else the next line stops, though s is empty and never read again *)
3882- Buf.done(b);
3883-end;
3884-```
3885-
3886-Every usage message and every `--help` of every program goes through
3887-`say`.
3888-
3889-**`Map` marks are easy, and its uses narrow.** `put(var m; keep k: K;
3890-keep v: V)` is one heading. `Map([]U8, V)` keys must now last, so a
3891-key made in a `Buf` is `Str.copy`'d and never freed, or goes in
3892-`Names(V)`. `Map(K, Buf.Buf)` can't be made at all: `put` takes `V` by
3893-value, and an owner can't be copied. A map of strings to buffers, an
3894-editor's "buffer by name", has no safe form but `Pool` handles.
3895-
3896-**The containers export what breaks them.** `Buf.len*`, `Vec.len*`,
3897-`List.head*` and `List.Node.next*` are fields a safe module can write.
3898-`b.len := 1 shl 40; Buf.bytes(b)` reads any memory, because `bytes`
3899-slices `b.data`, a pointer, unchecked. `l.head := other.head;
3900-List.clear(l)` frees another list's nodes. This is 5.3's rule 4, but
3901-section 17 doesn't list it. Hiding the fields changes every read of
3902-`b.len` in every program, dozens in rmacs alone, unless fields can be
3903-exported read-only (R6). `Files.load` writes `INC(b.len, n)` after
3904-`Buf.spare`, as `spare`'s own comment says to, so `Files` isn't safe
3905-either until `Buf` gets a checked `took(var b; n)`. `examples/Words`
3906-walks `order.head` and `n^.next`, three lines that become
3907-`Names.first` and `Names.next`.
3908-
3909-**`examples/Sh.raz`: its arena has no safe form.** `Sh` builds each
3910-word in a `Buf` over a module arena, keeps `Buf.bytes(b)` in the module
3911-variable `text` and in `Command.args`, and resets the arena for each
3912-script. Every one of those is refused: the `Buf` over the arena (keep,
3913-8.4), `text := Buf.bytes(b)` (7.3), `c^.args[c^.n] := text` through a
3914-pointer (6.2), `return Buf.bytes(b), true` in `find` (7.3), and `s :=
3915-script` from `run(Buf.bytes(line))` (keep). Building `argv` from spans
3916-at `spawn` is refused too, since a local array of slices may not hold
3917-a lend (7.3). What compiles is a bump allocator written by hand over a
3918-module array, whose slices last:
3919-
3920-```
3921-var
3922- pool: [1 shl 24]U8; (* the words of what is being run; a module's array lasts *)
3923- used: INT;
3924-
3925-proc add(c: U8);
3926-begin
3927- if used = LEN(pool) then say("out of room for words", []); Rt.exit(2); end;
3928- pool[used] := c;
3929- INC(used);
3930-end;
3931-
3932-(* in readWord, for Buf.init(b, ADR(arena.base)) ... text := Buf.bytes(b) *)
3933-start := used;
3934-...
3935-text := pool[start..used];
3936-```
3937-
3938-The rules let this pass, and that's right: `used := 0` makes old words
3939-show new bytes, which is a matter of logic, not memory. But it shows
3940-that the arena was refused for what it is, not for anything it does.
3941-`ADR(p^.cmds[i])` becomes an index, and `builtin` and `start` take
3942-`const`. The scanner's module state (`s`, `at`, `text`) goes into a
3943-`Scanner` record passed by `var`, so that `run` needn't keep its
3944-script. That is 45 of 387 lines, 12%. The scanner comes out clearer,
3945-and the allocator worse: an `Arena` was one line, and this is ten.
3946-
3947-### A7.6 rjson's `Json` (`src/Json.raz`, `test/Suite.raz`)
3948-
3949-`Doc` grows its nodes by hand with `Mem.alloc` and `Mem.free`, and
3950-copies strings into a list of chunks that `reset` frees. So `Json`
3951-says `unsafe;` and carries the owner protocol itself: a `LENDS` field,
3952-retiring chunks in `reset`, `ret` on `text`, `key` and `copy`. That is
3953-about 25 lines of trusted code outside the library, and the same holds
3954-for every program with a container of its own (`Text` in rmacs). The
3955-audit surface grows with each one. The zero-copy design ("the text
3956-must live as long as the document") means `parse` keeps its text. The
3957-suite's
3958-
3959-```
3960-v := Json.parse(ADR(d), Buf.bytes(ADR(text))); (* twice *)
3961-```
3962-
3963-is refused, since a `Buf`'s bytes don't last. Such a program either
3964-leaks each file's bytes with `Buf.leak`, which is fine for a test but
3965-not for a server parsing request bodies, or `Json` gets a `parseCopy`
3966-that copies the text into the document first: one copy per parse,
3967-small next to parsing. About 40 lines change, 4%.
3968-
3969-### A7.7 Holes the port found in the rules
3970-
3971-Each of these lets unsafe code through as the proposal is written, or
3972-leaves undecided whether correct code stops.
3973-
3974-- **H1. A store through a slice isn't a store that outlives.** 6.2
3975- lists module variables, `p^.f` and `var` parameters. It doesn't list
3976- `s[i] := e` for a slice `s`. So `proc fill(names: [][]U8); var buf:
3977- [8]U8; begin names[0] := buf[0..8]; end;` puts a slice of the frame
3978- in the caller's array. `Vec.all(v)[i] := e` puts a lend in a
3979- container the same way. The rule must say that a store through a
3980- slice not lent by the frame alone is a store that outlives.
3981-- **H2. A `ret` through a record that holds owners loses the owner.**
3982- `name*(ret const m: Message; i: INT): []U8`, the accessor section
3983- 14.2 recommends, returns a lend of `m.head`. The caller knows only
3984- that the result is lent by `m`, which isn't an owner (7.2), so it
3985- doesn't know whose count to raise, and it raises none. Then
3986- `readRequest` grows `m.head`, frees the old block, and the held
3987- slice dangles. Either the accessor is refused, and 14.2's way out
3988- doesn't compile, or it is allowed, and the count is lost. R1
3989- mends it.
3990-- **H3. The containers' exported fields** (A7.5): `Buf.len*`,
3991- `Vec.len*`, `List.head*`, `Node.next*`, and `Files.load`'s `INC(b.len,
3992- n)` by design.
3993-- **H4. A literal over a live owner.** `m := {minor: 1}` is allowed
3994- (7.6: a literal may leave an owner out). It drops the owner's block,
3995- which is a safe leak, and zeroes its allocator, so the owner's next
3996- growth stops. It is a trap that compiles, and the obvious rewrite of
3997- `Http.reset` falls into it.
3998-- **H5. The order of a hold's let-go and `defer`.** If holds are let go
3999- after the deferred statements, every `defer Buf.done(b)` over a
4000- local that holds `Buf.bytes(b)` stops the program. If before, a
4001- deferred statement that reads the local reads memory still allocated,
4002- which is fine. Section 7.3 must say "before".
4003-- **H6. Option 2 of 14.2 breaks rule 4 of 5.3** (A7.2). An unsafe
4004- `Http` with exported slice fields hands a safe module a slice it can
4005- read after `Http.done`.
4006-
4007-### A7.8 The verdict, in numbers
4008-
4009-| Code | Lines | The fence alone (`ADR` to own pointers, casts) | Parts B to F | Share | Result |
4010-|---|---|---|---|---|---|
4011-| rnet `Http`, `Conn`, tests, `Hello` | 2,700 | 330 | 230 | 9% | worse |
4012-| rmacs | 4,931 | 160 | 90 | 2% | the same |
4013-| raz `src/` | 14,285 | 60 sites | 420 | 3% | Scan, Diag clearer; Chunk, Link longer |
4014-| `lib/`: `Fmt`, `Opt`, `Map`, `Buf`, `Vec`, `List`, `Files` | 1,500 | 15 | 70 | 5% | Fmt worse; the rest the same |
4015-| `examples/Sh.raz` | 387 | 10 | 45 | 12% | scanner clearer, allocator worse |
4016-| rjson `Json`, `Suite` | 1,050 | 15 | 40 | 4% | the same, with a copy per parse |
4017-| **All** | **24,850** | **about 590** | **about 895** | **4%** | |
4018-
4019-Where parts B to F's 895 lines come from, by rule:
4020-
4021-| Rule | Lines | Share | What it hits |
4022-|---|---|---|---|
4023-| 7.3: an owner's lend returned, or held in a record or array | 450 | 50% | `Message`, `Url`, `Core.slice`, `Mini.Names`, `Chunk`'s accessors, `Sh`'s words, `Json`, `Diag.say` |
4024-| 5.1 and 8.4: no safe form for a context pointer, or for a container over an arena | 200 | 22% | `Conn.state`, `Server.arg`, `Thread.spawn`, `Fmt.eprint`, `Sh`'s arena |
4025-| 6.1 and 6.2 read strictly: `keep` on a pointer parameter that is stored | 60 | 7% | `Sym`, `Item`, rmacs's `Core` |
4026-| 7.6: owners aren't copied | 30 | 3% | `Http.reset`, `open`'s `out := req^` |
4027-| 5.3 rule 4: the containers' fields hidden | 20, or every read of `.len` | 2% | rmacs, `Files` |
4028-| D: no `free` | 5, leaking | 1% | rmacs's buffers and windows |
4029-| the rest: `ret` marks, `t := []`, views | 130 | 15% | everywhere, a line at a time |
4030-
4031-**Stops at run time in correct code: 8**, found by a search for a
4032-local holding `Buf.bytes(b)` when `b` is done: `Opt.say`,
4033-`Parse.raz:3696`, `examples/Elf.raz`, rmacs's `Commands` (two),
4034-ravite's `Ravite.raz`, rnet's `Dns` (two). Five of them depend on H5.
4035-Each is found the first time its code runs, and each is mended with one
4036-line. But there is one in the compiler and one in the library, so
4037-`make check` would stop the day part C came in.
4038-
4039-**Real bugs caught: none** in about 25,000 lines. One bound holds by
4040-the coincidence of two constants (Scan). Every slice held across a
4041-change of its buffer was right, by an order the code keeps. So the
4042-rules make "right by discipline" checked. They guard tomorrow's code;
4043-they don't mend today's. The five programs of section 1.2 were written
4044-to show the holes. None of them was found in this code.
4045-
4046-**Is the pain narrow?** By lines, yes: 96% of the code is left alone,
4047-or changes only where `STANDARDS.md` already asks it to. By kind, no.
4048-Five of the six pieces need a redesign of the one type they are built
4049-round. Each such type keeps a slice of a buffer in a record, or hands
4050-one out from a procedure that isn't the buffer's own, and those are
4051-the pieces that do I/O or hold data. Code that only computes, `Parse`'s
4052-statements, `Item`, `Gen`, rflate's inflater, `Fmt`'s formatting, is
4053-left alone, as section 14.1 says.
4054-
4055-### A7.9 Beside Rust and beside today's raz
4056-
4057-**Beside today's raz.** Today the six pieces compile as they are, and
4058-their rules of lifetime are comments ("good until the buffer next
4059-grows", "the text must live as long as the document"). Under the
4060-proposal four of those comments become checks, and the code that
4061-leans on them grows by about 4%. It loses three things that were
4062-easy: a record of slices of someone else's buffer, an accessor that
4063-returns a slice of a buffer, and a container over an arena.
4064-
4065-**Beside Rust.** Where a record holds slices of its *own* buffer
4066-(`Message`, `Doc`), Rust can't do it either: a struct can't borrow
4067-from itself, so Rust programs use spans, as here, or a crate built for
4068-it. Where a record holds slices of *another's* buffer (`Url` of a
4069-`Buf`, `Sh`'s `argv`, a `Doc` over a file's bytes), Rust writes
4070-`Url<'a>` and is done; raz must copy, or use a frame array. Where a
4071-procedure returns a slice of an owner it reaches through a global or a
4072-pointer (`Core.slice`, `bufferNames`, `Chunk.at`), Rust writes
4073-`&'static` or a lifetime on the result; raz can't write it at all.
4074-Where a callback needs its context (`Server.arg`, `Conn.state`), Rust
4075-has closures and trait objects; raz has `^U8`, which is fenced. On
4076-the other hand, 96% of the code needs no mark at all, where a Rust
4077-port of `Sym`, `Item` and `Parse`'s trees, with their `^Obj` and
4078-`^Type` links everywhere, would need `Rc`, arenas with lifetimes or
4079-indexes throughout. And Rust would reject at compile time the eight
4080-`done`-while-held places, where this proposal stops at run time. In
4081-short, the proposal costs much less than Rust in the code that
4082-computes, more than Rust in the code that holds buffers, and it has
4083-nothing for type-erased context, where Rust has a great deal.
4084-
4085-### A7.10 Relaxations and additions
4086-
4087-Each of these removes pain found above. Each says what it would cost,
4088-and what, if anything, it weakens.
4089-
4090-- **R1. A lend carries its count.** An owner's lend returned from any
4091- procedure carries the address of its owner's count, in a hidden word,
4092- as a held local already does. Then the caller counts it on the right
4093- owner, whoever returned it. This allows `Core.slice`, `Mini.text`,
4094- `Dired.nameAt`, `Chunk.at`, `Http.target` and `Json.text`, mends H2,
4095- and removes about 250 of the 450 lines of 7.3. A procedure type
4096- must say that its result carries a count (`proc(i: I64): lent
4097- []U8`). It costs a register on return. It weakens nothing.
4098-- **R2. A local array or record may hold lends** (question 4 of section
4099- 21: yes), with one hold for each owner it holds lends of, all let go
4100- when the local is assigned whole or the procedure returns. This
4101- allows `Url` of a `Buf`, `Sh`'s `argv`, and a local `[]Fmt.Arg` of
4102- several `Buf`s, and removes about 60 lines. It costs a few words in
4103- the frame. It weakens nothing.
4104-- **R3. A pointer parameter lasts, as STANDARDS says it does** ("a
4105- pointer, only when it is kept"). An unmarked `^T` parameter may be
4106- stored. An owner's pointer (`Vec.add`, `Pool.at`) may not be passed
4107- as a `^T` argument, only dereferenced at the call, `f(p^)` to a `var`.
4108- This removes the 60 `keep` marks, and it puts the check on the rare
4109- case, the owner's pointer, not the common one. It weakens nothing.
4110-- **R4. `Vec.get(const v; i: INT): T` and `Vec.set(var v; i: INT;
4111- keep x: T)`.** A copy of an element holds what was kept, and that
4112- lasts. This mends `Scan.nameOf` and `Diag.pathOf`. Library only,
4113- and it weakens nothing.
4114-- **R5. `Buf.leak(var b: Buf.Buf): []U8` and `Vec.leak`.** The owner
4115- gives its block up for good and is left empty, and the block lasts,
4116- since no one holds what could free it. This is Rust's `Box::leak`. It
4117- mends `Diag.say`, `Sym.typeName`, `Parse`'s and `Item`'s kept
4118- strings, and a test's file. Library only, and it weakens nothing,
4119- but leak-freedom, which the guarantee doesn't promise (3).
4120-- **R6. Fields exported read-only**, Oberon-2's `len-: INT`, and
4121- `Buf.took(var b; n: INT)`, checked against the room `spare` made. This
4122- closes H3 and keeps every read of `b.len` as it is, while the seven
4123- writes in rmacs become `Buf.cut`. A language change of one mark.
4124- It weakens nothing, and without it the containers aren't safe.
4125-- **R7. `done` with a lend held is caught when compiling where it
4126- can be, and otherwise retires.** In one pass, the compiler knows when
4127- a local was last assigned a lend of `b` and has not been assigned
4128- since, so at `Buf.done(b)` it can say "`s` still holds a lend of `b`:
4129- write `s := []` first". That turns six of the eight stops into
4130- messages. The two through a pointer stay. For those, `done` retires
4131- the block instead of stopping: question 3 of section 21, answered
4132- "leak". With H5 settled as "before", the eight become none. It weakens
4133- leak-freedom, not safety, and the debugging heap can report each
4134- leak.
4135-- **R8. A checked context pointer.** A type `^ANY`, which any pointer
4136- from `NEW` converts to, and a conversion back, `^T(p)`, checked
4137- against a type word that `NEW` writes before the record. A wrong
4138- type stops the program, as Oberon's type guard does. This mends
4139- `Conn.state`, `Http.Server.arg`, `Thread.spawn`'s `arg` and the
4140- tests' casts, about 150 lines, and lets a server keep its state
4141- without module variables shared across threads. It costs a word per
4142- record that is ever made `^ANY`, if `NEW` is told so, and a compare
4143- per conversion. It weakens nothing.
4144-- **R9. Growth with a *writable* lend held stops; with a lend that
4145- only reads, it retires.** `Vec.add` and `Buf.spare` lend for
4146- writing, and `bytes` and `all` lend for reading. A write into a
4147- retired block is lost with no message (A7.4); a stop says where.
4148- `Buf.str(b, Buf.bytes(b))` still runs. This is a tightening, not a
4149- relaxation. It costs a second count per owner, and `all` must split
4150- in two, since today it lends for both.
4151-
4152-Some pain has no relaxation that keeps the guarantee:
4153-
4154-- **A container over an arena** (`Fmt.eprint`, `Sh`). Making it safe
4155- needs the container to hold the arena's count for as long as it
4156- lives: an owner holding a lend, which is a lifetime in a record,
4157- Rust's apparatus. A module array with an index does it safely, as
4158- `Sh`'s rewrite shows, at a fixed size. Otherwise such code stays
4159- unsafe.
4160-- **A record that keeps slices of its own buffer** (`Message`, `Doc`)
4161- stays spans and accessors, in raz as in Rust. With R1 the accessors
4162- compile, and that is all the help there is.
4163-- **Freeing records one by one.** `Pool`, or leaking. For an editor
4164- leaking is the plain choice, and it is safe. `Pool` needs an `alloc`
4165- that hands out a zeroed slot, for records that hold owners.
4166-
4167-With R1 to R8, the port's 895 lines fall to about 400, under 2%. The
4168-contortions left are `Fmt`'s stand-in and `Sh`'s allocator, and no
4169-correct code stops at run time. The holes H1 to H6 are mended by
4170-R1, R6 and two sentences in 6.2 and 7.3.

PLAN.md (history) modified +349 -10

@@ -1,8 +1,8 @@
11 # raz: the plan to 1.0
22
33 What is left before raz is 1.0, in order, by the owner's word of
4-2026-10-23. `PROPOSALS.md` takes nothing new; what it still holds open is
5-the safety thaw and the Moss work below, and nothing else is planned.
4+2026-10-23. raz takes no proposals; what is left is the Moss work below,
5+its proposals kept in the appendix, and nothing else is planned.
66 Each step is a release, started on the owner's go-ahead; within it, one
77 commit per piece, the report first for any change to the language.
88
@@ -28,9 +28,10 @@
2828 ## 2. The safety thaw: v0.23.0, then v0.24.0
2929
3030 The scope, by the owner's word of 2026-10-26, after reviewing
31-`MEM_PROPOSAL.md` whole with its appendices. raz doesn't promise memory
32-safety: `free` stays, so a program can always keep a pointer to what
33-it freed. The thaw shrinks what is undefined, and fences what can reach
31+`MEM_PROPOSAL.md` (in git to 2026-10-26) whole with its appendices.
32+raz doesn't promise memory safety: `free` stays, so a program can
33+always keep a pointer to what it freed. The thaw shrinks what is
34+undefined, and fences what can reach
3435 memory it shouldn't, so a reader can find it.
3536
3637 What goes in:
@@ -107,14 +108,15 @@
107108
108109 1. Merge the branch `moss-platform-boundary`'s two plain fixes (a file's
109110 identity from `Sys.info`; a main file at the root), rebased on main.
110-2. `Host`, as "The compiler on another host" in `PROPOSALS.md` asks:
111+2. `Host`, as "The compiler on another host" in the appendix asks:
111112 five procedures, `Files.argCount`, a host chosen by staging, its tests
112113 in `sh`, not Python; rebased and merged. Moss's `RAZ_PORT.lock` then
113114 pins main.
114115 3. What the compiler asks of `Sys`, `Rt` and `Files`, written down in
115116 `doc/compiler.md` and held by a test.
116117 4. "A freestanding program, stated", "The assembler's instructions" and
117- "Implementation limits, and a compiler for a small stack".
118+ "Implementation limits, and a compiler for a small stack", in the
119+ appendix.
118120 5. Release.
119121
120122 ## 4. The hard freeze
@@ -128,9 +130,8 @@
128130
129131 The files that served the thaws are made a record, short and true:
130132
131-- `PROPOSALS.md` and `MEM_PROPOSAL.md`: what was built is in the report,
132- `doc/report-history.md` and git; each shrinks to a short index of what
133- was decided, and what was left out with its reason, or goes.
133+- `PROPOSALS.md` and `MEM_PROPOSAL.md`: gone, done early (2026-10-26);
134+ what was built is in the report, `doc/report-history.md` and git.
134135 - `~/r/RAZ-GAPS.md` and each repository's `RAZ-NOTES.md` (or `RAZ.md`):
135136 closed, each saying so at its top; a gap since mended is marked.
136137 - `CLAUDE.md` (raz's and `~/r`'s): "Where things stand" cut to the
@@ -148,3 +149,341 @@
148149 No date. raz is 1.0 when use shows it: programs written against v0.26.0
149150 for long enough that no defect is outstanding. Until then it is
150151 0.26.x, mending defects only.
152+
153+## Appendix: the Moss work, as proposed
154+
155+The four proposals 3 builds, kept from `PROPOSALS.md` (in git to
156+2026-10-26) when it and `MEM_PROPOSAL.md` went: what the thaws built is
157+in the report, `doc/report-history.md` and git.
158+### The compiler on another host: `Host`, and what it asks of the library
159+
160+**Status.** Built on the branch `moss-platform-boundary` (3eded0c),
161+which Moss pins: there raz compiles programs, rebuilds itself byte for
162+byte, and builds again after a restart (moss c606069,
163+`docs/native-raz.md`). Waiting for the owner's word on the questions
164+below before it is rebased and merged.
165+
166+The host is the system the compiler runs on; the target, the system
167+its program will run on. Until the branch they were one, Linux, and
168+the compiler reached Linux outside `Sys`: `Parse.identity` read a
169+`struct stat` by `SYSCALL(4)` into a guessed `[18]INT`; `Raz` read
170+`ARGC()` and `ARGV()`, found the library through `/proc/self/exe`,
171+probed two loader paths for musl, and ran a program by `memfd_create`
172+and `execve`; `Elf` set mode 755. The branch does three things.
173+
174+**1. A file's identity from `Sys.info`** (2644329). Its `dev` and
175+`ino`, so the parser makes no system call of its own. A plain fix:
176+merge it.
177+
178+**2. A main file at the root, and a directory ending in `/`**
179+(3eded0c). `/Main.raz` has `/` as its directory, not `""`, and a
180+directory given as `lib/` doesn't make `lib//Sys.raz`. A plain fix:
181+merge it.
182+
183+**3. `Host`, a module of what the compiler asks of its host**
184+(bb03e48): `argCount`, `arg`, `libraryDir`, `preferMusl`, `canRun`,
185+`canLinkC`, `writeExecutable`, `prepareRun`, `execute`. `src/Host.raz`
186+is Linux's; Moss stages the compiler's sources with its own
187+`Host.raz` (27 lines: the library at `/lib`, no run, no C, no mode
188+bits) and its own `Sys`, `Rt` and `Files`.
189+
190+Questions before the merge:
191+
192+**a. A smaller `Host`.** Two of its nine procedures are there only
193+because `Raz` reads the command line by built-ins:
194+- `argCount` and `arg` go if the library has the count beside
195+ `Files.arg`: a `Files.argCount()`, which Moss's `Files` gives from
196+ `Sys.argc`. `Files.arg` is already the library's, and Moss already
197+ replaces it.
198+- `preferMusl` and `canLinkC` are one question, which C library to
199+ link against: `Host.cLibrary(): CLib` with `CLib = (none, glibc,
200+ musl)`, or keep the two booleans.
201+- `canRun` goes if `prepareRun` is called while the command line is
202+ read, before any source, so that its error is the refusal.
203+That leaves `libraryDir`, `cLibrary`, `writeExecutable`, `prepareRun`
204+and `execute`: five procedures, each a real difference between hosts.
205+
206+**b. How a host is chosen.** The branch stages: copy `src/`, put the
207+host's `Host.raz` in place of raz's, build. The main directory is
208+searched first, so `-I` alone can't replace it, which is right: a
209+module isn't silently replaced. The other way is a target name, as
210+`Sys.linux-x86_64.raz` is chosen today from fixed suffixes: a
211+`-os moss` that makes the suffixes `.moss-x86_64`, `.moss`, `.x86_64`,
212+`""`, so that `Host.moss.raz` and `Sys.moss.raz` are found beside the
213+generic files. That puts Moss's files in raz's tree, and raz would
214+then know of Moss. The proposal is to keep staging, raz knowing
215+nothing of any host but Linux, and to document it in
216+`doc/compiler.md` as the one way to build for another host.
217+
218+**c. What the compiler asks of the library, written down.** Moss's
219+`Sys` has 23 exported procedures against Linux's 104, and is enough.
220+`doc/compiler.md` should list what the compiler and the modules it
221+imports (`Rt`, `Mem`, `Heap`, `Lock`, `Arena`, `Out`, `Fmt`, `Buf`,
222+`Str`, `Bytes`, `Files`) use of `Sys`, `Rt` and `Files`, as Moss's
223+`docs/raz-port.md` measured it, and a test should hold it: the
224+compiler built against a `Sys` with only those exports. Then a change
225+to the compiler that reaches for one more of `Sys` is seen in raz,
226+not in Moss's next build. The test host on the branch
227+(`test/host/Host.raz`) checks the `Host` side only.
228+
229+**d. The stack.** A self-build passed in 64 KiB of stack on Linux,
230+but 64 nested parentheses don't, and Moss gives a stored program 1
231+MiB. That is "Implementation limits, and a compiler for a small
232+stack", above; the merge needn't wait for it.
233+
234+**e. The tests in Python.** The branch adds `test/compiler-host.py`
235+(177 lines) and grows `test/library-path.py`, which came with
236+RAZ_PATH. raz's tests are otherwise `sh`, as a public project's
237+should be, needing nothing but a shell to run. The proposal is to
238+write both in `sh` before the merge.
239+
240+**f. Before the merge, in any case.** The system call numbers in
241+`Host.raz` named as constants, as `Raz` had them (`MemfdCreate`,
242+`MfdCloexec`, `Execve`); a comment on every procedure; the new section
243+of `doc/compiler.md` made as short and plain as the rest; a rebase on
244+main (`doc/compiler.md` and `src/Raz.raz` conflict). Moss's
245+`RAZ_PORT.lock` then pins a commit on main.
246+### A freestanding program, stated
247+
248+**Status.** Proposed 2026-10-22, collated from RAZ-GAPS.md.
249+
250+"For a kernel: three changes to the compiler" made a raz program run on
251+the bare machine; Moss, a kernel in raz, now boots on it. What it found
252+is less a missing feature than missing words: what a `-bare` program
253+must give the compiler, and what it may count on, are known only by
254+reading `Gen.entryPoint` and `Raz`. Five items, each standing alone.
255+The sixth thing Moss met, `jmp rax` read as a jump to a label, was a
256+bug, fixed in ac3c464.
257+
258+**1. The runtime ABI, written down.** A section of `doc/compiler.md`,
259+"A program with its own `Rt`", saying what the compiler asks of `Rt`
260+and what a program's start may count on:
261+- **Required:** `proc exit*(status: INT);`, which never returns (the
262+ compiler puts `ud2` after its call), and
263+ `proc fail*(what, a, b, len: INT; at: UINT; name: ^U8; rdi, rsi: UINT);`,
264+ with the kinds of `what` as `lib/Rt.raz` gives them (0 an index, 1 a
265+ slice, 2 an enumeration, 3 a backward slice of a pointer, 4 a nil
266+ pointer, 5 a division by zero, 6 a stack overflow, 7 a view), named
267+ constants in the text, not bare numbers.
268+- **Optional, found by name when declared:** `places`, `calls`,
269+ `teller`, `place`, `placer` (item 5), `startProfile` and `profiler`
270+ (never under `-bare`), `cExit` (only with C, which `-bare` refuses).
271+- **The entry:** `_start` runs every used module's body but `Rt`'s,
272+ then `main`. Under `-bare` it reads nothing from the stack and aligns
273+ nothing: the loader or boot stub enters it with the bss zeroed and
274+ `rsp` a multiple of 16, as Linux does.
275+- **`main` returning:** allowed. `Rt.exit` is then called with `main`'s
276+ result, or 0 for `proc main*`.
277+- **The panic hook:** `Rt.fail` is it. A kernel's `fail` prints and
278+ halts; nothing else is needed, and no second hook is proposed.
279+
280+A test holds it: `test/run/` builds a `-bare` program against a
281+smallest `Rt` of `exit` and `fail` alone, run under Linux, whose
282+`exit` and `fail` make the system call themselves.
283+
284+Met in Moss (`docs/raz-findings.md` §2), which copied the stock
285+signatures.
286+
287+**Recommendation:** take; it is words and one test, and the contract
288+already exists.
289+
290+**2. A recipe for an interrupt's entry.** Before any attribute or
291+generated stub, a tested recipe in `doc/compiler.md`, beside item 1,
292+stating what the compiler's code may assume and so what a stub must
293+restore:
294+- **What the compiler's code uses:** System V's caller-saved
295+ registers, `rax`, `rcx`, `rdx`, `rsi`, `rdi`, `r8` to `r11`, all of
296+ `xmm0` to `xmm15`, and the flags; the direction flag is clear at
297+ every call (the compiler's copies use `std` and `cld` and leave it
298+ clear).
299+- **The red zone:** whether the compiler ever writes below `rsp`. Not
300+ checked today ("For a kernel" leaves it open); it is to be checked
301+ and the answer written down. If it never does, an interrupt needs no
302+ IST stack for that reason.
303+- **The stub:** a `code` procedure per vector that pushes 0 where the
304+ CPU pushes no error code, pushes the vector, saves the caller-saved
305+ registers, aligns `rsp` to 16, saves the SSE state (`fxsave` or
306+ `xsave` to an aligned area), `cld`, calls an ordinary procedure
307+ `proc handle(vector, code: INT; frame: ^Frame)`, restores, drops the
308+ two words and `iretq`.
309+
310+It is testable on Linux: `iretq` from ring 3 to ring 3 is allowed, so
311+`test/run/Interrupt.raz` builds a frame by hand, jumps to the stub, has
312+the handler compute with reals, and checks on return that every
313+register the stub promised to keep is kept. The stub needs items 3 and
314+"The assembler's instructions", 1 (`push` of a constant, `cld`).
315+
316+Met in Moss (`docs/raz-findings.md` §4): its handlers use only `rax`
317+and make no call, which is safe but no recipe.
318+
319+**Recommendation:** take; a kernel's first stub is where the calling
320+convention is easiest to get wrong, and a test on Linux keeps it right.
321+
322+**3. A code procedure names a procedure or a global.** In a code
323+procedure, a name of the module's scope, or a qualified one, that is a
324+procedure or a global variable stands for its address, as an operand
325+of three forms only:
326+
327+ call fault; (* a procedure, rip-relative *)
328+ jmp fault;
329+ lea rax, [ticks]; (* a procedure or a global *)
330+
331+Each makes a reference to that chunk, so the linker keeps what is
332+named, as any call does. No other operand takes a name, and no type is
333+checked: a code procedure is the target's, and its author already
334+answers for the convention. The assembler gets the names as it gets
335+constants, by a function the parser hands in beside `ConstFn`.
336+
337+Moss stores `UINT(fault)` in a slot at start and calls through a
338+register (`docs/raz-findings.md` §5), so the slot must be filled
339+before the first fault, which nothing checks.
340+
341+**Recommendation:** take; three operand forms remove a hand-off that
342+can be forgotten, and the recipe in item 2 needs `call handle`.
343+
344+**4. A program brings its own `Rt`.** A `src/Rt.raz` beside the main
345+module meets `lib/Rt.raz`, and "a program has one module of each name"
346+refuses it, rightly. Moss copies the compiler beside an empty `lib/`.
347+Two ways out:
348+- **Staging,** as "The compiler on another host" proposes for the
349+ compiler's own sources: copy `raz` beside a library of the program's
350+ own. Nothing in raz changes; only words in `doc/compiler.md`. Every
351+ freestanding project then carries a copied compiler, and its library
352+ is all or nothing.
353+- **`raz -lib DIR`:** the library is `DIR`, not the one beside the
354+ compiler. A kernel's `-lib` is a directory holding its own `Rt` and
355+ `Sys` and, by symbolic links, whichever of raz's modules it takes
356+ (`Str`, `Fmt`, `Buf`). The duplicate check stays as it is. On the
357+ `Host` branch it is one line over `Host.libraryDir`; today a few
358+ lines in `Raz.raz` and raz(1).
359+
360+The option is the smaller for its users and nearly as small in raz;
361+staging stays the way for the compiler on another host, where the
362+whole of `src/` is replaced anyway.
363+
364+**Recommendation:** take `-lib`; a few lines save every freestanding
365+program a copy of the compiler.
366+
367+**5. Symbols without `Rt`'s places.** Without `-s` the compiler links
368+`places`, `calls`, `teller`, `place` and `placer` and stops with "Rt
369+has no places" where `Rt` lacks one, and `-noprofile` doesn't help, so
370+Moss builds with `-s` and loses the symbol table a debugger reads.
371+Two things are tied that needn't be: the ELF's symbols and lines, for
372+a debugger, and the places, for `Rt` to say where a check failed.
373+The change: each of the five is linked only when `Rt` declares it,
374+`calls` with `teller` and `place` with `placer`, a pair or neither; `-s`
375+still strips both. A kernel then keeps its symbols for GDB and gives
376+`fail` the raw address, or declares `places` and decodes them itself.
377+
378+A hosted program's `Rt` is raz's, which declares all five, so no
379+program changes. One that writes its own `Rt` and misspells `places`
380+loses its places silently; item 1 lists the names.
381+
382+Met in Moss (`docs/raz-findings.md` §3).
383+
384+**Recommendation:** take; it is a test on each name in `Raz.raz` and
385+gives a kernel its symbols back.
386+
387+### The assembler's instructions
388+
389+**Status.** Proposed 2026-10-22, collated from RAZ-GAPS.md.
390+
391+The report leaves which instructions the assembler knows to the
392+implementation, and `db` gives any other. That stays. What is missing
393+is a rule for when an instruction joins, and the few that programs
394+have already written in `db`.
395+
396+**1. `push` of a constant, and `cld` and `std`.** `push imm8` and
397+`push imm32` (6A, 68, sign-extended to 64 bits), and `cld` and `std`
398+in `Plain`. The encoder already writes `cld` and `std` for the
399+compiler's copies; only the assembler's table lacks them. Moss's
400+exception stubs write all three with `db`, and every stub of
401+"A freestanding program, stated", 2, needs them.
402+
403+**Recommendation:** take; three entries the encoder half has, and an
404+interrupt stub can't be written without them.
405+
406+**2. When an instruction joins, and the SHA and shuffle ones now.**
407+The rule, in `doc/compiler.md` beside the assembler: an instruction
408+joins when a program writes it in `db`, it is a family's member the
409+tables already hold (a code in `PackedOps`, an entry in `Plain`), and
410+its bytes are checked against GNU `as` in `test/run/`, as
411+`AsmKernel.raz` does. Anything else stays `db`, which is the permanent
412+answer for an instruction no program uses twice. By that rule, now:
413+- `paddd`, `punpcklqdq`, `punpckhqdq` into `PackedOps` (66 0F FE, 6C,
414+ 6D);
415+- `pshufb` (66 0F 38 00) and `palignr` (66 0F 3A 0F, with a byte),
416+ two more forms, three-byte opcodes;
417+- `sha256rnds2` (0F 38 CB, `xmm0` implied), `sha256msg1` (0F 38 CC),
418+ `sha256msg2` (0F 38 CD).
419+
420+Sauce's SHA-NI hash is 123 `db` lines assembled by GNU `as`, nothing
421+checking a byte against its mnemonic; with these it is read as written.
422+AES-NI, `pclmulqdq`, AVX and the rest wait for a program. (`movd` and
423+`movq`, `pxor`, `pshufd`, `movdqu`, `movdqa`, `pmovmskb` are there
424+already.)
425+
426+**Recommendation:** take; a rule stops the list growing by wish, and
427+eight instructions turn sauce's 123 unchecked lines into checked ones.
428+
429+**3. `raz -S`'s listing, stated.** raz(1) gives the listing's form, so
430+a tool may read it:
431+- a blank line, then a procedure's name as `Module.name:`;
432+- a source line: its number right-aligned in 6 columns, two spaces,
433+ the line's text;
434+- an instruction: its offset in the procedure right-aligned in 14
435+ columns, two spaces, the instruction as the assembler would read it,
436+ a jump within the procedure giving its target as an offset.
437+
438+Only the main module's live procedures, in the order they were made;
439+nothing is disassembled. A change to the form is then a change to the
440+manual, and rcrypto's constant-time guard (`tools/branches.sh`), which
441+counts conditional jumps by reading these three kinds of line, breaks
442+loudly instead of silently. A test in raz holds the form against a
443+small program's listing.
444+
445+**Recommendation:** take; it is a paragraph of raz(1) and one test,
446+for a form that already doesn't change.
447+### Implementation limits, and a compiler for a small stack
448+
449+**Status.** To investigate; nothing decided.
450+
451+The report names no implementation limits: how deep expressions,
452+statements, imports and generic instances may nest, how long a name or
453+a string may be. A compiler for a small machine that rejects a deep
454+nesting is then arguably not a raz compiler at all. C settles it with
455+its translation limits (C99 §5.2.4.1: 63 levels of nested parentheses,
456+15 of nested includes, and so on): every compiler must take at least
457+that much, and may take more. The proposal: a short section in the
458+report giving the least each compiler must accept, and saying that a
459+compiler that goes past its own limit stops with an error naming it,
460+never a crash. It changes the report, not the language.
461+
462+Behind it, three things in this compiler that need no change to the
463+report at all, so that it runs in a small stack:
464+
465+1. **Nesting.** Each level of a nested expression costs about 1 KiB
466+ of stack. A constant expression with 64 nested parentheses fails a
467+ 64 KiB stack and passes 256 KiB; 256 of them fail 256 KiB and pass
468+ 1 MiB. A limit from the section above, checked in the parser, makes
469+ the stack a program needs bounded and known.
470+2. **Imports.** `importModule` compiles an imported module in the
471+ middle of the one importing it, on the same stack, so the stack
472+ grows with the depth of the chain of imports. Ordering the modules
473+ first and compiling them from the leaves, in a loop, keeps whole
474+ program compilation and a stack that doesn't grow; symbol files, as
475+ Wirth's compilers have, would do it too, but must then carry a
476+ generic module's body.
477+3. **Instances.** `makeInstance` keeps the declaration under way aside
478+ in arrays on the stack (`[MaxFwd]PType`, `[MaxFwd]Diag.Pos`,
479+ `[MaxNames]INT`, several KiB) for every instance it nests. A list
480+ of instances still to make, made between declarations, would keep
481+ none.
482+
483+Not yet measured: which of these filled the stack when the stripped
484+compiler, given one more `-I` directory, overflowed 64 KiB building
485+itself, where the ordinary self-build fit.
486+
487+Met in moss (`docs/raz-port.md`): its stored programs get a guarded
488+64 KiB stack, and a native compiler must fit, or the stack must grow
489+(2026-10-22).

PROPOSALS.md deleted +0 -2986

@@ -1,2986 +0,0 @@
1-# raz: proposals
2-
3-What the language or the library might have, met while writing raz.
4-None is built while the freeze holds; each waits for a later thaw, by
5-the owner's word, and goes into the report before any code.
6-
7-**Closed to new proposals** (owner, 2026-10-23). Nothing new is added.
8-What is still open here, the safety thaw and the Moss work, is the
9-last; once it is done the language is in a hard freeze: the language
10-and the library's core change only to mend a defect, or the core to
11-plug a very big gap, and the rest of the library grows only
12-conservatively.
13-
14-## Installed source libraries and RAZ_PATH
15-
16-**Status.** Approved by the owner on 2026-10-19 and implemented after
17-this proposal was committed and pushed. This changes the compiler's
18-module search paths and documents an installation convention; it adds
19-no language syntax or package manager.
20-
21-A library should be usable by several programs without adding it as a
22-Git submodule to each. Install its source modules directly in
23-`$HOME/.raz/lib`, including any target-specific siblings. The compiler
24-searches that directory automatically. It does not search subdirectories
25-or create the directory itself.
26-
27-`RAZ_PATH` replaces that default with a colon-separated list of module
28-directories. An unset variable means `$HOME/.raz/lib`; an explicitly
29-empty value disables user library directories. Empty entries in a list
30-are ignored, rather than standing for the working directory. Relative
31-paths are relative to the compiler's working directory. The compiler
32-does not expand `~` or environment variables inside a path: the shell
33-can expand them when setting `RAZ_PATH`. If `HOME` is unset or empty,
34-there is no default user library directory.
35-
36-The search is the main module's directory, each `-I` directory, the user
37-library directories, and finally `lib/` beside the compiler. The standard
38-library is always searched, even with an empty `RAZ_PATH`. Existing
39-target suffixes, interface checks, duplicate-module errors and the
40-symbolic-link exception apply to the new directories too. `-I` does not
41-silently override an installed module.
42-
43-For example:
44-
45-```sh
46-mkdir -p "$HOME/.raz/lib"
47-install -m644 Json.raz "$HOME/.raz/lib/Json.raz"
48-raz Main.raz # import Json; needs no -I
49-export RAZ_PATH="$HOME/.raz/lib:$HOME/work/raz-libs"
50-RAZ_PATH= raz -I deps/json Main.raz # an isolated dependency selection
51-```
52-
53-A library's build file may provide install and uninstall tasks for its
54-own source files. Robbie can run those tasks, as make or a shell can;
55-the convention belongs to raz and needs no special robbie feature.
56-Dependency versions and downloads remain the project's or user's choice.
57-
58-Document this in the report's module lookup, raz(1), the README and the
59-compiler guide. Test the unset and empty cases, lists of directories,
60-paths with spaces, target-specific files and interface checks, duplicate
61-modules and symbolic links, and use with both compilation and `raz run`.
62-
63-## What a call does with its arguments, written at the call
64-
65-**Status.** Not approved. Drafted 2026-10-16 and reviewed twice on
66-2026-10-17 (the second review's findings are under "Open questions",
67-at the end of part 1). The owner judged the feature, and its use, not
68-settled: no change is made for the marks at the call, `ret` or `keep`.
69-It was drafted as five parts. Three of them went into report
70-2026-10.33 on their own, without the marks: the library's parameters
71-by `var` (part 2), a `const` parameter (part 4), and a variant in a
72-constant (part 5). What is left are the two parts not approved, kept
73-by their numbers. Left out of the safety thaw by the owner on 2026-10-26
74-(`PLAN.md` §2).
75-
76-1. **Marks at the call** (this section): an argument for a `var`
77- parameter is written `var x`, and one for a `keep` parameter
78- `keep x`.
79-3. **`ret` and `keep`** (below): a heading says what a procedure does
80- with what it is given, and the compiler holds the body to it.
81-
82-Nothing is built unless the owner starts it. The report changes first,
83-as always; the documentation listed below comes with it.
84-
85-### The problem: a call hides what it does
86-
87-A heading says whether a parameter is changed, kept or lent; the call
88-doesn't. This line of `src/Scan.raz` reads a character:
89-
90-```
91-v := utf8(cur.pos);
92-```
93-
94-It also moves `cur.pos` past it, since the heading is
95-`proc utf8(var pos: INT): INT`. Nothing at the call says so. Pascal
96-and Oberon leave it so; C#'s `ref`, Swift's `&` and Rust's `&mut`
97-write it at the call.
98-
99-`keep` would hide its promise in the same way. Here the map keeps the
100-name it is given, which must outlive the call; a reader of the call
101-can't tell:
102-
103-```
104-_ := Names.put(table, name, 1);
105-```
106-
107-Today `ADR` stands in for a mark, badly. `STANDARDS.md` says `ADR` at a
108-call means the callee keeps what it is given, but the library takes
109-`^T` where it keeps nothing, so `ADR` stands at nearly every call
110-(`Buf.add(ADR(b), c)`), and says nothing.
111-
112-### What a procedure does with what it is given
113-
114-| Heading | The procedure | At the call | Example |
115-|---|---|---|---|
116-| no mark | reads it while the call runs, then lets go | nothing | `Str.eq(a, b)` |
117-| `const x` | reads the caller's variable in place, without a copy, and doesn't change it | nothing | `Opt.number(p, 1, 9)` |
118-| `var x` | may change the caller's variable | `var x` | `Buf.add(var b, c)` |
119-| `keep x` | may store it where it outlives the call | `keep x` | `Names.put(var table, keep name, keep 1)` |
120-| `ret x` | its results may point into it | nothing | `s := Str.trim(line[0..n])` |
121-| `^T` | keeps a pointer, or takes one for C, an allocator, or what may be `nil` | `ADR(x)`, or a pointer it holds | `Thread.spawn(work, ^U8(ADR(job)))` |
122-
123-A slice given to an unmarked parameter is a value, two words, but the
124-elements it points at are the caller's: the procedure may write them,
125-and nothing at the call says so. `Sys.read(fd, line)` fills `line`,
126-`COPY(d, s)` fills `d`. A slice is a view of the caller's array, and
127-lending it is what it is for; the table says so in a note under it.
128-
129-`var` and `const` are in the language now (report 2026-10.33); `keep`
130-and `ret` would come with part 3. The table, and the note, go into the report (8), raz(7)
131-and the tutorial as they are here.
132-
133-### The rules
134-
135-1. **`var` at the call.** An argument for a `var` parameter is written
136- `var` and a variable: `var b`, `var p^`, `var a[i]`, `var r.f`.
137- Leaving the mark out is an error; so is writing it for a parameter
138- that isn't `var`. This holds for every call: of a procedure, of
139- another module's, of a procedure value, of a generic module's
140- instance.
141-2. **`keep` at the call.** An argument for a `keep` parameter is
142- written `keep` and the argument, whatever its type, as `var` is:
143- `Counts.put(var counts, keep 5, keep 7)`. The map does keep the 5.
144- Where the argument can't end, an `INT` or a literal, nothing is
145- checked, but the mark stands. So the mark follows the heading alone:
146- a generic module's body reads the same in every instance, as
147- `Bag(T)` calling `L.push(var l, keep x)` must, and a call never
148- hangs on fields of a record it can't see.
149-3. **Both.** An argument for a `keep var` parameter is written
150- `keep var x`, in the heading's order.
151-4. **`ret`** is never written at the call. It is about the result,
152- which the compiler checks where it is returned or stored (part 3);
153- and the calls it is on, `Str.trim`, `cut` and `field`, are the most
154- common ones.
155-5. **Built-in procedures** take no marks: `INC(v)`, `DEC(v)`,
156- `NEW(p, a)`, `COPY(d, s)`. They are the report's own words, and
157- their names say what they change. `extern` procedures have no `var`
158- or `keep` parameters, and so take none.
159-6. **What follows `keep`.** `keep` is a mark, not a name, when the
160- token after it is a name, a number, a string or character literal,
161- `{`, `[`, `var`, `-`, `not` or `~`: anything that starts an
162- argument and can't follow a name in one. Before `(`, `^`, `.`, `,`,
163- `)` or an operator between two operands it is the name `keep`:
164- `keep(x)`, `keep^`, `keep.f` and `keep + 1` are what they are today.
165- An argument that starts with `(` is written without it: `keep a + b`,
166- not `keep (a + b)`. `keep [` is the mark before an array literal or
167- the empty slice, `keep []`; an array literal lives in the frame
168- (part 3), so a kept one is an error unless it is a constant's.
169-7. **Procedure types** say `const`, `var` and `keep` as headings do
170- (5.9), so a call through a procedure value is marked as a call by
171- name.
172-8. **`const`** is never written at the call: the procedure neither
173- changes nor keeps what it is given. Its argument is any expression
174- of the parameter's type; a variable is passed in place, and anything
175- else in a temporary of the statement (report section 8).
176-
177-```
178-Arguments = "(" [ Argument { "," Argument } ] ")" .
179-Argument = [ "keep" ] [ "var" ] Expr .
180-```
181-
182-Each rule looks at the call and the heading only, so a one-pass
183-compiler makes them as it reads the call: perhaps 40 lines, beside the
184-250 to 400 of part 3 (400 to 600, by the second review).
185-
186-### Examples
187-
188-**Swapping**, from the tutorial (4):
189-
190-```
191-proc swap(var a, b: INT);
192-var t: INT;
193-begin
194- t := a; a := b; b := t;
195-end;
196-
197-swap(var x, var y);
198-```
199-
200-**A procedure that changes a place deep in a record**, from
201-`src/Scan.raz`:
202-
203-```
204-v := utf8(var cur.pos); (* cur.pos moves past the character *)
205-bigMul(var num, 10, digit); (* num changed; 10 and digit read *)
206-bigSub(var num, d); (* num changed; d read *)
207-```
208-
209-**A buffer.** `examples/Sh.raz`'s `readWord`, today:
210-
211-```
212-Buf.init(ADR(b), ADR(arena.base));
213-while (at < LEN(s)) and not special(s[at]) do
214- ...
215- | 39: Buf.add(ADR(b), s[at]); INC(at);
216- | '$': dollar(ADR(b));
217- | else: Buf.add(ADR(b), s[at]); INC(at);
218- end;
219-end;
220-text := Buf.bytes(ADR(b));
221-```
222-
223-and after the thaw:
224-
225-```
226-Buf.init(var b, ADR(arena.base)); (* b set up; the arena is an allocator: a pointer *)
227-while (at < LEN(s)) and not special(s[at]) do
228- ...
229- | 39: Buf.add(var b, s[at]); INC(at);
230- | '$': dollar(var b);
231- | else: Buf.add(var b, s[at]); INC(at);
232- end;
233-end;
234-text := Buf.bytes(b); (* only read: no mark *)
235-```
236-
237-The marks are as many as the `ADR`s were, and shorter; now they are
238-true. `Buf.bytes(b)` has none, and the one pointer left,
239-`ADR(arena.base)`, stands out as what it is.
240-
241-**Passing on what the procedure was given.** A `var` parameter is a
242-variable, and is marked like any other:
243-
244-```
245-proc dollar(var b: Buf.Buf);
246-begin
247- ...
248- Buf.str(var b, Sys.env(s[start..at]));
249-end;
250-```
251-
252-**What the program holds by pointer** is given as `p^`:
253-
254-```
255-proc emit(w: ^Writer; c: U8);
256-begin
257- Buf.add(var w^.out, c);
258-end;
259-```
260-
261-**A map that keeps its keys:**
262-
263-```
264-(* import Names := Map([]U8, INT, Str.hash, Str.eq);
265- table: Names.Map and heap: Heap's allocator, module variables *)
266-proc count(name: []U8);
267-var k: []U8; ok: BOOL;
268-begin
269- k, ok := Str.copy(heap, name); (* a copy, on the heap *)
270- if ok then _ := Names.put(var table, keep k, keep 1); end;
271- _ := Names.put(var table, keep "main", keep 1); (* a literal never ends *)
272-end;
273-
274-proc lookup(name: []U8): INT;
275-var n: INT; found: BOOL;
276-begin
277- n, found := Names.get(table, name); (* only read: no mark *)
278- ...
279-end;
280-```
281-
282-**A map that keeps nothing that can end.** The marks stand, as the
283-heading says, though nothing is checked:
284-
285-```
286-(* import Counts := Map(INT, INT, hashInt, eqInt) *)
287-_ := Counts.put(var counts, keep 5, keep 7);
288-```
289-
290-**A generic module calling another.** One body serves every instance:
291-
292-```
293-module Bag(T);
294-import Mem, L := List(T);
295-var l: L.List;
296-
297-proc add*(keep x: T);
298-begin
299- _ := L.push(var l, keep x);
300-end;
301-```
302-
303-**A table a procedure keeps**, a constant (report section 4), as `Sh`'s is now:
304-
305-```
306-const Rows: []Opt.Row = [
307- Opt.usage("", "Sh [-c script | file]"),
308- Opt.option("", 'c', "command", "script", "run script, not standard input")];
309-...
310-Opt.init(var p, keep "Sh", keep Rows);
311-while Opt.next(var p) do ... end;
312-secs := Opt.number(p, 1, 600); (* number only reads: const, no mark *)
313-```
314-
315-Today's `Opt.init(ADR(p), "Sh", [...])`, with the literal in the call,
316-is an error once `init` is `keep table`: the literal lives in the
317-frame, and `keep` can't say "as long as `p`" (part 3, "False alarms").
318-
319-**A large record only read**, by `const` (report section 8), as `tools/Pretty.raz` has it now:
320-
321-```
322-proc is(const sc: Scanner; s: []U8): BOOL; (* Scan's *)
323-
324-if Scan.is(sc, "-") or Scan.is(sc, "+") then ... end;
325-if Scan.among(Scan.text(sc), binaryWords) then ... end;
326-```
327-
328-Before 2026-10.33 each of these was `ADR(sc)`; by `var` each would say
329-`var sc`, and none changes it.
330-
331-**A list of names a procedure keeps, passed on.** The parameter is
332-`keep` in turn, so the promise travels up:
333-
334-```
335-(* import Seen := List([]U8) *)
336-proc remember(var l: Seen.List; keep name: []U8);
337-begin
338- _ := Seen.push(var l, keep name);
339-end;
340-
341-remember(var seen, keep "start");
342-```
343-
344-**`keep var`: a reader that keeps a slice of the caller's buffer.**
345-
346-```
347-proc start(var r: Reader; keep var page: [4096]U8);
348-begin
349- r.rest := page[0..0];
350- r.page := page[0..LEN(page)];
351-end;
352-
353-var page: [4096]U8; (* a module variable *)
354-...
355-start(var rd, keep var page);
356-```
357-
358-**A procedure value.**
359-
360-```
361-type Step = proc(var s: State): BOOL;
362-
363-proc run(step: Step; var s: State);
364-begin
365- while step(var s) do end;
366-end;
367-```
368-
369-**What stays a pointer**, and so keeps `ADR`:
370-
371-```
372-NEW(node, ADR(arena.base)); (* an allocator *)
373-t, err := Thread.spawn(work, ^U8(ADR(job))); (* kept by the thread *)
374-XNextEvent(dpy, ADR(ev)); (* C *)
375-p := Sys.mmap(size); (* bytes, not a variable *)
376-```
377-
378-**A slice's elements, lent unmarked:**
379-
380-```
381-n := Sys.read(fd, line); (* fills line[0..n] *)
382-Str.lower(word); (* writes word's bytes *)
383-```
384-
385-**`ret`, unmarked:**
386-
387-```
388-s := Str.trim(line[0..n]); (* s points into line *)
389-key, rest, ok := Str.cut(s, "="); (* both point into s *)
390-```
391-
392-### What the compiler says
393-
394-Each message names the mending, at the argument:
395-
396-```
397-Sh.raz:94:21: b: write `var b`: Buf.add may change it
398-Sh.raz:115:23: b: Buf.bytes only reads it: no `var`
399-Count.raz:12:27: name: write `keep name`: Names.put keeps it
400-Count.raz:14:34: 7: write `keep 7`: Counts.put keeps it
401-Count.raz:9:27: key[0..4]: kept by Names.put, but it points into this procedure's frame
402-Sh.raz:60:28: [...]: kept by Opt.init, but an array literal lives in this procedure's frame: make it a constant
403-Pretty.raz:123:19: sc: Scan.is only reads it (const): no `var`
404-```
405-
406-The compiler already says, since 2026-10.33, that a `const` parameter
407-can't be changed, and what to write for `ADR(b)` or `p` given to a
408-`var` or `const` parameter.
409-
410-### How much noise
411-
412-Measured by a search of `src/`, `lib/`, `tools/` and `examples/`, about
413-23,300 lines of code (rough: a search, not the compiler):
414-
415-- about 630 `ADR`s, before 2026-10.33; most were at calls to the
416- library, which now take `x` itself, and would take `var x`;
417-- about 580 calls of our own procedures with `var` parameters, unmarked
418- today: each gains `var`, about one line in 40;
419-- `keep`: a few dozen calls (`Map.put`, `List.push`, `Vec.push`,
420- `Opt.init`, `Opt.scope`, and procedures that pass a kept value on).
421- Since it follows the heading, it stands also before values that can't
422- end, `keep 1` in `Names.put(var table, keep name, keep 1)`: a word
423- each, the price of one rule for every instance;
424-- `const`: none at the call.
425-
426-So most of the marks stand where an `ADR` stands today. What is new is
427-the 580, and those are the calls, like `utf8(cur.pos)`, that change a
428-variable with nothing to say so.
429-
430-### `ADR` afterwards
431-
432-`ADR` stays, for the pointers `STANDARDS.md` lists: an allocator, what
433-may be `nil`, what the program holds by pointer already, C and memory
434-that is bytes, and a pointer a procedure keeps (`Thread.spawn`'s `arg`).
435-The marks of part 3 don't follow a pointer, so `ADR` at a call still
436-says "kept, or not a variable", unchecked, as now; with the library on
437-`var`, it is rare enough in ordinary code to be read so.
438-
439-### What the documentation gains
440-
441-The thaw is not done until each of these is:
442-
443-- **The report, `doc/raz.md`.** 8: the grammar above; "Parameters"
444- becomes "Parameters and arguments", with the table and its note on
445- slices, rules 1 to 8, and the swap and map examples; `keep` and
446- `ret` from part 3. 5.9: procedure types with marks. 7.3: `ret`. 10: the promise, whose
447- exceptions shrink to `ADR`, C, code procedures and `check off`.
448- 1, "A first look": its example marks its calls. Every example in the
449- report is marked. About two pages; the report stays under 40 (31
450- now), counted by `make pdf`.
451-- **`doc/report-history.md`**: the version's entry, with the mending:
452- `ADR(x)` to `var x`, `p` to `var p^`, `var` and `keep` at each call
453- the compiler names.
454-- **raz(7)**, the language at a glance: under PROCEDURES, the table, as
455- a list, and one line for each of `var`, `keep` and `ret` at the call;
456- THE GRAMMAR IN BRIEF gains `Argument`; BUILT-IN PROCEDURES says they
457- take no marks.
458-- **The tutorial, raz-tutorial(7).** Section 4 marks `swap(var x, var y)`
459- and says why. A new section after 6, "WHAT A CALL DOES WITH ITS
460- ARGUMENTS": the table; a whole program, with its output, that counts
461- the words of its input in a `Map([]U8, INT)` with a `Buf`, using
462- `var`, `keep`, `ret` and `const`, each said in a sentence where it
463- stands;
464- then "What the compiler stops", the four mistakes of the messages
465- above, each with its message. Section 16, "FROM PASCAL AND C TO RAZ",
466- gains: Pascal's `var` is unmarked at the call, raz's is marked, as C#'s
467- `ref` is; C's `&x` becomes `var x` when the callee only changes it,
468- and stays `ADR(x)` when it keeps it. Every other example in the
469- tutorial is marked. Each runs under `make check`, as now.
470-- **Volume 2, `doc/raz-lib.md`, and raz-lib(3)**: each module's
471- example marked, and `keep` and `ret` where the library has them.
472-- **`STANDARDS.md`**: `ADR` no longer marks what is kept, `keep` does.
473-- **`doc/compiler.md`**: where the marks are read and checked, the
474- checks of part 3 and the set each value carries, with the code
475- before and after, and the table of lines.
476-- **`README.md`**: its examples marked.
477-- **Tests.** `conform/`: a program for each rule, run and error;
478- `test/err` and `test/msg`: each message above; `test/pretty`: the
479- marks formatted; the vim and emacs support indent and colour `var`
480- and `keep` at a call.
481-- **`sbcl/`**, the reference compiler from the report alone, follows
482- the report.
483-
484-### What it breaks, and the order of the work
485-
486-Every call to a procedure with a `var` or `keep` parameter: in `src/`, `lib/`, the
487-tools, the examples, the tests, and rmacs, ravite, rat, rlX11, rloc,
488-rpg and rsqlite, each when it moves its pin. The mending is mechanical,
489-and the compiler names it at each place.
490-
491-**BOOT first.** The release `BOOT` names can't read a marked call, and
492-it builds `src/` and reads `Sys` and `CAbi`. So this thaw needs a
493-release that reads the marks, named by `BOOT` (CLAUDE.md, "The compiler
494-and BOOT"), before `src/` and that part of the library can be marked:
495-the owner's call, and the first step.
496-
497-Then, one commit each:
498-
499-1. The report, `report-history.md`, raz(7): for review.
500-2. The compiler reads the marks and checks rules 1 to 8, and every
501- caller in this repository is marked.
502-3. `ret` and `keep` in headings and their checks (part 3), and the
503- library marked (`Str.trim`, `Map.put`, `List.push`, `Vec.push`,
504- `Opt.init`, `Opt.scope`, ...).
505-4. The tutorial, volume 2, raz-lib(3), `STANDARDS.md`,
506- `doc/compiler.md`, `README.md`.
507-5. The tests: `conform/`, `test/err`, `test/msg`, `test/pretty`, the
508- editors.
509-
510-The examples of parts 2 and 3 are written as the whole thaw makes
511-them, with the marks of part 1.
512-
513-### Open questions
514-
515-The second review, 2026-10-17, read the five parts against `src/`,
516-`lib/Opt.raz`, `tools/Pretty.raz` and `examples/Words.raz`. It found
517-the direction sound, and parts 1, 2 and 4 clearly better in `tools/`
518-and `Opt`, but mostly noise in `src/Parse.raz`, where `var x` stands
519-on nearly every call. Left open, by the owner's word:
520-
521-1. **BOOT.** A release of today's compiler can't read the marks
522- either, so "BOOT first" can't work as written: it takes two
523- releases, one that accepts every new form without requiring it,
524- named by `BOOT`, then one that marks `src/` and requires the marks.
525-2. **An error here.** Part 3's `Names.put(var table, keep buf[0..n], 1)`
526- lacks `keep 1`. (The others the review found were in parts 2, 4
527- and 5, mended when they went into the report.)
528-3. **A hole in part 3's exception for `var`.** `proc fill(var r: R);
529- begin r.s := r.buf[0..4]; end;` passes, since `r` points where it
530- pointed; a caller's local `r` copied to a module variable then
531- points into a dead frame. Mend: the caller's variable and what its
532- slices point at as two places, the exception covering the second.
533-4. **Part 3's cost.** A local points wherever anything assigned to it
534- does, which needs a closure over local-to-local assignments at
535- `end` (`w, rest := Str.field(rest)`), and bits for locals, value
536- parameters and `match`'s names: 400 to 600 lines, not 250 to 400.
537-5. **Rule 6.** Its list contradicts itself: `keep - 1` and `keep[i]`
538- are expressions today, and `Sys.closeAllBut(keep: []INT)` indexes
539- `keep[i]`; `keep ^U8(p)` can't be marked. Proposed: decide by the
540- heading, which is known when the argument is read: at a `keep`
541- parameter a leading `keep` is the mark; elsewhere a name.
542-6. **`keep` before what can't end is noise**: `keep 5`, `keep "Sh"`,
543- and `keep k + 1`, which reads as `(keep k) + 1`. Proposed: optional
544- before a constant or a basic or pointer type, required where the
545- type carries a slice or is another module's record. It partly undoes
546- rule 2's "the heading alone": one rule and some noise, or less noise
547- and an exception.
548-7. **A mark that lends nothing in a plain heading**, `keep n: INT`,
549- costs every call a word. Proposed: a warning, but on a module
550- parameter's type or a procedure with a body for each target.
551-8. **`ret` with `const`.** `ret const` given a temporary that holds an
552- array would return a slice of the temporary: an error. The heading's
553- grammar, `Params = ["ret"] ["keep"] ["var" | "const"] ident ...`,
554- and the call's, a designator after `var`. (The rest of `const`'s
555- rules are report 2026-10.33's, section 8.)
556-9. **Procedure types** with fewer marks are assignable, not the same:
557- 5.10 must say so, for `=`, generic instances and `forward`.
558- `Map`'s `eq` can't take a `const` equality.
559-10. **False alarms to document.** A local container over a local
560- buffer, `Scan.init(var s, keep line[0..n])`, is refused though both
561- end together (a module variable, a `Buf` or the heap is the way
562- out); so is a store through `ADR` of a local.
563-
564-### Part 3: marking what a procedure does with what it is given: `ret` and `keep`
565-
566-#### The hole
567-
568-A procedure's locals, its value parameters and the array literals it
569-passes as slices live in its frame, which is gone once it returns. A
570-slice that still points there afterwards reads whatever the next call
571-put in its place, and writes into it. Section 7.3 catches the plain
572-case, a slice of a local returned at once:
573-
574-```
575-proc short(h: Hex): []U8; (* Hex = [64]U8 *)
576-begin
577- return h[0..8]; (* an error: h is the procedure's own copy *)
578-end;
579-```
580-
581-It can't catch the same slice once it has passed through a call,
582-since the caller can't see what the callee returns a slice of:
583-
584-```
585-proc head(var h: Hex): []U8;
586-begin
587- return h[0..8]; (* fine: h is the caller's *)
588-end;
589-
590-proc short: []U8;
591-var h: Hex;
592-begin
593- return head(h); (* a slice of short's frame; not caught *)
594-end;
595-```
596-
597-Nor the other way, a slice given to a procedure that keeps it:
598-
599-```
600-proc remember(name: []U8);
601-var buf: [16]U8;
602-begin
603- ...
604- _ := Names.put(var table, keep buf[0..n], 1); (* the map, on the heap, keeps a slice of buf *)
605-end;
606-```
607-
608-Section 10 leaves both undefined. The marks close them: each parameter
609-says what the procedure may do with what it is given, the compiler
610-holds the procedure's body to its heading, and a caller trusts the
611-heading without seeing the body. Each check needs only the procedure
612-it is in, so a one-pass compiler can make it.
613-
614-#### Words
615-
616-**Carrying a slice.** A type carries a slice if it is a slice, or an
617-array, record or variant with one in it: `[]U8`, `[4][]U8`,
618-`Sys.Program`, `Fmt.Arg`. `INT`, `[64]U8` and every pointer type don't.
619-What a pointer points at is not followed: a slice reached through a
620-pointer, `p^.s`, is the heap's or a module's, as far as the marks
621-know.
622-
623-**Where a value points.** Every value that carries a slice has, for
624-the compiler, a set of places its slices may point into:
625-
626-- **the frame**, this call's own: a slice of a local array, of a
627- value parameter's array, or an array literal used as a slice;
628-- **a parameter `p`**: what `p` lends. For a value parameter, that is
629- what its slices point at, which is the caller's business, not this
630- frame. For a `var` or `const` parameter whose type holds an array,
631- it is also the caller's variable itself: `h[0..8]` of `var h: Hex`
632- points into `h`. One whose type holds no array, as a `Scanner`, lends
633- only what its slices point at, as a value parameter does, so
634- `return Scan.text(n)` of a local `n: Scanner` is not frame-bound
635- when `n.src` isn't.
636-- **nowhere that ends**: module variables, constants, string literals,
637- and anything reached through a pointer.
638-
639-A value made from others points wherever any of them does: a slice, a
640-field, an element or a view of `x` points where `x` does; a record, a
641-variant or an array literal built from parts, wherever the parts do; a
642-call's result, wherever its arguments for `ret` parameters do (below).
643-A local variable that carries a slice points wherever anything
644-assigned to it anywhere in the procedure does, wherever the assignment
645-stands, since a loop can run a `return` after an assignment written
646-below it. **Frame-bound** means pointing into the frame.
647-
648-**Outliving the call.** A place outlives the call if it is a module
649-variable, anything reached through a pointer (`p^.f`, `p^[i]`), or a
650-`var` parameter of this procedure. A value stored there, or returned,
651-leaves the frame.
652-
653-#### No mark
654-
655-A parameter without a mark is only used while the call runs. The
656-procedure may read it, copy its bytes (`COPY`, `Buf.str`), keep it in
657-locals and pass it to other calls' unmarked or `ret` parameters. It
658-may not return what it points at, nor store it anywhere that outlives
659-the call. This is what most procedures do: `Str.eq`, `Str.find`,
660-`Buf.str`, `Sys.write`, `Fmt.print`, `Map.get`'s key.
661-
662-#### `ret`
663-
664-```
665-proc trim(ret s: []U8): []U8;
666-```
667-
668-`ret s` says: the results may point where `s` points. In the body,
669-returning a slice of `s` is allowed; in the caller, the result points
670-wherever the argument given for `s` did.
671-
672-```
673-proc greet: []U8;
674-var line: [80]U8; n: INT;
675-begin
676- n := Sys.read(Sys.stdin, line);
677- Out.str(Str.trim(line[0..n])); (* fine: used here, in the frame *)
678- return Str.trim(line[0..n]); (* an error: frame-bound through trim's ret *)
679-end;
680-
681-proc word(ret s: []U8): []U8;
682-begin
683- return Str.trim(s); (* fine: points where s does, and s is ret *)
684-end;
685-
686-proc word2(s: []U8): []U8;
687-begin
688- return Str.trim(s); (* an error: s isn't ret here *)
689-end;
690-```
691-
692-`ret` lends something when the parameter carries a slice, or is a
693-`var` or `const` parameter whose type holds an array (it lends the
694-caller's variable), of a procedure with a result that carries a slice.
695-Elsewhere, `ret n: INT`, `ret a: [4]U8` or on a procedure whose results
696-carry no slice, it lends nothing, and is allowed: a mark is leave to
697-do something, not a claim that it is done. Two cases need that. A
698-generic module's parameter may be any type, and a procedure with two
699-bodies, one for each target, has one heading: `Sys.nextEntry`'s `Dir`
700-holds the entry's bytes in an array on Linux, where `ret` lends them,
701-and a C pointer over C, where it lends nothing.
702-
703-With several results, `ret` covers them all: in `cut(ret s: []U8;
704-sep: []U8): ([]U8, []U8, BOOL)` both slices may point into `s`. With
705-several `ret` parameters, a result may point where any of them does,
706-and the caller takes the result as pointing where all of their
707-arguments do.
708-
709-#### `keep`
710-
711-```
712-proc put(var m: Map; keep k: K; keep v: V): BOOL;
713-```
714-
715-`keep k` says: what `k` points at may outlive the call; the procedure
716-may store it in a place that does. In the caller, an argument for a
717-`keep` parameter leaves the frame as a store would: it must not be
718-frame-bound, and if it points where one of the caller's own
719-parameters does, that parameter must be `keep` too.
720-
721-```
722-(* import Names := Map([]U8, INT, Str.hash, Str.eq);
723- table: Names.Map and heap: Heap's allocator, module variables *)
724-proc count(name: []U8);
725-var key: [32]U8; k: []U8; ok: BOOL;
726-begin
727- _ := Names.put(var table, keep name, keep 1); (* an error: name isn't keep here *)
728- _ := Names.put(var table, keep key[0..4], keep 1); (* an error: frame-bound to a keep *)
729- _ := Names.put(var table, keep "main", keep 1); (* fine: a literal never ends *)
730- k, ok := Str.copy(heap, name);
731- if ok then _ := Names.put(var table, keep k, keep 1); end; (* fine: copied to the heap *)
732-end;
733-```
734-
735-`keep` lends something on a parameter that carries a slice, or a
736-`var` parameter whose type holds an array; on another, `keep n: INT`,
737-it lends nothing and is allowed, as `ret` is. At the call it is
738-written all the same (part 1, rule 2).
739-
740-One exception keeps the common loop free of marks: a `var` parameter
741-may be given a value that points only where it already pointed, so
742-`s := s[1..LEN(s)]` with `var s: []U8` needs no `keep`. The caller's
743-variable is no worse off.
744-
745-#### Both, and the order
746-
747-`ret keep v: T` is both. The marks come before `var`, and each
748-mark covers the group it starts, so `(ret s, t: []U8)` marks both;
749-`(ret s: []U8; sep: []U8)` marks only `s`. `ret` and `keep` are not
750-reserved words: they are marks only before a parameter's name, as
751-`static` is a mark only in `link static;`. `proc f(ret: INT)` is a
752-parameter named `ret`.
753-
754-#### What the compiler checks, all of it
755-
756-In each procedure:
757-
758-1. `return e`, each result: `e` must not be frame-bound, and every
759- parameter it points at must be `ret`.
760-2. A store into a place that outlives the call, `M.x := e`,
761- `p^.f := e`, or `v := e` for a `var` parameter `v` or a part of it
762- (`v.f := e`, `v[i] := e`): `e` must not be
763- frame-bound, and every parameter it points at must be `keep`, but
764- for the exception above. `COPY` into such a place is no such store:
765- it copies bytes, not where they point.
766-3. An argument for a call's `keep` parameter, as 2.
767-
768-Checks 1 to 3 on a local variable's value wait for the procedure's
769-`end`, when everything assigned to it is known.
770-
771-#### Procedure values, generic modules, and the rest
772-
773-**Procedure types** carry the marks, `proc(ret s: []U8): []U8`. A
774-procedure with fewer `ret` and `keep` marks than a procedure type may
775-stand where that type is wanted, since it does less than the type
776-allows: a procedure without `ret` can stand where `ret` was allowed,
777-not the other way. `const` and `var` must match, as `var` must now
778-(5.9): they change how the argument is passed.
779-
780-**Generic modules.** A mark is allowed on a parameter whose type is a
781-module parameter, `keep v: T`, whatever `T` will be. The body is
782-checked in each instance: `Map(INT, INT)`'s `put` would pass without
783-`keep`, `Map([]U8, INT)`'s wouldn't, so the library marks its generic
784-modules for the instance that needs it. Calls write the marks the
785-heading has, in every instance (part 1, rule 2).
786-
787-**`extern` procedures** take no marks: C is outside the promise of
788-section 10 already. **Code procedures** take them, and are trusted:
789-there is no body to check.
790-
791-**`ADR`** gives a pointer, which the marks don't follow; a pointer to
792-a local that outlives it stays undefined, as section 10 says. So does
793-a slice reached through such a pointer, and a thread given a pointer
794-to its spawner's locals.
795-
796-#### False alarms
797-
798-The rules are sure, not exact: they reject some programs that were
799-right.
800-
801-- **A record that lives in the frame, filled through a pointer.**
802- `examples/Sh.raz` does
803-
804- ```
805- Opt.init(var p, keep "Sh", keep [Opt.usage(...), Opt.option(...)]);
806- ```
807-
808- `Opt.init` keeps its table in `p`, so it needs `keep table`, and
809- the array literal is frame-bound: an error, though `p` is a local
810- and dies with the literal. `keep` can't say "as long as `p`";
811- saying that needs lifetimes on records, Rust's whole apparatus, which
812- is not proposed. The way out: the table a constant, which report
813- 2026-10.33 allows, as part 1's example shows.
814-- **A local variable used twice.** One slice variable that holds a
815- slice of a local buffer early on and a result to return later is
816- frame-bound throughout. Two variables cure it.
817-- **Several `ret` parameters.** A result is taken to point at all of
818- them, though it may point at one.
819-
820-#### What it breaks
821-
822-Every procedure, in the library or a program, that returns or keeps
823-what a parameter points at stops compiling until it is marked: a
824-thaw. In the library, by a search of the headings: `Str.trim`,
825-`trimLeft`, `trimRight`, `cut` and `field` (`ret`); `Map.put`,
826-`List.push`, `Vec.push` and `Vec.tryPush` (`keep`: they store a `T`);
827-`Opt.init` (`keep name` and `keep table`) and `Opt.scope` (`keep
828-name`), and `Sh`'s call of `init`, as above; `Sys.nextEntry` (`ret`,
829-lending on Linux only). Not marked: `Str.copy` (its result is the allocator's),
830-`Sys.env` and `readLink` (their own buffer), `Buf.str` and
831-`Fmt.write` (they copy), `Map.get`. In sauce, `Svec.push` and `add`
832-(`keep`), and what returns a slice of its argument.
833-
834-#### What it costs
835-
836-Reports: 5.9 (procedure types), 7.3, 8 (parameters), 10 (the promise,
837-whose exceptions shrink to `ADR`, C, code procedures and `check
838-off`), appendix B. The compiler: a set of the places a value points
839-into, carried with each value as its type is, a 64-bit set (the frame
840-and up to 63 parameters); the same on each local; the checks above,
841-and a list per procedure of the checks that wait for its `end`.
842-Perhaps 250 to 400 lines; no cost at run time, and little at compile
843-time.
844-
845-Precedent: D's `scope` and `return scope` (DIP1000) are `keep`'s
846-opposite and `ret`; Rust's lifetime elision reads a call's result as
847-`ret` does. D's experience is that the corners (fields, generics,
848-procedure values) take years; the narrow form here leaves record
849-lifetimes out, and so the first false alarm above, on purpose.
850-
851-## A minus sign after an operator
852-
853-**Status.** Not planned (owner, 2026-10-23): dropped for good; `x & (-8)` or `x & ~7` stays the spelling.
854-
855-`x & -8` and `n * -1` are errors: a unary minus belongs to the start
856-of a `SimpleExpr` (6), not to a factor, so after an operator it needs
857-parentheses, `x & (-8)`, or another spelling, `x & ~7`. This is the
858-report's grammar, Oberon's, and the compiler is right to refuse it;
859-but nearly every other language takes it, and the error ("expected an
860-expression, found -") surprises.
861-
862-The proposal: a factor that follows an operator may be `"-" Factor`.
863-The minus at the start of a `SimpleExpr` stays as it is, applying to
864-the first term, so no program changes meaning: `-a & b` is still
865-`-(a & b)`, which isn't `(-a) & b`, nor is `-a shr n` the same as
866-`(-a) shr n`. Only text that is an error today, `x & -8`, gets one.
867-The cost is that a minus means two things by where it stands, which
868-the report would say in a line.
869-
870-Met in tery's `aligned`, `(a + 7) & -8`.
871-
872-## Dividing 128 bits by 64
873-
874-**Status.** Approved by the owner on 2026-10-23 and implemented in `lib/Math.raz` as `divMod`, since `div` is a reserved word: a code procedure over `div`, with `hi >= d` stopped first.
875-
876-`Math.mul` gives the 128-bit product of two `U64`s; there is nothing
877-to divide such a number back down. Forth's `UM/MOD` and `M*/`, and
878-any arithmetic on numbers wider than a word (a bignum, a fixed-point
879-product scaled back), need "this 128-bit number, given as its high
880-and low words, divided by a 64-bit one: the quotient and the
881-remainder". x86-64 does it in one instruction, `div`; a raz program
882-does it by a loop of 64 shifts and subtractions, or a code procedure
883-per target.
884-
885-The proposal, in the library:
886-
887-```
888-proc div*(hi, lo, d: U64): (U64, U64); (* hi, lo divided by d: the quotient and the remainder; hi < d *)
889-```
890-
891-in `Math`, beside `mul`; `hi >= d`, whose quotient doesn't fit a word,
892-and `d = 0` stop the program as a division by zero does. It breaks no
893-program, so it could come with any release, not only a thaw.
894-
895-Met in tery's `udivmod`, a loop of 64 rounds.
896-
897-## Inlining a procedure that only returns
898-
899-**Status.** Approved by the owner on 2026-10-23 and implemented: a call of a procedure whose body is `return e`, with no locals and one scalar result, is made in place, its arguments in temporaries; a failed check in `e` is told at the callee's line, and the callee is in no trace (scanning 887 ms to 638, grep 268 to 199).
900-
901-Not the language's but the compiler's: a call of a procedure whose
902-body is `return` and an expression, as `Grep.zeros` and
903-`Scan.tokPos` are, made in place of the call. One pass keeps no
904-tree to copy, but it can read source again, as `while` reads its
905-condition again (`saveScan`, `restoreScan`): the arguments go to
906-temporaries, each evaluated once and in order, a scope names the
907-parameters as them, and the expression is read again from where the
908-procedure's begins, in its own module's scope.
909-
910-Measured by hand on the kernels: Grep with `zeros` and `lowest`
911-written in place is 20% faster, 0.88 times FPC `-O2`'s time where it
912-is 1.14 now. The compiler has 78 such procedures and the library 28;
913-the compiler's profile names the calls of small routines as what is
914-left (doc/compiler.md).
915-
916-Kept narrow: scalars passed by value, no recursion, no code
917-procedure (a square root has its own way), a procedure taken as a
918-value still called. What it costs: an inlined procedure is not in
919-the trap report's list of procedures, nor in gdb's backtrace, though
920-a failed check in it is still told at its line; 60 to 100 lines of
921-the budget; and, across modules, the imported module's
922-text kept to be read again, which is to be checked.
923-
924-More cases, from sauce (`~/r/sauce`, RAZ-NOTES.md). Its SHA-256, with
925-the rotation a procedure, `return (x shr n) | (x shl (32 - n))`, and
926-each word read by `Str.be`, ran at 52 MB/s; with both written out in
927-the loop, 115 MB/s, where FPC `-O2` does about 200 and `check off`
928-adds only 9%. Most of the gap is calls. `ror` is the narrow case
929-above; `Str.be` is not, a loop over its bytes, and would want a
930-`Str.be32` of four bytes that only returns, or the loop unrolled where
931-it is. A rotate of the language's own, an operator or a built-in
932-procedure, would serve SHA, the other hashes and checksums without
933-any inlining, but it is a language change, for a thaw. **Taken into
934-the report (2026-10.35):** the built-ins `ROL(x, n)` and `ROR(x, n)`,
935-by the owner's word; the compiler has them. rcrypto met the
936-same (its `RAZ-NOTES.md`): SHA-256 at 32 MB/s with `ror` a procedure,
937-80 with it written out. On 100 MB of
938-new files `sauce commit` takes 1.2 s against the Pascal sauce's 0.7,
939-and `verify` 0.95 s against 0.48: the hashing.
940-
941-## Less that is undefined
942-
943-**Status.** Decided by the owner on 2026-10-26 for the safety thaw (`PLAN.md` §2): pieces 1 and 3 (said, not prevented) go in; 2 is answered by `[]const T`; 4 goes in as `import SYSTEM`.
944-
945-Section 10 lists what isn't defined: a stale or made-up pointer,
946-indexing through a pointer, a slice kept after its frame is gone, a
947-slice of an array a call returned kept past its statement, an index
948-out of range under `check off;`, writing a string's bytes, a code
949-procedure that breaks its rules, and C. Some of these can be closed at
950-little cost; the rest can be fenced, so that a reader sees which
951-modules can reach memory they shouldn't. Four pieces, each standing on
952-its own, the cheapest first.
953-
954-**1. An array a call returns lives to the end of its procedure.**
955-Section 8 says it lives to the end of its statement. Its slot in the
956-frame would stay reserved for the rest of the procedure instead, as a
957-deferred statement's slots already do, so that `s := f('a')[0..4]` is
958-defined until the procedure returns; in a loop the slot holds the
959-latest call's array. Section 10 loses a case, and what is left of it
960-is a slice leaving its frame (7.3), which `ret` and `keep`, above,
961-would close. It breaks nothing; the cost is a frame larger by each
962-such call's array.
963-
964-**2. Writing a string's bytes stops the program, or changes them.**
965-Two outcomes instead of any: where the target has read-only memory,
966-the string constants are in it, and a write stops the program as a
967-bad address (section 10), as this compiler's already does, since they
968-are in rodata; where it hasn't, the write changes the constant for the
969-rest of the run, everywhere its bytes are shared. Which of the two is
970-the target's (appendix A). It breaks nothing.
971-
972-**3. A race tears no slice.** 7.6 says a variable written by one
973-thread while another reads it holds a value it had, or a mixture of
974-their bytes, and that nothing else becomes undefined. For a slice
975-that is a defect: a mixture of one slice's address and another's
976-length is indexed, checked, against the wrong length, and reaches any
977-memory; a variant's tag torn from its fields is the same. The mend:
978-a slice, a variant, or a record holding either, read or written in a
979-race, is the exception of section 10, said so in 7.6. A pointer, a
980-word on every target, tears into nothing new. This is a defect, which
981-the freeze allows mending.
982-
983-**4. Fencing the rest: `unsafe;`.** A module that does any of the
984-following says `unsafe;` after its links and its `check` line, and it
985-is an error to do them in one that doesn't:
986-
987-- `ADR`, and `p + i`, `p - i`, `p[i]` and `p[lo..hi]` on a pointer;
988-- converting an integer to a pointer or a procedure, or one pointer
989- or procedure type to another;
990-- a view, `v.(T)`, whose `T` holds a pointer, a slice or a procedure
991- (one to integers, reals and their arrays stays safe);
992-- `check off;`, `extern`, `link`, code procedures and `SYSCALL`.
993-
994-`unsafe`, like `static` in `link static;`, is a word only there. In a
995-program none of whose modules says it, what is left undefined is
996-short: a pointer used after `Heap.free` or an arena's reset gave back
997-what it points at, and a slice leaving its frame (7.3). The library's
998-modules that need it (`Rt`, `Mem`, `Heap`, `Arena`, `Bytes`, `Sys`,
999-`Thread`, ...) say it, as a program trusts them; `grep unsafe` lists
1000-the rest. It breaks every module that does one of these and doesn't
1001-say it: rmacs, ravite, the tools and ten of `src/`'s modules (by
1002-`ADR`), each mended by one line, which
1003-the compiler's message names. The compiler's cost is a flag on the
1004-module, checked at each of those places. Since BOOT's release doesn't
1005-know `unsafe;`, `src/` can't say it until `BOOT` names one that does:
1006-for one release a missing `unsafe;` is a warning, then an error.
1007-
1008-Pieces 1 and 2 are small and change no program; 3 is a mend; 4 needs
1009-a thaw.
1010-
1011-## Windows
1012-
1013-**Status.** Not planned (owner, 2026-10-23).
1014-
1015-A Windows target would keep volume 2 as it is: it describes the
1016-library on a Unix target. Windows has no stable system calls, no
1017-signals, no fork, no termios, and fds that are handles, so its `Sys`
1018-can't be the one volume 2 gives. Appendix A's core already lets a
1019-target leave out all of `Sys` past writing, ending the program and
1020-getting memory: a Windows target gives the core, and what else it has
1021-in a module of its own (`Win`), told on a page of its own beside
1022-volume 2. Volume 1 needs at most a sentence, that `link static;`
1023-means no C library where there are no system calls to make. The
1024-compiler needs a PE writer and Microsoft's calling convention.
1025-
1026-## An enumeration's name read against the type it is given to
1027-
1028-**Status.** Not planned (owner, 2026-10-23): 5.7's rule, that the type is never taken from where the name stands, keeps reading local.
1029-
1030-Two enumerations of a scope may share a name, and then the name alone
1031-is an error: "the type is never taken from where the name stands"
1032-(5.7). So a table of records, which names its enumerations on every
1033-row, must write the type out on each row where the name is shared,
1034-though the field says which enumeration it is:
1035-
1036-```
1037-type
1038- MenuAction = (close, run, complete);
1039- BlockKind = (time, run, window);
1040- MenuKey = record sym: INT; act: MenuAction; end;
1041- Block = record kind: BlockKind; arg: []U8; end;
1042-const
1043- MenuKeys: []MenuKey = [{sym: 13, act: run}]; (* an error: MenuAction.run or BlockKind.run *)
1044- Blocks: []Block = [{kind: run, arg: "date"}]; (* and so is this *)
1045-```
1046-
1047-Adding `BlockKind`, with its `run`, broke `MenuKeys`, which had
1048-compiled until then: a name added to one table reaches into the other.
1049-
1050-The proposal: where a value is given to a place whose type is an
1051-enumeration, a name of that enumeration written alone is that name,
1052-though another enumeration of the scope has it too. The places are the
1053-right side of an assignment, a field of a record or variant written
1054-with braces, a value parameter, a `return`, and the other side of a
1055-relation with a value of the type. Everywhere else, and wherever the
1056-rule of 5.7 names something already (a constant, a variable or a
1057-procedure of the scope that isn't an enumeration's name), it stays as
1058-it is. A program that compiles today means the same; only some of the
1059-programs refused today compile, so it breaks none.
1060-
1061-It costs a line of 5.7, and in the compiler, a type passed down to the
1062-lookup of a name where the parser knows it.
1063-
1064-Met in mosaico's `Mconfig`, where `MenuAction.run` and a status block's
1065-kind `run` met; the block's kind was renamed `command`.
1066-
1067-## A slice that can't be written: `[]const T`
1068-
1069-**Status.** Decided by the owner on 2026-10-26 for the safety thaw (`PLAN.md` §2): it goes in, string literals and a constant's slices typed by it, `Str.trim`, `cut` and `field` returning `[]const U8`.
1070-
1071-raz has no slice whose elements can't be written. A `const` parameter
1072-(report 2026-10.33, section 8) is shallow: the procedure can't change
1073-the record, but it can write through a slice in it, and through a
1074-slice it makes of an array in it. A constant's slices, and every
1075-string literal, point at bytes whose writing "isn't defined" (5.10,
1076-10): the compiler doesn't refuse it, and on a target with read-only
1077-memory the program stops. Nothing in a heading says that `Str.eq`
1078-only reads its slices and `Str.lower` writes them.
1079-
1080-```
1081-type Rule = record class: []U8; tag: INT; end;
1082-const Rules: [2]Rule = [{class: "firefox", tag: 2}, {class: "mpv"}];
1083-
1084-proc shout(const r: Rule);
1085-begin
1086- r.class[0] := 'F'; (* allowed today: writes the constant's bytes, undefined *)
1087-end;
1088-```
1089-
1090-The proposal: a slice type may say its elements are read only,
1091-`[]const T`, as a pointer type says `^VOLATILE T`.
1092-
1093-- Its elements can be read and sliced, and not written: no `s[i] :=`,
1094- no `COPY` into it, no `var` argument or `ADR` of an element, no
1095- `INC` of one. A slice of it is `[]const T` too.
1096-- A `[]T` goes where a `[]const T` is wanted, as `U8` widens to `INT`;
1097- never the other way. A procedure that only reads a slice takes
1098- `[]const T`, and every caller's `[]T` still fits it: `Str.eq(a, b:
1099- []const U8)`, `Sys.write(fd: INT; s: []const U8)`, `Out.str`. Those
1100- changes break no program.
1101-- A record field may be `[]const U8`, so a record, a constant's above
1102- all, can hold slices that can't be written: `type Rule = record
1103- class: []const U8; ... end`, and `shout` above is refused.
1104-
1105-What a procedure returns of its argument is the hard part. `Str.trim(s:
1106-[]const U8): []const U8` would hand a caller with a `[]U8` back a
1107-slice it can't write, and break the caller that does. Either such
1108-procedures keep `[]U8` until `ret` (above) can say "of the same kind
1109-as the argument", or they come in pairs. This is where D's `inout` and
1110-C++'s `const` overloads went; neither is small.
1111-
1112-A second step, for a thaw: a string literal and a constant's slices
1113-are `[]const U8` and `[]const T`, so that writing them is an error,
1114-not undefined, and section 10 loses a case. It breaks every program
1115-that keeps a literal in a `[]U8` variable or field, which is most of
1116-them, `Opt`'s rows included; each is mended by writing `[]const U8`
1117-where nothing writes the bytes.
1118-
1119-Precedent: C's `const char *`; D's `const(T)[]`; Rust's `&[T]` and
1120-`&mut [T]`; ulam, the other language here, makes `[]T` read only and
1121-writes `[]var T` for one that may be written, which is the safer
1122-default but breaks every raz program.
1123-
1124-Costs: the report, 5.3, 5.10 and 10, and 8 for `const` parameters,
1125-which could then read their slices as `[]const`, making `const` deep
1126-for slices; the compiler, a flag on a slice type, as `vol` is on a
1127-pointer, checked where an element is written, about 60 to 100 lines;
1128-the library, its read-only slice parameters, a long list but each
1129-change one word.
1130-
1131-Met in the discussion of `const` parameters (2026-10-17): "If a const
1132-can still be written, what's the point?", and "Can records have
1133-constant slices?"
1134-
1135-## For a kernel: three changes to the compiler
1136-
1137-**Status.** Done in v0.21.0 (2026-10-17), all three: `raz -base`, `raz -bare`, and the privileged instructions.
1138-
1139-Not the language's but this compiler's, kept together since they serve
1140-one end: a raz program run on the bare machine, a unikernel, with no
1141-operating system under it. None is needed for one: a kernel can be
1142-made today, with a boot stub of its own that enters long mode, `db`
1143-for the instructions the assembler lacks, and either a library of its
1144-own beside a copy of `raz` (the library is read from beside the
1145-compiler) or a handler for `syscall` that does what `Rt` and `Sys` ask
1146-of Linux. Each piece below takes away one of those work-arounds, and
1147-stands on its own.
1148-
1149-**1. A load address chosen at the command line.** Done (2026-10-17):
1150-`raz -base ADDR`, a multiple of the page, the program wholly in the low
1151-or the top 2 GB (`doc/compiler.md`, the linker).
1152-
1153-**2. A program with no `Rt` body.** Done (2026-10-17): `raz -bare`
1154-reads no `argc` and `argv`, runs no body of `Rt` and gives it no
1155-profiler. It still gives `Rt` the places, by stores alone, so that a
1156-failed check says where it was, which the proposal had left out as
1157-`-s` does (`doc/compiler.md`, the command line).
1158-
1159-**3. The privileged instructions in the assembler.** Done (2026-10-17):
1160-`cli`, `sti`, `iretq`, `swapgs`, `lgdt`, `lidt`, `ltr`, `invlpg`,
1161-`mov` to and from the control registers, `rdmsr`, `wrmsr`, `in`, `out`,
1162-`wbinvd`, `xsave` and `xrstor` (`doc/compiler.md`, the assembler).
1163-
1164-What is still left to a kernel's own code, with all three: zeroing
1165-the bss and a stack aligned to 16 bytes before `_start`, as Linux
1166-gives; the boot stub, since no common loader enters an ELF64 file in long mode but
1167-Firecracker (GRUB's Multiboot2 and QEMU's PVH enter in 32-bit mode,
1168-and the assembler makes only 64-bit code); interrupt stubs that save
1169-the XMM registers, since the compiler's code uses them; and, if the
1170-compiler's code ever writes below `rsp`, which isn't yet checked, an
1171-IST stack for each interrupt.
1172-
1173-Met in the question "how difficult to create a simple amd64 unikernel
1174-in raz?" (2026-10-17).
1175-
1176-## `Sys.setsid`: a session of a process's own
1177-
1178-**Status.** Approved by the owner on 2026-10-23 and implemented in both backends.
1179-
1180-Library growth that breaks no program: one procedure, beside `fork`,
1181-in `Sys.raz` (C's `setsid`) and `Sys.linux-x86_64.raz` (system call
1182-112).
1183-
1184- (* A new session and process group, led by this process, with no
1185- controlling terminal: its process id, or minus an errno (-1,
1186- EPERM, if it leads a process group already, as a process just
1187- forked doesn't). *)
1188- proc setsid*: INT;
1189-
1190-A daemon forks, and its child calls `setsid` so that the terminal it
1191-was started from is no longer its own: closing that terminal sends it
1192-no `SIGHUP`, and the terminal's job control doesn't reach it. Without
1193-it, a program can ignore `SIGHUP` and `SIGINT` (`Sys.ignore`), but
1194-stays in the terminal's session and process group, so job control and
1195-any other signal sent to the group still reach it.
1196-
1197-Met in rabble, whose daemon (its `PLAN.md`, from 0.2.0) is started by
1198-the client with `fork` and must outlive the terminal (2026-10-21).
1199-
1200-## The local time zone
1201-
1202-**Status.** Not planned (owner, 2026-10-23): rzone answers it outside raz.
1203-
1204-Library growth that breaks no program: a module, `Zone`, that tells
1205-the offset from UTC of the user's time zone at a given time, so that a
1206-program can show times as its user's clock does.
1207-
1208- (* The local zone's offset from UTC, in seconds east, at the time
1209- t (seconds since 1970 UTC), and its abbreviation ("CEST"); 0 and
1210- "UTC" if no zone can be read. *)
1211- proc offset*(t: I64): (INT, []U8);
1212-
1213-The zone is the one `TZ` names, as a file under `/usr/share/zoneinfo`
1214-(`TZ=Europe/Madrid`) or a path (`TZ=/etc/localtime`); with `TZ` unset,
1215-`/etc/localtime`. The file is TZif, versions 1 to 4, read once and
1216-kept: its transitions, and the POSIX rule in its footer for the times
1217-past the last one. A `TZ` written as a POSIX rule itself
1218-(`CET-1CEST,M3.5.0,M10.5.0/3`) is read too. No C: the same on every
1219-target, with or without libc, so a program's times don't change with
1220-the target it is built for.
1221-
1222-Met in rabble, which shows every time in UTC, in the screen and in its
1223-logs, since the library has no zone (2026-10-21).
1224-
1225-## Implementation limits, and a compiler for a small stack
1226-
1227-**Status.** To investigate; nothing decided.
1228-
1229-The report names no implementation limits: how deep expressions,
1230-statements, imports and generic instances may nest, how long a name or
1231-a string may be. A compiler for a small machine that rejects a deep
1232-nesting is then arguably not a raz compiler at all. C settles it with
1233-its translation limits (C99 §5.2.4.1: 63 levels of nested parentheses,
1234-15 of nested includes, and so on): every compiler must take at least
1235-that much, and may take more. The proposal: a short section in the
1236-report giving the least each compiler must accept, and saying that a
1237-compiler that goes past its own limit stops with an error naming it,
1238-never a crash. It changes the report, not the language.
1239-
1240-Behind it, three things in this compiler that need no change to the
1241-report at all, so that it runs in a small stack:
1242-
1243-1. **Nesting.** Each level of a nested expression costs about 1 KiB
1244- of stack. A constant expression with 64 nested parentheses fails a
1245- 64 KiB stack and passes 256 KiB; 256 of them fail 256 KiB and pass
1246- 1 MiB. A limit from the section above, checked in the parser, makes
1247- the stack a program needs bounded and known.
1248-2. **Imports.** `importModule` compiles an imported module in the
1249- middle of the one importing it, on the same stack, so the stack
1250- grows with the depth of the chain of imports. Ordering the modules
1251- first and compiling them from the leaves, in a loop, keeps whole
1252- program compilation and a stack that doesn't grow; symbol files, as
1253- Wirth's compilers have, would do it too, but must then carry a
1254- generic module's body.
1255-3. **Instances.** `makeInstance` keeps the declaration under way aside
1256- in arrays on the stack (`[MaxFwd]PType`, `[MaxFwd]Diag.Pos`,
1257- `[MaxNames]INT`, several KiB) for every instance it nests. A list
1258- of instances still to make, made between declarations, would keep
1259- none.
1260-
1261-Not yet measured: which of these filled the stack when the stripped
1262-compiler, given one more `-I` directory, overflowed 64 KiB building
1263-itself, where the ordinary self-build fit.
1264-
1265-Met in moss (`docs/raz-port.md`): its stored programs get a guarded
1266-64 KiB stack, and a native compiler must fit, or the stack must grow
1267-(2026-10-22).
1268-
1269-## `Sys.blocking`: whether a descriptor's reads and writes wait
1270-
1271-**Status.** Approved by the owner on 2026-10-23 and implemented in both backends.
1272-
1273-Library growth that breaks no program: one procedure, beside
1274-`setBlocking`, in `Sys.raz` (C's `fcntl` with `F_GETFL`) and
1275-`Sys.linux-x86_64.raz` (system call 72, `F_GETFL`, as `setBlocking`
1276-already makes it).
1277-
1278- (* Whether reads and writes on fd wait, as they do at first: 1 if
1279- they do, 0 if they return -11 (EAGAIN) at once, or minus an
1280- errno. *)
1281- proc blocking*(fd: INT): INT;
1282-
1283-`setBlocking` sets the flag but nothing reads it, so a library that
1284-must make a caller's descriptor non-blocking for a while can't put it
1285-back as it found it: it can only guess. rnet's `Tls.accept` makes the
1286-socket it is given non-blocking for the handshake and, on failure,
1287-makes it blocking again, as `Sys.accept` gives it; a caller that gave
1288-it a non-blocking one gets it back changed. With `blocking`, it would
1289-note the flag first and restore that. A test, too, can't check that a
1290-descriptor was put back without it.
1291-
1292-Met in rnet, after a review of its STARTTLS (2026-10-22).
1293-
1294-## Base64 in `Str`
1295-
1296-**Status.** Approved by the owner on 2026-10-22 and implemented in
1297-`lib/Str.raz`, with the interface below; `out` too short stops the
1298-program at the byte it lacks, as any slice does. Decoding also rejects
1299-padding bits that are not 0 (RFC 4648, section 3.5 allows it).
1300-
1301-Library growth that breaks no program: three procedures in `Str.raz`,
1302-beside `hexVal` and `toHex`, of base64 as RFC 4648 (4) has it: its
1303-alphabet, `A` to `Z`, `a` to `z`, `0` to `9`, `+` and `/`, and `=` to
1304-pad the last group to four.
1305-
1306- (* The bytes base64 makes of n bytes: 4 for each 3, or part of 3. *)
1307- proc base64Size*(n: INT): INT;
1308-
1309- (* s in base64 into out, which holds base64Size(LEN(s)) bytes at
1310- least: the bytes written. *)
1311- proc base64*(s, out: []U8): INT;
1312-
1313- (* s, base64, decoded into out, which holds LEN(s) div 4 * 3 bytes at
1314- least: the bytes written; false if s isn't base64, its length
1315- not a multiple of 4, a byte outside the alphabet, or padding
1316- anywhere but at the end. *)
1317- proc unbase64*(s, out: []U8): (INT, BOOL);
1318-
1319-The caller gives the room, as `Fmt` and the rest of `Str` have it, so
1320-nothing is allocated. Decoding is strict: line breaks and missing
1321-padding, which MIME and some programs allow, are the caller's to take
1322-out or put back first.
1323-
1324-Programs each carry their own copy meanwhile: rnet's `Ws`, for the
1325-WebSocket handshake's accept key, and `Smtp`, for AUTH PLAIN, the same
1326-twenty lines twice in one library; flojo, for the terminal's clipboard
1327-(OSC 52), its own fifteen. HTTP's Basic authentication and data URLs
1328-want it as well, and want decoding too, which none of those copies
1329-does.
1330-
1331-Left out: base64url (RFC 4648, 5), for JWTs, which is the same with
1332-`-` and `_` and usually no padding; a flag, or a second pair of
1333-procedures, if a program needs it.
1334-
1335-Met in rnet, whose `Smtp` copied `Ws`'s (2026-10-22); listed in
1336-`~/r/RAZ-GAPS.md` before that, from rnet and flojo.
1337-
1338-## A library that says which raz it was written for
1339-
1340-**Status.** Approved by the owner on 2026-10-22 and implemented: the deprecation step as policy alone, with no mark (`doc/raz-lib.md`, `README.md`); the note from a library's `RAZ-VERSION` (`Diag`, `Parse`); and `--version` naming the commit with no tag (`Makefile`).
1341-
1342-0.19 moved the library from pointers to `var` and `const` parameters,
1343-and every library pinned to an older raz stopped building: rnet, rjson,
1344-rfetch, rj and arno needed fixes, and alba, clima and linia carried
1345-their own JSON reader meanwhile. The errors were loud but far from the
1346-cause: "can't use ^Buf as Buf" inside rjson, read by someone building
1347-clima. The report says the library "grows only by what breaks no
1348-program", and the move broke all of them. Three small pieces, none of
1349-them syntax.
1350-
1351-**A deprecation step.** A change to the standard library that breaks
1352-programs keeps the old form for one minor version beside the new, the
1353-old one marked so that a call to it is a warning naming the new one:
1354-
1355- (* deprecated: Buf.add(var b, ...) *)
1356- proc addOld*(b: ^Buf; s: []U8);
1357-
1358-How the mark is written is the open question: a comment the compiler
1359-reads is a pragma in disguise; a word like `obsolete` before `proc` is
1360-a reserved word for a rare case. The step could also be policy alone,
1361-with no mark: the release notes list the old forms and the next
1362-version removes them.
1363-
1364-**An error says whose module it is in.** An error in a module found
1365-through `-I` or `RAZ_PATH` names the directory it came from and, if
1366-that directory holds a file `RAZ-VERSION` (one line, `0.21`), the raz
1367-it was written for:
1368-
1369- /home/luis/.raz/lib/Json.raz:41: can't use ^Buf as Buf
1370- (a library written for raz 0.18; this is raz 0.21)
1371-
1372-The compiler only reads the file; it never refuses to build. A library
1373-that has none is no worse off than today.
1374-
1375-**`raz --version` says its commit** when `git describe` finds no tag,
1376-as from a shallow fetch, instead of "unknown" (rcrypto pins a commit
1377-and always sees "unknown").
1378-
1379-Met in rnet, rjson, rfetch, rj, arno, alba, clima and linia (0.19),
1380-and rcrypto (`--version`).
1381-
1382-## Sys for a server
1383-
1384-**Status.** Approved in part by the owner on 2026-10-23 and implemented in both backends: `closeWrite`, `peer` (its record is `Remote`, since `Peer` is taken by `receive` and `reply`), `socketPair`, `nonblocking` and `errConnAborted`. `closeOnExec` is unneeded now that every open closes on exec. A send that doesn't wait (`sendNow`), a fifo (`makeFifo`) and an owner (`Info.uid`, `Info.gid`, `chown`) followed on 2026-10-23. `poll`, waiting on any number of descriptors, and the abstract Unix socket followed on 2026-10-23. Keepalive waits for a second program.
1385-
1386-Library growth that breaks no program. Programs that serve sockets
1387-(rabble's relay and daemon, dwa's broker, rdbus, awizo, arno's te
1388-protocol) each declare a few C procedures or make system calls with
1389-`SYSCALL` in a `.linux.raz` file, for what any server needs. Each piece
1390-below stands alone; together they are about a dozen procedures in
1391-`Sys.raz` and `Sys.linux-x86_64.raz`.
1392-
1393-- **`shutdown`.** `proc closeWrite*(fd: INT): INT;` ends this side's
1394- writing, `SHUT_WR`, so the peer reads an end and can still answer
1395- on the same socket (te's protocol; rabble wakes a thread waiting in
1396- a handshake with it). Met in dwa, rabble, arno.
1397-- **Who is at the other end.** `proc peer*(fd: INT): (Peer, INT);`
1398- with `Peer` the address of a TCP peer (family, address bytes, port)
1399- and, for a Unix socket, the peer's uid and pid (`SO_PEERCRED`). A
1400- server can log who connected and a broker can check that its client
1401- is the same user, instead of trusting a 0700 directory. Met in
1402- rabble, dwa.
1403-- **A pair of sockets.** `proc socketPair*(): (INT, INT, INT);` the two
1404- ends and 0, or minus an errno. Met in rdbus's tests and rabble's
1405- relay.
1406-- **A send that doesn't wait.** `proc sendNow*(fd: INT; s: []U8): INT;`
1407- (`MSG_DONTWAIT`): -11 where `send` would wait, without making reads
1408- non-blocking too. Met in rdbus.
1409-- **Opening without waiting.** `nonblocking` and `closeOnExec` among
1410- `Access`. (`closeOnExec` falls away if "Sys for files and
1411- memory" makes it the default.) Opening a fifo to write waits for a reader, and a fifo
1412- given where a file was expected waits for a writer. Met in mosaico,
1413- awizo, surco, raudio.
1414-- **A fifo.** `proc makeFifo*(path: []U8; mode: INT): INT;`. Met in
1415- awizo.
1416-- **An owner.** `Info.uid`, `Info.gid` and `proc chown*(path: []U8;
1417- uid, gid: INT): INT;`, so a save through rename keeps the owner and a
1418- daemon can check that its directory is the user's. Met in dwa,
1419- rabble.
1420-- **Keepalive.** `proc keepAlive*(fd: INT; idle, interval, count:
1421- INT): INT;` rather than a general `setsockopt`, whose value is a
1422- pointer and a length of any type. Met in rabble.
1423-- **An abstract Unix socket.** `connect` passes `2 + LEN(path)` as the
1424- address's length when the path starts with a zero byte, so Linux's
1425- abstract names (D-Bus's `unix:abstract=`) are reached. A fix, not a
1426- procedure. Met in rdbus.
1427-- **`errConnAborted`** (-103), which `accept` gives for a client gone
1428- before it was taken. Met in rabble.
1429-
1430-**Waiting**, the one piece that changes a procedure's answer, and so
1431-better as a new procedure than a change to `readyFor`:
1432-
1433- (* Waits up to ms milliseconds (ms < 0: as long as it takes) until
1434- one of fds may be read or written as each of its wants says, and
1435- sets each one's ready. The number ready, 0 on a timeout, or minus
1436- an errno. *)
1437- proc poll*(var fds: []Poll; ms: INT): INT;
1438-
1439-with `Poll = record fd: INT; read, write: BOOL; ready: BOOL; end`.
1440-It takes as many as it is given (`readyFor` stops at 64, so dwa's
1441-broker serves 31 editors), answers every ready descriptor in one call
1442-(`readyOf` gives only the first, so awizo takes two rounds and rabble
1443-rotates its clients so that the first doesn't starve the rest), gives
1444-the place in the list, not the fd, and tells a timeout from an error
1445-(both are -1 today). `readyFor` and `readyOf` stay, written over it.
1446-Whole milliseconds stay too: surco rounds up, and a wait in
1447-nanoseconds is `ppoll`, Linux's, for one program.
1448-
1449-Each item is listed in `~/r/RAZ-GAPS.md` under "Standard library: Sys,
1450-files, processes".
1451-
1452-## Sys for running a program
1453-
1454-**Status.** Approved by the owner on 2026-10-22 and implemented in both `Sys` backends, all four. `spawn` also gives -13 (EACCES), as `exec` does, for a program found that can't be run.
1455-
1456-Library growth, but two of the four change what `spawn` and `wait`
1457-do, so they need the owner's word on whether a change of behaviour
1458-counts as breaking.
1459-
1460-- **`spawn` says a program isn't there.** Today a missing program
1461- still gives a pid, and the child exits 127, which a caller can't tell
1462- from the program's own 127; clima, alba, sauce and raztest search
1463- `PATH` first, about 20 lines each, and sauce still reads curl's 127
1464- as "cannot run curl". `spawn` searches `PATH` in the parent, as
1465- `exec` already does, and gives -2 (ENOENT) before it forks. A
1466- program found but failing in `execve` (not executable, a bad
1467- interpreter) still exits 127, since only the child sees that; a
1468- close-on-exec pipe would carry its errno back, at the cost of a pipe
1469- per spawn.
1470-- **Ignored signals stay ignored.** `spawn` and `exec` give the child
1471- every signal as at first, SIG_IGN included, where `execve` keeps an
1472- ignored one ignored: a robbie under `nohup` runs its recipes without
1473- it, and ssh run by fdn doesn't keep SIGPIPE ignored. A
1474- `Program.keepIgnored: BOOL`, false as today, keeps them.
1475-- **`fds` with `tty`.** With `tty`, the pseudo-terminal is all three
1476- files and `fds` is ignored, so dwa's background job that should read
1477- `/dev/null` waits on a terminal nobody types to. A non-zero `fds[i]`
1478- replaces the terminal for that file; zero keeps it.
1479-- **`wait` without the stopped.** `wait` always asks for stopped
1480- children (WUNTRACED), so a program waiting for `$EDITOR` loops past
1481- Ctrl-Z (notis, fdn). `proc waitExit*(pid: INT): (INT, Status, INT);`
1482- waits only for an end, or `wait` takes `stopped: BOOL`, which
1483- changes its signature.
1484-
1485-`PATH` read empty as unset (pict) stays: the library volume says so,
1486-and it is `execvp`'s choice.
1487-
1488-## An investigation: where a hot loop's time goes
1489-
1490-**Status.** Done 2026-10-23: neither a register allocator nor statement inlining earns its lines; an array parameter indexed as `[pointer + index * size]`, kept parameters in callee-saved registers, and inlining a procedure that only returns, were.
1491-
1492-Not a change: a measurement, whose report would say whether register
1493-allocation, inlining (see "Inlining a procedure that only returns"),
1494-or neither is worth its weight in the compiler.
1495-
1496-What is known, from rcrypto, rat and sauce:
1497-
1498-| Code | MB/s | Against |
1499-|---|---|---|
1500-| ChaCha20, `quarter` on a `var x: [16]U32` | 40 | 78 written out on sixteen locals; OpenSSL scalar 589 |
1501-| Poly1305, arithmetic on locals, no calls | 491 | |
1502-| AES-128 bitsliced, 115 gates on 130 local `U64`s | 23 | GHASH 180 |
1503-| SHA-256 with `ROR` | 76 | 40 before `ROR` |
1504-
1505-and rat's parser, which inlines `Utf8.take` by hand because the call
1506-costs 7 to 10 per cent.
1507-
1508-The steps: a `bench/` of these few kernels, each in its plain form and
1509-its hand-tuned one; their `raz -S` read side by side, counting loads
1510-and stores of locals, spills and calls; then the same kernel with the
1511-generator changed by hand (a local kept in a register across a loop, a
1512-small procedure inlined) to put a number on each. The outcome is a
1513-page here saying which change buys what, and none is made before it.
1514-
1515-Listed in `~/r/RAZ-GAPS.md` as "A state in an array or behind a `var`
1516-is slow" and "No procedure is inlined".
1517-
1518-## A width in `Fmt`
1519-
1520-**Status.** Approved by the owner on 2026-10-22 and implemented in `lib/Fmt.raz`, with `lowHex` as a case of `Arg`; a width is at most four digits.
1521-
1522-Library growth that breaks no program. `Fmt` has only `{}`, so seven
1523-programs pad by hand: arno, rat, notis and poczta each have a
1524-two-digit helper for times, surco writes `m:ss` and its cover files'
1525-lower-case hashes with loops of its own, rttf writes `U+00E9` and raz's
1526-own `Prop` a fixed-width hex name.
1527-
1528-The proposal: a width between the braces, and a zero before it to pad
1529-with zeros, right-aligned:
1530-
1531- Fmt.print("{2}:{02}", [Fmt.int(m), Fmt.int(s)]); (* " 3:07" *)
1532- Fmt.print("U+{04}", [Fmt.hex(0E9H)]); (* "U+00E9" *)
1533-
1534-A value wider than the width is written whole. A minus pads on the
1535-right (`{-10}`), for columns of names. Zeros go after a sign: `{04}` of
1536--7 is `-007`. Nothing else: no precision (`Fmt.real` has `places`), no
1537-other fill, no named or numbered arguments.
1538-
1539-And a lower-case hexadecimal: a case `lowHex(h: U64)` beside `hex`, or
1540-`{x}` against `{X}`, which is a second letter in the format for a thing
1541-an argument could say. The argument is the plainer.
1542-
1543-`{` followed by anything but `}` or a width is printed as it stands
1544-today, so no format changes meaning unless it already had `{2}` in it,
1545-which printed `{2}`.
1546-
1547-Settled by "One exponent letter: `Fmt` writes `E`", below.
1548-
1549-## Selectors after a `^T(e)` conversion
1550-
1551-**Status.** Not planned (owner, 2026-10-23): it makes unchecked code shorter and adds nothing a named pointer type can't do; `BYTES` serves the checked uses.
1552-
1553-A conversion through a pointer type's name is a designator, so
1554-selectors follow it: with `PR = ^R` and `PU = ^U8`, `PR(ADR(r))^.b`
1555-and `PU(ADR(r))[0..4]` compile today. The same conversion written out
1556-is the grammar's own factor, `"^" ["VOLATILE"] Type "(" Expr ")"`, and
1557-takes none: `^R(ADR(r))^.b` is "a conversion can't be dereferenced",
1558-and `^U8(ADR(r))[0..4]` is "can't use ^U8 as []U8", the slice read as
1559-part of the operand. So a program declares a pointer type, or a
1560-variable, for one read through a C struct or one slice of raw memory.
1561-
1562-The proposal: that factor takes selectors, as a named conversion does.
1563-
1564- Factor = ... | "^" ["VOLATILE"] Type "(" Expr ")" { Selector } | ...
1565-
1566-`^U8(p)[0..n]` is a slice of `n` bytes from `p`; `^XMapEvent(ADR(ev))^.window`
1567-is one field of an event. Nothing new is checked or left unchecked: the
1568-selectors are a pointer's, as they are after `PU(p)`. A statement still
1569-starts with a name or `try`, so `^T(x)^ := v` stays out (the report
1570-says so already, and a view, `mem[a].(I64) := v`, writes it). What is
1571-text with an error today gets a meaning, and nothing else changes.
1572-
1573-Met in znaczy, raudio, rcrypto and linia (the slice) and rx11 (the
1574-dereference).
1575-
1576-## The limits of an integer type: `MIN(T)` and `MAX(T)`
1577-
1578-**Status.** Approved by the owner on 2026-10-22, a twelfth thaw. In the report, 2026-10.36 (sections 4, 6.1 and 6.8), and in the compiler (2026-10-23).
1579-
1580-Programs write `7FFFFFFFFFFFFFFFH` for the largest `I64` and `-10^12`
1581-for "below anything real", and nothing ties either to its type: change
1582-a field from `I64` to `I32` and the constant still compiles, wrong.
1583-Oberon has `MIN` and `MAX` of a basic type for this.
1584-
1585-The proposal: two built-in procedures, for an integer type `T` only:
1586-
1587-| Call | Result |
1588-|---|---|
1589-| `MIN(T)` | the smallest value of `T`, an untyped constant |
1590-| `MAX(T)` | the largest value of `T`, an untyped constant |
1591-
1592-`MIN(U64)` is 0, `MAX(U64)` is 18446744073709551615, `MIN(I64)` is
1593--9223372036854775808, so the constants need the compiler's
1594-`U64`-and-`I64` range, which constant folding already has. A name for
1595-another type, an enumeration, a set or a real, is an error: an
1596-enumeration has `LEN`-like answers of its own, and a real's limits
1597-(an infinity, the largest finite) are a separate question. Two words
1598-taken among the built-ins, which a program can't declare anyway.
1599-
1600-Met in mosaico, rfuzz and raudio.
1601-
1602-## `OFFSET(T, f)`, and `SIZE` of a field
1603-
1604-**Status.** Approved by the owner on 2026-10-23, with the twelfth thaw. In the report, 2026-10.36 (4, 6.1 and 6.8), and in the compiler (2026-10-23).
1605-
1606-A record handed to C by pointer must match C's struct byte for byte;
1607-a field one word off is read wrong with no error. mosaico and rx11 test
1608-their Xlib records against C's `offsetof` and `sizeof`, and today
1609-measure an offset on a dummy variable, `INT(ADR(v.f)) - INT(ADR(v))`:
1610-a run-time value, a variable declared for it, and pointer arithmetic
1611-where the test means "where `f` is". rx11's `test/layout.sh` copies
1612-each field's type out of the source text, since `SIZE` takes only a
1613-type.
1614-
1615-The proposal, two additions to the built-in procedures:
1616-
1617-| Call | Result |
1618-|---|---|
1619-| `OFFSET(T, f)` | the byte offset of field `f` in the record type `T`, an untyped constant |
1620-| `SIZE(T.f)` | the size of field `f` of the record type `T`, an untyped constant |
1621-
1622-`f` is one field name; a path, `OFFSET(T, a.b)`, would be the sum of
1623-two and is left out, and so is a variant, whose cases share their
1624-place. `SIZE` still takes no
1625-variable: `T.f` names a type's field, not storage, so `SIZE` stays a
1626-question about types.
1627-
1628-C has `offsetof`; Modula-2 and Oberon kept such things in `SYSTEM`,
1629-and raz has no `SYSTEM`. It is constant folding of what the compiler
1630-already knows, and it is also what a view through raw memory wants,
1631-`mem[a + OFFSET(Hdr, len)].(U32)`, in place of a number, and what a
1632-kernel's `code` procedures would want if their operands take constants.
1633-
1634-Met in mosaico and rx11.
1635-
1636-## The compiler on another host: `Host`, and what it asks of the library
1637-
1638-**Status.** Built on the branch `moss-platform-boundary` (3eded0c),
1639-which Moss pins: there raz compiles programs, rebuilds itself byte for
1640-byte, and builds again after a restart (moss c606069,
1641-`docs/native-raz.md`). Waiting for the owner's word on the questions
1642-below before it is rebased and merged.
1643-
1644-The host is the system the compiler runs on; the target, the system
1645-its program will run on. Until the branch they were one, Linux, and
1646-the compiler reached Linux outside `Sys`: `Parse.identity` read a
1647-`struct stat` by `SYSCALL(4)` into a guessed `[18]INT`; `Raz` read
1648-`ARGC()` and `ARGV()`, found the library through `/proc/self/exe`,
1649-probed two loader paths for musl, and ran a program by `memfd_create`
1650-and `execve`; `Elf` set mode 755. The branch does three things.
1651-
1652-**1. A file's identity from `Sys.info`** (2644329). Its `dev` and
1653-`ino`, so the parser makes no system call of its own. A plain fix:
1654-merge it.
1655-
1656-**2. A main file at the root, and a directory ending in `/`**
1657-(3eded0c). `/Main.raz` has `/` as its directory, not `""`, and a
1658-directory given as `lib/` doesn't make `lib//Sys.raz`. A plain fix:
1659-merge it.
1660-
1661-**3. `Host`, a module of what the compiler asks of its host**
1662-(bb03e48): `argCount`, `arg`, `libraryDir`, `preferMusl`, `canRun`,
1663-`canLinkC`, `writeExecutable`, `prepareRun`, `execute`. `src/Host.raz`
1664-is Linux's; Moss stages the compiler's sources with its own
1665-`Host.raz` (27 lines: the library at `/lib`, no run, no C, no mode
1666-bits) and its own `Sys`, `Rt` and `Files`.
1667-
1668-Questions before the merge:
1669-
1670-**a. A smaller `Host`.** Two of its nine procedures are there only
1671-because `Raz` reads the command line by built-ins:
1672-- `argCount` and `arg` go if the library has the count beside
1673- `Files.arg`: a `Files.argCount()`, which Moss's `Files` gives from
1674- `Sys.argc`. `Files.arg` is already the library's, and Moss already
1675- replaces it.
1676-- `preferMusl` and `canLinkC` are one question, which C library to
1677- link against: `Host.cLibrary(): CLib` with `CLib = (none, glibc,
1678- musl)`, or keep the two booleans.
1679-- `canRun` goes if `prepareRun` is called while the command line is
1680- read, before any source, so that its error is the refusal.
1681-That leaves `libraryDir`, `cLibrary`, `writeExecutable`, `prepareRun`
1682-and `execute`: five procedures, each a real difference between hosts.
1683-
1684-**b. How a host is chosen.** The branch stages: copy `src/`, put the
1685-host's `Host.raz` in place of raz's, build. The main directory is
1686-searched first, so `-I` alone can't replace it, which is right: a
1687-module isn't silently replaced. The other way is a target name, as
1688-`Sys.linux-x86_64.raz` is chosen today from fixed suffixes: a
1689-`-os moss` that makes the suffixes `.moss-x86_64`, `.moss`, `.x86_64`,
1690-`""`, so that `Host.moss.raz` and `Sys.moss.raz` are found beside the
1691-generic files. That puts Moss's files in raz's tree, and raz would
1692-then know of Moss. The proposal is to keep staging, raz knowing
1693-nothing of any host but Linux, and to document it in
1694-`doc/compiler.md` as the one way to build for another host.
1695-
1696-**c. What the compiler asks of the library, written down.** Moss's
1697-`Sys` has 23 exported procedures against Linux's 104, and is enough.
1698-`doc/compiler.md` should list what the compiler and the modules it
1699-imports (`Rt`, `Mem`, `Heap`, `Lock`, `Arena`, `Out`, `Fmt`, `Buf`,
1700-`Str`, `Bytes`, `Files`) use of `Sys`, `Rt` and `Files`, as Moss's
1701-`docs/raz-port.md` measured it, and a test should hold it: the
1702-compiler built against a `Sys` with only those exports. Then a change
1703-to the compiler that reaches for one more of `Sys` is seen in raz,
1704-not in Moss's next build. The test host on the branch
1705-(`test/host/Host.raz`) checks the `Host` side only.
1706-
1707-**d. The stack.** A self-build passed in 64 KiB of stack on Linux,
1708-but 64 nested parentheses don't, and Moss gives a stored program 1
1709-MiB. That is "Implementation limits, and a compiler for a small
1710-stack", above; the merge needn't wait for it.
1711-
1712-**e. The tests in Python.** The branch adds `test/compiler-host.py`
1713-(177 lines) and grows `test/library-path.py`, which came with
1714-RAZ_PATH. raz's tests are otherwise `sh`, as a public project's
1715-should be, needing nothing but a shell to run. The proposal is to
1716-write both in `sh` before the merge.
1717-
1718-**f. Before the merge, in any case.** The system call numbers in
1719-`Host.raz` named as constants, as `Raz` had them (`MemfdCreate`,
1720-`MfdCloexec`, `Execve`); a comment on every procedure; the new section
1721-of `doc/compiler.md` made as short and plain as the rest; a rebase on
1722-main (`doc/compiler.md` and `src/Raz.raz` conflict). Moss's
1723-`RAZ_PORT.lock` then pins a commit on main.
1724-
1725-## Constants built from constants
1726-
1727-**Status.** Approved by the owner on 2026-10-23, with the twelfth thaw. In the report, 2026-10.36, and in the compiler (2026-10-23).
1728-
1729-Three small changes to what a constant may be written with, and a defect. Each stands
1730-alone; none changes what a program that compiles today means.
1731-
1732-- **A named constant as an element.** `const Y: [2]R = [X, {a: 2}]`,
1733- with `X` a record constant, is "expected a literal of R", and so is
1734- `[X, [3, 4]]` with `X` an array constant, and `{a: X}` for an array
1735- field. A named integer is taken (`[N, 2]` compiles), and so is a
1736- named array constant for a slice part (`[R1, R2]` for a `[][]INT`).
1737- The report already allows it: the value is "a literal of constants",
1738- and its elements may be "arrays, records and variants of these". So
1739- this is a defect of the compiler, mended with no change to the
1740- report: where an array, record or variant is wanted, a constant of
1741- that type stands for its literal. Met in mgla.
1742- **Recommendation:** take, as a defect mended. Fixed in 065335a
1743- (2026-10-22).
1744-
1745-- **A literal for a slice part.** `const T: [][]INT = [[1, 2], [3]]`
1746- is "a constant slice is a string, an array constant of its elements
1747- or []", and so is `{r: [1, 2]}` for a `[]INT` field. Each row must be
1748- named first, `R1: []INT = [1, 2];`, and the table written `[R1, R2]`,
1749- or the rows flattened into one slice walked by counts, as raudio's
1750- Sbr test does. The proposal, one clause of 4: where a slice part is
1751- wanted, an array literal of its element type makes an array constant
1752- of its own, with no name, as `[]` there makes the empty slice. `[]`
1753- stays the empty slice. Met in raudio.
1754- **Recommendation:** take, since the named rows say nothing the
1755- literal doesn't.
1756-
1757-- **An `ERROR` constant named by another.**
1758- `const Short*: ERROR = PictBase.Short;` is "an error is made from a
1759- string", so an interface module can't pass on the errors of the
1760- modules under it, and its callers import a second module only to
1761- compare. The proposal, a sentence of 5.8: an `ERROR` constant whose
1762- value is another `ERROR` constant is that same error, not a new one,
1763- and `Short = PictBase.Short` holds. Only a string makes a new error,
1764- as now. Met in pict.
1765- **Recommendation:** take, since the alternative is a second import
1766- on every caller.
1767-
1768-- **A comma after the last element.** `[a, b,]` is "expected an
1769- expression", so a table written one row a line, by hand or by a
1770- program, treats its last row apart, and adding a row changes two
1771- lines. The proposal, in the grammar:
1772-
1773- | "[" [ Expr { "," Expr } [ "," ] ] "]"
1774- | "{" [ Element { "," Element } [ "," ] ] "}"
1775-
1776- for array, record and set literals alike; not for calls, parameter
1777- lists or `match` labels. `Pretty` keeps the comma where a literal
1778- runs over lines and drops it where it fits on one. Met in rtui.
1779- **Recommendation:** take, since a generated table is the common case
1780- for literals this long.
1781-
1782-## A record's procedure field that takes the record
1783-
1784-**Status.** Approved by the owner on 2026-10-23, with the twelfth thaw. In the report, 2026-10.36 (4 and 5.9), and in the compiler (2026-10-23): a bare name a procedure type's parameter or result names before its declaration waits, as a pointer's base does.
1785-
1786-A record that carries its own callback can't give the callback the
1787-record:
1788-
1789-```
1790-type Lines = record each: proc(var r: Lines; s: []U8); n: INT; end;
1791- (* "Lines isn't declared" *)
1792-```
1793-
1794-Only the base type of a pointer may name a type declared later (4), so
1795-the callback takes `^Lines` and is called with `ADR(l)`, which by
1796-`STANDARDS.md` says the callee keeps it, and it doesn't. Met in znaczy.
1797-
1798-The proposal, a clause of 4: the type of a parameter or result of a
1799-procedure type may also name a type declared later in the same `type`
1800-section. A procedure value is an address whatever its signature, so
1801-the record's size doesn't depend on it; a call through the field
1802-comes after the section, when `Lines` is whole. Nothing that compiles
1803-today changes. In the compiler, the pointer's forward reference
1804-reused where a signature is read in a `type` section.
1805-
1806-**Recommendation:** take, since the workaround puts a false `ADR` at
1807-every call.
1808-
1809-## A `match` arm names its case as everywhere else
1810-
1811-**Status.** Approved by the owner on 2026-10-23, with the twelfth thaw. In the report, 2026-10.36, and in the compiler (2026-10-23).
1812-
1813-An arm takes a case written alone, or with its type when the type is
1814-the module's own (`| K.a:`). An imported case can't be written as
1815-everywhere else outside its module:
1816-
1817-```
1818-import Xml;
1819-...
1820-if x.kind = Xml.done then ... end; (* qualified here *)
1821-match x.kind of
1822-| Xml.done: ... (* "Xml isn't a case of Xml.Kind" *)
1823-| Xml.Kind.text: ... (* the same *)
1824-| done: ... (* taken: a name this module otherwise hasn't *)
1825-```
1826-
1827-The same holds for a variant's cases (`| Ev.circle(r):`). Met in
1828-rslack, rxml and fraco.
1829-
1830-This is the complement of "An enumeration's name read against the type
1831-it is given to": an arm already reads a bare name against the matched
1832-type. The proposal, a sentence of 7.4: an arm on an enumeration or a
1833-variant names its case alone or as it is written anywhere else, with
1834-its type, its module, or both (`done`, `Kind.done`, `Xml.done`,
1835-`Xml.Kind.done`), and a qualified name must be a case of the matched
1836-type. The bare form stays, so nothing breaks. A wrong qualified name
1837-says so: "Ev.dot isn't a case of Xml.Kind".
1838-
1839-**Recommendation:** take, since the natural spelling is refused with a
1840-message that doesn't say what to write.
1841-
1842-## Two warnings
1843-
1844-**Status.** Approved by the owner on 2026-10-23 and implemented in `Parse` and `Scan`.
1845-
1846-Compiler warnings, which are the implementation's own (10, appendix
1847-A): no change to the report, and `-Werror` builds break only where the
1848-text is in fact doubtful.
1849-
1850-- **A relation of `BOOL`s beside `and` or `or`.** In raz the relations
1851- bind tighter than `and` and `or`, so
1852- `(b[i] = 0) # (i >= 2) and (i < 9)` is
1853- `((b[i] = 0) # (i >= 2)) and (i < 9)`. It was meant the Pascal way,
1854- and a test passed for the wrong reason. The warning: an `=` or `#`
1855- whose operands are `BOOL`s, written unparenthesised as an operand of
1856- `and` or `or`:
1857-
1858- a # b and c is (a # b) and c: put the # of two BOOLs in parentheses
1859-
1860- Comparing integers is untouched, so `i < n and a[i] # 0` stays
1861- quiet. Met in rcrypto.
1862- **Recommendation:** take, since the slip is silent and the fix is a
1863- pair of parentheses.
1864-
1865-- **`\0` before a digit.** `"\01"` is a zero byte and `1`; a reader who
1866- knows C reads one octal byte. Moss's keyboard table,
1867- `"\0\01234567890-="`, cost a bug. The warning, in a string or a
1868- character where `\0` is followed by `0` to `7`:
1869-
1870- \0 is a zero byte and the digit after it is itself: write \x00 to keep them apart
1871-
1872- Met in moss (and dwa's tests have the same text, in a comment).
1873- **Recommendation:** take, as a few lines in `Scan` for a bug already
1874- paid for.
1875-
1876-## A `BOOL` as an integer: `INT(b)`
1877-
1878-**Status.** Approved by the owner on 2026-10-23, with the twelfth thaw. In the report, 2026-10.36 (6.7), and in the compiler (2026-10-23).
1879-
1880-Moved here from the list of what to leave out, because three programs
1881-met it and one of them for a reason an `if` can't serve. 6.7 says
1882-there is no conversion between `BOOL` and integers, left out until
1883-needed. Programs now write `8 + Ord(b)` as an `if` (raudio, surco's
1884-Lyrcheck). Constant-time code needs a comparison as a mask with no
1885-branch: rcrypto rebuilds each test from byte differences,
1886-`INT((d - 1) shr 31)`, since an `if` would branch on a secret.
1887-
1888-The proposal, one row of 6.7's table:
1889-
1890-| From | To | Result |
1891-|---|---|---|
1892-| `BOOL` | integer | 0 for `false`, 1 for `true` |
1893-
1894-`U64(a = b)` is 0 or 1, and `0 - U64(a = b)` the mask. Only this way:
1895-no integer to `BOOL` (`x # 0` says it). In a constant it folds. The
1896-compiler has the comparison's `setcc` already, so it is computed
1897-without a branch; the report doesn't promise that (no word of it says
1898-anything of time), but this compiler does it.
1899-
1900-**Recommendation:** take, since Oberon has `ORD(b)` and a constant-time
1901-mask has no other plain spelling.
1902-
1903-## Counting bits: `CLZ`, `CTZ` and `POPCOUNT`
1904-
1905-**Status.** Approved by the owner on 2026-10-22, with `MIN` and `MAX`. In the report, 2026-10.36, and in the compiler (2026-10-23).
1906-
1907-raz has `ROL` and `ROR` (report 2026-10.35) but nothing that counts
1908-bits, so programs loop. raudio's Rice decoder finds the one bit that
1909-ends a unary code by shifting until it meets it (`Bitio.unary`); oku's
1910-`Grid.count` asks `d in s` for each of nine digits to learn how many a
1911-set holds. The library meets the same three times in `Bytes`: `highest`
1912-is a loop, the lowest set byte is found by a multiply, and `count` sums
1913-bits by a multiply, each with a paragraph to explain it. Oberon has
1914-none of these; C compilers, Go (`math/bits`), Rust and Zig all do, as
1915-one instruction each on every machine raz targets.
1916-
1917-The proposal: three built-in procedures, beside `ROL` and `ROR` in 6.8.
1918-
1919-| Call | Result |
1920-|---|---|
1921-| `CLZ(x)` | the number of zero bits above the highest one in `x`, an `INT`; the width of `x`'s type if `x` is 0; `x` of an unsigned integer type |
1922-| `CTZ(x)` | the number of zero bits below the lowest one in `x`, an `INT`; the width of `x`'s type if `x` is 0; `x` as for `CLZ` |
1923-| `POPCOUNT(x)` | the number of one bits in `x`, an `INT`; `x` of an unsigned integer type, or a set, whose members it counts |
1924-
1925-The width is the type's, as for `ROL`: `CLZ(U8(1))` is 7, `CLZ(U64(1))`
1926-is 63. Defining 0 rather than leaving it undefined, as C does, costs a
1927-test where the machine's instruction doesn't give the width (x86-64's
1928-baseline `bsr` and `bsf`); `lzcnt`, `tzcnt` and `popcnt`, which the
1929-compiler's assembler already knows, are newer than the baseline, so
1930-the compiler emits `bsr` or `bsf` with a test, and the multiply that
1931-`Bytes` uses for `POPCOUNT`, unless the target says the instructions
1932-are there. A set goes to `POPCOUNT` and not to `LEN`, which already
1933-means a fixed number of elements and would read as the size of the
1934-set's type.
1935-
1936-Why three and not one: `CLZ` is what reads a code from the top bit
1937-down (Rice, Golomb, UTF-8's lead byte, a log base 2), `CTZ` what walks
1938-the members of a bit mask from the bottom, and `POPCOUNT` what counts.
1939-Each can be written from another only in a way that needs a comment.
1940-Three words among the built-ins, which a program can't declare anyway.
1941-It breaks nothing.
1942-
1943-Met in raudio, oku and the library's own `Bytes`.
1944-
1945-**Recommendation:** take; three one-instruction built-ins replace loops
1946-and multiplies that each need a paragraph.
1947-
1948-## The bytes of a variable or a slice: `BYTES(x)`
1949-
1950-**Status.** Approved by the owner on 2026-10-23, with the twelfth thaw. In the report, 2026-10.36 (6.8 and 7.3), and in the compiler (2026-10-23).
1951-
1952-A view, `v.(T)`, reads one value from bytes, and can't be sliced,
1953-since it has no address (6.9). So a program that has words and wants
1954-their bytes takes an unchecked pointer: raudio writes a `[]I32` of
1955-samples to a file through `p := ^U8(PTR(s))` and `p[0..LEN(s) * 4]`
1956-(`Ao.bytesOf`); surco's Engcheck reads a file into a `[]I32` the same
1957-way; rcrypto wipes each hash state through `p := ^U8(ADR(c));
1958-RcBytes.wipe(p[0..SIZE(Ctx)])`, with a `p` that says nothing. "Selectors
1959-after a `^T(e)` conversion" makes the last one expression,
1960-`^U8(ADR(c))[0..SIZE(Ctx)]`, but it stays unchecked: the length is
1961-written by hand and nothing ties it to `c`.
1962-
1963-The proposal: one built-in procedure.
1964-
1965-| Call | Result |
1966-|---|---|
1967-| `BYTES(x)` | the bytes of `x` as a `[]U8`: for a slice `s: []T`, its `LEN(s) * SIZE(T)` bytes; for a variable of any other type `T`, its `SIZE(T)` bytes |
1968-
1969-```
1970-n := Sys.write(fd, BYTES(samples)); (* samples: []I32 *)
1971-n := Sys.read(fd, BYTES(words)); (* fills words: []I32 *)
1972-RcBytes.wipe(BYTES(c)); (* c: Ctx, all of it *)
1973-```
1974-
1975-`T` must be a type a view may take (6.9): integers, reals, pointers,
1976-and records and arrays of these alone, the types for which any bytes
1977-are a value. So writing through the slice can make nothing mean
1978-nothing, which is why a `BOOL`, a set, an enumeration, a slice, a
1979-variant or a procedure, or a record holding one, is an error. The
1980-slice is checked as any slice is; its length comes from the type, not
1981-from the program. A variable given to `BYTES` follows the rules for a
1982-slice of it: a local's bytes can't be returned (7.3); a `const`
1983-parameter, a view and a volatile variable are errors, as `ADR` of them
1984-is; a string constant is an error, as writing its bytes isn't defined.
1985-The bytes are in the target's order (appendix A), as a view's are.
1986-
1987-It is `PTR` and `SIZE` made one checked expression, about 30 lines in
1988-the compiler. It breaks nothing. With "Filling bytes: `Bytes.fill`", below, an array
1989-of words is zeroed as `Bytes.fill(BYTES(a), 0)`.
1990-
1991-Met in raudio, surco and rcrypto.
1992-
1993-**Recommendation:** take; it replaces an unchecked pointer and a
1994-hand-written length with one checked expression.
1995-
1996-## Filling: `FILL(d, x)`
1997-
1998-**Status.** Approved by the owner on 2026-10-23, with the twelfth thaw. In the report, 2026-10.36 (6.8), and in the compiler (2026-10-23): `rep stos` of the element's width, a loop of stores for a short run, or a record copied forward.
1999-
2000-`COPY` copies and `NEW` zeroes, but nothing sets the elements of an
2001-array or a slice already in hand. rttf clears each glyph's raster a
2002-byte at a time (`clear`), its `Pgm` the same for an image, a
2003-`Buf.spare` slice is cleared by a loop, and raudio zeroes a `[576]F32`
2004-with a loop or a helper. Pascal has `FillChar`, C `memset`.
2005-
2006-rat fills with a value that isn't zero, on its hottest path: each
2007-pixel row of a cell's background is `U32` pixels of the cell's colour,
2008-some 4 million pixels for a full redraw of a 3440 by 1440 window. The
2009-loop for it was most of `Draw.paint`'s time, itself 81 per cent of
2010-rat's on full redraws, as its counter had lost its register to
2011-`paint`'s busier variables; moved into a procedure of its own it has
2012-one, and rat's time on full redraws fell by 30 per cent. Even then a fill does better:
2013-libc's `wmemset`, against the loop with its counter in a register,
2014-fills runs of 10 `U32`s in 0.6 of the time, and of 4 million in a
2015-third. A `Bytes.fill(s: []U8; b: U8)`, as this proposal first was,
2016-can't serve it: a colour's four bytes differ.
2017-
2018-The proposal: one built-in procedure, a statement, as `COPY` is.
2019-
2020-| Call | Result |
2021-|---|---|
2022-| `FILL(d, x)` | sets every element of `d`, an array or a slice of elements of type `T`, to `x`, a value of `T` |
2023-
2024-```
2025-FILL(w^.band[row..row + w^.cellW], U32(l.bg)); (* a row of pixels *)
2026-FILL(window, 0.0); (* window: [576]F32 *)
2027-FILL(raster, 0); (* raster: []U8 *)
2028-```
2029-
2030-`d` is written as `COPY`'s destination is, and `x` is assigned to each
2031-element as by `:=`. An element of one, two, four or eight bytes is
2032-stored with `rep stos` of that width, or with moves when there are
2033-few, as `zeroBytes` does; any other is stored once and copied forward
2034-from there. A zero of any type is `rep stosb`, as `NEW`'s zeroing is.
2035-
2036-It breaks nothing, and leaves `Bytes.fill` out: a slice of bytes is
2037-filled as any other. It is not a wipe: an optimizer may leave out a
2038-fill that nothing reads after, as it may any write (7.6). Its size in
2039-the compiler is not yet measured.
2040-
2041-Met in rttf, raudio and rat.
2042-
2043-**Recommendation:** take; one statement for a loop every buffer-handling
2044-program writes, as fast as the machine fills, for any element type.
2045-
2046-## `COPY` forwards unless it must go back
2047-
2048-**Status.** Approved by the owner on 2026-10-23 and implemented in `Gen.copySlice`: backwards only when the destination starts inside the source, and then by words; up copies 8 to 25 times faster.
2049-
2050-`COPY` is right when its two sides overlap (6.8), and the compiler
2051-makes it so by copying backwards whenever the destination is above
2052-the source (`Gen.copySlice`): `std`, `rep movsb` down from the last
2053-byte, `cld`. That is right, but it goes backwards for every copy to a
2054-higher address, overlapping or not, and a backward `rep movsb` gets
2055-none of the processor's fast copying: it moves a byte at a time. Ten
2056-million copies between the two halves of one `[4096]U32`, never
2057-overlapping:
2058-
2059-| Elements | Down | Up |
2060-|---|---|---|
2061-| 10 `U32`s | 66 ms | 510 ms |
2062-| 1000 `U32`s | 390 ms | 9,800 ms |
2063-
2064-rat meets it drawing a scaled font: each pixel row of a cell is copied
2065-to the rows under it, a higher address in the same image, for every
2066-cell drawn.
2067-
2068-The proposal, the compiler's alone, as the report already says what
2069-`COPY` does: copy backwards only when the destination starts inside
2070-the source (`rsi < rdi < rsi + rcx`, one more comparison), and
2071-forwards otherwise. A backward copy that must be made could go by
2072-words, eight bytes at a time down to the last few, rather than by
2073-`rep movsb`.
2074-
2075-It breaks nothing: no program can tell, but by its time.
2076-
2077-Met in rat.
2078-
2079-**Recommendation:** take; one comparison in `copySlice` for a copy up
2080-to eight times faster at ten elements and twenty-five at a thousand.
2081-
2082-## A slice of a `const` parameter, returned
2083-
2084-**Status.** Approved by the owner on 2026-10-23, with the twelfth thaw. In the report, 2026-10.36 (7.3), which the compiler already did; a conformance test holds it.
2085-
2086-7.3 says a slice of a `var` parameter, of a module variable, or of
2087-what a pointer points at may be returned, and says nothing of a
2088-`const` one. rimap's `proc sectionOf(const p: Part): []U8; begin
2089-return p.section[0..p.sectionLen]; end;` compiles and works, but the
2090-report doesn't promise it, so rimap leaves its callers to slice the
2091-field themselves.
2092-
2093-A `const` parameter is the caller's variable read in place (8), as a
2094-`var` one is, so its slice is the caller's, not this procedure's
2095-frame. When the argument isn't a variable it is a temporary of the
2096-caller's statement, and a slice of it kept past that statement is
2097-already the exception of section 10. The rule only has to say so.
2098-
2099-The proposal, 7.3's sentence:
2100-
2101-> A slice of a `var` or `const` parameter, of a module variable, or of
2102-> what a pointer points at may be returned: none of them is this
2103-> procedure's frame. For a `const` parameter given a temporary, the
2104-> slice lives to the end of the caller's statement (section 8).
2105-
2106-Only the report changes; the compiler already accepts it. It breaks
2107-nothing. Whether the caller may write through the slice it gets back
2108-is the question of "A slice that can't be written: `[]const T`", which
2109-this doesn't settle.
2110-
2111-Met in rimap.
2112-
2113-**Recommendation:** take; a sentence promises what the compiler already
2114-does.
2115-
2116-## What wiping can't reach, said in appendix A
2117-
2118-**Status.** Approved by the owner on 2026-10-23, with the twelfth thaw. In the report, 2026-10.36 (appendix A); no code.
2119-
2120-A wipe through `^VOLATILE U8` is never left out (7.6), but it writes
2121-only what the program can name. A spilled register, a statement's
2122-temporary, a value parameter's copy and an array a call returned are
2123-the compiler's, and stay in memory after the procedure returns, until
2124-something else writes there. rcrypto found that its wipes can't reach
2125-them, and nothing in the report says they exist. C has the same limit
2126-and says nothing either; OpenSSL's `OPENSSL_cleanse`, which rnet's
2127-`Tls.wipe` calls, wipes only what it is given.
2128-
2129-The proposal: a paragraph in appendix A, among what an implementation
2130-says of itself, and no feature.
2131-
2132-> **Copies.** A procedure's frame may hold copies of its variables
2133-> that the program can't name: registers saved to it, temporaries of
2134-> its statements, its value parameters, and arrays its calls return.
2135-> This implementation leaves them where they are when the procedure
2136-> returns; they last until the stack is used again. A wipe (7.6)
2137-> reaches only the variables it is given. A secret is best kept in
2138-> one variable, passed by `var` or `const` or by pointer, never by
2139-> value, and wiped there.
2140-
2141-Zeroing a frame on return, by a word on the procedure or a flag, was
2142-weighed and left: it costs every call of such a procedure a write of
2143-its frame, and still misses registers and the kernel's copies of a
2144-thread's state. It breaks nothing.
2145-
2146-Met in rcrypto.
2147-
2148-**Recommendation:** take; a paragraph says a limit every program that
2149-wipes must know.
2150-
2151-## Sys for files and memory
2152-
2153-**Status.** Approved by the owner on 2026-10-23 and implemented in both backends, all items: `mapRead`, `protect`, and `open`, `openMode`, `openRead`, `create` and `openDir` closing on exec, with `keepOnExec(fd, true)` to keep one.
2154-
2155-Library growth, but the last item changes what `open` does, so it
2156-needs the owner's word on whether that counts as breaking. Each item
2157-stands alone; each is in both `Sys.raz` (the C library) and
2158-`Sys.linux-x86_64.raz` (system calls).
2159-
2160-- **A file mapped to be read.** `mapFile` maps to read and write,
2161- shared, so a file opened only to read (a dictionary that isn't the
2162- user's to write) can't be mapped: `mmap` fails with EACCES. znaczy
2163- makes the system call itself in a `Zmap.linux.raz` (30 lines), and
2164- raudio's Inmem does the same.
2165-
2166- (* The first size bytes of the file fd, which may be open only to
2167- read, mapped to be read only: writing there stops the program.
2168- nil if it can't be; munmap gives them back. *)
2169- proc mapRead*(fd, size: INT): ^U8;
2170-
2171- C's `mmap` with `PROT_READ` and `MAP_PRIVATE`; system call 9 with
2172- the same. Met in znaczy, raudio. **Recommendation:** take, two
2173- programs carry a Linux-only file for it.
2174-
2175-- **Memory that can't be touched.** A test that puts its input against
2176- a guard page, so that a read one byte out of range stops it, calls
2177- `SYSCALL(10, ...)` itself and is tied to Linux; raudio's Inmem grows
2178- a large mapping readable a step at a time, so that the bytes never
2179- move.
2180-
2181- (* Lets the pages from p, size bytes from a page boundary, be read
2182- and written as read and write say; neither, and touching them
2183- stops the program. 0, or minus an errno. *)
2184- proc protect*(p: ^U8; size: INT; read, write: BOOL): INT;
2185-
2186- C's `mprotect`; system call 10. With `mmap` it serves raudio's
2187- reserve too: map the most it will hold, `protect` it all to neither,
2188- and open it as it fills. Met in rttf, raudio. **Recommendation:**
2189- take, the one portable way to a guard page.
2190-
2191-- **Files closed in a program exec starts.** `pipe`, sockets and
2192- `memFile` are closed across `exec`; a file `open` gives is not, so a
2193- fifo mosaico holds reaches every program it starts, unasked, and it
2194- calls `keepOnExec(fd, false)` after each open. `openMode`, `open`,
2195- `openRead` and `create` would pass `O_CLOEXEC`, and their comments
2196- say "closed in a program exec starts" as `pipe`'s does;
2197- `keepOnExec(fd, true)` keeps one open. `spawn`'s `fds` are unchanged,
2198- since `dup2` in the child clears the flag. This makes the
2199- `closeOnExec` access in "Sys for a server" unneeded (`nonblocking`
2200- stays). A program that hands an opened file to an exec'd one by its
2201- number, without `fds`, must then say `keepOnExec`. Met in mosaico.
2202- **Recommendation:** take, one rule for every descriptor Sys makes.
2203-
2204-## Files: what programs write over Sys
2205-
2206-**Status.** Approved by the owner on 2026-10-22 and implemented in `lib/Files.raz`, all three; `Files.write` is written over `writeAll`.
2207-
2208-Library growth that breaks no program. Each is portable, written in
2209-`Files.raz` over procedures `Sys` already has, so neither backend nor
2210-Moss's `Sys` grows.
2211-
2212-- **Writing all of it.** A `write` may be short (a pipe, a socket) or
2213- broken by a signal, and each program carries its loop; `Files.write`
2214- has one, but only for a whole file it creates.
2215-
2216- (* Writes all of s to fd, again after a short write or a signal:
2217- 0, or minus the errno of the write that failed. *)
2218- proc writeAll*(fd: INT; s: []U8): INT;
2219-
2220- `Files.write` is then written over it. Met in surco (Sjournal), and
2221- the loop is in most programs that write to a pipe.
2222- **Recommendation:** take, the loop every writer to a pipe needs.
2223-
2224-- **A path made absolute and plain.** surco makes `-r` and a playlist
2225- absolute with an `extern` to C's `realpath(3)`; dwa's
2226- `Docs.canonical` does `setWorkDir`, `workDir` and `setWorkDir` back,
2227- which is wrong with threads.
2228-
2229- (* Adds to b the absolute path of the file at path, with no ".",
2230- "..", or symbolic link in it: 0, or minus an errno (-2, ENOENT,
2231- if a part of it isn't there). *)
2232- proc realPath*(path: []U8; var b: Buf.Buf): INT;
2233-
2234- About 40 lines over `workDir`, `linkInfo` and `readLink`, with a
2235- bound on links followed (-40, ELOOP). Met in surco, dwa.
2236- **Recommendation:** take, two programs and the workaround is wrong.
2237-
2238-- **Removing a tree.** A sauce clone cut short leaves
2239- `<dir>.sauce-clone`, since removing a tree is a walk of `openDir`,
2240- `remove` and `removeDir`; a test that makes a directory to work in
2241- has the same walk to clean up.
2242-
2243- (* Removes the file at path and, if it is a directory, all within
2244- it, without following a symbolic link: 0, or minus the first
2245- errno. *)
2246- proc removeTree*(path: []U8): INT;
2247-
2248- Over `openDir`, `entryKind`, `linkInfo`, `remove` and `removeDir`,
2249- about 30 lines. Met in sauce. **Recommendation:** take, easy to get
2250- wrong (a link to a directory followed) and wanted by every test with
2251- a scratch directory.
2252-
2253-## Sys for signals and the process
2254-
2255-**Status.** Approved by the owner on 2026-10-23 and implemented in both `Sys` backends and `Rt`, all four: `ignored`, `findEnv` (which `env` is written over), `processors` and `Rt.exitStatus`.
2256-
2257-Library growth that breaks no program. The first three are in both
2258-`Sys` backends; the last is in `Rt`.
2259-
2260-- **Whether a signal is ignored.** A program started in the
2261- background or under `nohup` starts with some signals ignored, and
2262- should leave those alone, as a shell does, rather than `handle` or
2263- `catch` them. `handle` and `ignore` don't say what was there, so
2264- robbie asks the kernel through `rt_sigaction` in an `Rsig.linux.raz`.
2265-
2266- (* Whether the signal sig does nothing now, as ignore(sig, true)
2267- or the program that started this one left it. *)
2268- proc ignored*(sig: INT): BOOL;
2269-
2270- C's `sigaction` with no new action; system call 13 the same.
2271- Independent of `keepIgnored` in "Sys for running a program", which is
2272- about the child. Met in robbie. **Recommendation:** take, any
2273- program that takes SIGINT or SIGHUP should ask it first.
2274-
2275-- **An environment variable unset or empty.** `env` gives `""` for
2276- both, but `TZ` unset means `/etc/localtime` and `TZ=` means UTC, so
2277- alba and rzone walk `envAt` themselves.
2278-
2279- (* The value of the environment variable name and true, or "" and
2280- false if it isn't set. *)
2281- proc findEnv*(name: []U8): ([]U8, BOOL);
2282-
2283- `env` stays, written over it. Met in alba, rzone, surco.
2284- **Recommendation:** take, three programs walk `envAt` for it.
2285-
2286-- **How many processors.** `raztest -j` would default to it, as
2287- `make -j$(nproc)` does, and defaults to 1; rayo makes
2288- `SYSCALL(204)` itself.
2289-
2290- (* The number of processors this program may run on, at least 1. *)
2291- proc processors*: INT;
2292-
2293- C's `sched_getaffinity` and `CPU_COUNT`; system call 204, counting
2294- the bits. Moss's gives 1. Met in raztest, rayo.
2295- **Recommendation:** take, two programs and no portable way without it.
2296-
2297-- **How the program ends, for `atExit`.** A procedure `Rt.atExit`
2298- registered can't tell an end by `exit(0)` from a failed check or
2299- `Rt.stop`, so surco's log can't note a crash.
2300-
2301- (* The status exit was given, while the procedures atExit
2302- registered run; 0 before. *)
2303- proc exitStatus*: INT;
2304-
2305- `Rt.exit` sets it before running them. A failed check and `stop`
2306- both end with 2, which is enough to note a crash. Met in surco.
2307- **Recommendation:** take, three lines and nothing else can say it.
2308-
2309-## Numbers in the library
2310-
2311-**Status.** Approved in part by the owner (2026-10-22 and 23) and implemented: `Str.toU64`, `Math.tanh`, `Math.roundEven`, `Fmt.short` and `Fmt` writing `E`. `ABS`, `min`, `max` and `clamp` wait.
2312-
2313-### An unsigned decimal reader: `Str.toU64`
2314-
2315-Library growth that breaks no program. `Str.toInt` stops at the largest
2316-`I64`, so a `U64` written by `Fmt.uint`, such as a `Rand.seed` read back
2317-from `$PROP_SEED`, needs a loop of its own (raz's own `Prop.decimal`).
2318-`toHex` already gives a `U64`; decimal should too:
2319-
2320- (* s as a decimal number, digits only; false if it isn't one, or a
2321- U64 can't hold it. *)
2322- proc toU64*(s: []U8): (U64, BOOL);
2323-
2324-No sign: a `-` is no `U64`, and a `+` nobody writes. `Opt.number`
2325-stays on `toInt`.
2326-
2327-Met in raz's `Prop`.
2328-
2329-**Recommendation:** take; it is the reader for what `Fmt.uint` writes.
2330-
2331-### `ABS`, and `min`, `max` and `clamp` of integers
2332-
2333-**Status.** `ABS` approved by the owner on 2026-10-23, with the twelfth thaw, and in the report, 2026-10.36 (6.1 and 6.8); and in the compiler (2026-10-23): `neg` and `cmovs` for a signed integer, the sign bit cleared for a real. `min`, `max` and `clamp` dropped (owner, 2026-10-23): a two-line `if` each.
2334-
2335-Library and language growth that breaks no program. `Math` is `F64`
2336-only and there are no built-ins, so rat writes `min` and `max` in Draw,
2337-Font, Layout and Shapes, `abs` in Shapes and `clamp` in Rat; raudio's
2338-Tags and rabble's Remote the same; mgla and fraco each write a 4-line
2339-`abs` of an `F64`.
2340-
2341-The proposal, in two parts. A built-in, as Oberon has it, for every
2342-numeric type, since one name serves integers and reals and no
2343-procedure can:
2344-
2345-| Call | Result |
2346-|---|---|
2347-| `ABS(x)` | `x` without its sign, of `x`'s type; for an integer, `-x` if `x < 0`, so the smallest `I64` gives itself, as `-x` does |
2348-
2349-And three procedures in `Math`, of `INT`, the type that indexes and
2350-counts:
2351-
2352- (* The smaller of a and b. *)
2353- proc min*(a, b: INT): INT;
2354- (* The larger of a and b. *)
2355- proc max*(a, b: INT): INT;
2356- (* x, or lo if it is below lo, or hi if it is above hi. *)
2357- proc clamp*(x, lo, hi: INT): INT;
2358-
2359-`MIN` and `MAX` are taken for a type's limits ("The limits of an
2360-integer type"), so these are lower-case procedures, not built-ins.
2361-`Math`'s opening line then says "and `min`, `max` and `clamp` of
2362-`INT`". Left out: the same of `F64`, which no program asked for.
2363-
2364-Open: `ABS` touches the report (6.8's table), so it may move to
2365-the language proposals, beside `MIN(T)` and `MAX(T)`.
2366-
2367-Met in rat, raudio, rabble, mgla, fraco.
2368-
2369-**Recommendation:** take; five programs write the same four lines.
2370-
2371-### `Math.tanh`
2372-
2373-Library growth that breaks no program. `Math`'s header leaves the
2374-hyperbolic functions out "until a program needs them"; mgla soft-clips
2375-its mix with tanh, written `1 - 2/(exp(2x)+1)`, which loses every digit
2376-near 0.
2377-
2378- (* The hyperbolic tangent of x, from -1 to 1. *)
2379- proc tanh*(x: F64): F64;
2380-
2381-fdlibm's, over a private `expm1` (which `Math.pow` and `exp` already
2382-come close to). `sinh` and `cosh` stay left out, as the header says,
2383-until a program needs them.
2384-
2385-Met in mgla.
2386-
2387-**Recommendation:** take; the header's own rule says when, and mgla is it.
2388-
2389-### Rounding a half to even: `Math.roundEven`
2390-
2391-Library growth that breaks no program. `Math.round` takes a half away
2392-from 0, as C's `round` does: `round(2.5)` is 3.0. Pascal's `Round`, and
2393-IEEE 754's default, take it to the even one, 2.0, and a program that
2394-must give Pascal's numbers (alba's, raudio's `Sbr`) writes its own,
2395-where the case of `x + 0.5` rounding up is easy to get wrong.
2396-
2397- (* The whole number nearest x; a half to the even one, as IEEE 754's
2398- default and Pascal's Round have it. *)
2399- proc roundEven*(x: F64): F64;
2400-
2401-Met in alba and raudio.
2402-
2403-**Recommendation:** take; two programs, and the edge cases are subtle.
2404-
2405-### The fewest digits that read back: `Fmt.short`
2406-
2407-Library growth that breaks no program. `Fmt.real(x, places)` writes a
2408-fixed number of places; nothing writes a real as briefly as it can be
2409-written and still read back as itself. arkusz carries 150 lines for it
2410-(`Afmt`: base-10^9 big numbers, and the halves to the neighbouring
2411-`F64`s); fraco writes its own decimals for a deep zoom's centre, which
2412-needs up to 17 places; alba prints coordinates.
2413-
2414-A case of `Arg`:
2415-
2416- (* r in the fewest digits that Math.toReal reads back as r; with an
2417- exponent below 1E-4 and from 1E15 on, as real writes one. *)
2418- short(r: F64);
2419-
2420-The result is unique (Steele and White; Ryu's answer). It costs a
2421-correctly rounded conversion, so about arkusz's 150 lines, moved into
2422-`Fmt`; `Fmt.real` keeps its own fast path.
2423-
2424-Left out: arkusz's exact 17-digit expansion (`sci(x, digits)`), which
2425-`short` makes unneeded for the round trip, and rounding the 17-digit
2426-text again as Pascal's `Str` does, which gives `45.1603` for
2427-`Fmt.real(45.16025, 4)` where the binary value, below the half, gives
2428-`45.1602`: that is Pascal's double rounding, not a fault in `Fmt`.
2429-
2430-Met in alba, arkusz and fraco.
2431-
2432-**Recommendation:** take; three programs, and the hard part is the
2433-library's to do once.
2434-
2435-### One exponent letter: `Fmt` writes `E`
2436-
2437-**Status.** Approved by the owner on 2026-10-22 and implemented in `lib/Fmt.raz`.
2438-
2439-A change to output. `Fmt.real` writes `1.50e17`; the language reads a
2440-real's exponent as `E` only (report section 2), so a value a program
2441-prints can't be pasted into code (rayo). `Math.toReal` reads both.
2442-
2443-The proposal: `Fmt` writes `E`, as the report's own numbers are
2444-written, `1.50E17`. Reading `e` in the compiler instead would add a
2445-spelling to the report. A test that compares printed exponents changes
2446-by one letter; raz's own `Fmt` test is one.
2447-
2448-This settles the open question in "A width in `Fmt`".
2449-
2450-Met in rayo.
2451-
2452-**Recommendation:** take; one letter for the language and its library.
2453-
2454-## Memory, Buf and Vec
2455-
2456-**Status.** Proposed 2026-10-22, collated from RAZ-GAPS.md.
2457-
2458-### An allocator that stops when memory runs out: `Heap.sure`
2459-
2460-**Status.** Approved by the owner on 2026-10-22 and implemented in `lib/Heap.raz`.
2461-
2462-Library growth that breaks no program. `Buf` and `Vec` stop the program
2463-when the allocator has no room; `NEW(p, Heap.heap)` and `Mem.alloc`
2464-give `nil`, so rat checks and stops in about a dozen places. A
2465-procedure that allocates or stops can't be written for every `T`, but
2466-an allocator can, and `NEW` is already generic:
2467-
2468- (* The heap, but running out of memory stops the program, as
2469- Buf.add does, instead of giving nil: for NEW where nil would be
2470- a bug nobody checks for. *)
2471- sure*: ^Mem.Allocator;
2472-
2473-`NEW(p, Heap.sure)` then gives a `p` or stops, with `Rt.trace`. Its
2474-`free` is the heap's. Ten lines, and nothing new to learn.
2475-
2476-Met in rat.
2477-
2478-**Recommendation:** take; one variable makes every `NEW` safe without a
2479-check at each.
2480-
2481-### Freeing back to a mark: `Arena.mark` and `Arena.release`
2482-
2483-**Status.** Approved by the owner on 2026-10-23 and implemented in `lib/Arena.raz`.
2484-
2485-Library growth that breaks no program. `Arena` frees only everything at
2486-once, so fdn's recursive walk, which makes a few strings per entry,
2487-gives each back to the heap by hand. An arena that goes back to where
2488-it stood gives one line per level:
2489-
2490- (* Where ar stands now, for release. *)
2491- proc mark*(const ar: Arena): INT;
2492-
2493- (* Everything allocated from ar since mark m freed at once; a mark
2494- past where it stands stops the program. *)
2495- proc release*(var ar: Arena; m: INT);
2496-
2497-A mark is the arena's `used`, so each is a line. `reset` is
2498-`release(ar, 0)`, and stays for its name.
2499-
2500-Met in fdn.
2501-
2502-**Recommendation:** take; two lines in `Arena` replace a free per string.
2503-
2504-### Inserting and removing in the middle of a `Vec`
2505-
2506-**Status.** Approved by the owner on 2026-10-23 and implemented in `lib/Vec.raz`.
2507-
2508-Library growth that breaks no program. dwa's edit takes lines out and
2509-puts others in by resizing around a `COPY` by hand, twice, where the
2510-overlapping copy's direction is the thing to get wrong.
2511-
2512- (* n zero elements opened at i, those from i on moved up; i from 0
2513- to v.len. Stops the program, as push does, if there is no room. *)
2514- proc insert*(var v: Vec; i, n: INT);
2515-
2516- (* The n elements from i taken out, those after them moved down;
2517- i + n at most v.len. *)
2518- proc remove*(var v: Vec; i, n: INT);
2519-
2520-`insert` gives zeros, as `add` and `resize` do, for the caller to fill
2521-in `all(v)[i..i + n]`. Left out: a `tryInsert`, until a program wants
2522-one.
2523-
2524-Met in dwa; any editor's lines, and a list kept in order, want it.
2525-
2526-**Recommendation:** take; it is the one `Vec` operation that is easy to
2527-get wrong by hand.
2528-
2529-## Strings, base64 and text for C
2530-
2531-**Status.** Approved by the owner on 2026-10-23 and implemented in `lib/Str.raz` and `lib/Fmt.raz`: `fromC`, `toC`, `base64With` and `unbase64With` with `Base64` and `Base64Url`, and `Fmt.into`.
2532-
2533-### A slice of a C string, and a C string of a slice
2534-
2535-Library growth that breaks no program. C gives a `^U8` ending in a zero
2536-byte (an X resource's value, a class hint's name), which awizo counts
2537-by hand to make a `[]U8`. The other way, a path for C's `open` or
2538-`realpath` must be followed by a zero, which callers copy into a
2539-`[PathMax + 1]U8` by hand.
2540-
2541- (* The bytes at p up to its zero byte, not copied; "" for nil. *)
2542- proc fromC*(p: ^U8): []U8;
2543-
2544- (* s copied into out with a zero byte after it, for C: out holds
2545- LEN(s) + 1 bytes at least. *)
2546- proc toC*(s, out: []U8): ^U8;
2547-
2548-`toC` gives `PTR(out)`, so the call reads as what C is given:
2549-`C.realpath(Str.toC(path, room), ...)`. `out` too short stops the
2550-program, as a slice does. Left out: a `CStr` type, which would say in
2551-a signature that a zero follows; that is a language question, and
2552-`Sys` takes `[]U8` already.
2553-
2554-Met in awizo and surco; every binding to a C library meets both.
2555-
2556-**Recommendation:** take; the two ends of every C call that takes or
2557-gives text.
2558-
2559-### Base64 in another alphabet, unpadded
2560-
2561-Library growth that breaks no program. `Str.base64` has RFC 4648's
2562-section 4 alphabet, padded. Section 5's, `-` and `_` and no padding, is
2563-PKCE's and JWTs', and IMAP's modified UTF-7 is `,` for `/`, unpadded:
2564-roauth carries 13 lines over `Str.base64`, rimap 40 of hand-packed
2565-6-bit letters. "Base64 in `Str`" left this out until a program needed
2566-it; two do.
2567-
2568- const
2569- (* The alphabets of RFC 4648, sections 4 and 5. *)
2570- Base64* = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2571- Base64Url* = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
2572-
2573- (* s in base64 with the 64 letters of alphabet into out, which
2574- holds base64Size(LEN(s)) bytes at least, padded with = if pad:
2575- the bytes written. *)
2576- proc base64With*(s, out, alphabet: []U8; pad: BOOL): INT;
2577-
2578- (* s decoded as base64With wrote it, into out, which holds
2579- (LEN(s) + 3) div 4 * 3 bytes at least: the bytes written; false
2580- as unbase64 says, or, without pad, for a length that leaves one
2581- letter over. *)
2582- proc unbase64With*(s, out, alphabet: []U8; pad: BOOL): (INT, BOOL);
2583-
2584-`base64` and `unbase64` become `base64With(s, out, Str.Base64, true)`
2585-and stay, for the common case. rimap passes its own alphabet.
2586-
2587-Met in roauth and rimap.
2588-
2589-**Recommendation:** take; two programs, and the existing proposal named
2590-this as the way to grow.
2591-
2592-### Formatting into a caller's slice: `Fmt.into`
2593-
2594-Library growth that breaks no program. `Fmt.write` goes only to a
2595-`Buf`, which needs an allocator, so a library with no heap (rxml, for
2596-"... on line 12"; rttf and magma are the same kind) joins pieces by
2597-hand with `Str.fromInt`. `Buf` says the core has no heap to assume;
2598-`Fmt` should then work without one.
2599-
2600- (* f formatted into out as write formats it: the bytes written, and
2601- false if out was too short and the text is cut there. *)
2602- proc into*(out: []U8; f: []U8; args: []Arg): (INT, BOOL);
2603-
2604-Cut short, not stopped: the length of formatted text isn't known
2605-before, as base64's is. Inside, `put` writes to a target that is a
2606-`Buf`, a slice, or standard output, in place of today's `^Buf.Buf` or
2607-`nil`.
2608-
2609-Met in rxml.
2610-
2611-**Recommendation:** take; it makes `Fmt` usable in the no-heap core
2612-`Buf` itself is written for.
2613-
2614-## `Opt`
2615-
2616-**Status.** Approved by the owner on 2026-10-23 and implemented in `lib/Opt.raz`, both.
2617-
2618-### A negative number as an operand
2619-
2620-A change to what `Opt` reads, for scopes it can't hurt. `alba -33.87
2621-151.21` is "unknown option -3", and `--` changes the command line the
2622-user types, so alba reads its arguments by hand and loses `Opt`'s help
2623-and mistakes.
2624-
2625-The proposal: in a scope with no option whose letter is a digit, a
2626-word of a `-` and then a digit is an operand, and so ends the options
2627-as any operand does. A scope that gives a digit a letter (`head -5`
2628-style) reads it as today. No new procedure; the library volume's list
2629-of rules gains a line.
2630-
2631-Met in alba.
2632-
2633-**Recommendation:** take; one rule, no interface, and it lets a numeric
2634-program keep `Opt`.
2635-
2636-### A mistake in the operands, with the synopsis: `Opt.misuse`
2637-
2638-Library growth that breaks no program. `Opt.fail` writes the program's
2639-sentence alone, for "no command; see keep -h". The one that adds the
2640-synopsis lines, as `Opt`'s own mistakes and `refuse` do, is the private
2641-`mistake`, so raztest's "no tests named", a mistake in the operands,
2642-comes without the usage a user needs.
2643-
2644- (* The program's own mistake, written as Opt's are, with the
2645- scope's synopsis lines after it, and status 2. *)
2646- proc misuse*(const p: Parser; text: []U8);
2647-
2648-It is `mistake` with `text` as its one argument. A flag on `fail`
2649-would read worse at the call.
2650-
2651-Met in raztest.
2652-
2653-**Recommendation:** take; three lines, and no workaround without
2654-copying the table's synopsis by hand.
2655-
2656-## A freestanding program, stated
2657-
2658-**Status.** Proposed 2026-10-22, collated from RAZ-GAPS.md.
2659-
2660-"For a kernel: three changes to the compiler" made a raz program run on
2661-the bare machine; Moss, a kernel in raz, now boots on it. What it found
2662-is less a missing feature than missing words: what a `-bare` program
2663-must give the compiler, and what it may count on, are known only by
2664-reading `Gen.entryPoint` and `Raz`. Five items, each standing alone.
2665-The sixth thing Moss met, `jmp rax` read as a jump to a label, was a
2666-bug, fixed in ac3c464.
2667-
2668-**1. The runtime ABI, written down.** A section of `doc/compiler.md`,
2669-"A program with its own `Rt`", saying what the compiler asks of `Rt`
2670-and what a program's start may count on:
2671-- **Required:** `proc exit*(status: INT);`, which never returns (the
2672- compiler puts `ud2` after its call), and
2673- `proc fail*(what, a, b, len: INT; at: UINT; name: ^U8; rdi, rsi: UINT);`,
2674- with the kinds of `what` as `lib/Rt.raz` gives them (0 an index, 1 a
2675- slice, 2 an enumeration, 3 a backward slice of a pointer, 4 a nil
2676- pointer, 5 a division by zero, 6 a stack overflow, 7 a view), named
2677- constants in the text, not bare numbers.
2678-- **Optional, found by name when declared:** `places`, `calls`,
2679- `teller`, `place`, `placer` (item 5), `startProfile` and `profiler`
2680- (never under `-bare`), `cExit` (only with C, which `-bare` refuses).
2681-- **The entry:** `_start` runs every used module's body but `Rt`'s,
2682- then `main`. Under `-bare` it reads nothing from the stack and aligns
2683- nothing: the loader or boot stub enters it with the bss zeroed and
2684- `rsp` a multiple of 16, as Linux does.
2685-- **`main` returning:** allowed. `Rt.exit` is then called with `main`'s
2686- result, or 0 for `proc main*`.
2687-- **The panic hook:** `Rt.fail` is it. A kernel's `fail` prints and
2688- halts; nothing else is needed, and no second hook is proposed.
2689-
2690-A test holds it: `test/run/` builds a `-bare` program against a
2691-smallest `Rt` of `exit` and `fail` alone, run under Linux, whose
2692-`exit` and `fail` make the system call themselves.
2693-
2694-Met in Moss (`docs/raz-findings.md` §2), which copied the stock
2695-signatures.
2696-
2697-**Recommendation:** take; it is words and one test, and the contract
2698-already exists.
2699-
2700-**2. A recipe for an interrupt's entry.** Before any attribute or
2701-generated stub, a tested recipe in `doc/compiler.md`, beside item 1,
2702-stating what the compiler's code may assume and so what a stub must
2703-restore:
2704-- **What the compiler's code uses:** System V's caller-saved
2705- registers, `rax`, `rcx`, `rdx`, `rsi`, `rdi`, `r8` to `r11`, all of
2706- `xmm0` to `xmm15`, and the flags; the direction flag is clear at
2707- every call (the compiler's copies use `std` and `cld` and leave it
2708- clear).
2709-- **The red zone:** whether the compiler ever writes below `rsp`. Not
2710- checked today ("For a kernel" leaves it open); it is to be checked
2711- and the answer written down. If it never does, an interrupt needs no
2712- IST stack for that reason.
2713-- **The stub:** a `code` procedure per vector that pushes 0 where the
2714- CPU pushes no error code, pushes the vector, saves the caller-saved
2715- registers, aligns `rsp` to 16, saves the SSE state (`fxsave` or
2716- `xsave` to an aligned area), `cld`, calls an ordinary procedure
2717- `proc handle(vector, code: INT; frame: ^Frame)`, restores, drops the
2718- two words and `iretq`.
2719-
2720-It is testable on Linux: `iretq` from ring 3 to ring 3 is allowed, so
2721-`test/run/Interrupt.raz` builds a frame by hand, jumps to the stub, has
2722-the handler compute with reals, and checks on return that every
2723-register the stub promised to keep is kept. The stub needs items 3 and
2724-"The assembler's instructions", 1 (`push` of a constant, `cld`).
2725-
2726-Met in Moss (`docs/raz-findings.md` §4): its handlers use only `rax`
2727-and make no call, which is safe but no recipe.
2728-
2729-**Recommendation:** take; a kernel's first stub is where the calling
2730-convention is easiest to get wrong, and a test on Linux keeps it right.
2731-
2732-**3. A code procedure names a procedure or a global.** In a code
2733-procedure, a name of the module's scope, or a qualified one, that is a
2734-procedure or a global variable stands for its address, as an operand
2735-of three forms only:
2736-
2737- call fault; (* a procedure, rip-relative *)
2738- jmp fault;
2739- lea rax, [ticks]; (* a procedure or a global *)
2740-
2741-Each makes a reference to that chunk, so the linker keeps what is
2742-named, as any call does. No other operand takes a name, and no type is
2743-checked: a code procedure is the target's, and its author already
2744-answers for the convention. The assembler gets the names as it gets
2745-constants, by a function the parser hands in beside `ConstFn`.
2746-
2747-Moss stores `UINT(fault)` in a slot at start and calls through a
2748-register (`docs/raz-findings.md` §5), so the slot must be filled
2749-before the first fault, which nothing checks.
2750-
2751-**Recommendation:** take; three operand forms remove a hand-off that
2752-can be forgotten, and the recipe in item 2 needs `call handle`.
2753-
2754-**4. A program brings its own `Rt`.** A `src/Rt.raz` beside the main
2755-module meets `lib/Rt.raz`, and "a program has one module of each name"
2756-refuses it, rightly. Moss copies the compiler beside an empty `lib/`.
2757-Two ways out:
2758-- **Staging,** as "The compiler on another host" proposes for the
2759- compiler's own sources: copy `raz` beside a library of the program's
2760- own. Nothing in raz changes; only words in `doc/compiler.md`. Every
2761- freestanding project then carries a copied compiler, and its library
2762- is all or nothing.
2763-- **`raz -lib DIR`:** the library is `DIR`, not the one beside the
2764- compiler. A kernel's `-lib` is a directory holding its own `Rt` and
2765- `Sys` and, by symbolic links, whichever of raz's modules it takes
2766- (`Str`, `Fmt`, `Buf`). The duplicate check stays as it is. On the
2767- `Host` branch it is one line over `Host.libraryDir`; today a few
2768- lines in `Raz.raz` and raz(1).
2769-
2770-The option is the smaller for its users and nearly as small in raz;
2771-staging stays the way for the compiler on another host, where the
2772-whole of `src/` is replaced anyway.
2773-
2774-**Recommendation:** take `-lib`; a few lines save every freestanding
2775-program a copy of the compiler.
2776-
2777-**5. Symbols without `Rt`'s places.** Without `-s` the compiler links
2778-`places`, `calls`, `teller`, `place` and `placer` and stops with "Rt
2779-has no places" where `Rt` lacks one, and `-noprofile` doesn't help, so
2780-Moss builds with `-s` and loses the symbol table a debugger reads.
2781-Two things are tied that needn't be: the ELF's symbols and lines, for
2782-a debugger, and the places, for `Rt` to say where a check failed.
2783-The change: each of the five is linked only when `Rt` declares it,
2784-`calls` with `teller` and `place` with `placer`, a pair or neither; `-s`
2785-still strips both. A kernel then keeps its symbols for GDB and gives
2786-`fail` the raw address, or declares `places` and decodes them itself.
2787-
2788-A hosted program's `Rt` is raz's, which declares all five, so no
2789-program changes. One that writes its own `Rt` and misspells `places`
2790-loses its places silently; item 1 lists the names.
2791-
2792-Met in Moss (`docs/raz-findings.md` §3).
2793-
2794-**Recommendation:** take; it is a test on each name in `Raz.raz` and
2795-gives a kernel its symbols back.
2796-
2797-## The assembler's instructions
2798-
2799-**Status.** Proposed 2026-10-22, collated from RAZ-GAPS.md.
2800-
2801-The report leaves which instructions the assembler knows to the
2802-implementation, and `db` gives any other. That stays. What is missing
2803-is a rule for when an instruction joins, and the few that programs
2804-have already written in `db`.
2805-
2806-**1. `push` of a constant, and `cld` and `std`.** `push imm8` and
2807-`push imm32` (6A, 68, sign-extended to 64 bits), and `cld` and `std`
2808-in `Plain`. The encoder already writes `cld` and `std` for the
2809-compiler's copies; only the assembler's table lacks them. Moss's
2810-exception stubs write all three with `db`, and every stub of
2811-"A freestanding program, stated", 2, needs them.
2812-
2813-**Recommendation:** take; three entries the encoder half has, and an
2814-interrupt stub can't be written without them.
2815-
2816-**2. When an instruction joins, and the SHA and shuffle ones now.**
2817-The rule, in `doc/compiler.md` beside the assembler: an instruction
2818-joins when a program writes it in `db`, it is a family's member the
2819-tables already hold (a code in `PackedOps`, an entry in `Plain`), and
2820-its bytes are checked against GNU `as` in `test/run/`, as
2821-`AsmKernel.raz` does. Anything else stays `db`, which is the permanent
2822-answer for an instruction no program uses twice. By that rule, now:
2823-- `paddd`, `punpcklqdq`, `punpckhqdq` into `PackedOps` (66 0F FE, 6C,
2824- 6D);
2825-- `pshufb` (66 0F 38 00) and `palignr` (66 0F 3A 0F, with a byte),
2826- two more forms, three-byte opcodes;
2827-- `sha256rnds2` (0F 38 CB, `xmm0` implied), `sha256msg1` (0F 38 CC),
2828- `sha256msg2` (0F 38 CD).
2829-
2830-Sauce's SHA-NI hash is 123 `db` lines assembled by GNU `as`, nothing
2831-checking a byte against its mnemonic; with these it is read as written.
2832-AES-NI, `pclmulqdq`, AVX and the rest wait for a program. (`movd` and
2833-`movq`, `pxor`, `pshufd`, `movdqu`, `movdqa`, `pmovmskb` are there
2834-already.)
2835-
2836-**Recommendation:** take; a rule stops the list growing by wish, and
2837-eight instructions turn sauce's 123 unchecked lines into checked ones.
2838-
2839-**3. `raz -S`'s listing, stated.** raz(1) gives the listing's form, so
2840-a tool may read it:
2841-- a blank line, then a procedure's name as `Module.name:`;
2842-- a source line: its number right-aligned in 6 columns, two spaces,
2843- the line's text;
2844-- an instruction: its offset in the procedure right-aligned in 14
2845- columns, two spaces, the instruction as the assembler would read it,
2846- a jump within the procedure giving its target as an offset.
2847-
2848-Only the main module's live procedures, in the order they were made;
2849-nothing is disassembled. A change to the form is then a change to the
2850-manual, and rcrypto's constant-time guard (`tools/branches.sh`), which
2851-counts conditional jumps by reading these three kinds of line, breaks
2852-loudly instead of silently. A test in raz holds the form against a
2853-small program's listing.
2854-
2855-**Recommendation:** take; it is a paragraph of raz(1) and one test,
2856-for a form that already doesn't change.
2857-
2858-## `Doc` for a library's pages
2859-
2860-**Status.** Approved by the owner on 2026-10-23 and implemented in `tools/Doc.raz`, both.
2861-
2862-`tools/Doc.raz` writes raz-lib(3) from `lib/`, and other libraries
2863-have started to use it for their own pages. Two changes let them.
2864-
2865-**1. A comment that heads a group of constants.** A comment just
2866-before `const`, `type` or `var`, on lines of its own, is the group's:
2867-`Doc` writes it once, before the group's declarations, as it writes a
2868-module's own comment, and each declaration keeps the comment just
2869-before it as now. Today `section` reads past the keyword and drops it
2870-(checked: each constant then shows alone), so mosaico's `Mxlib` has a
2871-comment line for each of its 237 constants where one before each group
2872-would halve the file. In mdoc the group's comment is filled text before
2873-the literal display; in plain text, the comment as written.
2874-
2875-**Recommendation:** take; a few lines in `section` keep a comment the
2876-standards already ask for.
2877-
2878-**2. `Doc man` writes the modules, not the page.** Today it writes
2879-raz-lib(3)'s `.Dd`, `.Dt`, NAME, DESCRIPTION and SEE ALSO, fixed in the
2880-tool, and a `Date` constant in `Doc.raz` dated by hand. The change:
2881-`Doc man Module.raz ...` writes only what is now between `.Sh MODULES`
2882-and `.Sh SEE ALSO`; raz's `Makefile` puts the head and tail around it
2883-from `doc/raz-lib.head` and `doc/raz-lib.tail` (or one file with a
2884-marker line), and the date lives with the page, not the tool. rcrypto's
2885-`tools/man3.sh`, which cuts Doc's page between the two `.Sh` lines and
2886-sets its own around it, then just wraps it, as raz does. Title, name
2887-and description from the command line were the other way; three
2888-options to replace two small files is the larger.
2889-
2890-**Recommendation:** take; it makes `Doc man` serve any library, and
2891-`Doc.raz` loses its fixed text and its date.
2892-
2893-## Left out
2894-
2895-What the collation of 2026-10-22 recommended leaving out, each with its
2896-reason; it is marked "Not planned" in `~/r/RAZ-GAPS.md`.
2897-
2898-**Status.** Confirmed by the owner on 2026-10-23, but for the exported
2899-array, parked with `[]const T`.
2900-
2901-### The language
2902-
2903-
2904-- Several values are assigned at once only from a call — two statements say it; `a, b := b, a` would need a rule that every right side is read before any is stored.
2905-- No conditional compilation — a constant module chosen by `-I` is the Wirth idiom, and `if Fake then` on a constant already reads as one program.
2906-- Records don't compare with `=` — padding, reals (`-0.0`, NaN) and slices make a byte compare wrong; a `same` procedure says what equal means. Confirmed by the owner, 2026-10-22.
2907-- No type of its own for an array — a one-field record keeps two hashes apart, as it keeps generic arrays (owner's idiom).
2908-- No exporting a record's fields as a whole — each `*` is the reader's mark of what is public; `Mxlib` is a C mirror, made by a program.
2909-- An exported array can't be read as a slice outside its module — a slice can be written through; "A slice that can't be written: `[]const T`" in PROPOSALS.md would answer it. Comes with `[]const T` in the safety thaw (`PLAN.md` §2).
2910-- An exported variable can't be assigned from outside — Oberon's read-only export; a setter shows who writes.
2911-- A generic instance isn't reachable through the module that imported it — no bug: an import's name is never exported (3); export a type of the instance, or import it again.
2912-- `I32` doesn't widen to `INT` — `INT` may be 16 bits (5.1), so the widening would not hold everywhere.
2913-- Common words are reserved — settled.
2914-- Text built at run time needs a `Buf` — with no collector a `+` of texts has no owner for its result; `Fmt.write` into a `Buf` is it.
2915-- Every string a record keeps is freed by hand — no collector; an `Arena` per record frees all of them at once.
2916-- Nothing in the report says anything of time — this is about constant-time code, not clocks (rzone doesn't answer it); a sentence would bind every later optimiser, and rcrypto isn't to be depended on.
2917-- An `ERROR` carries no text from the other end — an `ERROR` is an identity as big as an address; text from a peer belongs in a result field.
2918-- A module's test drags its imports into every user — costs compile time and a few bytes; a comment `(* for the test *)` on the import tells the reader.
2919-
2920-### Bits and bytes
2921-
2922-
2923-- **`Buf` gives memory back unwiped.** — a program with secrets sizes
2924- its `Buf` with `Buf.room` and calls `Tls.wipe(Buf.bytes(b))` before
2925- `Buf.done`, as roauth does; a wipe in the library would duplicate
2926- rnet's `Tls` backends.
2927-- **No hash but FNV, and no wipe the compiler can't drop.** — hashing
2928- and wiping go through rnet's `Tls` backends (`Tls.sha256`,
2929- `Tls.wipe`); `Ws`'s SHA-1 and the two 8-line wipes in `Smtp` and
2930- `Imapnet` move to `Tls` in rnet, and raz gains nothing.
2931-
2932-### Sys and Files
2933-
2934-
2935-- No reserving address space — `mmap` of the most it will hold, then
2936- `protect`, serves raudio; `MAP_NORESERVE` alone is not worth a
2937- procedure.
2938-- `Sys.openDir` gives no order — sorting the names is a few lines with
2939- `Sort`, in the one program.
2940-- No glob — one program (robbie), and which wildcards it takes is that
2941- program's choice; a `*` over `openDir` is about 40 lines.
2942-- A signal noted just before a `wait` doesn't break it — already
2943- answered: `catch` SIGCHLD with the others and wait in `ready` on
2944- catch's fd (child, signal or deadline at once), then `wait(pid,
2945- false)`; `ignore(sig, false)` gives a caught signal its default back.
2946- Worth a paragraph in the library volume (written there), not a procedure.
2947-- No word from the kernel when a file changes — inotify is Linux's,
2948- with no match in the C backend's other systems or Moss; a 300 ms
2949- look serves.
2950-- No sleep a signal breaks into — `ready(-1, ms)` is that sleep for
2951- `handle`, and `ready` on catch's fd for `catch`.
2952-- No sockets but streams and datagrams to addresses — netlink and HCI
2953- are Linux's, for one program.
2954-- No user's name — the password database with NSS needs the C
2955- library, which mosaico links anyway.
2956-- `Sys.rawMode` doesn't flush typed-ahead input — keys typed ahead are
2957- usually meant for the program; flushing would lose them.
2958-- No positional read (`pread`, `fadvise`) — `seek` then `read` serves
2959- the one program; `fadvise` is a hint, fine as a `SYSCALL`.
2960-- No `madvise` in `Sys` — `munmap` then `mmap` gives pages back.
2961-
2962-### Numbers, strings, memory and Opt
2963-
2964-
2965-- No fixed-capacity string — one program, a record of a length and an array, three lines.
2966-- `Math.toReal` refuses `.5` and `5.` — it reads reals as the language writes them, and arkusz's 3-line `withZeros` serves its one user.
2967-- `Math.toReal` is slow far from 10^0 — a fast path (Eisel and Lemire) is 60 lines and a table for one program's benchmark.
2968-- `Math.pow` is not correctly rounded, and `Math.exp(y * Math.ln(x))` is worse — within an ulp as the header promises; correct rounding costs far more than one bit is worth.
2969-- `Opt` has no GNU reordering, and does not say a `--` ended the options — options ending at the first operand is `Opt`'s stated rule, so that a command's own options pass through.
2970-- `Opt` carries no completion words — completion is concha's, one program, and the table would grow for every user.
2971-- A zero `Buf` or `Vec` isn't usable — deliberate: the core assumes no heap, and `init` says which allocator.
2972-- Joining texts into a kept `[]U8` costs a `Buf` and a copy — `Str.join` then `Str.copy` is two calls, for one program.
2973-- Case is ASCII only — Unicode case maps are large tables for one program; rrem has them.
2974-- `Vec` gives no pointer to an element already in it — `Nodes.all(v)[k].next := m` already sets a field in place.
2975-- No lenient base64 reader in `Str` — mail's junk is rmime's to handle; its 30 lines serve the one reader that meets it.
2976-- `Check.int` takes `I64` — an `I32` widening to `I64` is the language's question, and one call site converts.
2977-- `Rand` has no shuffle — `Rand` isn't generic, and Fisher and Yates over `below` is four lines. Confirmed by the owner, 2026-10-22.
2978-- `Fmt.real(x, n)` rounds the binary value, not the decimal text — the Pascal double rounding is left; the round-trip need is met by `Fmt.short` above.
2979-
2980-### Freestanding programs and tools
2981-
2982-
2983-- `Doc` fills a list. Done (owner, 2026-10-23), by lazy continuation: a
2984- line starting with `- ` at a comment's margin begins a bullet, the
2985- lines at the margin after it continue it, and a blank line or code
2986- ends it, so an indented line is still code.

README.md (history) modified +4 -4

@@ -48,7 +48,6 @@
4848 | `conform/` | The conformance suite: what every implementation must do |
4949 | `sbcl/` | An example: a second compiler, in Common Lisp for SBCL, written from the report alone and kept as a reference; it passes `conform/` and builds `src/` into a compiler that makes the same bytes. Not part of the build |
5050 | `test/` | This compiler's own tests, and the scripts that run them |
51-| `PROPOSALS.md` | What the language might have, waiting for a later thaw |
5251
5352 ## Building
5453
@@ -307,9 +306,10 @@
307306 defect, and the library grows only by what breaks no program. A library
308307 change that must break programs keeps the old form for one minor version
309308 beside the new; the release notes list the old forms, and the next
310-version removes them. Wishes
311-wait in `PROPOSALS.md`, for a later thaw; v0.6.0 was one, for a
312-language anyone can build again from its report.
309+version removes them. Thaws, by the owner's word, changed it since;
310+the last, for safety, was v0.24.0. After the Moss work (v0.25.0) it is
311+frozen hard: no more thaws, the language mended only where it does
312+other than the report says.
313313
314314 ## Not here
315315

doc/compiler.md (history) modified +2 -2

@@ -941,8 +941,8 @@
941941 ## Inlining a procedure that only returns
942942
943943 A call of a procedure whose body is only `return e`, with no locals,
944-is made in place of the call, as PROPOSALS.md's "Inlining a procedure
945-that only returns" has it. One pass keeps no tree to copy, but it can
944+is made in place of the call, as the proposal "Inlining a procedure
945+that only returns" had it. One pass keeps no tree to copy, but it can
946946 read source again, as `while` reads its condition again: `body` notes
947947 such a procedure (`onlyReturns`), keeping in its `Obj` an `Inline`
948948 (`Sym.raz`): the scanner's state at the `return`, its file, whether

src/README.md (history) modified +1 -1

@@ -110,7 +110,7 @@
110110 same; whether the compiler built from this is slower for it is for
111111 the speed test of step 4 to say. A `const` parameter (a hint that
112112 the callee won't change it, so that the caller may pass its address)
113- would be a language change: it is in `../PROPOSALS.md`. (It came in
113+ would be a language change. (It came in
114114 report 2026-10.33; since v0.20.0, built by v0.19.0, which has it,
115115 the routines that every program's compile goes through take their
116116 `Item` as `const`, measured, as `doc/compiler.md` says.)