From 3282a9a1c6922e90c4081a282b1c3860e91d3aad Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Mon, 26 Oct 2026 16:29:25 +0000 Subject: [PATCH] PROPOSALS.md and MEM_PROPOSAL.md gone: the Moss work's four proposals kept in PLAN.md's appendix --- diff --git a/CLAUDE.md b/CLAUDE.md index 3f4ba1e..9aea382 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -3,8 +3,8 @@ Read `doc/raz.md` (the language report, volume 1) and `doc/compiler.md` (the guide to the compiler) first; `doc/raz-lib.md` is volume 2, the library, `doc/report-history.md` what each version of -the report changed, and `PROPOSALS.md` what waits for a thaw. The -report defines the language. +the report changed, and `PLAN.md` what is left before 1.0. The report +defines the language. ## Setup and checks @@ -103,7 +103,7 @@ built-ins, what `SYSTEM` fences without it, an atomic given `ADR(x)`. `BOOT` names v0.23.0 (2026-10-26), so `src/` and the library it imports may use all of 10.37. CI couldn't run for it either; `make dist` made its tarball here. -v0.22.0, report 2026-10.36, before it, is the twelfth thaw, what `PROPOSALS.md` +v0.22.0, report 2026-10.36, before it, is the twelfth thaw, what the proposals collated: `MIN`, `MAX`, `ABS`, `CLZ`, `CTZ`, `POPCOUNT`, `INT(b)`, `OFFSET`, `SIZE(T.f)`, `BYTES` and `FILL`; a qualified case in an arm, slice and `ERROR` constants, a record's procedure field that takes the @@ -120,7 +120,7 @@ or the top 2 GB; `raz -bare` makes a program for the bare machine, which reads no arguments and runs no body of `Rt`; `BOOT` named v0.20.0, and `Sys` takes `PTR` where it had its private `bytes`. `MEM_PROPOSAL.md` -proposes a memory-safe raz, for a thaw. +proposed a memory-safe raz (the safety thaw took part of it). v0.20.0, report 2026-10.34, before it: v0.19.0 builds `src/` and the Pascal seed is gone; `Buf.bytes`, `Sys.entryKind` and `src/`'s `Item`s only read take `const`; and the tenth thaw, by the owner's word, @@ -159,16 +159,17 @@ for it. Thaws happen only by the owner's word (v0.6.0, reports 2026-10.13 to 10.23, 10.25 for strings, 10.26 for `INT` and views, 10.33 for `const` parameters, variants in constants and the library by `var`, -10.34 for `PTR`, and 10.35 and 10.36 for what `PROPOSALS.md` collated). +10.34 for `PTR`, and 10.35 and 10.36 for what the proposals collated). **The hard freeze** (owner, 2026-10-23). raz takes no more proposals: -nothing new goes in `PROPOSALS.md`, and a wish, the owner's or yours, -isn't recorded. What is open there, the safety thaw and the Moss work -(`Host`, a freestanding program stated, the assembler's instructions, -implementation limits), is the last. `PLAN.md` gives the order: v0.22.0 for what is -done, the safety thaw, the Moss work, the hard freeze, a clean-up, then -1.0 when use shows it. Once it is done the language is in -a hard freeze: no more thaws. The language changes only to mend a +a wish, the owner's or yours, isn't recorded. `PROPOSALS.md` and +`MEM_PROPOSAL.md` are gone (2026-10-26; in git before). What was left +open, the safety thaw (done, v0.24.0) and the Moss work (`Host`, a +freestanding program stated, the assembler's instructions, +implementation limits, in `PLAN.md`'s appendix), is the last. `PLAN.md` +gives the order: v0.22.0 for what is done, the safety thaw, the Moss +work, the hard freeze, a clean-up, then 1.0 when use shows it. Once it +is done the language is in a hard freeze: no more thaws. The language changes only to mend a defect, the compiler or the library doing other than the report says; the library's core (appendix A) only to mend a defect or to plug a very big gap; and the rest of the library grows only conservatively, by what @@ -312,8 +313,8 @@ - A returned slice of the frame (report 2026-10.27, 7.3) is caught by `Item.frame`, which sees only the expression: a slice held first in a local slice variable or a record, stored, or come back from a call, - isn't, and is left undefined (10). `ret` and `keep`, in - PROPOSALS.md, would close it; the owner keeps it open for now. + isn't, and is left undefined (10). `ret` and `keep`, once + proposed, would close it; the owner keeps it open for now. - An empty slice constant, `const E: []T = [];` (report 2026-10.32), is 16 zero bytes in read-only data, read as an array constant is; `LEN` of it is no constant. A constant's slice part takes `[]`, names diff --git a/HANDOVER.md b/HANDOVER.md index c47f550..762043b 100644 --- a/HANDOVER.md +++ b/HANDOVER.md @@ -53,5 +53,5 @@ ## What comes next -Not started; each the owner's call. `PROPOSALS.md` and -`MEM_PROPOSAL.md` hold what waits for a later thaw. +Not started; each the owner's call. `PLAN.md` says what is left before +1.0. diff --git a/MEM_PROPOSAL.md b/MEM_PROPOSAL.md deleted file mode 100644 index baf5d5a..0000000 --- a/MEM_PROPOSAL.md +++ /dev/null @@ -1,4170 +0,0 @@ -# MEM_PROPOSAL: a memory-safe raz - -**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). -Nothing in it is built. Four adversarial reviews, made the same day, -are appendices 4 to 7. They find real holes in the guarantee -(appendix 4), wrong and imprecise claims about other languages and -hardware (5), wrong counts and unsupported benchmark conclusions (6), -and pain in real code that sections 14 and 15 understate (7). The body -below is as first drafted; where an appendix contradicts it, the -appendix stands until the body is revised. It assumes that anything may change: the -language, the library, the compiler, and the programs written for -them. It builds on two entries of `PROPOSALS.md`, "Less that is -undefined" and part 3 of "What a call does with its arguments" (`ret` -and `keep`), and goes further than either: it puts them together into -one promise, closes the holes they leave open, and counts the cost. - -**In one paragraph.** Raz checks where memory is (an index against a -length, `nil`, zeroed variables) but not when it is still there, and -anything that can break memory may stand in any module. This proposal -splits modules in two. An `unsafe;` module may do what raz allows today. -Every other module is safe: the compiler holds it to rules under which -it can't read or write memory that isn't a live variable of the right -type. The rules are four: - -1. Pointer arithmetic, casts, `ADR`, C and code procedures go behind - `unsafe;`. -2. A slice or pointer *lent* by a variable can't outlive that - variable. Most of this is checked when compiling, and it takes - PROPOSALS' `ret` and `keep`. -3. A container that hands out slices of its memory *counts* them, - and won't free a block while one is held. -4. Safe code doesn't free heap memory by hand. It keeps that memory - for the life of the program, or holds it in a container or a - `Pool` that frees it. - -The library's own unsafe modules are trusted to keep the promise, as -a safe program is trusted to keep its logic. The cost, measured below: - -- **Programs:** nothing for code that keeps to slices and records. 1.5 - to 2 times for chasing a linked structure through checked handles - instead of raw pointers, where a program chooses handles. -- **Compiler:** about 5% more instructions, if its scanner checks its - buffer instead of reading it through a pointer. -- **Ergonomics:** a record can't keep a slice into a buffer that - belongs to someone else. - ---- - -## Contents - -1. Motivation -2. What the code we have does: a survey -3. The guarantee -4. The design, in brief -5. Part A: the fence, `unsafe;` -6. Part B: lending, `ret` and `keep` -7. Part C: owners that count what they lend -8. Part D: the heap without `free` -9. Part E: threads -10. Part F: the small mends -11. Part G: a debugging heap -12. Raz beside other languages -13. Performance -14. Ergonomics -15. What breaks -16. Changes to the report -17. Changes to the library -18. Changes to the compiler -19. Alternatives considered -20. Order of work -21. Open questions -- Appendix 1: the survey's numbers -- Appendix 2: the benchmarks -- Appendix 3: the five programs of section 1 -- Appendix 4: adversarial review, soundness -- Appendix 5: adversarial review, claims about other languages and hardware -- Appendix 6: adversarial review, the proposal's numbers and samples -- Appendix 7: adversarial review, porting real code - ---- - -## 1. Motivation - -### 1.1 What raz promises today - -| Check | Today | -|---|---| -| Index and slice bounds | checked, unless `check off;` | -| `nil` dereference, `nil` procedure | stops the program | -| Division by zero, `low / -1` | stops the program | -| Stack overflow | stops the program | -| Variables start at zero | always | -| Integer overflow | wraps, defined | -| A variant's fields read only through `match` | always | -| A view's bytes stay inside its variable | checked | -| Integer to enumeration conversion | checked | -| A slice returned from its own frame | an error, but only for a direct `return` (7.3) | -| Use after free, after `Arena.reset`, after a `Vec` grows | nothing | -| A slice kept past its frame by any other route | nothing | -| A slice of a call's array kept past its statement | nothing | -| Pointer arithmetic, `p[i]` | unchecked, anywhere | -| Integer to pointer, pointer to pointer | allowed, anywhere | -| `ADR` of a local, kept | allowed, anywhere | -| C, code procedures, `SYSCALL` | allowed, anywhere | -| A race tearing a slice or a variant | the report says nothing becomes undefined (7.6); it does | - -This is close to Oberon's or Pascal's promise, without a garbage -collector behind it. Spatial safety (indexes, lengths, `nil`) is -mostly there. Temporal safety (whether memory is still there) isn't -there at all. Nothing marks the code that can break memory, so any -module may. - -### 1.2 Five programs that compile with no warning - -Each is complete, compiled by today's compiler with no warning, and run. -The full texts are in appendix 3. - -**Appending a buffer to itself.** - -``` -Buf.init(b, Heap.heap); -for i := 1 to 64 do Buf.add(b, 'a'); end; (* full: 64 of 64 *) -Buf.str(b, Buf.bytes(b)); (* doubles it, or should *) -``` - -`Buf.str` grows `b` first: it allocates a new block, copies the bytes -and frees the old block. It then copies from `s`, which still points at -the old block. It prints 24 `a`s, as it should, because the heap didn't -reuse the freed block in time. With another allocator, or another -thread using the heap, it prints garbage. Nothing tells the programmer -that this line is wrong. A test passes. - -**A slice kept across a `Vec`'s growth.** - -``` -first := Vec.all(v); (* good until v next grows *) -p := Vec.add(v); (* grows: first now points at freed memory *) -... -p^ := -1; (* after another growth: writes into a block the heap took back *) -Out.int(first[0]); (* prints 1, as if nothing were wrong *) -``` - -The library's comments say "good until the array next grows". The -compiler doesn't know that comment. - -**A slice of the frame, through a call.** - -``` -proc head(var h: Hex): []U8; begin return h[0..8]; end; (* allowed *) -proc short: []U8; var h: Hex; -begin ... return head(h); end; (* not caught *) -``` - -The caller prints `########`, the bytes the next call left in the dead -frame. 7.3 catches `return h[0..8]` in `short` but not the same slice -handed back through `head`. - -**A map keeping a slice of a frame.** - -``` -proc remember(n: INT); -var buf: [8]U8; -begin - buf := "name-000"; buf[7] := U8('0' + n); - _ := Names.put(table, buf[0..8], n); (* the map keeps a slice of this frame *) -end; -``` - -After `remember(1); remember(2);` both `name-001` and `name-002` are -"missing": the map's keys point at a frame that is gone. Every caller -of `Map([]U8, ...).put` must know, from the documentation alone, that -the key is kept. - -**A slice of a call's array, kept.** - -``` -a := named('a')[0..8]; -b := named('b')[0..8]; -Out.str(a); Out.str(" "); Out.str(b); -``` - -It prints `name-..b ^A^@^@^@^@^@^@^@`. Both arrays used the same -temporary, so `a` shows `b`'s bytes and `b` shows whatever came after. -Section 8 says this is undefined, and nothing catches it. - -None of these is exotic. Three are what the library's own -documentation warns of; two are what 7.3 and 8 warn of. Each runs to -the end with status 0. - -### 1.3 Why it matters for raz in particular - -- **Raz's audience.** CLAUDE.md asks that the compiler be "a model of - plain code that a beginner can follow". A beginner can't follow a - rule that lives only in a comment ("good until it next grows"). A - language that checks every index and then lets a slice outlive its - buffer teaches a false sense of safety: the checks cover the easy - half. -- **Undefined behaviour passes tests.** In four of the five programs - above the output is plausible, or right. The heap's free lists keep - freed bytes for a while; a dead frame keeps its bytes until the - next call. A program can carry such a bug for years. -- **No fence means no audit.** Today, to know whether a program can - corrupt memory, you read all of it. With a fence, you read the - modules that say `unsafe;`, and `grep` finds them. The survey - (section 2) shows how few modules would need to say it. -- **The library is growing.** Each container added (`Vec`, `Map`, `Buf`, - `List`, and `Svec` in sauce) adds rules of the "good until" kind. Those - rules should be the compiler's to check. -- **Threads.** `Thread` and `Lock` are in the library, and rnet and - rsqlite use them. A race on a slice reaches any memory today, though - 7.6 promises it can't. - ---- - -## 2. What the code we have does: a survey - -### 2.1 How it was measured - -For an exact count, not an estimate from `grep`, the compiler itself -was changed in a scratch copy. It printed one line for each operation -this proposal would fence, where it compiled one: a pointer indexed or -sliced, pointer arithmetic, a conversion to or from a pointer, `ADR`, -`PTR`, `SYSCALL`, a view, `NEW` and every dereference. Each program -and each library module's test was compiled with it. The places are -counted once each, whatever number of programs compiled them. The -hooks stand where most of the fence's checks would go (section 18). - -Code surveyed: - -| Code | Version | Lines | How | -|---|---|---|---| -| raz `src/` (the compiler) | main | 14,323 | compiler-counted | -| raz `lib/` | main | 10,291 | compiler-counted | -| raz `tools/`, `examples/`, `test/libc` | main | 2,207+ | compiler-counted | -| rnet (HTTP, DNS, TLS seams) | raz 0.15.0 | 5,111 | compiler-counted, with 0.15.0's `lib/` | -| rjson | raz 0.15.0 | 1,882 | compiler-counted, with 0.15.0's `lib/` | -| rflate (inflate) | raz 0.15.0 | 1,319 | compiler-counted, with 0.15.0's `lib/` | -| rsqlite (SQLite over C) | raz 0.18.0 | 705 | compiler-counted, with 0.18.0's `lib/` | -| rterm | raz 0.15.0 | 101 | compiler-counted | -| rmacs (an editor, archived) | raz v0.5.0+7 | 4,932 | `grep`: written before `INT`, today's compiler refuses it | -| ravite (an editor) | raz v0.5.0+7 | 2,460 | `grep`, as rmacs | -| rlX11 (X11 over a socket) | raz v0.3.0+52 | 7,026 | `grep`, as rmacs | - -About 50,000 lines in all. Code written for an older raz was compiled -by today's compiler against the library of the version it was written -for. The full tables are in appendix 1. - -### 2.2 What it found - -**Nobody uses `check off;`.** Not one module in 50,000 lines. Bounds -checks are cheap enough that no one has wanted them off. - -**Almost every `ADR` is an argument to the library.** Of rnet's 572 -`ADR`s, 571 are arguments, and so are 556 of rmacs's 560 and all 77 of -rjson's. They are the library's old pointer parameters, which report -2026-10.33 made `var` and `const`; code written for v0.19.0 and later -has lost them already. `src/`, which has been ported, keeps 27, and -none of them needs to be an `ADR`: - -| What `src/` does with `ADR` and pointer casts | Sites | The safe form | -|---|---|---| -| a grown array: `^Chunk(Scan.regrab(^U8(chunks), ...))` | 35 | `Vec(Chunk)`, or a slice and `Mem`'s growth, in one trusted module | -| a real's bits: `p := ^F64(ADR(x.val))` | 6 | a view, `x.val.(F64)`, safe today | -| a slice passed as two words: `Scan.intern(ADR(s[0]), LEN(s))` | 7 | `Scan.intern(s)`: a slice parameter | -| out-parameters: `isReg(w, ADR(r), ADR(size))` | 5 | `var r, size` | -| a pointer to a local record: `curLoop := ADR(lp)` | 1 | a field index, or `var` | -| `SYSCALL(4, ...)`: `stat` | 1 | `Sys.info` | - -**Pointer indexing is buffers.** `src/` indexes a pointer 277 times -and slices one 30 times, nearly all in six modules: `Scan` (76), `Link` -(63), `Chunk` (53), `X64` (23), `Elf` (17) and `Diag` (15). Each keeps -a byte or record buffer that it grows by hand: `text[pc + i] := ...`, -`lp[lpLen] := ...`, `buf[at + i] := ...`. That is `Vec` and `Buf` -written out again, for speed, without checks. The scanner reads its -source through `buf: ^U8`, past the end to a sentinel zero. - -**Dereferences are everywhere and harmless.** 1,015 in `src/` (`Parse` -517, `Item` 256, `Sym` 106): `o^.typ`, `t^.base`. Every one is a pointer -from `NEW` on the heap, which the compiler never frees. Under part D -they stay as they are, unchecked and free of cost. - -**The library is where the unsafe code is.** `Sys` (287 operations, -129 of them `SYSCALL`), `Rt` (111), `Thread` (33), `Heap` (16) and `Map` -(19). It is the code that should be trusted and read twice. `Math`, -`Out`, `Sort` and `Width` have none; `Str`, `Fmt`, `Opt`, `Files` and -`Lock` have two to five each, all of them avoidable. - -**Slices held from containers.** 35 places assign `Buf.bytes`, -`Vec.all` or `Windows.all` to a variable and use it over several -statements; the rest pass it straight on. Some places store one in a -record: - -``` -m^.body := Buf.bytes(ADR(m^.data)); (* rnet Http.readWhole *) -m^.headers[m^.n] := {name: l[0..colon], value: trim(...)}; (* l is a slice of m^.head's bytes *) -res^.body := Buf.bytes(ADR(text)); (* rnet's test server: a module Buf, reset per request *) -``` - -`Http.Message` holds slices into two buffers of its own. It is right, -as long as nobody grows `m^.head` after the headers are read and -nobody uses the headers after `Http.done`. The compiler knows neither -condition. Section 14 shows what this pattern costs under the -proposal. - -**Records that hold slices** (each one is a place where something must -decide how long the slice lives): `src/` 10, `lib/` 22, rnet 12, rjson 8, -ravite 5, rmacs 4, `tools/` 4, rlX11 3, rflate 2, rsqlite 1. - -**Threads are rare.** Two of the eight other repositories spawn -threads (rnet's server, rsqlite's test). `src/`, the tools and the -editors have none. - -**Freeing is rare too.** `Mem.free`, `Heap`'s `free` or `Str.free` by -hand: `src/` 7 (all in grown arrays), rmacs 9, rjson 6, ravite 2, -rlX11 1, rnet, rflate and rsqlite 0. Programs free memory through -`done` on a container (rnet 30, rmacs 16) far more than by hand: 54 -`done`s to 26 frees, outside the library. - -### 2.3 What the survey says about the design - -1. A fence costs little. Outside the library and the compiler's - buffers, the operations it fences are almost all `ADR`s that the - v0.19.0 library already removed. In `src/`, the fenced - operations are buffers and small habits, each with a safe form. -2. Leaving pointers unchecked costs nothing as long as nothing frees - them. The compiler's 1,015 dereferences are of heap memory that - lives as long as the program. Making `free` unsafe, and giving - containers the job of freeing (part D), keeps those dereferences - free of cost. -3. The hard case is a slice of a container's memory held while the - container changes. It is found in rmacs, ravite, rnet and the - library itself (`Fmt`, `Opt`), and nothing today checks it. Part C - is aimed at it. -4. Threads can wait for a weaker rule than Rust's (part E), since few - programs use them. - ---- - -## 3. The guarantee - -The proposal puts one paragraph into section 10 of the report, in -place of today's list of what isn't defined: - -> **The guarantee.** A program is *safe* if none of its modules says -> `unsafe;`, the library's aside, and its threads race (7.6) only on -> variables of a basic, pointer, procedure or slice type. A safe -> program reads and writes only variables that exist, each as a value -> of its own type, and calls only procedures. It does what this report -> says, or stops with status 2 and says where and why. The library's -> unsafe modules are trusted to keep this promise for every use a safe -> program can make of what they export. - -What the guarantee covers: - -- **Spatial:** no read or write outside a variable: indexes and views - checked, as now; pointers in safe code made only by `NEW` and by the - library, never by arithmetic or conversion. -- **Temporal:** no read or write of memory that has been freed or - reused: slices and pointers lent by a frame or a container can't - outlive it (B, C); the heap is never freed under a pointer safe code - holds (D). -- **Type:** no value read as another type: views of pointers and - conversions to pointers fenced; variants only through `match`; enums - and `BOOL` only from their values. -- **Initialization:** as now, every variable starts at zero. -- **Races:** within the bounds above (part E). - -What it doesn't cover, on purpose: - -- **Leaks.** A safe program may keep memory it no longer needs, as a - garbage-collected one may. -- **Running out of memory or stack.** These stop the program, as now. -- **Logic.** A stale handle into a `Pool` stops the program; it doesn't - fix the bug. A slice of a buffer that was cleared shows the buffer's - new contents, safely. -- **Deadlock**, and a race on a whole record, variant or container. - The second is undefined, as in Go, and part E says why. -- **The unsafe modules themselves.** They are trusted, as `unsafe` - code is in Rust and `UNSAFE MODULE`s are in Modula-3. - -The guarantee is stated once and is the same on every target. -Appendix A keeps only how it is carried out: whether the machine or -the code catches a fault, and how a slice is read in one access. - ---- - -## 4. The design, in brief - -| Part | What it does | Checked | Cost at run time | -|---|---|---|---| -| 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 | -| 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 | -| 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 | -| 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 | -| 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 | -| 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 | -| G. Debugging | `Heap` in a mode that poisons and holds back freed blocks | at run time, when chosen | when chosen | - -A program that is safe today, which is to say every program that -keeps to slices, records and the library, mostly stays as it is. Section 15 counts -what breaks. - ---- - -## 5. Part A: the fence, `unsafe;` - -### 5.1 The rule - -A module that says `unsafe;`, after its imports, links and `check` -line, may do everything raz allows today. A module that doesn't is -*safe*, and it is an error for it to do any of the following: - -| Operation | Why it's fenced | -|---|---| -| `ADR(x)` | a pointer to anything, a local included, that outlives nothing | -| `p + i`, `p - i`, `p[i]`, `p[lo..hi]` on a pointer | no length to check against | -| 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 | -| 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 | -| `PTR(s)` | the first word of a slice, unchecked | -| a view `v.(T)` whose `T` holds a pointer, procedure or slice | makes one from bytes | -| writing through a view of a variable that holds a pointer, procedure, slice, variant, enumeration or `BOOL` | changes those bytes behind their type | -| `check off;` | indexes unchecked | -| `extern`, `link` | C can do anything | -| a code procedure, `SYSCALL` | the machine can do anything | -| `ARGV()` | a `^^U8` from C; `Files.arg` gives a slice | -| a call of an `unsafe proc`, or of a value of an `unsafe proc` type | the procedure says it can break the promise | - -What stays safe, though it involves pointers: `p^`, `p^.f`, `p^[i]` (an -array through a pointer is indexed and checked), `nil`, comparing -pointers, `p - q` (an integer), `NEW`, and passing and storing a -pointer as any value. A pointer in safe code is only ever `nil`, from -`NEW`, or handed out by the library. Part B says how long each one -lives. - -The message names the mending: - -``` -Window.raz:41:13: error: ADR is for unsafe modules - 41 | XNextEvent(dpy, ADR(ev)); - | ^^^^^^^ - help: say "unsafe;" after the module's imports, or pass ev as a var -``` - -### 5.2 Unsafe procedures - -Some of the library's procedures can break the promise whatever safe -code does: `Mem.free`, `Heap`'s `free`, `Str.free`, `Sys.mmap`, -`Sys.munmap`, `Thread.spawn` with its `^U8`. They are declared - -``` -unsafe proc free*(a: ^Allocator; p: ^U8); -``` - -and only an unsafe module may call one. A procedure type may say -`unsafe proc(...)`; a value of that type may be called only from an -unsafe module, and a safe procedure may stand where an unsafe type is -wanted, not the other way. `Mem.Allocator`'s two fields are of unsafe -types: safe code may pass an allocator to the library but can't call -it. - -`unsafe`, like `static` in `link static;`, is a word only where it -stands: before `proc`, and as the module's line. Elsewhere it is a -name. - -### 5.3 The trust - -A safe module may import an unsafe one. What the unsafe module -exports, other than its `unsafe proc`s, it promises safe to use: for -any arguments a safe module can make, its procedures keep the -guarantee. This is Modula-3's rule for an `UNSAFE MODULE` that -implements a safe `INTERFACE`, and Rust's for a safe function built -on `unsafe` blocks. What the promise demands of an unsafe module, in -the report (section 16): - -1. What it returns as lasting (part B) lasts: its memory is never - freed or reused while the program runs. -2. What it returns through `ret` lives no longer than the argument it - says. If the argument is an owner, the module doesn't free memory - it lent while the owner's `LENDS` count is above zero (part C). -3. What it keeps (`keep` parameters) it may hold for as long as it - likes; what it doesn't mark `keep`, it doesn't hold past the call. -4. Its exported types hide whatever a safe module could misuse: a - container's pointer fields aren't exported. -5. Its procedures given to other threads, or shared by them, are safe - to call from several threads at once, or say otherwise. - -So `grep -l '^unsafe;'` lists every module whose bugs could corrupt -memory, and the library's are among them, as they are today. - -### 5.4 Which modules would say it - -From the survey, as the code stands: - -- **The library:** `Rt`, `Mem`, `Heap`, `Arena`, `Bytes`, `Sys`, - `Thread`, `Lock`, `C`, `CAbi`, and the containers `Buf`, `Vec`, `Map`, - `List`, which hold raw blocks and grow them. `Str`, `Fmt`, `Opt` and - `Files` can drop their two to five fenced operations and be safe. - `Math`, `Out`, `Sort` and `Width` are safe already. -- **`src/`:** all eleven modules today. Mended as section 2.2's - table says, with the six buffer modules' grown arrays made `Vec`s or - slices, `src/` keeps one unsafe module: `Scan`, for its allocator - (`grab`) and, if it keeps it, the pointer through its source buffer. - `Elf` writes the executable through `Sys.write` and needs none. -- **`examples/`:** `Args` (it reads `ARGV()`, which `Files.arg` does - for it), `Cpu` (a code procedure), `Pthreads`, `Printf`, `Window` - (C), `Volatile` (a device's address), `Sh` and `Workers` (`ADR` at - calls: mended by `var`). Five stay unsafe (`Cpu`, `Pthreads`, - `Printf`, `Window`, `Volatile`), as an example of each kind of - unsafety should be. -- **Elsewhere:** rsqlite's `Sqlite` (C); rlX11's three casts look like - work for views; rnet needs it only to keep `Http.Message` as it is - (section 14). - ---- - -## 6. Part B: lending, `ret` and `keep` - -Part B is PROPOSALS' part 3 (`ret`, `keep`) with two changes. Pointers -are followed, not only slices, and a third kind of lender, the owner, -comes from part C. What is said there of "frame-bound", "outliving the -call" and the checks stands. This section gives the rules in the -terms the guarantee needs. - -### 6.1 Lasting and lent - -Every value that holds a slice or a pointer (a *reference*) is, for -the compiler, either: - -- **lasting:** it points at memory that lives to the end of the - program: `nil`, `[]`, a string constant, a module variable or a part - of one, memory from `NEW` on the heap (part D), and what the library - returns as lasting (a result with no `ret` parameter); -- **lent** by one or more *lenders* of the procedure it is in: - - **the frame**: a slice of a local array, of a value parameter's - array, or of an array literal; an array a call returned (part F); - - **a parameter `p`**: a slice parameter's value, what a `var` or - `const` parameter's arrays hold or its references point at; and - the parameter's own variable, for `var` and `const`; - - **an owner `o`** (part C): what `o` lent through a `ret`. - -A value made from others is lent by every lender of its parts: a slice, -a field, an element of `x`; a record, variant or array literal of -parts; a call's result, from its arguments for `ret` parameters. A -local variable holding references is lent by everything assigned to -it anywhere in its procedure. That is PROPOSALS' rule, and the reason -some checks wait for the procedure's `end`. - -### 6.2 What may be done with a lent reference - -A lent reference may be: - -- read, indexed, sliced, compared, and passed to any parameter not - marked `keep`; -- held in a local variable, or in a field or element of one (owner-lent - values only in a local of slice or pointer type: see 7.3); -- returned, if each of its lenders is a parameter marked `ret`. - -It may not be: - -- stored in a module variable, through a pointer (`p^.f := s`), or into - a `var` parameter or part of one; -- given to a `keep` parameter; -- returned while lent by the frame, an owner, or a parameter not - marked `ret`; -- given to `Task.spawn` (part E). - -The rules are PROPOSALS' checks 1 to 3, with "frame-bound" read as -"lent". Every check needs only the procedure in hand and the headings -of what it calls, so a one-pass compiler can make it: the checks on a -local wait for the procedure's `end`, as PROPOSALS describes. - -### 6.3 Marks - -``` -proc trim*(ret s: []U8): []U8; (* the result may point where s does *) -proc bytes*(ret const b: Buf): []U8; (* the result is lent by b, an owner *) -proc put*(var m: Map; keep k: K; keep v: V): BOOL; (* k and v must last *) -``` - -`ret` and `keep` stand before `var` or `const`, and are words only -there. A mark that lends nothing (`keep n: INT`) is allowed, so a -generic module can mark `keep v: T` for every `T`. PROPOSALS covers -procedure values, generics, `extern` (no marks; unsafe anyway) and -code procedures (trusted; unsafe anyway). - -Marks at the call (PROPOSALS' part 1) are not part of this proposal: -the checks hold whether or not the call repeats them. - -### 6.4 Examples - -``` -proc greet: []U8; -var line: [80]U8; n: INT; -begin - n := Sys.read(Sys.stdin, line); - Out.str(Str.trim(line[0..n])); (* fine: lent by the frame, used here *) - return Str.trim(line[0..n]); (* error: lent by the frame *) -end; - -proc first(ret s: []U8): []U8; -begin - return s[0..1]; (* fine: s is ret *) -end; - -proc remember(n: INT); -var buf: [8]U8; k: []U8; ok: BOOL; -begin - buf := "name-000"; buf[7] := U8('0' + n); - _ := Names.put(table, buf[0..8], n); (* error: put keeps k, and this is lent by the frame *) - k, ok := Str.copy(Heap.heap, buf[0..8]); (* lasting: a copy on the heap *) - if ok then _ := Names.put(table, k, n); end; (* fine *) -end; -``` - -The messages: - -``` -Kept.raz:10:30: error: Names.put keeps its key, and buf[0..8] is lent by this call's frame - 10 | _ := Names.put(table, buf[0..8], n); - | ^^^^^^^^^ - help: give put a copy that lasts: Str.copy(Heap.heap, buf[0..8]) -``` - -``` -Escape.raz:14:12: error: head(h) is lent by h, a local of short, and can't be returned - 14 | return head(h); - | ^^^^^^^ - help: head's result points into what it is given (ret h); return a copy, or take h as a var parameter of short -``` - -### 6.5 Pointers - -PROPOSALS' marks follow slices only and leave pointers to the promise -of section 10. Here pointers are references too. In a safe module the only -pointers are lasting (from `NEW` on the heap, or from the library) or -lent by an owner (`Vec.add`, `Pool.at`). `ADR` is fenced, so a safe -module can't make a pointer to the frame. A pointer lent by an -owner follows the same rules as a slice. - -### 6.6 What it closes - -- A slice of the frame returned or stored by any route (today's 7.3 - catches one route). -- A slice of a parameter's array stored past the call, or returned - unmarked. -- A map, list or vector keeping a slice that doesn't last. -- `Opt.init` keeping a table built on the frame (it becomes `keep - table`, and `examples/Sh.raz` passes a constant, as PROPOSALS shows). - ---- - -## 7. Part C: owners that count what they lend - -### 7.1 The problem part B can't solve - -`Buf.bytes(b)` returns a slice of heap memory, so by PROPOSALS' rule it -points "nowhere that ends", and part B would call it lasting. It -isn't: the next `Buf.add` may free that memory. The slice is lent by -`b`, and how long it stays good depends on what happens to `b`, at run -time, often through a pointer: `Buf.bytes(x^.path)`. - -There are two ways to check that when compiling. One is Rust's: no -change to `b` while any slice of it is live, found by liveness and -the exclusivity of `&mut`. The other is flow analysis in one pass: -mark a slice stale when its lender is passed as `var`, and refuse to -read it after that. Both fail raz's limits. Rust's needs lifetimes in -types and borrow regions. The one-pass flow analysis can't see a -loop's second iteration before it compiles the first: - -``` -s := Buf.bytes(b); -while more do - Out.str(s); (* compiled before the add below; but the second time round s is stale *) - Buf.add(b, c); -end; -``` - -and through a pointer every call may change the lender, so every call -would make the slice stale, which is false alarms everywhere. - -So part C checks at run time, as raz checks an index. The cost is an -add when a lent slice is taken into a variable and a subtract when the -variable lets go of it. - -### 7.2 Owners - -A record type with a field of the new built-in type `LENDS` is an -*owner*: - -``` -type - Buf* = record - lends: LENDS; (* how many slices of data are held *) - a: ^Mem.Allocator; - data: ^U8; - len*, cap: INT; - end; -``` - -`LENDS` is an `INT` that only the compiler changes: the owner's own -module may read it, and nothing may assign it. An owner is lent from -only through a `ret` parameter of its type, `var` or `const`: - -``` -proc bytes*(ret const b: Buf): []U8; -proc all*(ret const v: Vec): []T; -proc add*(ret var v: Vec): ^T; -proc spare*(ret var b: Buf; n: INT): []U8; -``` - -A record that holds an owner, `Http.Message` with its two `Buf`s, is -not an owner itself. What its `Buf`s lend is counted on each `Buf`. - -### 7.3 Counting - -Where a call returns a reference lent by an owner `o`: - -- **Used in its statement** (`Out.str(Buf.bytes(b))`, `Buf.str(c, - Buf.bytes(b))`): `o.lends` is raised by one as the call returns and - lowered at the end of the statement. -- **Assigned to a local** of slice or pointer type, `s := Buf.bytes(b)`: - the local gets a hidden word, its *hold*, which records the address of - `o.lends`. Assigning the local again lowers the old count and raises - the new; when the procedure returns, by any path, each hold still set - lowers its count, as a `defer` would. `s := []` lets go. -- **Anywhere else**: stored in a record, an array, a module variable, - through a pointer, or returned. This is an error by part B, since - the reference is lent by an owner. A local record holding one is - also an error, so that each hold covers one reference: - -``` -Fmt.raz:140:5: error: Buf.bytes(b) is lent by b, which counts what it lends: hold it in a slice variable -``` - -A reference passed to another procedure needs no count of its own: -the caller holds it, by a statement's count or a local's hold, for the -whole call. A `ret` result lent by a lent value (`t := Str.trim(s)`, -with `s` lent by `b`) is lent by `b` too, and its local gets its own -hold. - -The owner's address is fixed while it is lent. An owner is either a -local, a parameter, or a variable reached through a lasting pointer, -and part B keeps the lent value from outliving a local or parameter -owner. So the hold's address stays good until it is let go. - -### 7.4 What an owner does with its count - -The owner's module, which is unsafe and trusted, reads `lends` -before it frees memory it has lent: - -- **Growing:** if `lends` is 0, free the old block, as now. If not, - keep it on a list of *retired* blocks, and free those at the next - growth, `reset` or `done` that finds `lends` 0. A slice held across - the growth keeps pointing at the old block, which stays allocated: - it reads what the buffer held when the slice was taken. This is Go's - `append`: the old slice still sees the old array. -- **`done`**, which gives everything back: if `lends` is above 0, the - program stops: - - ``` - Buf.done while 1 slice it lent is still held - ``` - - and the calls under way are shown, as a failed check shows them. - `done` can't wait, and can't leave the memory to the slice without - leaking it for good. -- **`reset`** keeps the block, so it is always safe: a slice held - reads the new bytes as they are written over the old. - -With this, the self-append of 1.2 is right: `Buf.str(b, Buf.bytes(b))` -holds a count across the call, the growth retires the old block, and -`COPY` reads the old block, still allocated. The `Vec` example reads -`1 2` because the memory is still there. The stale `p^ := -1` writes -into a retired block: lost, but harmless. Section 11's debugging heap -can say so. - -### 7.5 What it costs - -- **Run time:** two adds per lend held: on x86-64, `inc qword [r]` and - `dec qword [r]`, about two cycles each. In a program that uses - `Thread` they are `lock xadd`, about 20 cycles each (part E). Lends - are rare next to element accesses: `Fmt.format` lends once per call, - and a loop over `Buf.bytes(b)` lends once. -- **Memory:** a word per owner, a word per local that holds a lend, - and at most the retired blocks, which add up to less than the - current block (each was half the next). -- **Compiler:** the hold slots, the raise and lower code, and the - epilogue's let-go. The epilogue reuses the machinery `defer` already - has. - -### 7.6 Owners aren't copied - -Copying a `Buf` today makes two records that both own one block. -Freeing it twice, or growing one while the other reads, breaks -memory. rnet's `Http.reset` does exactly this, safely by luck: -`head := m^.head; ...; m^ := {..., head: head}`. In a safe module, a -value of an owner type, or of a type that holds one, may not be: - -- assigned from another variable, returned, passed as a value - parameter, or put in a literal. A literal may still leave it out, so - that it is zero (`{}`), the empty owner; -- compared, or viewed. - -It is passed as `var` or `const`, and moved by the library: `Buf.swap(var -a, b)`, `Buf.take(var from, to)`. The message: - -``` -Http.raz:153:5: error: a Buf.Buf owns memory, and can't be copied - help: Buf.take(m^.data, data) moves it, leaving m^.data empty -``` - -### 7.7 Who is an owner - -`Buf`, `Vec`, `Map` (it lends nothing, but owns its table; `LENDS` -stops a copy), `List`, `Pool`, `Arena` and the owned-string map of -part D. A program's own record may be an owner too, if an unsafe -module of the program frees what it lends. - ---- - -## 8. Part D: the heap without `free` - -### 8.1 The rule - -In a safe module: - -- `NEW(p, a)` with `a` lasting (`Heap.heap`) gives a lasting `p`. - `Heap.heap` never frees it under safe code, because only unsafe code - can call `free`. -- `NEW(p, a)` with `a` lent by an owner (an arena, part C) gives a - `p` lent by that owner, counted like a slice. -- `Mem.free`, `Heap`'s `free`, `Str.free` and `Mem.unmap` are `unsafe - proc`s. - -So a safe program frees memory in one of three ways: - -1. **Through a container** that owns it: `Buf.done`, `Vec.done`, - `Map.done`, `List.clear`, `Pool.free`. Most programs do this already: - outside the library, the survey's `done` calls outnumber its hand - frees 54 to 26. -2. **Through a `Pool(T)`**, for records that come and go one by one - (8.2). -3. **By ending the program.** A compiler, a tool or a short-lived - server process frees nothing by hand, and `src/` frees only its - grown arrays, which become `Vec`s. - -The 1,015 dereferences in `src/` stay as they are, with no check and -no cost: every pointer behind them is lasting. - -### 8.2 `Pool(T)`: handles with a generation - -``` -module Pool(T); - -type - Handle* = record i, gen: INT; end; (* zero: no record *) - Pool* = record lends: LENDS; ... end; - -proc init*(var p: Pool; a: ^Mem.Allocator); -proc add*(var p: Pool; keep x: T): Handle; (* a new record, x copied in *) -proc get*(const p: Pool; h: Handle): T; (* a copy; stops if h is stale *) -proc set*(var p: Pool; h: Handle; keep x: T); (* stops if h is stale *) -proc at*(ret var p: Pool; h: Handle): ^T; (* in place, lent by p, counted *) -proc valid*(const p: Pool; h: Handle): BOOL; -proc free*(var p: Pool; h: Handle); (* the record gone; h, and every copy, stale *) -proc done*(var p: Pool); -``` - -Each slot holds a `T` and a generation. `free` raises the slot's -generation and puts the slot on a free list. `get`, `set` and `at` check -the handle's generation against the slot's, and the index against the -pool's length, and stop the program if they differ: - -``` -Pool.get: a stale handle (slot 4, generation 3; the slot is at 5) -``` - -A slot is used only for a `T`, so even a pointer from `at` kept past -`free` points at a `T`: a wrong record, perhaps, but never memory -of another type. `at`'s count also keeps the pool from moving its slots -while the pointer is held (7.4). - -This is the generational arena of Rust's `slotmap` and -`generational-arena`, and the handle pattern Zig and game engines use; -Vale builds the same check into every reference. Measured cost -(section 13): a list chased through handles takes 1.5 times as long as -one chased through raw pointers when it is too big for the caches, and -2 times when it fits in L1. Part of the first is that each slot is 32 -bytes, not 16. - -### 8.3 Owned strings - -`Str.copy` gives a lasting copy, which a safe program can't free. For a -long-running program that makes and drops strings (an editor's buffer -names, a server's paths), the library adds: - -- `Buf` as the string a program owns: `Buf.str(name, s)`, freed by - `Buf.done`; -- `Names(V)`, a map from strings to `V` that copies each key in on - `put` and frees it on `remove` and `done`: `Map([]U8, V, ...)` with - its keys owned, for those who would otherwise `Str.copy` and leak. - -### 8.4 Arenas - -An arena hands out memory and frees it all at once, so what it gives -is lent by the arena: - -``` -var ar: Arena.Arena; t: ^Tree; -... -NEW(t, Arena.allocator(ar)); (* lent by ar *) -... -Arena.reset(ar); (* stops the program if t is still held *) -``` - -`Arena.allocator(ret var ar): ^Mem.Allocator` gives the allocator, -lent by `ar`; `NEW` from it gives a `t` lent by `ar`, counted. Lent -values can't be stored in records (part B), so an arena in safe code -holds no linked structure: the pointer to a tree's root may live in -a local, but the tree's own links can't. A program that builds -linked structures in an arena does it in an unsafe module, or with -indexes into a `Vec`. Section 14 weighs this. - ---- - -## 9. Part E: threads - -### 9.1 What races can break - -7.6 says a variable that two threads touch without ordering "holds a -value it had or was given, or a mixture of their bytes" and that -"nothing else of the program becomes undefined". The second half is -wrong today: - -- a **slice** torn between two writes, one's address with the other's - length, is checked against the wrong length and reaches any memory; -- a **variant** torn between two cases reads one case's bytes as the - other's fields: an integer as a pointer; -- a **container** written by two threads at once (`Buf.add` in each) - races on its length and its block: one thread writes past the end of - the block the other just freed. - -Go has the same hole: its memory model says that a race on a -multi-word value (an interface, a slice, a string) "can lead to -arbitrary memory corruption". Rust closes it with `Send` and `Sync`, -traits that the type system checks. Java closes it by tearing only -`long` and `double`, never a reference. - -### 9.2 The proposal - -1. **A slice is one access.** On every target, a slice is read and - written in one access that can't tear, as a word is. On x86-64 a - slice is aligned to 16 bytes and moved with `movdqa`, which Intel - and AMD guarantee single-copy atomic on processors with AVX. On - x86-64 without AVX, the implementation uses `lock cmpxchg16b`, or - refuses the target, as appendix A says. ARMv8.4 has 16-byte - atomic `LDP`/`STP` (FEAT_LSE2). A program that hands slices from - thread to thread, publishing a buffer for others to read, is then - safe with no lock. -2. **The guarantee holds for races on basic, pointer, procedure and - slice variables, and no others.** A race on a variant, or on a - whole record or array copied at once, or calls of one container's - procedures from two threads at once without a lock, is outside - it: undefined, as in Go. Section 3 says so, and 7.6 is rewritten - to say so. -3. **A safe way to start a thread.** `Thread.spawn(p, arg: ^U8)` becomes - an `unsafe proc`. A generic `Task(T)` takes its place for safe - modules: - - ``` - module Task(T); - proc spawn*(p: proc(var x: T); keep x: T): (^Thread.Thread, ERROR); - ``` - - `x` is copied into the new thread's stack before `spawn` returns. - Its references must be lasting (`keep`), so a thread never holds - a slice of its spawner's frame. -4. **Atomics take a variable.** `CAS(x, old, new)`, `XCHG(x, v)` and - `XADD(x, k)` take a variable, as `INC` does; through a pointer, `XADD(p^, - 1)`. A safe module can then use them, with no `ADR`. -5. **Counts are atomic where there are threads.** Part C's raise and - lower are `lock xadd` in a program that imports `Thread`, so that two - threads lending from one locked `Buf` keep its count right. A - program without `Thread` gets the plain `inc` and `dec`. -6. **`Lock.Guarded(T)`**, a value with its lock, for sharing a - container: - - ``` - g: Guarded(Names.Map); - Guarded.with(g, addName); (* addName(var m: Names.Map) runs under the lock *) - ``` - - It makes the safe pattern the easy one, as Rust's `Mutex` does, - though nothing stops a program from sharing a container without it. - -### 9.3 Why not Rust's way - -A static rule that a container can be reached from two threads only -under a lock needs, at the least, marks on types for what may cross -threads (`Send`) and be shared (`Sync`), and a way to see that module -variables are shared. Module variables are reachable from every thread, -and raz has no thread-local storage to put them in instead. It would -add a second type system to the language for a feature two -repositories out of eight use. Section 19 keeps it as a later step. - ---- - -## 10. Part F: the small mends - -### 10.1 An array a call returns lives to the end of its procedure - -"Less that is undefined", piece 1. The temporary's slot in the frame is -reserved for the rest of the procedure, as a deferred statement's slots -already are, so `s := f('a')[0..4]` is lent by the frame, not by the -statement: defined until the procedure returns, and part B keeps it -from going further. In a loop the slot holds the latest call's array. -1.2's last program then prints `name-..a name-..b`, since each call has -a slot of its own. - -The same for a `const` parameter's temporary (section 8): its slot is -reserved to the end of the procedure. - -Cost: a frame bigger by each such call's array. That is not measured -here; in `src/`, arrays returned by calls are small (`Str.fromInt`'s -20 bytes, `Str.encode`'s 4), so the estimate is tens of bytes per -frame. - -### 10.2 A string's bytes - -"Less that is undefined", piece 2. Writing a string constant's bytes, -through a slice of it, either stops the program (a bad address, as now -on Linux, since constants are in read-only data) or changes the -constant for the rest of the run. Which one is the target's choice -(appendix A). Either is defined, and neither touches another -variable. A later `[]const U8` (PROPOSALS) would make it a compile-time -error. - -### 10.3 Views - -A view reading any variable's bytes as an integer type is safe: it -reveals an address, but it can't make one. Writing through a view of a -variable that holds a pointer, slice, procedure, variant, enumeration -or `BOOL` is fenced (5.1), since it would make one of those from -arbitrary bytes. Views of plain data, the survey's every use outside -`Rt`, stay safe. - -### 10.4 `match` on a lent variant - -A `match` on a variant whose case holds references gives names that -are lent as the variant is: a field of a local variant lent by the frame -is lent by the frame. Part B's rules follow. - ---- - -## 11. Part G: a debugging heap - -Unsafe modules are trusted, and trust must be tested. `Heap` gets a -second mode, chosen when the program starts (`RAZ_HEAP=debug` in the -environment, or `Heap.debug(true)` before the first allocation): - -- every freed block is filled with `0DEH` and kept off the free lists - for the next 1,024 frees (a quarantine), so a stale read sees junk - and a stale write is found when the block leaves the quarantine and - its bytes are checked; -- each block gets eight guard bytes after it, checked when it is freed; -- `Buf`, `Vec` and `Pool` fill a retired block with `0DEH` too, so a - slice held across a growth reads junk in the debugging heap and the - old bytes otherwise. - -A break is reported as a failed check is: where, and the calls under -way. `make check` runs the library's tests and `test/run` in both modes. -This is Zig's debug allocator, glibc's `MALLOC_PERTURB_`, and Chrome's -MiraclePtr quarantine, without their reach. It costs nothing unless -chosen. It is the one part that changes no rule and could come first. - ---- - -## 12. Raz beside other languages - -| Language | Spatial | Temporal | Forged pointers | Races | Fence | What it costs | -|---|---|---|---|---|---|---| -| C | none | none | anything | UB | none | nothing | -| C++, hardened | hardened `std` containers; `-fbounds-safety` for C (clang) | none | anything | UB | none | a little | -| 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 | -| Odin, Hare, C3 | checked | none | anywhere | UB | none | a check per index | -| 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 | -| Java, C# | checked | a garbage collector | none | references never tear; `long` may in Java | C#: `unsafe` blocks | a GC, a runtime | -| Swift | checked | reference counting; exclusivity checked at compile and run time | only through `Unsafe*` types | Swift 6: `Sendable`, checked | `Unsafe` in names | refcounting traffic | -| Rust | checked | the borrow checker, at compile time | only in `unsafe` | `Send`/`Sync`, at compile time | `unsafe` blocks and functions | lifetimes, learning, compile time | -| 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 | -| 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 | -| Oberon | checked | a garbage collector | only through `SYSTEM` | n/a | `IMPORT SYSTEM` | a GC | -| 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 | -| Cyclone | fat pointers | regions, checked statically | none | n/a | none | annotations, wider pointers | -| 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 | -| **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 | - -What raz takes from each: - -- **From Modula-3:** the fence by module, and the trust in an unsafe - module's safe interface. The unit of review is a file, as Wirth's - languages always had it. -- **From Ada:** a static rule that a reference can't outlive its - object's level, with no lifetime variables in types. Ada's - accessibility levels are part B's frame, parameters and lasting - memory, nearly exactly. Ada also names deallocation as unchecked. -- **From Rust:** `ret` is lifetime elision written out; `keep` is - `'static`. What raz doesn't take is lifetimes in records, which is - what lets Rust check `Http.Message` and what costs Rust its - learning curve. -- **From Swift:** checking exclusivity at run time where the compiler - can't, as part C counts lends. -- **From Go:** a slice held across a growth sees the old array; and an - honest statement about races. -- **From Vale, `slotmap` and Zig's handle idiom:** generations, - but in a container (`Pool`), not in every pointer, so that the 99% of - pointers that are never freed pay nothing. -- **From Zig:** the debugging allocator as the first line of defence - for unsafe code. - -Where raz ends up: about as safe as Go or Modula-3 for a program that -uses no threads, with no garbage collector and no run time beyond a -count per lend; less expressive than Rust (no record may borrow); and -far simpler to learn and to compile. - ---- - -## 13. Performance - -All measurements are on the session's machine, 4 cores of an x86-64 -virtual machine, using today's compiler. Wall-clock times are the -best of several runs; on this machine they vary by 10 to 20% between -runs, so where it matters instruction counts from `valgrind ---tool=callgrind` are given, which don't vary. - -### 13.1 The compiler's speed - -The largest cost of the proposal to `src/` itself would be checking the -scanner's buffer, if `Scan` stops being unsafe. To measure it, `Scan`'s -`buf: ^U8` was made a checked `[]U8` (with the sentinel inside its -length) and everything else left as it was. Five lines changed: - -| Compile | Pointer (today) | Checked slice | More | -|---|---|---|---| -| `src/Raz.raz`, the compiler itself | 240,851,288 instructions | 251,595,933 | **+4.5%** | -| the generated benchmark, 58,025 lines | 40,305,841 | 42,519,299 | +5.5% | - -`make bench`'s 348,025 lines compile in 625 to 660 ms here, about -530,000 to 557,000 lines a second; 5.5% more is about 500,000 to 528,000, inside the 400,000-line -floor and inside `make prev-bench`'s tenth. Most of the cost is the -scanner's inner loops, `while (c = ' ') ... c := buf[p]`, checking -each byte. Section 21 asks whether `Scan` stays unsafe instead, -leaving the compiler as fast as it is. - -The other changes to `src/` (grown arrays to `Vec`, `intern(s)`, views) -cost nothing measurable: `Vec`'s access through `all` is a slice index, -which is the same check the hand-grown arrays don't have, on paths -much cooler than the scanner's. - -The compiler's own checks (part B, C, the fence) are flags on items -and modules and run while each expression is compiled: no measurable -compile time. - -### 13.2 Kernels - -`MemBench.raz` and `GenBench.raz` (appendix 2): - -| Kernel | Run 1 | Run 2 | What it shows | -|---|---|---|---| -| chase a 1,000,000-node list (16-byte nodes), raw pointers | 8,312 ms | 7,515 ms | the baseline | -| 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 | -| chase a 1,000-node list (in L1), raw pointers | 857 ms | 810 ms | | -| the same through handles | 1,631 ms | 1,643 ms | **1.9–2.0×**: the checks themselves | -| chase 1,000,000 32-byte nodes, raw pointers | 14,001 ms | 13,725 ms | the larger node alone, against row 1: **+70–85%** | -| 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 | -| 1,000 32-byte nodes, raw | 870 ms | 917 ms | | -| 1,000 32-byte nodes, fat pointers | 830 ms | 1,047 ms | within noise to +15% | -| sum 16,000,000 bytes through `^U8`, 50 times | 305 ms | 342 ms | | -| the same through a checked `[]U8` | 271 ms | 434 ms | within noise: the check hides behind the loads | -| sum 4,000 bytes (in L1), 200,000 times, `^U8` | 261 ms | 265 ms | | -| the same, checked `[]U8` | 256 ms | 306 ms | 0–15% | - -What they say: - -- **Bounds checks are cheap.** On sequential access the check is - hidden by the loads it guards. This is why nobody uses `check off;`. -- **A generation check is cheap when it is in the object's cache line** - (the fat-pointer rows). **Wider references are not cheap:** doubling a - node from 16 to 32 bytes costs 70 to 85% when the structure doesn't fit - in the caches. This is the main argument against making every `^T` - a fat generational pointer (section 19). It is also why `Pool`'s - handles cost half again: the 32-byte slots, not the check. -- **Handles cost 1.5–2× where pointer chasing dominates**, which is - linked lists and trees. A safe program pays it only for the records - it frees one by one; everything else stays a lasting `^T` with no - check. - -### 13.3 What each part costs a program - -| Part | Cost | Where | -|---|---|---| -| A, the fence | none | compile time | -| B, lending | none | compile time | -| 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 | -| C, retired blocks | memory: at most the current block again, only while a lend is held across a growth | rare | -| D, no `free` | none for lasting pointers; handles where chosen, 1.5–2× on chasing | `Pool` users only | -| 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 | -| E, atomic counts | about 20 cycles per lend, with threads only | | -| F, temporaries | frame size | | -| G, the debugging heap | none unless chosen | | - ---- - -## 14. Ergonomics - -### 14.1 What doesn't change - -Most raz is already safe under this proposal: the survey's `Parse`, -`Item`, `Sym` and `Gen`, `tools/`, rjson's parser, rflate's inflater, -rterm. They use records, slices, `var`, `const` and pointers from -`NEW`, and they don't free. For them the change is a few `ret`s in the -library's headings, which the caller never writes. - -### 14.2 What a programmer meets - -**A slice of a buffer kept in a record.** rnet's `Http.Message` keeps -`headers[i].name` as slices of `m^.head`'s bytes and `body` as a slice -of `m^.data`. Under part B and C these are lent by owners and can't be -stored in a record. The choices: - -1. Offsets instead of slices: - - ``` - Header* = record name, value: Span; end; (* Span = record at, len: INT; end *) - proc name*(ret const m: Message; i: INT): []U8; (* m^.head's bytes, lent by m *) - ``` - - which is safe, a little longer, and survives `m^.head` growing. It - is how Rust programs without lifetimes in structs do it. -2. `Http` says `unsafe;`, and keeps its invariant by hand, as it does - today. It becomes one of the modules a reviewer reads twice. - -The proposal recommends the first for libraries, since it is what -the guarantee is for. - -**A slice held across a call that might change its owner.** This is -allowed. Part C counts it, and the owner retires instead of freeing. -rmacs's `save`, with its `path := Buf.bytes(x^.path)` held across -`Buf.reset(tmp)` and `Buf.str(tmp, path)`, compiles and runs as -before. - -**`done` with a slice still held.** This stops the program at run time: - -``` -proc report(x: ^Buffer); -var name: []U8; -begin - name := Buf.bytes(x^.name); - Buf.done(x^.name); (* stops: name still holds a lend *) - ... -end; -``` - -The cure is `name := []` before `done`, or not holding it. It is a -false alarm only when `name` is never read again. Since a stop is -loud and the cure is one line, the proposal accepts it. - -**Owners can't be copied.** `head := m^.head` in rnet becomes -`Buf.take(m^.head, head)`. The survey didn't count such copies; rnet's -`Http.reset` is the one found by reading. - -**Records that come and go.** An editor's windows, freed when closed, -become a `Pool(Window)` with `Handle`s where rmacs had `^Window` and -`Mem.free`. Each access is `Windows.at(pool, h)^.field` or `get`. This is -longer than `w^.field`, and 1.5–2× slower in a pointer-chasing loop, -which an editor doesn't have. - -**An arena with links.** A tree built in an arena with `^Node` links -can't be safe (8.4): links are stored in records, and lent pointers -can't be. It becomes indexes into a `Vec(Node)`, which is often faster -(smaller, contiguous), or stays in an unsafe module. - -**Strings that must be freed.** `Str.copy` and `Str.free` become -`Names(V)` or a `Buf` per string (8.3). - -**Threads.** `Thread.spawn(work, ^U8(ADR(job)))` becomes -`Jobs.spawn(work, job)`, with `import Jobs := Task(Job)`. That is -shorter. - -### 14.3 What the compiler says - -Each new error names the rule and the mending, in the house style: - -``` -error: ADR is for unsafe modules - help: pass x as a var parameter, or say "unsafe;" after the module's imports -error: Names.put keeps its key, and buf[0..8] is lent by this call's frame - help: give put a copy that lasts: Str.copy(Heap.heap, buf[0..8]) -error: Buf.bytes(b) is lent by b, which counts what it lends: hold it in a slice variable -error: a Buf.Buf owns memory, and can't be copied - help: Buf.take(from, to) moves it -error: Str.trim(s) is lent by s, which isn't marked ret - help: mark the parameter "ret s: []U8" to return what points into it -error: Mem.free is an unsafe procedure - help: free through the container that owns the memory, or say "unsafe;" -``` - -and two new run-time stops: - -``` -Buf.done while 1 slice it lent is still held -Pool.get: a stale handle (slot 4, generation 3; the slot is at 5) -``` - ---- - -## 15. What breaks - -Everything breaks that uses a fenced operation in a module that -doesn't say `unsafe;`, or stores a lent reference, or copies an -owner. By codebase: - -| Code | What breaks | The mending | -|---|---|---| -| `lib/` | every module with a fenced operation: `Rt`, `Mem`, `Heap`, `Arena`, `Bytes`, `Sys`, `Thread`, `Lock`, `C`, `CAbi`, `Buf`, `Vec`, `Map`, `List` | `unsafe;` | -| | `Str`, `Fmt`, `Opt`, `Files` | drop two to five operations each; they become safe | -| | 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 | -| | `Buf`, `Vec`, `Map`, `List`, `Arena`: a `LENDS` field, retiring, `done`'s stop, `take`, `swap` | about 15 lines each | -| | new: `Pool`, `Task`, `Names`, `Lock.Guarded`, `Arena.allocator`; `Heap`'s debugging mode | about 400 lines in all | -| | `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 | -| `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;` | -| `tools/` | nothing fenced; any `Map.put` of a frame slice | none found | -| `examples/` | `Args`, `Cpu`, `Pthreads`, `Printf`, `Window`, `Volatile`, `Sh`, `Workers` | `Args`, `Sh`, `Workers` mended; the other five say `unsafe;`, as examples of it | -| `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 | -| rnet | `Http.Message` keeps lent slices; `reset` copies `Buf`s; `Thread.spawn` | spans and accessors; `take`; `Task` | -| rjson | `Str.free` and `Mem.free` (6); a few casts | `Names` or `Buf`; views | -| rflate | none beyond `ADR` at calls (gone with v0.19.0's library) | none | -| rsqlite | C | `unsafe;` on `Sqlite` | -| rmacs, ravite | `ADR` at calls (gone with v0.19.0); `Mem.free` (9 and 2) of windows and buffers | `Pool` | -| rlX11 | casts on X11 replies | views; one unsafe module for the socket's bytes | -| rmacs's and ravite's `Scan` use | `tools/Scan.raz` | nothing fenced | - -Every break is found when compiling, with a message that names its -mending, except a `done` while a lend is held, which shows up at run -time with a message. No program changes meaning without an error. - -A `raz -fix` (or `tools/Mutate.raz` taught the rewrites) can make -the mechanical ones: `ADR(x)` at a `var` parameter, `^F64(ADR(x))` to -a view, `intern(ADR(s[0]), LEN(s))` to `intern(s)`, `unsafe;` where a -module keeps a fenced operation after those. - ---- - -## 16. Changes to the report - -The report grows by about three pages, from 32 to 35, inside its -40. By section: - -**1. A first look.** One paragraph: what is safe, what `unsafe;` -means, where to read more. - -**3. Modules.** The grammar takes the line: - -``` -Module = "module" ident [ "(" ModParams ")" ] ";" - { Import } { Link } [ Check ] [ Unsafe ] { Declaration } - [ "begin" Statements ] "end" ident "." . -Unsafe = "unsafe" ";" . -``` - -A new paragraph, **`unsafe;`**, says what it allows (the table of -5.1), and that `link` and `check off;` need it. **Generic modules**: -an instance is safe or unsafe as its generic module is, as with -`check`. - -**5.3 Slices.** "A slice is aligned to twice an address's -alignment, and read and written in one access (7.6)." - -**5.4 Pointers.** A paragraph: in a safe module a pointer is `nil`, -from `NEW`, or from the library; section 8.x says how long it lives. - -**5.5 Records.** **Owners**: a record with a `LENDS` field; it can't -be copied in a safe module (7.6 of this proposal). `LENDS` joins the -basic types in 5.1, as a type only a record's field may have. - -**5.9 Procedure types.** `unsafe proc`, and the marks `ret` and `keep`, -which a procedure type carries; what may stand where (PROPOSALS). - -**6.4 Pointers.** `p + i`, `p - i`, `p[i]` and `p[lo..hi]`: "only in an -unsafe module". - -**6.7 Conversions.** The pointer rows: "only in an unsafe module". - -**6.8 Built-in procedures.** `ADR`, `PTR`, `SYSCALL` and `ARGV`: "only in -an unsafe module". `NEW` (part D): what it gives lasts, or is lent by -its allocator's owner. `CAS`, `XCHG` and `XADD` take a variable. - -**6.9 Views.** Writing a view of a variable that holds a pointer, -slice, procedure, variant, enumeration or `BOOL`, and a view as a -pointer type, are for unsafe modules. - -**7.3 Return.** The paragraph on slices of the frame is replaced by a -reference to the new section 8.x, which covers every route. - -**7.6 Volatile.** "Nothing else of the program becomes undefined by -it" becomes: a race on a variable of a basic, pointer, procedure or -slice type gives a value it had or was given, never a mixture; a race -on anything else, or on a container's procedures called at once, is -outside the guarantee (10). - -**8. Procedures.** The marks `ret` and `keep` in the grammar, -`Params = [ "ret" ] [ "keep" ] [ "var" | "const" ] ...`, and -`ProcDeclaration` takes `[ "unsafe" ]` before `proc`. A new section, -**8.x Lending**, about two pages, with part B's rules (lasting, -lent, by whom; what may be done with each) and part C's counting, -and the examples of 6.4 of this proposal. An array a call returns, and a -`const` parameter's temporary, live to the end of the procedure -(part F). The paragraph "kept past its statement ... the exception of -section 10" goes. - -**9. Calling C.** "`extern` and `link` only in an unsafe module." - -**10. Programs.** **Defined behaviour** becomes **The guarantee** -(section 3), and the list of exceptions shrinks to one sentence: an -unsafe module, a code procedure and C may break memory, and what -follows isn't defined; a safe program can't. The stops stay as they -are, and the two new run-time stops are added: an owner's `done` with -lends held, and a library container's own checks (a stale handle). **Errors**: a -fenced operation outside an unsafe module, a lent value where it can't -go, a copied owner, a call of an `unsafe proc` from a safe module. - -**Appendix A.** How slices are made one access (16-byte moves, or a -lock, or a refused target); whether writing a string constant stops or -changes it; how the debugging heap is chosen. - -**Appendix B.** The grammar's new lines. - -**The library volume.** `unsafe proc` and `ret`/`keep` in every -heading; `Pool`, `Task`, `Names`, `Lock.Guarded`; owners' `take`, -`swap` and their stop; `Heap`'s debugging mode. `Mem.Allocator` -described as an unsafe interface. Which modules are unsafe, and their -promise. - -**`doc/report-history.md`**, **`doc/compiler.md`** (each rule, where in -the compiler, with code before and after), **raz(7)**, the tutorial and -`STANDARDS.md` ("a parameter is a value, `var`, `const`, or `keep`; a -pointer only in an unsafe module or where `NEW` gave it"). - ---- - -## 17. Changes to the library - -| Module | Change | -|---|---| -| `Mem` | `Allocator`'s fields `unsafe proc`; `free`, `unmap`, `pages` `unsafe proc`s | -| `Heap` | `free` unsafe; the debugging mode (part G); big blocks' address ranges kept reserved after `free` in debugging mode | -| `Arena` | an owner; `allocator(ret var ar)`; `reset` and `done` stop if lends are held | -| `Buf` | an owner; `bytes`, `spare` `ret`; retiring; `done` stops; `take`, `swap` | -| `Vec` | an owner; `all`, `add`, `tryAdd` `ret`; `push`, `tryPush` `keep x`; retiring; `done` stops; `take`, `swap` | -| `Map` | an owner (it counts no lends, but isn't copied); `put` `keep k`, `keep v` | -| `List` | an owner; `push` `keep v` | -| `Str` | `trim`, `trimLeft`, `trimRight`, `cut`, `field` `ret`; `free` unsafe; `copy` documented as lasting; safe module | -| `Fmt`, `Opt`, `Files` | made safe; `Opt.init`, `scope` `keep` | -| `Sys` | the raw-pointer calls `unsafe proc`; `nextEntry` `ret`; the rest safe to call | -| `Thread` | `spawn` unsafe; `Mutex` taken by `var`, as now | -| `Lock` | `Guarded(T)` | -| new `Pool(T)` | 8.2 | -| new `Task(T)` | 9.2 | -| new `Names(V)` | 8.3 | - ---- - -## 18. Changes to the compiler - -Where each part goes in `src/`, and about how big each is. The -budget is 14,000 lines of code and the compiler is about 11,500 today. - -| Part | Where | Lines | -|---|---|---| -| 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 | -| 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 | -| 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 | -| D. `NEW`'s provenance | lasting or lent by its allocator | 20 | -| 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 | -| F. Temporaries | the slot reserved to the end, as `defer`'s are | 20 | -| Messages, with help | | 100 | -| **In all** | | **840–990** | - -So the compiler grows to about 12,400–12,500 lines, inside the budget, -with room for the documentation the house style demands. The -rewrite of `src/` to be safe (section 15) takes lines away: 35 grown -arrays made `Vec`s. - -Each rule is explained in `doc/compiler.md` where it is done, with the -code before and after, as CLAUDE.md asks. - ---- - -## 19. Alternatives considered - -**A garbage collector.** It would make `free` and part C unneeded, as in -Go, Java and Oberon. It is rejected: raz promises "a static executable -with no run time besides the code it uses" (10). A collector needs -stack maps, barriers or pauses, and a heap the language owns, and it -would end raz as a systems language with a C-like footprint. - -**Rust's borrow checker.** It closes everything, races included, at -compile time. It is rejected for raz: lifetimes in types, regions -inferred over whole procedures (non-lexical lifetimes are a fixpoint -over the control flow, not one pass), and a learning curve that is -the opposite of "a beginner can follow". The proposal takes from it -`ret` (elision, written) and `keep` (`'static`), and leaves out -lifetimes in records, knowing what that costs (14.2). - -**Fat generational pointers for every `^T`** (Vale). Every `^T` would -become (address, generation), and `free` would be safe and checked at -every dereference. Measured (13.2): the check costs little, since the -generation sits in the object's cache line, but doubling a pointer -cost 70–85% on a structure past the caches. Records with pointers grow, -C interop needs a second, raw pointer type, and the 1,015 dereferences -in `src/`, of memory never freed, would pay for a check they can't fail. -It is kept as a fallback if part D proves too narrow: `Pool` is the -same mechanism, where it is paid for only by what is freed. - -**Statically killing a lent slice when its owner changes.** One-pass -flow analysis can't see a loop's back edge, and through a pointer -every call may change the owner (7.1). It would need a second pass, or -a rule so strict ("a lent slice dies at the end of its statement") -that `s := Buf.bytes(b)` over several lines, 35 places in the survey, -would all break. - -**Stop on growth while lent, instead of retiring.** It is simpler to -explain, and it finds the stale-pointer bug in 1.2 at once. But it also -stops `Buf.str(b, Buf.bytes(b))`, which is right and common in other -languages (Go's `append(s, s...)`). Retiring keeps right programs -running, and the debugging heap (part G) shows the stale ones. - -**Thread-local module variables, or `Send`/`Sync`.** They are needed -for a static race guarantee. They are left for later (9.3): they -cost a second type system for a feature little used. If they come, -part E's statement grows to cover every program, and nothing else in -this proposal changes. - -**Hardware: memory tagging (ARM MTE) and CHERI.** They catch use -after free and out-of-bounds by tagging memory and pointers. They -help unsafe modules and C, they aren't on x86-64, and they are -probabilistic (MTE's four bits). They would make part G stronger, -not replace B to D. - -**Only the fence (PROPOSALS' piece 4).** It is cheap and gives a list -of modules to audit, but what it leaves undefined in safe code is -exactly 1.2's first four programs. A fence around code that is still -unsafe would mislead the reader. That is why this proposal exists. - ---- - -## 20. Order of work - -Each step is a release, and each leaves `make check` passing and every -program building, with warnings where a later step will make errors. - -1. **The debugging heap (G).** It changes no rule, and finds bugs in - today's code, the library's above all, before the rules arrive. - Run `make check` under it. -2. **Temporaries to the end of the procedure (F.1), strings (F.2).** - No program breaks. -3. **Atomic slices, and 7.6 rewritten (E.1, E.2).** No program breaks. -4. **`ret` and `keep` (B), as warnings,** then errors a release later. - Mark the library. This is PROPOSALS' part 3, extended to - pointers. -5. **Owners (C).** `LENDS` in the containers, retiring, counting, - `take` and `swap`; the copy check as a warning, then an error. -6. **The heap (D).** `Pool`, `Names`, `Task`; `free` an `unsafe - proc`, warned of first. -7. **The fence (A),** last, as a warning for one release, then an - error, once everything it would flag has a safe form. `src/` comes - to it, keeping `Scan` unsafe, or not, by the owner's word (21). -8. **The report's guarantee (section 10),** stated when step 7 makes - it true. - -`src/` must build with the release `BOOT` names, so it takes up each -step one release after the step ships. - ---- - -## 21. Open questions - -1. **Does `Scan` stay unsafe?** Checking its buffer costs the - compiler 4.5% (13.1). Leaving it unsafe keeps the speed, and the - compiler then has one unsafe module, which is easy to read. -2. **`LENDS` as a type, or a mark on the record** (`owner record`)? - The field makes the count visible to the module that reads it, and - needs no new word; a mark would be more explicit. -3. **Should `done` with a lend held leak instead of stopping?** It - would mean no false alarms, but a silent leak that can grow. -4. **Is a local record holding an owner-lent slice worth allowing?** - (7.3 forbids it.) It needs one hold per reference in the record, and - a let-go when the record is reassigned. `Fmt.Arg` arrays are the - case: `[Fmt.str(Buf.bytes(b))]` is fine inside a statement, but not - held in a local array. -5. **Is the race guarantee enough?** A cheap dynamic check would close - the container case in programs with threads: each owner records - the thread that last changed it, and changes from another thread - without the lock stop the program, as Swift's exclusivity checks do. -6. **`Pool`'s handle**: two words, or one, with 40 bits of index and 24 - of generation? One word fits in a register and halves `Pool`'s - memory for handles, and generations would wrap after 16 million - frees of one slot. -7. **`unsafe` per procedure, not per module?** Rust's `unsafe` blocks - are finer. A module is raz's unit of review, and a module can be - split, but `Sys` would need a split into a safe and an unsafe half - for readers to see the difference. - ---- - -## Appendix 1: the survey's numbers - -Places of each operation, counted once each, by the instrumented -compiler. `deref` and `new` are shown for scale; they stay safe, as -does `p - q`, which the module table below counts with the rest. - -| Code | `ADR` | deref | `p[i]` | `p[a..b]` | `p ± i` | `p - q` | ptr cast | int→ptr | ptr→int | view | `NEW` | `SYSCALL` | -|---|---|---|---|---|---|---|---|---|---|---|---|---| -| raz `src/` | 27 | 1,015 | 277 | 30 | 3 | 0 | 42 | 0 | 0 | 0 | 5 | 3 | -| raz `lib/` | 144 | 93 | 88 | 14 | 49 | 2 | 52 | 13 | 4 | 2 | 1 | 140 | -| raz `examples/` | 15 | 46 | 2 | 1 | 0 | 0 | 5 | 0 | 0 | 3 | 1 | 0 | -| raz `test/libc` | 110 | 15 | 35 | 11 | 18 | 0 | 64 | 1 | 6 | 0 | 1 | 0 | -| rnet | 471 | 359 | 0 | 0 | 0 | 0 | 9 | 1 | 1 | 0 | 0 | 0 | -| rjson | 91 | 105 | 0 | 7 | 1 | 0 | 13 | 0 | 0 | 0 | 0 | 0 | -| rflate | 61 | 102 | 0 | 0 | 0 | 0 | 7 | 0 | 0 | 0 | 2 | 0 | -| rsqlite | 38 | 12 | 1 | 3 | 0 | 0 | 2 | 0 | 1 | 0 | 0 | 0 | - -The fenced operations of each module of `src/` and `lib/`: - -| Module | Fenced | Of which | -|---|---|---| -| `src/Scan` | 99 | `p[i]` 76, casts 12, `p[a..b]` 6, `ADR` 3, `p ± i` 2 | -| `src/Link` | 71 | `p[i]` 63, `p[a..b]` 4, casts 4 | -| `src/Chunk` | 65 | `p[i]` 53, casts 10, `p[a..b]` 1, `ADR` 1 | -| `src/X64` | 31 | `p[i]` 23, `ADR` 5, casts 3 | -| `src/Diag` | 23 | `p[i]` 15, `p[a..b]` 3, casts 3, `ADR` 2 | -| `src/Elf` | 23 | `p[i]` 17, `p[a..b]` 3, `ADR` 3 | -| `src/Parse` | 21 | `p[a..b]` 8, `ADR` 5, `p[i]` 5, casts 2, `SYSCALL` 1 | -| `src/Sym` | 17 | `p[i]` 12, casts 3, `ADR` 2 | -| `src/Item` | 16 | `p[i]` 5, `p[a..b]` 4, casts 4, `ADR` 3 | -| `src/Gen` | 8 | `p[i]` 5, `ADR` 2, casts 1 | -| `src/Raz` | 8 | `p[i]` 3, `SYSCALL` 2, `ADR` 1, `p[a..b]` 1, `p ± i` 1 | -| `lib/Sys` | 287 | `SYSCALL` 129, `ADR` 98, `p[i]` 31, casts 12, `p ± i` 8, `p[a..b]` 6 | -| `lib/Rt` | 111 | `p ± i` 32, `p[i]` 31, casts 20, `ADR` 10, int→ptr 10, `SYSCALL` 6 | -| `lib/Thread` | 33 | `ADR` 16, casts 6, `SYSCALL` 5, `p[i]` 3, `p ± i` 3 | -| `lib/Map` | 19 | `p[i]` 16, casts 3 | -| `lib/Heap` | 16 | `p ± i` 4, casts 4, ptr→int 4, `p[i]` 2 | -| `lib/Bytes` | 10 | `ADR` 5, casts 5 | -| `lib/Buf` | 6 | `p[a..b]` 4, `p[i]` 1, `ADR` 1 | -| `lib/Opt` | 5 | `ADR` 5 | -| `lib/Arena` | 4 | `p ± i` 2, `ADR` 1, cast 1 | -| `lib/Fmt` | 4 | `ADR` 4 | -| `lib/Files`, `lib/Str` | 3 each | | -| `lib/Lock`, `lib/Mem` | 2 each | | -| `lib/List` | 1 | | -| `lib/Math`, `Out`, `Sort`, `Width` | 0 | | - -`Vec` (generic, and instantiated by no program surveyed) has 11 by -`grep`. `C` and `CAbi` are `extern` declarations (96 and 2). - -By `grep`, for the code today's compiler refuses (written before -`INT`): - -| Code | Lines of code | `ADR` | at a call | casts | frees | `done` | `reset` | -|---|---|---|---|---|---|---|---| -| rmacs | 4,323 | 560 | 556 | 9 | 9 | 16 | 66 | -| ravite | 2,185 | 202 | 200 | 3 | 2 | 1 | 15 | -| rlX11 | 5,226 | 89 | 87 | 3 | 1 | 0 | 0 | - -## Appendix 2: the benchmarks - -Built with `raz -o MemBench MemBench.raz` and run as they are. Both -are in the session's scratch space and can be added to `test/bench` -if the proposal goes ahead. - -``` -module MemBench; -import Out, Sys; - -const - Big = 1000000; (* past the caches *) - Small = 1000; (* in L1 *) - Bytes = 16000000; - -type - Node = record next: ^Node; val: INT; end; - H = record i: INT; gen: INT; end; - Slot = record next: H; val: INT; gen: INT; end; - -var - nodes: [Big]Node; - slots: [Big]Slot; - perm: [Big]INT; - bytes: [Bytes]U8; - sink: INT; - -(* A random cycle through the first n nodes, the same in both arrays *) -proc build(n: INT); -var i, j, t: INT; seed: U64; -begin - seed := 7; - for i := 0 to n - 1 do perm[i] := i; end; - for i := n - 1 to 1 by -1 do - seed := seed * 6364136223846793005 + 1442695040888963407; - j := INT(seed shr 33) mod (i + 1); - t := perm[i]; perm[i] := perm[j]; perm[j] := t; - end; - for i := 0 to n - 1 do - j := perm[(i + 1) mod n]; - nodes[perm[i]] := {next: ADR(nodes[j]), val: i}; - slots[perm[i]] := {next: {i: j, gen: 3}, val: i, gen: 3}; - end; -end; - -proc chasePtr(steps: INT): INT; -var p: ^Node; s, k: INT; -begin - p := ADR(nodes[perm[0]]); - for k := 1 to steps do s := s + p^.val; p := p^.next; end; - return s; -end; - -(* As a checked Pool.get would: the generation, and the index *) -proc chaseHandle(steps: INT): INT; -var h: H; s, k: INT; -begin - h := {i: perm[0], gen: 3}; - for k := 1 to steps do - if slots[h.i].gen # h.gen then Sys.exit(3); end; - s := s + slots[h.i].val; - h := slots[h.i].next; - end; - return s; -end; - -proc sumPtr(p: ^U8; n, reps: INT): INT; -var s, i, r: INT; -begin - for r := 1 to reps do - for i := 0 to n - 1 do s := s + INT(p[i]); end; - end; - return s; -end; - -proc sumSlice(b: []U8; reps: INT): INT; -var s, i, r: INT; -begin - for r := 1 to reps do - for i := 0 to LEN(b) - 1 do s := s + INT(b[i]); end; - end; - return s; -end; -``` - -`main` builds `Big`, times each chase for 100,000,000 steps, builds -`Small`, times each for 500,000,000, then the sums: 16,000,000 bytes 50 -times and 4,000 bytes 200,000 times. `GenBench.raz` is the same chase -with 32-byte records on both sides: - -``` -type - Node = record next: ^Node; val, pad1, pad2: INT; end; - GP = record p: ^GNode; gen: INT; end; - GNode = record gen: INT; next: GP; val: INT; end; - -proc chaseGen(steps: INT): INT; -var g: GP; s, k: INT; -begin - g := {p: ADR(gnodes[perm[0]]), gen: 5}; - for k := 1 to steps do - if g.p^.gen # g.gen then Sys.exit(3); end; - s := s + g.p^.val; - g := g.p^.next; - end; - return s; -end; -``` - -The compiler's instruction counts: `valgrind --tool=callgrind raz -I src --I build/src -o /dev/null src/Raz.raz`, the same compiler built twice -from `src/`, once with `Scan.State.buf: ^U8` and once with `[]U8`. The -five lines changed were the field's type, `grab(n + 1)[0..n + 1]`, -`Diag.addFile(path, PTR(cur.buf), n)`, the local `buf` in `next`, and -`intern(PTR(buf) + start, p - start)`. The second compiler builds -itself. - -## Appendix 3: the five programs of section 1 - -``` -module SelfAppend; -import Buf, Heap, Out; - -proc main*; -var b: Buf.Buf; i: INT; -begin - Buf.init(b, Heap.heap); - for i := 1 to 64 do Buf.add(b, 'a'); end; (* full: 64 of 64 *) - Buf.str(b, Buf.bytes(b)); (* doubles it: or should *) - Out.str(Buf.bytes(b)[56..80]); Out.ln; -end; - -end SelfAppend. -``` - -Prints `aaaaaaaaaaaaaaaaaaaaaaaa`, status 0: right, by luck. - -``` -module Stale; -import Vec := Vec(INT), Heap, Out; - -proc main*; -var v: Vec.Vec; first: []INT; i: INT; p: ^INT; -begin - Vec.init(v, Heap.heap); - for i := 1 to 16 do Vec.push(v, i); end; - first := Vec.all(v); (* good until v next grows *) - p := Vec.add(v); (* grows: first now points at freed memory *) - p^ := 99; - for i := 0 to 15 do Vec.push(v, 1000 + i); end; (* grows again: p is stale *) - p^ := -1; (* writes into a block the heap has taken back *) - Out.int(first[0]); Out.str(" "); Out.int(first[1]); Out.ln; -end; - -end Stale. -``` - -Prints `1 2`, status 0: it read and wrote freed memory, and looks right. - -``` -module Escape; -import Out; - -type Hex = [16]U8; - -proc head(var h: Hex): []U8; -begin - return h[0..8]; (* allowed: h is the caller's *) -end; - -proc short: []U8; -var h: Hex; i: INT; -begin - for i := 0 to 15 do h[i] := 'x'; end; - return head(h); (* a slice of short's frame: not caught *) -end; - -proc noise; -var junk: [64]U8; i: INT; -begin - for i := 0 to 63 do junk[i] := '#'; end; -end; - -proc main*; -var s: []U8; -begin - s := short(); - noise; - Out.str(s); Out.ln; -end; - -end Escape. -``` - -Prints `########`, status 0: `noise`'s bytes, read through a slice of -a dead frame. - -``` -module Kept; -import Names := Map([]U8, INT, Str.hash, Str.eq), Str, Heap, Out; - -var table: Names.Map; - -proc remember(n: INT); -var buf: [8]U8; -begin - buf := "name-000"; - buf[7] := U8('0' + n); - _ := Names.put(table, buf[0..8], n); (* the map keeps a slice of this frame *) -end; - -proc main*; -var v: INT; ok: BOOL; -begin - Names.init(table, Heap.heap); - remember(1); - remember(2); - v, ok := Names.get(table, "name-001"); - Out.str("name-001: "); if ok then Out.int(v); else Out.str("missing"); end; Out.ln; - v, ok := Names.get(table, "name-002"); - Out.str("name-002: "); if ok then Out.int(v); else Out.str("missing"); end; Out.ln; -end; - -end Kept. -``` - -Prints `name-001: missing` and `name-002: missing`, status 0. - -``` -module Temp; -import Out; - -type Name = [8]U8; - -proc named(c: U8): Name; -var n: Name; -begin - n := "name-..."; n[7] := c; - return n; -end; - -proc main*; -var a, b: []U8; -begin - a := named('a')[0..8]; (* the array lives to the end of the statement *) - b := named('b')[0..8]; - Out.str(a); Out.str(" "); Out.str(b); Out.ln; -end; - -end Temp. -``` - -Prints `name-..b`, a space and eight bytes of junk, status 0. - ---- - -## Appendix 4: adversarial review, soundness - -This appendix tests section 3's promise against parts A to F, read as -written. It finds 12 ways a program of safe modules and the library, as -section 17 would change it, still breaks the guarantee; 7 ambiguities -or contradictions; and 3 problems with checking or building the rules -in one pass. Two of the breaks are in today's language too, and the -proposal leaves them as they are: a variant changed while `match` names -its fields, and an `ERROR` written through a view. Both were run with -today's compiler. The rest follow from the text of the proposal. - -### Breaks the guarantee - -**1. A variant changed under its `match`.** - -``` -type V = variant ptr(p: ^INT); num(n: INT); end; -var v: V; (* a module variable *) -proc flip(a: INT); begin v := num(a); end; -... -v := ptr(q); -match v of -| ptr(p): flip(h.(INT) + 8); p^ := 1000000; (* p reads num's bytes as a pointer *) -| num(_n): -end; -``` - -Run today, this sets the length of a heap slice, `h^.s`, to 1,000,000. -Every operation in it stays safe under 5.1: the view only reads a -pointer's bytes as an integer (10.3), and that is allowed. 7.4 says the -names stand for the fields of `s` itself, and nothing stops the arm, a -call it makes, or an alias (`var` parameter, pointer) from giving `s` -another case. 10.4 covers only lending. Fix: in a safe module, an arm's -names are a copy of the fields whenever the arm could change the -variable (any call, any store through a pointer or `var` parameter, or -the variable named), or each use of a name checks the tag first. Cost: -a compare per use, or a copy per `match`, and one line less of 7.4. - -**2. An `ERROR` written through a view.** `e.(INT) := h.(INT); -Out.str(MSG(e))` printed 64 KB of memory today. `ERROR` is an address -(5.8), but the list in 5.1 and 10.3 of what may not be written through -a view (pointer, procedure, slice, variant, enumeration, `BOOL`) leaves -it out. Fix: add `ERROR`, and better, state the rule the other way round: -a view may write only a variable made wholly of the types 6.9 allows as -a view's `T`. Cost: none. - -**3. A safe module makes its own allocator.** `Mem.Allocator`'s fields -are exported. 5.2 lets a safe procedure stand where an `unsafe proc` -type is wanted. So a safe module can build `{alloc: mine, free: none}` -and pass it to `NEW`. Its `mine` can return the same lasting `^U8` for -every call, or a 1-byte block for a large `T`. Then `NEW` zeroes and -hands out memory that two pointers of different types share, or that -runs past its block. The same goes for copying `Arena.allocator(ar)^`, -or `ar.base`, into a heap record and passing that: Arena's `alloc` -casts its argument to `^Arena`, and reads past the copy. The trust of -5.3 is broken by code the trusted module calls back. Fix: a field of an -`unsafe proc` type may be set only in an unsafe module, and -`Mem.Allocator` becomes a type safe code can't build or copy (its -fields unexported, copying refused as for an owner). Cost: a rule in -5.2 and in 7.6. - -**4. Procedures that take an allocator report arena memory as lasting.** -`Mem.alloc`, `Str.copy` and the result of `NEW` through such a call -carry no `ret` on their allocator, so by 6.1 what they return is -lasting. Given `Arena.allocator(ar)`, they return arena memory. After -`Arena.reset`, that memory goes to the next `NEW` of another type. The -same holds for `Buf.init`, `Vec.init`, `Map.init`, `List.init` and -`Pool.init`, which keep the allocator in the owner without a `keep` -mark, against obligation 3. Fix: `ret a` on every procedure whose -result comes from `a`, and `keep a` on every `init`. Then an arena's -allocator can't be kept by a container, and what `Str.copy` gives from -it is lent by the arena. Cost: marks on about ten headings. - -**5. Storing a lent slice in an element of a slice.** 6.2 allows a -lent value to be "held in a local variable, or in a field or element of -one". An element of a local slice is someone else's memory: - -``` -proc stash(s: [][]U8); (* s: the caller's array, or a Vec's block *) -var buf: [8]U8; -begin s[0] := buf[0..8]; end; (* allowed by 6.2's words; dangles after return *) -``` - -PROPOSALS' "outliving the call" lists `p^.f` and `p^[i]` but not -`s[i]`. Fix: what is reached through a slice is a place that outlives -the call, as through a pointer, unless the slice is lent only by the -frame. Cost: a few false alarms on local slices of local arrays. - -**6. Only a call's result is counted.** 7.3 counts "where a call -returns a reference lent by an owner". `t := s`, `t := s[1..3]` and -`u := t^[0..10]`, with `s` held, are not calls. Read as written, `t` -gets no hold. Then `s := []` lets the count fall to zero while `t` -still points into the block, and the next growth frees it. Fix: every -assignment to a local of a value lent by an owner sets that local's -holds, whatever the expression. Cost: none beyond what was meant. - -**7. One hold, two owners.** A value may be lent by two owners at once: -`Buf.bytes(all[0])` with `all := Bufs.all(v)`; `NEW(t, al)` with `T` an -owner, then `Buf.bytes(t^)`; `pick(Buf.bytes(a), Buf.bytes(b))` with -two `ret` parameters. 7.3 gives a local one hidden word. Whichever owner -it leaves uncounted can free or move the memory: the outer `Vec` frees -the block that holds the inner `Buf`, and the hold then lowers a word of -freed memory. Fix: a hold per owner a value can be lent by, which the -compiler knows from the heading. Or forbid an owner reached through an -owner-lent value. Cost: a word per extra owner. The second choice -forbids `Vec(Buf.Buf)` and `Pool` of owners in practice. - -**8. Library containers copy owners.** 7.6 forbids copies only in safe -modules. `Vec`, `Pool`, `Map` and `List` are unsafe and generic, so -they can't know that `T` is an owner. `Pool.get` returns a copy of a -slot. `Vec`'s growth copies every element into the new block, and, with -a lend held, keeps the old copy alive too. `Vec.pop`, `List.pop` and -`Map.get` copy out. Two `Buf`s then own one block: one grows and frees -it, and the other reads it. 7.6's rule also misses the result of a call -(`b := Pools.get(p, h)` isn't "assigned from another variable"). Fix: a -generic module's type parameter may be an owner only if the module says -it takes owners. Those modules move owners, never copy them, and -`get` is refused for them. Cost: a mark on generic parameters, and -`Pool` and `Vec` written for both cases. - -**9. Other routes that copy or overwrite an owner.** None of these is in -7.6's list: - -- `COPY(y, x)` on arrays of owners; -- `match` on another module's variable, which today names fields of a - copy (confirmed by running it), and so counts on the copy; -- a variant case built from an owner, `has(b)`, which isn't plainly - "a literal"; -- `b := {}`, `x^ := {}`, and `Pool.add(p, {})`, which 7.6 allows, and - `Buf.init(b, a)` on a `Buf` with a lend held. Each sets `lends` to - zero under a hold. The hold's later let-go makes it -1. The next lend - brings it back to 0 while that slice is held, and the next growth - frees the block under it. - -Fix: state the rule as "a value of a type that holds an owner is never -copied or overwritten in a safe module, nor by the library while its -`lends` is above zero". Add `COPY`, case construction, `match` on a -copy, and `{}` over a variable that isn't already empty (or make -`init` and `{}` stop when `lends` isn't zero). Cost: a few rules and a -test in each `init`. - -**10. `take`, `swap` and the count.** 7.6 names `Buf.take(var from, to)` -and `Buf.swap` and says nothing of `lends`. Holds point at `from.lends`. -After the move, `to` owns the block with a count of 0, and frees it at -its next growth while the slices are held. Fix: `take` and `swap` stop -when either owner's `lends` is above zero. Cost: a compare each. Add it -to obligation 2. - -**11. Letting go of a hold while a `match` names its fields.** - -``` -p := Vs.add(v); p^ := a("abc"); -match p^ of -| a(s): p := nil; grow(v); Out.str(s); (* s names a field of a freed block *) -| b: -end; -``` - -The names stand for the variable in place, and assigning `p` lets its -hold go. Fix: a `match` on a lent variable takes its own count for the -whole statement. Cost: an add and a subtract per such `match`. - -**12. The library breaks its own obligations.** Section 17 leaves these -as they are, and each lets a safe program reach freed memory: - -- `List.head*` and `Node.next*` are exported, against obligation 4. - `n := l.head; List.pop(l); n^.val` reads a freed node. -- `Thread.join` unmaps the mapping that holds the `Thread` record. The - `^Thread` that `Task.spawn` returns stays "lasting", and a second - `join` or a `signal` reads, and unmaps by, whatever the address - holds next. -- Over C, `Sys.nextEntry`'s name points into C's `readdir` buffer, - which `closeDir` frees. `Dir` is no owner, so nothing counts it. A - `nextEntry` or `closeDir` after `closeDir` hands C a freed `DIR`. -- Over musl, `Sys.env`'s "lasting" result can be freed by a later - `setEnv` of the same name, since musl frees the strings it made. -- `Names(V)`'s procedures that return a key must be `ret`, or `remove` - frees what they gave. The proposal doesn't give its headings. - -Fix: unexport `List`'s pointers and give an iterator that lends; -`Task` returns an owner handle that `join` takes by `var` and empties; -`Dir` an owner; `env` copied into lasting memory over C. Cost: small, -but it shows that obligations 1 to 5 need an audit of each module, not -only the marks of section 17. - -### Ambiguities and contradictions - -**13. Section 3 calls a racing container program safe.** Section 3's -definition counts a program as safe if its threads race "only on -variables of a basic, pointer, procedure or slice type". Two threads -calling `Buf.add` on one `Buf` race only on such fields (`len`, -`data`), so the guarantee claims their behaviour is defined. 9.2 says -it isn't. Fix: put 9.2's "a container's procedures called at once" -into section 3's sentence. - -**14. A slice in a packed record, or in a block aligned to 8.** E.1 -promises one access for every slice. A slice field of a packed record -is read in parts (5.5). `Vec` asks its allocator for 8-byte alignment. -Either tears, or `movdqa` faults on it. Fix: no slice in a packed -record; every allocator call for a type holding a slice asks for 16. - -**15. Returning what an owner inside a parameter lent.** 6.2 forbids -returning a value "lent by an owner", even when the owner is a `ret` -parameter. So `proc bytes2(ret const b: Buf): []U8 begin return -Buf.bytes(b) end` is an error, and 14.2's recommended -`Http.name(ret const m: Message; i): []U8` can't be written. If it is -allowed, a caller of `name` sees only `m`, which is no owner (7.2), and -has no count to raise. Fix: allow it when the `ret` parameter is itself -the owner. For a record that holds owners, the caller raises each of -their counts, or the accessor is refused. - -**16. When the epilogue lets go.** 7.3 says the let-go happens "as a -`defer` would". If it is placed as a `defer` at the assignment, a user -`defer f(b, s)` written before it runs after the let-go, and `f` can -grow `b` and read `s`. Fix: holds are let go after every deferred -statement has run. - -**17. "The end of the statement" for compound statements.** A count -taken in a `while` condition, a `for` bound, an `if` condition or a -`match` head: is it lowered once per evaluation or at the statement's -`end`? Lowered once at `end`, a `while` raises it each round and leaks -counts. Then `done` stops though nothing is held. A `try` that leaves -mid-statement must lower it too. Fix: say per evaluation, and on every -exit. - -**18. Two arms of one rule for `{}`.** 7.6 forbids passing an owner as -a value parameter but allows a literal that leaves it out. So is -`Pool.add(p, {})` allowed? Item 9 shows why the answer matters. - -**19. Writable constants beyond strings.** F.2 covers a string's bytes. -An array constant of variants, enumerations or `BOOL`s may be sliced -(4), and on a target where constants are writable, a compiler that -folds `match Rows[0]` from the constant's case reads fields of another -case. Fix: on such targets, writing any constant through a slice stops -the program, or slices of non-string constants can't be written. - -### One-pass and implementability problems - -**20. A hold must be kept for every reference local.** A local may hold -a lasting value at one assignment and an owner's lend at a later one -(a loop's next round), and one pass doesn't know the later one when it -compiles the earlier. So every assignment to every slice or pointer -local must test and lower a hold, and every copy from one local to -another must pass the hold on. That cost is per assignment, not "per -lend held", and it falls on `src/`'s pointer loops (`o := o^.next`). -Section 13 doesn't count it. Fix: measure it, or let a hold word exist -only for locals declared with a mark (say `lent s: []U8`), checked at -`end`. - -**21. Atomic counts depend on the whole program.** E.5 makes the counts -`lock xadd` "in a program that imports `Thread`". A module compiled -before another module's `import Thread` is read can't know which to -emit, and separate compilation (10) forbids depending on it. Fix: -always `lock`, or read every module's imports first. Cost: about 20 -cycles per lend, or a pass over the import graph. - -**22. Re-entry through the procedures a container is given.** `Map` -calls `hash` and `eq`, `Sort` calls `less`, `Guarded.with` calls its -procedure, and `Rt.atExit` procedures run after a failed check inside -any of these. A safe callback can call `put`, `remove` or `done` on the -same container while its own code is mid-loop: `done` inside `eq` while -`get` probes leaves `slots` nil with an index still in hand. No -obligation in 5.3 speaks of it, and checking the trusted code for every -re-entry is not one pass of anything. Fix: obligation 6, "a module that -calls a procedure given by safe code holds its own `lends` across the -call", so that `done` stops; the library's containers do it. - -### Checked and found covered - -- `Pool.at` across `Pool.free`: the slot keeps its type, so a stale - pointer reads the wrong record of the right type, as 8.2 says. That - holds except for variants (item 1) and owners in slots (items 7 to 9). -- Retired blocks and `reset`: the bytes keep their type; a held slice - sees new contents, safely. -- `var` parameters aliasing: `f(x, x)` with a `done` inside stops on - the count; a callee assigning the caller's held local through `var` - leaves the hold set, which errs on the safe side. -- Holds and threads: a thread raises a count only while it already - holds one, so the count can't pass through zero under another - thread's test. -- `Task.spawn`: `keep x` refuses lent values, and owners can't be - passed by value. -- `a, b := f(x)` and `return f(x)`: each target is checked as a single - assignment. -- A `const` parameter of another module's variable is passed in place - today (run to confirm), so its count lands on the real owner. -- A safe generic module instantiated with an owner: each instance is - checked, so a copy inside it is refused there. - ---- - -## Appendix 5: adversarial review, claims about other languages and hardware - -This appendix checks every claim MEM_PROPOSAL.md makes about other -languages, hardware, research and precedent. Of 44 claims checked, 5 -are wrong, 22 imprecise, 15 correct and 2 unverifiable. None of the -errors breaks the design. Three of them touch it, though: 21.5 leans on -Swift for a cross-thread check that Swift doesn't make; 9.2 says a -slice published with no lock is safe, which fails on ARM; and 11 files -Chrome's BackupRefPtr under debugging heaps, when it is the closest -precedent for part C. Most of the imprecise ones are table cells that -leave out a condition or a newer fact. - -How it was checked: through the session's proxy, which let through only -GitHub-hosted sources (raw.githubusercontent.com) and web search. So -primary sources were read where they live on GitHub (the Go memory -model and spec, the C# standard, swift-evolution, Zig's langref and -library, Fil-C, Chromium, glibc, slotmap, generational-arena, -portable-atomic, GCC's libatomic, the Linux kernel's MTE document, D's -DIPs, CPython). Vendor manuals (Intel SDM, AMD APM, Arm ARM) and the -Modula-3, Ada and Java texts were checked through quotations that web -search returned. Where a manual's section number could not be seen -directly, the entry says so. - -### Wrong - -**W1. Section 21.5: "changes from another thread without the lock stop -the program, as Swift's exclusivity checks do."** -Wrong. Swift's run-time exclusivity checks are not required to see -accesses from other threads, and by design they don't look. SE-0176 -says: "Dynamic enforcement is not required to detect concurrent -conflicting accesses, and we propose that by default it should not -make any effort to do so ... it can track accesses in a thread-local -data structure." Swift leaves races to Thread Sanitizer and, since -Swift 6, to `Sendable` checking at compile time. -Source: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0176-enforce-exclusive-access-to-memory.md (section "Concurrency"). -Correct wording: "... stop the program. Swift's run-time exclusivity -checks don't do this: they track accesses per thread. The nearest -precedents are Go's run-time check for concurrent map writes and -ThreadSanitizer." - -**W2. Section 12, Zig row: "`@ptrCast`, `@intToPtr` anywhere".** -Wrong name. `@intToPtr` was renamed `@ptrFromInt` in Zig 0.11 (2023), -and `@ptrToInt` became `@intFromPtr`. Today's langref has -`@ptrFromInt` (7 uses) and `@intFromPtr` (6), and no `@intToPtr`. -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). -Correct wording: "`@ptrCast`, `@ptrFromInt` anywhere". - -**W3. Section 12, "Java, C#" row: forged pointers "none".** -Wrong for C#. C# has real pointers, pointer arithmetic and casts from -integers in `unsafe` code. The same row names C#'s `unsafe` blocks as -its fence, so the row contradicts itself. Also, -`System.Runtime.CompilerServices.Unsafe` and `MemoryMarshal` reinterpret -references with no `unsafe` keyword at all, so the fence has holes. Java -can forge addresses through `sun.misc.Unsafe` (its memory methods were -deprecated for removal in JDK 23, JEP 471) and through the FFM API's -restricted methods, which warn unless `--enable-native-access` is given -(JEP 454 and 472). -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. -Correct wording: split the row. Java: "none in the language; -`sun.misc.Unsafe` and FFM restricted methods, behind a flag". C#: "in -`unsafe` code; also the `Unsafe` and `MemoryMarshal` classes, which -need no `unsafe`". - -**W4. Section 9.2, point 1: "A program that hands slices from thread to -thread, publishing a buffer for others to read, is then safe with no -lock."** -Wrong on ARM, and true on x86-64 only if the compiler keeps the stores -in order. Single-copy atomicity means the 16 bytes don't tear. It says -nothing about the order in which other stores are seen. AArch64 is -weakly ordered. A reader can see the new slice and still see old bytes -in the buffer it points at, unless the store is a release (`STLR`, or -`DMB` then `STP`) and the load an acquire. If the buffer was a recycled -heap block, those old bytes may be another type's pointers. That breaks -the type guarantee of section 3, which publication with no lock is -meant to keep. x86-64's TSO keeps store order, so there it holds, -provided the compiler doesn't reorder. -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. -Correct wording: "... is then safe with no lock on x86-64. On AArch64 a -slice store that publishes is a release and its load an acquire; -appendix A says how." - -**W5. Section 12, "Java, C#" row: "references never tear; `long` may in -Java".** -Wrong by omission for C#, the row's other language. The C# standard -(9.6) promises atomic reads and writes only for `bool`, `char`, the -integer types up to 32 bits, `float` and references. It says "Reads and -writes of other types, including `long`, `ulong`, `double`, and -`decimal`, as well as user-defined types, need not be atomic." So C# -structs tear, and that includes multi-word ones such as `ArraySegment` -and `Memory`. C# stays memory-safe anyway because every array access -is checked again against the array itself. That is worth saying, since -it is the other way out of the torn-slice problem. -Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/standard/variables.md#96-atomicity-of-variable-references. -Correct wording: "references never tear; `long` and `double` may (in -C#, structs too), but each array access is checked again". - -### Imprecise - -**I1. Section 9.2: "`movdqa`, which Intel and AMD guarantee single-copy -atomic on processors with AVX"; section 4: "none on x86-64 with AVX".** -Right in substance, but conditions are missing. Intel's SDM Vol. 3A, -"Guaranteed Atomic Operations" (section 9.1.1 in the editions that GCC -and Microsoft's STL quote; numbering shifts between editions), says: -"Processors that enumerate support for Intel AVX (by setting the -feature flag CPUID.01H:ECX.AVX[bit 28]) guarantee that the 16-byte -memory operations performed by the following instructions will always -be carried out atomically: MOVAPD, MOVAPS, and MOVDQA; VMOVAPD, -VMOVAPS, and VMOVDQA when encoded with VEX.128; VMOVAPD, VMOVAPS, -VMOVDQA32, and VMOVDQA64 when encoded with EVEX.128 and k0 (masking -disabled)", with the operands 16-byte aligned. AMD's APM Vol. 2 -(Access Atomicity; I couldn't see the section number) is broader in one -way and narrower in another: "Processors that report CPUID -Fn0000_0001_ECX[AVX](bit 28) = 1 extend the atomicity for cacheable, -naturally-aligned single loads or stores from a quadword to a double -quadword." So AMD's covers any aligned 16-byte load or store, but only -to cacheable memory. Neither promise belongs to "x86-64 with AVX" in -general. GCC's libatomic trusts it only on Intel, AMD, Zhaoxin and -newer Centaur parts, and clears AVX for other vendors: "We don't have -a guarantee from vendors of other CPUs with AVX, like VIA." -"Single-copy atomic" is Arm's term; Intel says "carried out -atomically". -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. -Correct wording: "moved with `movdqa` from a 16-byte-aligned address. -Intel (SDM Vol. 3A, Guaranteed Atomic Operations) and AMD (APM Vol. 2, -Access Atomicity, for cacheable memory) guarantee this atomic on -processors that report AVX, and so does Zhaoxin. Other vendors' AVX -parts take the fallback." - -**I2. Section 9.2: "ARMv8.4 has 16-byte atomic `LDP`/`STP` -(FEAT_LSE2)".** -True, but the conditions and the reach are missing. FEAT_LSE2 is -optional from Armv8.2 and mandatory from Armv8.4. The Arm ARM (DDI -0487, B2.2.1.1, as quoted on LKML) makes LDP/LDNP/STP of two 64-bit -registers single-copy atomic only when the access is 16-byte aligned -and goes to Inner Write-Back, Outer Write-Back Normal cacheable memory. -Many 64-bit Arm machines in use don't have it: Cortex-A72 (Raspberry -Pi 4), Cortex-A76 (Pi 5), Neoverse N1 (AWS Graviton2, Ampere Altra). -They need `LDXP`/`STXP` loops (Armv8.0) or `CASP` (FEAT_LSE, Armv8.1). -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)"). -Correct wording: "With FEAT_LSE2 (mandatory from Armv8.4) an aligned -16-byte `LDP`/`STP` to normal cacheable memory is single-copy atomic. -Earlier cores use `LDXP`/`STXP` or `CASP`." - -**I3. Section 9.2: "On x86-64 without AVX, the implementation uses -`lock cmpxchg16b`".** -Works, with three costs left unsaid. First, CMPXCHG16B (CPUID CX16) is -not in the x86-64 baseline (x86-64-v1): the first AMD64 processors -lack it. Second, a load done as `lock cmpxchg16b` writes the line. So -it faults on read-only pages, needs the memory to be writable (as -portable-atomic's safety comments say), and makes readers contend with -one another. libatomic: "Since load and store are implemented with -CAS, they are not fast." Third, a store needs a CAS loop. Raz keeps -slice constants, `[]` among them, in read-only data. The compiler would -have to know those are never raced and read them plainly. -Sources: https://raw.githubusercontent.com/gcc-mirror/gcc/master/libatomic/config/x86/host-config.h; portable-atomic's x86_64.rs, as above. - -**I4. Section 13.3, row E: "none: two 8-byte moves become one 16-byte -one".** -Not free when the slice goes to or from general registers. That is -the usual case, since raz returns a slice in rax and rdx. A 16-byte -load into an XMM register then needs `movq` plus `pextrq` (or a shuffle -and `movq`) to split it, and a store needs `movq` plus `pinsrq` or -`punpcklqdq` to join it: two to three more uops, and a few cycles of -latency. `pextrq` and `pinsrq` are SSE4.1, which is not baseline -x86-64. This is the machine's cost, and it should be measured like the -others. -Correct wording: "a load or store of a slice through an XMM register: -one or two more instructions where its words go to or from general -registers; records holding slices may grow by padding to 16." - -**I5. Section 7.5: "`inc qword [r]` ... about two cycles each ... `lock -xadd`, about 20 cycles".** -Rough. On Intel, an uncontended `lock` read-modify-write measures about -18 cycles (uops.info, Skylake). On recent AMD cores it is lower. It is -a full barrier, and under contention, with the line bouncing between -cores, it costs hundreds of cycles. That is the case that matters for -two threads lending from one locked `Buf`. A memory-destination `inc` -has a throughput near one a cycle, but about five to six cycles of -latency when chained through store forwarding. -Sources: https://uops.info/html-instr/INC_LOCK_M32.html; https://www.agner.org/optimize/instruction_tables.pdf. -Correct wording: "... `lock xadd`, about 20 cycles uncontended on -Intel, and far more when threads contend for one owner". - -**I6. Section 12, Zig row: "the debug allocator finds use after free and -double frees at run time; nothing in release".** -Partly. `std.heap.DebugAllocator` (renamed from `GeneralPurposeAllocator` -in 0.14.0) lists "Double free detection" and "Leak detection, with -stack traces". It doesn't detect use after free. It "Never reuses -memory addresses" and gives freed pages back "so that it causes page -faults when used", and in safe modes freed memory reads as `0xaa`. So -a use after free may fault or read junk, and nothing reports it as -such. The allocator is chosen by the program, not by the build mode: -it works in ReleaseSafe too. -Source: https://raw.githubusercontent.com/ziglang/zig/master/lib/std/heap/debug_allocator.zig (header comment). -Correct wording: "the debug allocator finds double frees and leaks, and -never reuses addresses, so a use after free tends to fault; a program -chooses it, usually in Debug". - -**I7. Section 12, "C++, hardened" row: "hardened `std` containers; -`-fbounds-safety` for C (clang)".** -This mixes two things. `-fbounds-safety` is a C extension, not C++ -hardening. Apple designed it and ships it in Apple's clang. Upstream, -it is "being incrementally upstreamed", behind -`-fexperimental-bounds-safety`. On the C++ side, the newer fact is -missing: C++26 standardizes library hardening (P3471, adopted at -Hagenberg, February 2025), on top of libc++'s hardening modes and -libstdc++'s `_GLIBCXX_ASSERTIONS`. -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. -Correct wording: C row: "Spatial: none; Apple's `-fbounds-safety` -extension (clang, partly upstream) adds checked bounds". C++ row: -"hardened standard library (libc++, libstdc++; standard in C++26 by -P3471)". - -**I8. Section 12, "Odin, Hare, C3" row: spatial "checked".** -True by default for all three, but each can turn it off. C3 checks -only in its safe (debug) mode, and in fast builds an out-of-bounds index -is undefined. Hare checks every slice and array access, but its `[*]T` -arrays are unchecked. Odin has `#no_bounds_check` and -`-no-bounds-check`. -Sources: https://c3-lang.org/language-rules/undefined-behaviour/; https://harelang.org/blog/2022-06-21-safety-features/. -Correct wording: "checked by default (C3: in safe builds only); each can -turn it off". - -**I9. Section 12, Swift row: fence "`Unsafe` in names".** -Out of date. SE-0458, "Opt-in Strict Memory Safety Checking", is -implemented in Swift 6.2. It adds `-strict-memory-safety`, an `@unsafe` -attribute, a `@safe` attribute for a declaration that is "actually -safe to use" though its signature holds unsafe types, and an `unsafe` -expression "much like `try` and `await`". That is a real fence, and -`@safe` is section 5.3's trust in a safe interface. -Source: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0458-strict-memory-safety.md. -Correct wording: "`Unsafe` in names; since Swift 6.2, an opt-in -checked fence (`@unsafe`, `@safe`, `unsafe` expressions)". - -**I10. Section 12, Ada row: races "protected objects".** -Protected objects are the tool, not the guarantee. In Ada, two -unsynchronized conflicting uses of a shared variable are erroneous (RM -9.10): "The execution of two concurrent actions is erroneous if the -actions make conflicting uses of a shared variable." SPARK, under the -Ravenscar and Jorvik profiles, proves there are no data races. -Source: https://ada-lang.io/docs/arm/AA-9/AA-9.10/. -Correct wording: "erroneous unless synchronized (protected objects, -atomics); SPARK proves their absence". - -**I11. Section 12: "Ada's accessibility levels are part B's frame, -parameters and lasting memory, nearly exactly."** -Overstated. Ada's levels (RM 3.10.2) attach mainly to where an access -type is declared. A library-level access type can't designate a -deeper object. Most checks are static, but those for anonymous access -parameters and some others run at run time and raise `Program_Error`. -There is no notion of "lent by this parameter" for a result. The -closest match to part B is C#'s ref-safety rules: their "safe-context" -values are "declaration-block", "function-member" and -"caller-context". Those are part B's frame, parameters and lasting -nearly one for one. C# 11 adds `scoped` and `[UnscopedRef]`, which play -the roles of `ret` and `keep`. -Source: https://github.com/dotnet/csharplang/blob/main/proposals/csharp-11.0/low-level-struct-improvements.md. -Correct wording: "Ada's accessibility levels are the idea; C#'s -safe-contexts (declaration block, function member, caller) are part -B's three lenders nearly exactly." - -**I12. Section 5.3: "This is Modula-3's rule for an `UNSAFE MODULE` -that implements a safe `INTERFACE`".** -Right as far as it goes, but Modula-3 also fences imports, and raz -doesn't. The Modula-3 report's Safety section says: "It is a static -error for a safe interface to import an unsafe one or for a safe module -to import or export an unsafe interface." Raz lets any safe module -import an unsafe one and fences per procedure (`unsafe proc`). That is -closer to D's `@safe`/`@trusted`/`@system` per function, and to Rust's -`unsafe fn`, than to Modula-3. -Source: https://www.cs.purdue.edu/homes/hosking/m3/reference/safety.html. -Correct wording: add "Unlike Modula-3, which forbids a safe module to -import an unsafe interface, raz fences per procedure, as D's -`@trusted` and Rust's `unsafe fn` do." - -**I13. Section 12: "The unit of review is a file, as Wirth's languages -always had it."** -Modula-3 isn't Wirth's. It came from DEC SRC and Olivetti, building on -Modula-2+. Pascal had no modules, so "always" is wrong. Modula-2 and -Oberon do mark low-level code by importing `SYSTEM` per module. -Correct wording: "The unit of review is a module, as in Modula-2's and -Oberon's `IMPORT SYSTEM` and Modula-3's `UNSAFE`." - -**I14. Section 12, Vale row: "regions skip the check"; races "regions"; -fence "`unsafe`".** -These are mostly Vale's plans. Vale's last release is 0.2 (2022). Its -own project page lists the region borrow checker and hybrid-generational -memory as medium-term goals, and its `unsafe` blocks and "Fearless -FFI" were proofs of concept. Generational references themselves, -section 8.2's claim, are right: each object carries a current -generation, each non-owning reference a remembered one, checked on -dereference. Owning references aren't checked. -Sources: https://vale.dev/memory-safe; https://vale.dev/project; https://vale.dev/blog/version-0.2-released. -Correct wording: "generational references, checked at each -dereference; regions, which would skip the check, are designed and not -finished". - -**I15. Section 12, Cyclone row: temporal "regions, checked -statically".** -Leaves out that Cyclone's heap region is garbage collected -(conservatively, with the Boehm collector). Grossman's PLDI 2002 paper -integrates regions "with stack allocation and a garbage collector". -Unique and reference-counted pointers came later (Hicks et al.). -Cyclone's temporal safety for the heap is a GC, which is what raz -refuses. -Sources: https://www.cs.umd.edu/~mwh/papers/GrossmanMJHWC02.html; https://www.cs.washington.edu/homes/djg/slides/cyclone_pldi02.pdf. -Correct wording: "regions checked statically; the heap region garbage -collected". - -**I16. Section 12, "Fil-C, CHERI" row: "Fil-C: a few times slower"; -"Fil-C: atomic capabilities"; "CHERI: revocation".** -Fil-C's own figures are "about 1.5x-4x slower" (README and Manifesto, -version 0.686). On races, Fil-C says "Pointer races on pointers not -marked `_Atomic` or `volatile` lead to Fil-C panics, at worst". Only -atomic pointers get an "atomic box". CHERI's capabilities give spatial -safety in hardware. Its temporal safety needs software revocation -sweeps (Cornucopia, in CheriBSD), and it costs 128-bit pointers. -Sources: https://raw.githubusercontent.com/pizlonator/fil-c/deluge/README.md; https://raw.githubusercontent.com/pizlonator/fil-c/deluge/Manifesto.md. -Correct wording: "Fil-C: 1.5 to 4 times slower, and a concurrent GC; -CHERI: 128-bit capabilities, and revocation by software sweeps". - -**I17. Section 19: "[MTE and CHERI] aren't on x86-64, and they are -probabilistic (MTE's four bits)."** -Two fixes. First, only MTE is probabilistic: a 4-bit tag per 16-byte -granule (Linux's document: "a 4-bit allocation tag for each 16-byte -granule"), so a stale pointer passes 1 time in 16 by chance. CHERI's -bounds are exact. Second, x86 is on its way: Intel and AMD announced -ChkTag, a common x86 memory-tagging specification, on 13 October 2025, -with no shipping date. MTE is also not only for debugging any more. -Apple's Memory Integrity Enforcement runs Enhanced MTE always on and -synchronously on the iPhone 17 (September 2025). -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. -Correct wording: "They aren't on x86-64 yet (Intel and AMD announced -ChkTag in 2025). MTE is probabilistic, with four bits a tag; CHERI is -exact, but needs software revocation for use after free." - -**I18. Section 11: "This is ... Chrome's MiraclePtr quarantine".** -MiraclePtr is not a debugging heap, and its quarantine isn't a fixed -count. `raw_ptr`, implemented by BackupRefPtr, keeps a reference -count in each PartitionAlloc slot. It is "quarantining the freed memory -as long as any dangling `raw_ptr` pointing to it exists, and -poisoning it (with 0xEF..EF pattern)". Its constructor, destructor and -assignment "need to maintain BackupRefPtr's ref-count (atomic -increment/decrement)". It ships in production Chrome. That makes it a -precedent for part C, not part G: count the references a block has -lent, and retire the block instead of freeing it while the count is -above zero. Its documentation also records the cost part C should -expect: "on a couple occasions it led to significant memory leaks". A -fixed FIFO quarantine with guard bytes, like part G's, is -AddressSanitizer's quarantine and redzones, and GWP-ASan's. -Source: https://raw.githubusercontent.com/chromium/chromium/main/base/memory/raw_ptr.md. -Correct wording in 11: "This is AddressSanitizer's quarantine and -redzones, Zig's debug allocator and glibc's `MALLOC_PERTURB_`, without -their reach." Add to section 7: "Chrome's BackupRefPtr (MiraclePtr) -does the same in C++: it counts a block's references and quarantines -it on free while the count is above zero." - -**I19. Section 3 and 9.2, point 2: a race on a whole record or variant -"is undefined, as in Go".** -Go doesn't call it undefined. The memory model says a racy read of a -multi-word value may see "inconsistent values not corresponding to a -single write". Only "when the values depend on the consistency of -internal (pointer, length) or (pointer, type) pairs, as can be the case -for interface values, maps, slices, and strings in most Go -implementations, such races can in turn lead to arbitrary memory -corruption." Go sets itself apart from C and C++, "where the meaning of -any program with a race is entirely undefined". A race on a plain -struct of integers just gives mixed values. -Source: https://raw.githubusercontent.com/golang/go/master/doc/go_mem.html (go.dev/ref/mem). -Correct wording: "undefined. Go is narrower: a race tears such a value, -and corrupts memory only through its pointer and length or type pairs." - -**I20. Section 9.1: Go's memory model on races over multi-word values.** -The quotation is right, but the list it gives is short. Go names -"interface values, maps, slices, and strings", hedged "in most Go -implementations", and says such races "can in turn lead to arbitrary -memory corruption". The proposal's list drops maps, and its "an -interface, a slice, a string" reads as Go's words when they are a -paraphrase. -Source: as I19. -Correct wording: "Go's memory model says that races on values made of -(pointer, length) or (pointer, type) pairs, 'interface values, maps, -slices, and strings in most Go implementations', 'can in turn lead to -arbitrary memory corruption'." - -**I21. Section 12: "From Swift: checking exclusivity at run time where -the compiler can't, as part C counts lends."** -Loose. Swift's dynamic exclusivity tracks the start and end of each -access to a class property, global or escaped variable, per thread -(W1). It doesn't count. Part C counts outstanding loans and refuses or -defers a release while any is held. That is Rust's `RefCell` (a borrow -count that panics), CPython's `bytearray` (it keeps `ob_exports` and -refuses to resize: "Existing exports of data: object cannot be -re-sized"), Java's and .NET's fail-fast iterators (a modification -count), and Chrome's BackupRefPtr (I18). -Sources: https://raw.githubusercontent.com/python/cpython/main/Objects/bytearrayobject.c; https://raw.githubusercontent.com/rust-lang/rust/master/library/core/src/cell.rs. -Correct wording: "From Rust's `RefCell`, CPython's buffer exports and -Chrome's BackupRefPtr: a count of what is lent, checked at run time, -where the compiler can't see it." - -**I22. Section 8.2: "Part of the first is that each slot is 32 bytes, -not 16"; and open question 6, one word or two for a handle.** -The precedent the proposal cites answers the question, and the -proposal doesn't use it. slotmap's key is one 64-bit word: a 32-bit -index and a 32-bit version (`idx: u32, version: NonZeroU32`). A slot -costs `4 + max(sizeof(T), 4)` bytes. Versions wrap after 2^31 reuses of -a slot, "and in all circumstances is the behavior safe". So the 32-byte -slot of the benchmark comes from the two-word `Handle` chosen here, not -from generational handles as such. The 1.5x past the caches is partly -an artifact of that choice. -Source: https://raw.githubusercontent.com/orlp/slotmap/master/src/lib.rs. -Correct wording: add to 21.6: "slotmap takes one word, 32 bits each, -and lets the version wrap; with it, a slot of a 16-byte `T` is 20 or -24 bytes, not 32." - -### Correct - -**C1. Section 9.1: "Java closes it by tearing only `long` and `double`, -never a reference."** Correct. JLS 17.7: a non-volatile `long` or -`double` write may be treated "as two separate writes, one to each -32-bit half"; "Writes to and reads of references are always atomic, -regardless of whether they are implemented as 32-bit or 64-bit -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). - -**C2. Section 7.4: "This is Go's `append`: the old slice still sees the -old array."** Correct for a growing append. The spec says: "If the -capacity of s is not large enough to fit the additional values, append -allocates a new, sufficiently large underlying array ... Otherwise, -append re-uses the underlying array." In Go the GC keeps the old array -while it is referenced. Raz retires the block and frees it at a later -growth once the count is 0, which matches for every slice still held. -Source: https://raw.githubusercontent.com/golang/go/master/doc/go_spec.html. - -**C3. Section 19: `append(s, s...)` is right in Go.** Correct: append -copies with memmove semantics, so overlap is safe. Source: as C2. - -**C4. Section 12, Go row: checked, GC, forged pointers "only through -`unsafe`", fence `import "unsafe"`.** Correct. cgo is the other way -out, and it is also visible in imports (`import "C"`). - -**C5. Section 8.2: "the generational arena of Rust's `slotmap` and -`generational-arena`".** Correct. slotmap: "persistent unique keys ... -The keys returned by `slotmap` are versioned." generational-arena: "A -safe arena allocator that allows deletion without suffering from the -ABA problem by using generational indices." Sources: https://github.com/orlp/slotmap; https://github.com/fitzgen/generational-arena. - -**C6. Section 8.2: "the handle pattern Zig and game engines use".** -Correct as practice. The pattern's best-known write-up is Andre -Weissflog's "Handles are the better pointers" (2018), worth citing: -https://floooh.github.io/2018/06/17/handles-vs-pointers.html. - -**C7. Section 12, Rust row, and 9.1: `Send`/`Sync` checked by the type -system; `unsafe` blocks and functions.** Correct. - -**C8. Section 19: "non-lexical lifetimes are a fixpoint over the control -flow, not one pass".** Correct. NLL (RFC 2094) computes liveness and -region constraints by dataflow over MIR's control-flow graph. - -**C9. Section 12, Swift row: "exclusivity checked at compile and run -time"; "Swift 6: `Sendable`, checked".** Correct. Swift 5 enabled -run-time exclusivity checks in release builds; the Swift 6 language -mode makes data-race checks errors. Source: https://github.com/swiftlang/swift-org-website/blob/main/_posts/2019-02-05-swift-5-exclusivity.md. - -**C10. Section 12, Modula-3 row: a GC for traced references, `DISPOSE` -only in unsafe modules, `UNSAFE MODULE` and `UNSAFE INTERFACE`.** -Correct. The report: "An interface or module not explicitly labeled -UNSAFE is called safe." SRC's compiler: `IF Module.IsSafe () THEN -Error.Msg ("DISPOSE: unsafe operation")`. Untraced references (`UNTRACED -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. - -**C11. Section 12, Oberon row: unsafe only through `SYSTEM`, marked by -`IMPORT SYSTEM`.** Correct. The GC belongs to the Oberon system rather -than the language report, which is a fine point. - -**C12. Section 12, Ada row: `Unchecked_Deallocation`, -`Unchecked_Conversion`, "SPARK adds ownership".** Correct. SPARK's -pointers follow "the Rust model": move for pool-specific access types, -borrow and observe for anonymous ones (SPARK Community 2020 onward). -Source: https://docs.adacore.com/spark2014-docs/html/ug/en/source/access.html. - -**C13. Section 12, Zig row: bounds "checked in Debug and -ReleaseSafe".** Correct. The langref: "In Debug and ReleaseSafe mode -... triggers a safety panic"; ReleaseFast and ReleaseSmall assume -the checks away. - -**C14. Section 11: "Zig's debug allocator".** Correct name since Zig -0.14.0 (`std.heap.DebugAllocator`; `GeneralPurposeAllocator` survives -as a deprecated alias). Source: https://ziglang.org/download/0.14.0/release-notes.html. - -**C15. Section 11: glibc's `MALLOC_PERTURB_`.** Correct: it fills -blocks "when they are allocated ... and freed". It has no quarantine -and no guard bytes; the proposal's "without their reach" allows for -that. Source: https://raw.githubusercontent.com/bminor/glibc/master/manual/memory.texi. - -### Unverifiable - -**U1. Section 12, Zig row: races "UB".** Zig has no written memory -model. Its atomics follow LLVM's, under which a data race on a -non-atomic location is undefined, so the claim is very likely right. -No Zig document says so. - -**U2. Section 12, Modula-3 row: races "not promised".** The report -doesn't speak to it in what I could read. Since Modula-3's open arrays -and `TEXT`s are behind references, a race in a safe module may not -break memory at all. Leave it, or write "not addressed by the report". - -### Precedent the proposal misses - -- **D: `@safe`, `@trusted`, `@system`, and DIP1000's `scope` and `return - scope`.** This is the closest match to parts A and B together. - `@trusted` is section 5.3's trust, per function. `return scope` is - `ret`, and plain `scope` is the opposite of `keep`. PROPOSALS.md - cites DIP1000; MEM_PROPOSAL.md doesn't. It should, together with D's - lesson that the corners (fields, generics, delegates) took years. - DIP1000 is still behind `-preview=dip1000`, and its document is marked - "Superseded". Source: https://github.com/dlang/DIPs/blob/master/DIPs/other/DIP1000.md. -- **C#: `ref struct`, `Span`, `scoped`, ref-safety contexts.** C# - checks with local, one-pass rules that a `Span` never outlives what - it points at, with three contexts that are part B's three lenders - (I11). It is the strongest evidence that part B works in a - mainstream compiler without lifetimes in types. Source: https://github.com/dotnet/csharplang/blob/main/proposals/csharp-11.0/low-level-struct-improvements.md. -- **Swift: `~Escapable` types, lifetime dependencies, `Span`, and - SE-0458.** Swift 6.2's non-escapable types (SE-0446) and `Span` - (SE-0447) give a slice that can't outlive its source, with a - dependence written on the function. That is `ret` again. SE-0458's - `@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. -- **Chrome's BackupRefPtr.** Counted references with quarantine on - free, in production C++ (I18). It is the precedent for part C's - retirement, with measured costs and recorded leaks. -- **Rust's `RefCell`, CPython's buffer exports, Java's `modCount`.** - Run-time counts of loans that refuse a change while one is held - (I21). CPython's `bytearray` refusing to resize while exported is - part C's "stop" alternative from section 19, shipped for years. -- **Checked C.** Microsoft's extension of C with checked pointer types - (`_Ptr`, `_Array_ptr` with bounds) and `_Checked`/`_Unchecked` - scopes. It is a fence in a C-like language, at a finer grain than a - module, and it shows the cost of a per-block fence. - https://github.com/checkedc/checkedc. -- **SafeStack (clang).** It moves address-taken locals to a separate - stack. That is relevant to what an unsafe module's `ADR` of a local - can reach, and to part F's frame slots. https://clang.llvm.org/docs/SafeStack.html. -- **Hylo (formerly Val).** Mutable value semantics: no stored - references at all, only projections that last the call. That is the - extreme of section 14's "a record can't keep a slice into a buffer - that belongs to someone else", and it argues that the limit is - livable. https://www.hylo-lang.org. -- **Austral.** Linear types with lexical borrows, kept small on purpose - so that one person can hold the whole checker in their head. That - matters to raz's "a beginner can follow". https://austral-lang.org. -- **Mojo and Carbon.** Mojo has ownership with inferred "origins", a - Rust-like model with lighter syntax. Carbon plans a safe subset - reached by incremental migration from C++, as part of section 20's - order of work. Both are worth a line in section 19's view of Rust's - way. https://docs.modular.com/mojo/manual/values/lifetimes; https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/safety/README.md. -- **Modula-2+ and Cedar.** They had safe and unsafe (Cedar: checked, - trusted, unchecked) modules before Modula-3, and are where the - module fence of section 12 comes from. -- **AddressSanitizer and GWP-ASan.** The real models for part G's - quarantine and guard bytes (I18). - ---- - -## Appendix 6: adversarial review, the proposal's numbers and samples - -**Summary.** The five demo programs compile with `-Werror`, print what -the proposal says, and do the undefined thing claimed. The callgrind -figures repeat to within a thousand instructions. Several other things -don't hold: - -- The survey counts lines, not operations, and the proposal calls them - operations. -- Its "test/libc" row is really `lib/Sys.raz`. -- rnet's TLS backends and two of its tests were never compiled. -- Most `ADR`s in rnet, rjson, rlX11 and ravite are arguments to the - programs' own procedures, not to the library. So the claim that - v0.19.0 "removed them already" is wrong. -- Every one of raz's own benchmark kernels says `check off;`. -- The kernels don't run "past the caches": the machine reports a - 260 MB L3. -- The 16-to-32-byte and fat-pointer conclusions are confounded by node - layout and by noise. -- Part C's run-time rule would stop the library's own `Opt.say`, the - compiler's `Parse.moduleParams` and ravite's `load`. -- 7.3 forbids the accessor that 14.2 recommends. -- No container's `init` is marked `keep`, so a `Buf` over an `Arena` - (used by `Fmt.eprint` and `examples/Sh`) can't be written safely. -- Three of the sample error messages are wrong, and one gives help that - doesn't compile. -- The compiler cost is likely low by 40 to 70%, judged against - PROPOSALS' own revised figure. - -Commands below were run on 2026-10-17. The scratch data used is in -`/tmp/claude-0/-home-user-raz/bab05b52-9d9d-4262-9f3e-de1807ce50a5/scratchpad/` -(S below). Files made for this review are in -`/tmp/claude-0/-home-user/f9bd1744-45c5-5c51-82fd-fddfc77d01cc/scratchpad/` -(W below). - -### 1. Survey counts - -**1.1 "Places", counted once each, are lines (2.1, 2.2, appendix 1).** -`Diag.tally` prints `path:line` with no column, and `agg.py` keys on -(kind, file, line). So two operations of one kind on one line count -once. I rebuilt the tally compiler to print the offset as well -(`W/tc/raz`) and compiled `src/Raz.raz` with it: - -| kind | lines (proposal) | distinct places | -|---|---|---| -| `ADR` | 27 | 32 | -| deref | 1,015 | 1,410 | -| `p[i]` | 277 | 372 | -| `p[a..b]` | 30 | 44 | -| ptr cast | 42 | 48 | -| `p ± i` | 3 | 4 | - -The distinct places are themselves a floor: nested operations at one -position still merge. **Correction:** call them "lines with", or give -the operation counts. The ratios between modules hold. - -**1.2 The `test/libc` row is library code.** `test/libc/mods/Sys.raz` -is a link to `lib/Sys.raz`, the C `Sys`. It holds 108 of the row's 110 -`ADR`s, 63 of its 64 casts and all 35 of its `p[i]`. The tests' own -files hold 2 `ADR`s, 1 cast and 1 `NEW`. **Correction:** move 242 -fenced operations to `lib/` (`lib/Sys`, the C one), and say so when -naming the library's unsafe modules (2.2, "Sys (287 operations)" is -the Linux file only). - -**1.3 rnet was compiled in part.** `S/out/rnet.log` shows -`test/Net.raz` and `test/Https.raz` failing, because `module Tls is in -.../gnutls/Tls.raz and .../openssl/Tls.raz`. So neither TLS backend -was counted. Both are `extern` modules: 26 and 35 `extern`s, 27 and 24 -`ADR`s. **Correction:** 5.4 says "rnet needs it only to keep -`Http.Message`". In fact both `tls/*/Tls.raz` must say `unsafe;`, as -`Sqlite` must. Section 15's rnet row should list them. - -**1.4 rnet's and rjson's `ADR` totals disagree with appendix 1.** 2.2 -gives rnet 572 and rjson 77. Appendix 1 gives 471 and 91 (lines, from -the tally). A grep outside comments finds 792 occurrences in rnet (621 -lines) and 110 in rjson. rlX11's 89 doesn't come out either: grep -finds 108, 78 of them in `src/`. ravite's 202 and rmacs's 560 match a -grep. - -**1.5 "Almost every ADR is ... the library's old pointer parameters" -is wrong for most repositories.** I sorted each `ADR` by the call it -is an argument to (`W/py/adr.py`, a textual parser): - -| repo | `ADR`s | to the library | to its own procedures and modules | casts and other | -|---|---|---|---|---| -| rnet | 792 | 226 | 525 | 41 (34 to `Tls`) | -| rjson | 110 | 35 | 70 | 5 | -| rflate | 67 | 48 | 16 | 3 | -| rsqlite | 42 | 12 | 27 (some to C) | 3 | -| rmacs | 560 | 424 | 132 | 4 | -| ravite | 202 | 107 | 93 | 2 | -| rlX11 | 108 | 5 | 100 | 3 | - -The top callees in rnet are its own `fetches`, `resolves`, -`Conn.close` and `parseAnswer`. In rlX11 it is its own `expect`. Those -are the programs' pointer-taking headings. They mend by `var`, but the -programs have to be rewritten for it; v0.19.0's library didn't remove -them. **Correction:** "Most `ADR`s are arguments; in rmacs and rflate -mostly to the library, in rnet, rjson and rlX11 mostly to the -programs' own pointer parameters." - -**1.6 "Nobody uses `check off;`" (2.2, 13.2) is wrong.** All seven -kernels in `test/bench` say `check off;` (`grep -l '^check off' -test/bench/*.raz` gives 7 of 7). The Makefile says so too: "the -kernels of test/bench, which say check off". So does -`test/run/mods/Unchecked.raz`. The survey left `test/` out, but the -inference "no one has wanted them off" doesn't follow: raz's own speed -comparison with FPC turns the checks off. **Correction:** "No library -module or program surveyed turns them off. raz's benchmark kernels do, -to match FPC -O2." - -**1.7 Frees and `done`s (2.2, 8.1).** - -- The hand frees match: `src/` 7, rmacs 9 (4 `Mem.free` plus 5 - `Heap.heap^.free`), rjson 6, ravite 2, rlX11 1, others 0. -- rnet has 41 `done`s, not 30: `src/` has 30, its tests 11. With 41, - "54 to 26" becomes 65 to 25 or 26. That still makes the point. -- The mendings in section 15 misdescribe some of the frees: - - rjson's 6 are all `Mem.free` of grown arrays (`nodes`, `kids`, - `stack`), with no `Str.free`. They mend by `Vec`, not by `Names` - or `Buf`. - - ravite's 2 are `Text`'s grown `data` and `changes`, not windows. - They mend by `Vec` or `Buf`, not `Pool`. - - Only rmacs's 5 `Heap` frees, of windows and parts, are `Pool` - material. - -**1.8 "35 places assign Buf.bytes, Vec.all or Windows.all"** holds. -A grep finds 36 assignments to locals and 3 to fields (`m^.body`, and -`res^.body` twice). The only `.all` is rmacs's `Windows.all`. - -**1.9 "Records that hold slices: src/ 10" isn't reproduced.** I find -three slice fields in `src/`'s records: `Diag.File.path`, -`Sym`'s `path*` (line 116) and `X64.Said.text`. 13.3 repeats "10". -**Correction:** 3, or say how 10 was counted. - -**1.10 Dereferences: "Every one is a pointer from NEW on the heap, -which the compiler never frees" (2.2) is false today.** Some are not: - -- `X64`'s `r^`, `size^` and `o^` point at locals through `ADR(r)` and - `ADR(ao[an])`. -- `Elf`'s `dynSize^` and `roExtra^` point at locals. -- `Scan`'s `bits^` points at a local. -- `Diag`'s `f^` and `Chunk`'s `c^` point into grown arrays that - `regrab` frees (`Scan.raz:137`, `Diag.raz:103`). - -They are few (tens), and part A's mendings would remove them. But the -sentence should say "nearly every". - -**1.11 The `src/` `ADR`-and-cast table (2.2) misses some sites and -miscounts others.** The table sums to 55. There are 62 distinct lines -with an `ADR` or a cast. - -- Grown arrays: 31 lines are `grab`/`regrab`/`free` of arrays. 3 more - are single records, `^Buf.Buf(Scan.grab(SIZE(Buf.Buf)))`, which - should be `NEW`, not `Vec`. -- "A real's bits" are 4 lines (Item 152, 165, 364; Scan 879). 3 more - are a value's bytes for data (`Gen.raz:293`, `Parse.raz:3186`, - `Parse.raz:3334`). They need `setData` and the copy to take a slice, - besides the view. -- `intern`: 7, correct. Two `Elf.putBytes(ADR(s[0]), LEN(s))` are - missing. -- Out-parameters: 4 lines, 8 `ADR`s, not 5. -- Not listed at all: - - `ADR(chunks[n])`, `ADR(files[i])` ×2 and `ADR(ao[an])`; - - `Scan.raz:119` (`return ADR(sbuf[0])`, the allocator); - - `Item.raz:2155` (`^I64(p)`); - - `Raz.raz`'s two `SYSCALL`s (`memfd_create`, and `execve` with - `ARGV() + first`). - - The `SYSCALL`s mend by `Sys.memFile`, and `Sys.execve` with - `Sys.envAt`, but they are not "1 SYSCALL". - -### 2. The five programs - -Each was extracted from appendix 3 and compiled with -`/home/user/raz/raz -Werror`. Each is identical to `S/demo/`. - -| program | printed | status | -|---|---|---| -| SelfAppend | 24 `a` | 0 | -| Stale | `1 2` | 0 | -| Escape | `########` | 0 | -| Kept | `name-001: missing`, `name-002: missing` | 0 | -| Temp | `name-..b`, a space, then `01 00 00 00 00 00 00 00` | 0 | - -All as claimed. - -**2.1 SelfAppend's explanation (1.2) is vague where it could be -exact.** - -- `Buf.room` copies, then frees the old block (`Buf.raz:36-37`). - `Buf.str` then copies from `s`. -- The old block is size class 3 and the new one class 4. `Heap.free` - writes only the 16-byte header (`b := ^Block(h)`, `Heap.raz:96`). - Nothing allocates between the free and the copy. -- So with `Heap` in one thread the program is always right. That is - not luck "in time". -- A block past 4,080 bytes gets pages of its own, and `free` unmaps - them. Filled to 8,192 bytes, the same line stops the program: - `Buf.raz:67:5: stopped by a bad address` (`W/demo/SelfBig.raz`). - That makes a stronger demonstration than the one shown. - -**2.2 Stale.** Holds as explained: - -- The class-4 block of 16 elements is freed when the `Vec` grows to 32. -- `p` points into the class-5 block, which is freed at the next growth. -- `free` touches only headers, so `first[0]` and `first[1]` read 1 - and 2. - -**2.3 Escape** holds. - -**2.4 Temp.** The listing (`raz -S`) confirms one slot, -`[rbp - 40]`, for both calls. - -- `a` was printed before anything overwrote the slot, so it shows - `b`'s bytes. -- `b` points at the same slot. That slot was overwritten by the next - call's argument, `Out.str(" ")`, whose length 1 lands at - `[rbp - 40]`. Hence `01 00 ...`. -- "Whatever came after" is right. The precise cause is the next - statement's temporaries. - -**2.5 "Three are what the library's own documentation warns of" (1.2) -is two.** `Buf` ("until it next grows") and `Vec` warn. `Map`'s -documentation says nothing about keeping its keys: neither the module -comment nor `put`'s "k now maps to v". The proposal itself says the -caller "must know, from the documentation alone". **Correction:** "two -are what the library's documentation warns of, one what it doesn't -say, and two what 7.3 and 8 warn of." Or mend `Map`'s comment. - -### 3. Benchmarks - -The machine is a 4-core Xeon VM at 2.1 GHz, with AVX-512. `lscpu` -reports L2 2 MiB a core and **L3 260 MiB**. THP is `madvise`. - -**3.1 Two runs each of MemBench and GenBench (ms):** - -| kernel | proposal | mine, run 1 | mine, run 2 | -|---|---|---|---| -| big, raw, 16-byte nodes | 8,312 / 7,515 | 5,300 | 4,859 | -| big, handles, 32-byte slots | 12,336 / 11,992 | 10,665 | 10,429 | -| small, raw | 857 / 810 | 864 | 876 | -| small, handles | 1,631 / 1,643 | 1,829 | 1,734 | -| big, raw, 32-byte nodes | 14,001 / 13,725 | 13,734 | 13,499 | -| big, fat pointers | 8,672 / 10,145 | 9,232 | 10,624 | -| small, raw, 32-byte | 870 / 917 | 852 | 870 | -| small, fat | 830 / 1,047 | 815 | 888 | -| sum, big, `^U8` / `[]U8` | 305 / 342; 271 / 434 | 296 / 279 | 318 / 370 | -| sum, small, `^U8` / `[]U8` | 261 / 265; 256 / 306 | 336 / 428 | 387 / 392 | - -Findings: - -- **Big handles cost 2.0 to 2.2 times here, not 1.5 to 1.6.** The raw - baseline varies by 40% between sessions. -- **The working sets are not "past the caches".** The big arrays are - 16 MB and 32 MB, inside a reported 260 MB L3. So "doesn't fit in - the caches" and `Big = 1000000; (* past the caches *)` are wrong - here. What grows with the node is the page-walk footprint and the - share of L3, not a miss to DRAM. -- **"Half of it the larger slot" is not supported.** Across the two - programs, the 32-byte raw chase (13.5 s) is *slower* than the - 32-byte handle chase (10.5 s). The two programs aren't comparable. - -**3.2 Why big-gen beats big-ptr.** I tested three explanations: - -- Run order (`W/mb/GenOrder.raz`): not it. Gen first or second, gen - 11.4 to 11.6 s, ptr 13.4 s. -- Array placement in bss (`W/mb/GenSwap.raz`): not it. Ptr stays - slower. -- Layout and code (`W/mb/GenWhy.raz`, 50M steps): - - ptr 6.8 s; - - gen 3.8 to 4.5 s; - - gen with no check 2.7 to 3.9 s; - - a raw pointer chase over the *gnodes* array 4.2 to 5.8 s. - - In `W/mb/Offs.raz`, the same 32-byte node chased raw takes 6.3 to - 6.5 s with the link at offset 0, and 5.3 to 5.9 s with it at offset - 8. - -So part of the gap is the node's layout (where the link and the value -sit), and the rest is noise of ±20 to 30% on this VM. The generation -check itself isn't what the rows measure. Its cost is within noise; -calling it "free" or "the check is free here" goes further than the -data. The same layout effect sits inside the "+70–85%" for doubling a -node: the comparison is across two programs with different layouts. -**Correction:** "On this machine, wider records and handles cost 1.5 to -2.2 times in a pointer chase; the measurements can't separate the -check from layout and noise." Keep the conclusion against fat -pointers on other grounds: C interop, record size. - -**3.3 MemBench understates a real `Pool`.** `chaseHandle` indexes a -fixed module array inline: no call, no copy of `T`, no heap -indirection, no `LENDS` count. `Pool.get` (8.2) is a call that copies -`T`, through a `const p: Pool`, into a heap block. `Pool.at` adds a -counted lend. Expect more than the table's figure. - -**3.4 The bounds-check sums** do test the check: the listing shows -`cmp r12, rsi; jae` in the loop. My figures run from -6% to +27%. -"0–15%" is about right, given the noise. - -**3.5 The scanner experiment** repeats: `valgrind --tool=callgrind` -of `S/base/raz` and `S/safe/raz` over `src/Raz.raz` gives 240,850,230 -and 251,594,863 instructions, +4.46%. - -Caveats: - -- The "safe" `Scan` still uses `PTR(cur.buf)` and - `intern(PTR(buf) + start, ...)`, so it isn't safe. The cost of - `intern(s)` taking a slice isn't measured. -- `PTR` is not in v0.19.0, so this `Scan` can't be built by `BOOT` - yet. -- Wall-clock times of the 348,025-line bench were 688 to 891 ms for - the base compiler and 723 to 858 ms for the "safe" one, interleaved - six times. The "safe" one was sometimes faster. Wall clock can't - show 5% here. -- The proposal's "625 to 660 ms" was a quiet moment. At this - session's best (688 ms, 506,000 lines a second) 5% more is about - 480,000, still above the floor. On a slow run (891 ms, 390,000) the - floor already fails today. - -**3.6 "Two 8-byte moves become one 16-byte one" (13.3)** is true only -from memory to memory. Into the rax/rdx pair the ABI returns a slice -in, or from it, a `movdqa` needs `movq` and `pextrq`/`pinsrq`. That is -three instructions and a domain crossing, not none. - -### 4. Library signatures, report sections, quotations - -- **Exact:** - - `Thread.spawn*(p: proc(arg: ^U8); arg: ^U8): (^Thread, ERROR)`; - - `Str.copy*(a: ^Mem.Allocator; s: []U8): ([]U8, BOOL)`; - - `Buf.spare*(var b: Buf; n: INT): []U8`; - - `Buf.bytes*(const b: Buf): []U8`; - - `Map.put*(var m: Map; k: K; v: V): BOOL`; - - `Sys.mmap`, `Sys.munmap`, `Sys.nextEntry(var d: Dir)`, - `Sys.read(fd: INT; buf: []U8): INT`; - - `Item.raz:58` is `frame*: BOOL` with the comment the proposal - describes; - - `C` has 96 `extern`s and `CAbi` 2; `Vec` has 11 fenced lines; - - `src/` is about 11,550 lines of code by a comment-stripping count - (rloc isn't installed), so "about 11,500" holds. -- **`Vec.all`'s comment** is "The elements, until the array next - grows." "Good until the array next grows" is in `Vec`'s module - comment and in `add`'s (capitalized). The quote is fair, but not - `all`'s own words. -- **7.6 is misquoted (9.1).** The report says a variable raced on - "holds no particular value then: a read of it gives a value it had - or was given, or a mixture of their bytes. Nothing else of the - program becomes undefined by it." The proposal puts "holds" in - front of "a value it had or was given", which the report doesn't - say. **Correction:** quote "a read of it gives a value it had or was - given, or a mixture of their bytes". -- **Section 10's "no run time besides the code it uses" (19)** is said - of "a program that doesn't [use C]". The quote is exact. It is a - property of programs without C, not a promise of the language. That - weakens the argument a little; line 7 of the report ("no hidden run - time") supports it better. -- **5.3 (16):** a slice's alignment is set in 5.1 ("a slice is aligned - as an address is"), not 5.3. The sentence to change is there. -- **Elf "writes the executable through `Sys.write`" (5.4):** it uses - `Files.write(path, buf[0..len])` (`Elf.raz:442`). The conclusion - holds. -- **Zig in 12:** `@intToPtr` has been `@ptrFromInt` since Zig 0.11. -- **The Go memory-model wording** in 9.1, "arbitrary memory - corruption", is accurate. -- **Section 15's `ret` list** leaves out `Vec.tryAdd`, which 17 marks. - **Neither list marks `init`'s allocator `keep`** on `Buf`, `Vec`, - `Map`, `List` or `Pool`. Every one stores `a` in its record, and - 5.3(3) says "what it doesn't mark keep, it doesn't hold past the - call". See 5.5 below. - -### 5. Code samples and the proposal's own rules - -**5.1 Today's-raz samples compile.** - -- Appendix 2 and 3 compile. -- 6.4's `greet`, `first` (without `ret`) and `remember` compile. -- 7.1's loop compiles (`W/demo/Samples.raz`). - -**5.2 The help in 6.4 and 14.3 doesn't compile.** "give put a copy -that lasts: `Str.copy(Heap.heap, buf[0..8])`". `Str.copy` has two -results: - -``` -Samples.raz:31:27: error: copy returns several results - help: they go to variables: a, b := copy(...) -``` - -**Correction:** "copy it first: `k, ok := Str.copy(Heap.heap, -buf[0..8])`". - -**5.3 The message positions are off.** The positions shown don't match -the programs: - -- `Kept.raz:10:30`: the call is at line 11, column 27. -- `Escape.raz:14:12`: it is at 15:12. -- `Window.raz:41:13 ... XNextEvent(dpy, ADR(ev))`: the line in - `examples/Window.raz` is 59, `_ := XNextEvent(d, ^U8(ADR(ev)))`. - -Window's help, "or pass ev as a var", is impossible. An `extern`'s -parameters are integers, `BOOL`, reals, pointers or procedures (report -9), and the module is unsafe for its `extern`s anyway. Pick a safe -module's `ADR` for that example. - -**5.4 The Escape message assumes a `head` that 6.2 forbids.** It says -"head's result points into what it is given (ret h)". Appendix 3's -`head(var h: Hex)` has no `ret`, so under 6.2 the first error is in -`head` itself: "returning what is lent by h, not marked ret". - -**5.5 7.3 forbids what 14.2 recommends.** 7.3 says an owner-lent -reference "returned ... is an error". 14.2's option 1 is `proc -name*(ret const m: Message; i: INT): []U8; (* m^.head's bytes, lent by -m *)`, which returns bytes of `m.head`, a `Buf`. That is exactly an -owner-lent return. 7.2 also says a `Message` is not an owner, so it -can't lend through `ret` at all. - -The same rule refuses `tools/Widths.raz`'s `load(path; var b: -Buf.Buf): []U8 ... return Buf.bytes(b)`, yet section 15 says `tools/` -has "none found". It also refuses any safe wrapper over `Vec.all` or -`Pool.at`. - -Either 7.3 allows returning through a `ret` parameter that is itself -an owner, or the library's own exports, which do this, need a -different rule from safe code. If returning is allowed, the hold must -pass to the caller, and 7.3 doesn't say how. - -**5.6 Part C stops correct programs, the library's and the compiler's -included.** 7.3 lets a local's hold go only when the procedure -returns, and 7.4 makes `done` stop while a count is above zero. A scan -for a slice held from `Buf.bytes(b)` and a later `Buf.done(b)` in one -procedure (`W/py/heldone.py`) finds: - -- `lib/Opt.raz` `say`: `s := Buf.bytes(b)`, loop, `Buf.done(b)`; -- `src/Parse.raz` `moduleParams`, lines 3696 to 3699 (every generic - instance); -- ravite's `load` (`Ravite.raz:1402`, done at 1411). - -Five more do `defer Buf.done(x)` and then hold `Buf.bytes(x)`: -`examples/Elf.raz` `main`, rnet `Dns.init` and `fromHosts`, and rmacs -`writeFile` and `loadInit`. Whether those stop depends on whether a -hold's let-go runs before or after the deferred statements. The -proposal says only "as a defer would". - -So the compiler itself would stop on every program with a generic -import. 14.2 calls this "a false alarm only when name is never read -again", and these are exactly such cases. Section 15's claim that -every break is found when compiling, but `done`, should count them. -**Correction:** let a hold go at the variable's last use, or at a -`done` of the owner from the same procedure (both known in one pass -only for straight-line code). Or count these breaks and mend them with -`s := []`. - -**5.7 A `Buf` or `Vec` over an `Arena` has no safe form.** By 8.4, -`Arena.allocator(ar)` is lent by `ar`, and a lent value can't be -stored in a record (6.2) or given to `keep` (5.5 above). `Buf.init` -keeps its allocator, so `Buf.init(b, Arena.allocator(ar))` is an -error. This pattern appears in: - -- `Fmt.eprint`; -- `Fmt`'s test; -- `Buf`'s test; -- `examples/Sh.raz`, lines 88 and 188. - -So "Fmt ... can be safe" (5.4, 15, 17) and "Sh ... mended by var" (5.4, -15) fail. `Fmt.format` also takes `^Buf.Buf` with `nil` for standard -output, which needs an interface change. - -**5.8 Other "can be safe" claims (5.4).** - -- `Files.arg` *is* `ARGV()[i]` and pointer indexing - (`Files.raz:10-13`). 5.1 fences `ARGV` and names `Files.arg` as the - safe form, so `Files` must stay unsafe, or `ARGV` must move into a - trusted module. -- `Str.copy` and `Str.free` index and free a `Mem.alloc` pointer. `Str` - can be safe only if `Mem` gains a safe slice allocation. Section 17 - doesn't add one, and `free` is an `unsafe proc` in a module 17 calls - safe. -- `Lock` needs E.4 (`CAS` on a variable) first. -- `examples/Workers.raz` uses `Thread.spawn(work, nil)` and - `XADD(ADR(next), 1)`. It needs `Task` and E.4, not `var`. - -**5.9 Owners can't sit in generic containers.** 7.6 forbids passing an -owner as a value parameter or copying it. `Vec.push(x: T)`, -`Pool.add(keep x: T)`, `Map.put(..., v: V)` and `List.push` all copy. -So `Vec(Buf.Buf)`, `Pool(Window)` where a `Window` holds a `Buf`, and -`Names(Buf.Buf)` can't be used. Yet 14.2 turns rmacs's windows, which -hold `Buf`s, into a `Pool(Window)`. The proposal needs an `add` that -gives a zero slot in place (`Pool.at` after a zero `add`) and says -that copies are refused there. - -### 6. The compiler's cost (section 18) - -- **A, 120:** about right, perhaps to 150. It needs `unsafe proc`'s - rules in `Sym.same` and assignability, the two contextual places the - word stands, the interface check, and a generic instance taking its - module's mark. -- **B, 300–450: low.** PROPOSALS' own second review (its open - question 4, PROPOSALS.md line 476) revised part 3 to "400 to 600 - lines, not 250 to 400", for slices alone. This proposal adds - pointers, owners as lenders, `match` names (10.4), literal parts and - generic instances checked one by one. Likely 550 to 800. -- **C, 200: low.** - - Hidden hold slots per local. - - A raise at each call that returns an owner-lent value. - - A lower at the end of each statement. Only `const`'s temporaries - have such a point today. - - A let-go on every exit, `try` and early `return` included, with - an order against `defer` (5.6). - - The copy check at assignment, value parameters, results, literals, - comparison, views and generic instances (5.9). - - Likely 300 to 450. -- **D, 20:** plausible. -- **E, 80: low.** - - 16-byte alignment of slices changes record layout in `Sym`, and - frame-slot and temporary alignment in `Gen`. - - Every slice load and store goes through xmm, with - `movq`/`pinsrq`/`pextrq` for the rax/rdx pair. `X64` today - encodes `movdqu` but not those. - - Records holding slices are copied by `rep movsb` past `MaxMoves`. - - `CAS`, `XCHG` and `XADD` change from pointer to variable in - `Parse` and `Item`. - - `lock xadd` when `Thread` is imported. - - Likely 150 to 250. -- **F, 20:** plausible, since `defer`'s reserved slots exist. -- **Messages, 100:** plausible for about 10 new kinds with help. - -**In all, likely 1,250 to 1,700, not 840 to 990.** That still fits -under 14,000, from about 11,550, but with much less room than 18 -suggests for the documentation the house style requires. - -The `src/` rewrite is also larger than "35 grown arrays". `Chunk.chunks`, -`Chunk.text` and `Chunk.rodata` are exported and indexed from `Item`, -`Parse`, `Gen`, `Raz`, `Elf`, `Link` and `X64`: about 250 lines of -`p[i]` and `p[a..b]` outside `Scan`. Each would become a `Vec.all(...)` -with a counted lend, often in `X64`'s emitter and `Link`'s patching, -which are hot. 13.1's "cost nothing measurable" for these is -unmeasured. - -### 7. `src/` becoming safe (2.2, 5.4, 15) - -The plan is plausible module by module, with three gaps: - -- **Elf:** its buffers are a `grab`/`regrab` byte array (a `Buf`), plus - `putBytes(ADR(s[0]), LEN(s))` (a slice parameter) and - `sizeTables(ADR, ADR)` (`var`). It can be safe. -- **Diag:** `files` is a grown array (`Vec`), and two `^Buf.Buf(grab)` - become `NEW`. `File.buf: ^U8` keeps a pointer to the scanner's - source. As a slice it is lasting only if `Scan`, unsafe, promises - so. It can be safe. -- **Link:** four arrays sized once from `Scan.grab`, then `p[i]` 63 - times. They need `Vec(INT)` with `resize`, or a typed `grab` that - gives a slice. Safe, at the cost of checks on the linker's paths. -- **Chunk:** grown record arrays exported to every module, and - `ADR(chunks[n])`. Safe as `Vec`s, but see 6 on cost and lines. -- **X64:** `said` is grown, `^Buf.Buf(grab)` becomes `NEW`, and the - `isReg` out-parameters and `operand(ADR(ao[an]))` become `var`. It - writes `Chunk.text` per byte. Safe, with that cost. -- **Gaps:** - - `Raz.raz` needs its `SYSCALL`s and `ARGV() + first` replaced: - `Sys.memFile`, and `Sys.execve` with an environment built from - `Sys.envAt`. - - `Scan.grab`'s callers outside `Scan` (`Item.raz:2154`, - `Parse.raz:452`, `Parse.raz:3812`, `Raz.raz:165`) index its - `^U8`. `grab` must give a slice. - - `Parse.moduleParams` stops at run time under part C (5.6). - -"`src/` keeps one unsafe module: Scan" can be reached, but it is -several hundred changed lines, not the table's 55 sites. - -### Confirmed - -- The demos' outputs and status 0, and that each does the undefined - thing claimed. -- The callgrind counts, +4.5%. -- Appendix 1's per-module tallies, as the aggregator gives them, read - as lines. -- The hand-free counts. -- rmacs's 560 and 556, and ravite's 202, `ADR`s. -- About 36 held `Buf.bytes`/`Windows.all` slices. -- `tools/` has no fenced operation. -- Threads in rnet (`Http`'s server, tests) and rsqlite (`Sqlite`'s - test) only. -- Lines per repository, about 50,000. -- `src/`'s 7 frees all in grown arrays. -- The cited signatures, and `Item.raz:58`. -- 7.3's and 8's text on what isn't caught. -- `C` 96 and `CAbi` 2 `extern`s. -- The sums' bounds check really emitted. -- `src/` about 11,500 lines of code. - ---- - -## Appendix 7: adversarial review, porting real code - -Section 14 says most raz stays as it is and the pain is narrow. To -test that, six pieces of real code were ported on paper under parts A -to F, read as strictly as a compiler would read them: rnet's `Http` -with its test servers, rmacs's buffers and windows, the compiler's -name table, grown arrays, files and scopes, the library's `Fmt`, `Opt`, -`Map` and the containers, `examples/Sh.raz`, and rjson's `Json`. About -25,000 lines were read; about 900 of them change for parts B to F, 4%, -on top of the `ADR`s the fence turns into `var`, which `STANDARDS.md` -asks for anyway. By lines, then, the claim holds. By kind it doesn't. -The changes gather in the one type each piece is built round -(`Http.Message`, rmacs's `Text` and its accessors, `Chunk`'s arrays, -`Sh`'s arena, `Json.Doc`), and each of those needs a redesign, not a -mark. Three rules cause most of it: an owner's lend can't be returned -by any procedure but the owner's own, can't sit in a record, and the -fence has no safe form for a pointer to "the caller's state". The -port also found six holes in the rules as written (A7.7): four let -unsafe code through, and two leave a trap or an undecided stop. It -found eight places in correct code that would stop at run time with -`done` while held, and no real bug in today's code. -Most of the pain goes away with seven additions that weaken nothing -(A7.10). - -### A7.1 How it was done - -Each piece was first brought to today's library, so that an `ADR` at a -call where the library now takes `var` doesn't count. Then each rule -was applied to every line. Where the proposal is unclear, the stricter -reading was taken, and noted: - -- **A pointer parameter is lent by its parameter** (6.1, 6.5). Storing - one in a module variable or a record needs `keep`. -- **Reading through a pointer gives a lasting value.** Only lasting - values may be stored through a pointer (6.2), so what is read back - is lasting too. The more lenient reading is taken here. -- **An owner's lend may be returned only through a `ret` parameter - that is the owner itself**, as `Buf.bytes` does. 7.3 says that - returning one is an error. 6.2 allows it through `ret`. The middle - reading is the only one under which the caller still knows whose - count to raise. -- **A local array or record may not hold an owner's lend** (7.3), not - even one of slices. - -"Changed" counts lines touched, written or removed, against the -source as it stands. The counts come from reading and `grep`, not from -a compiler, and are good to about a fifth. - -### A7.2 rnet's `Http` (`src/Http.raz`, `src/Conn.raz`, `test/Webserver.raz`, `test/Server.raz`, `examples/Hello.raz`) - -**What the rules reject.** - -| Line or construct | Rule | The compiler's error | -|---|---|---| -| `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` | -| `m^.raw := text`, `m^.method := l[0..i]`, `m^.target := ...`, `m^.reason := ...` | 7.3 | the same | -| `m^.body := Buf.bytes(ADR(m^.data))` (`readWhole`) | 7.3 | the same | -| `res^.body := Buf.bytes(ADR(text))` (Webserver, twice) | 7.3 | the same, in the program that uses `Http` | -| `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` | -| `head := m^.head; ... m^ := {..., head: head, data: data}` (`reset`) | 7.6 | `a Buf.Buf owns memory, and can't be copied` | -| `out := req^` (`open`): a `Message` with two `Buf`s, copied | 7.6 | the same | -| `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` | -| `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` | -| `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` | -| `return ADR(cl^.body), nil` (`open`) | 5.1 | `ADR is for unsafe modules` | -| `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` | -| `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 | -| `t := ^Text(c^.state)` (`Http`'s and `Conn`'s tests); `Conn.state: ^U8` | 5.1 | the same | -| `proc trim(s: []U8): []U8` returns `s` | 6.2 | `trim's result is lent by s, which isn't marked ret` | -| 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` | - -The last row is what `STANDARDS.md` asks for, `var` or `const`. It -changes `Http`'s whole interface, and every program that calls it. -It is counted apart below. - -Section 14.2 offers a way out: `Http` says `unsafe;` and keeps -`Message` as it is. That breaks the proposal's own rule 4 of 5.3. A -safe program can read `req^.body` after `Http.done(req)`, so the -exported slice fields are just what a safe module could misuse. And -the programs that *write* messages (Webserver, `Hello`) are safe -modules: they still can't store a `Buf`'s bytes in `res^.body`. So the -spans are the only design that compiles. - -**Rewritten.** The text a message holds goes in its own buffers, as -spans. Everything a program gives it is copied in. - -``` -(* Before *) -Header* = record - name*, value*: []U8; -end; -Message* = record - method*, target*: []U8; - status*: INT; - reason*: []U8; - minor*: INT; - headers*: [MaxHeaders]Header; - n*: INT; - body*: []U8; - maxBody*: INT; - close*: BOOL; - raw*: []U8; - head, data: Buf.Buf; -end; - -(* After *) -Span = record at, len: INT; end; (* bytes at up to at + len of one of the buffers *) -Header = record name, value: Span; end; (* in head *) -Message* = record - status*, minor*, n*, maxBody*: INT; - close*: BOOL; - method, target, reason, raw: Span; (* in head *) - headers: [MaxHeaders]Header; - body: Span; (* in data *) - head, data: Buf.Buf; (* all of its text, read or to be written *) -end; - -(* s added to b, and where it stands there *) -proc put(var b: Buf.Buf; s: []U8): Span; -begin - Buf.str(b, s); - return {at: b.len - LEN(s), len: LEN(s)}; -end; - -proc add*(var m: Message; name, value: []U8): ERROR; -begin - if m.n = MaxHeaders then return TooManyHeaders; end; - m.headers[m.n] := {name: put(m.head, name), value: put(m.head, value)}; - INC(m.n); - return nil; -end; - -proc setBody*(var m: Message; s: []U8); (* new: s copied into the message *) -begin - Buf.reset(m.data); - m.body := put(m.data, s); -end; - -(* The bytes of sp in b *) -proc bytesOf(ret const b: Buf.Buf; sp: Span): []U8; -begin - return Buf.bytes(b)[sp.at..sp.at + sp.len]; (* fine: b is the owner, and ret *) -end; - -proc target*(ret const m: Message): []U8; -begin - return bytesOf(m.head, m.target); (* refused as written: lent by m.head, a part of m; see A7.7, H2 *) -end; -``` - -`target`, `method`, `reason`, `raw`, `body`, `header`, `name(i)` and -`value(i)` are new accessors, and the setters `setMethod`, -`setTarget`, `setReason` and `setBody` are new too. They need the -relaxation R1 of A7.10 to compile at all. In the programs: - -``` -(* Before (Webserver) *) -path := req^.target; -Fmt.write(ADR(text), "{}", [Fmt.int(conns)]); -res^.body := Buf.bytes(ADR(text)); - -(* After *) -path := Http.target(req); (* held, and counted on req's head *) -Fmt.write(text, "{}", [Fmt.int(conns)]); -Http.setBody(res, Buf.bytes(text)); (* copied *) -``` - -`reset` keeps its buffers by moving them out and back: - -``` -proc reset*(var m: Message); -var head, data: Buf.Buf; max: INT; -begin - Buf.take(m.head, head); - Buf.take(m.data, data); - max := m.maxBody; - m := {minor: 1, maxBody: max}; (* the owners left out: empty *) - Buf.take(head, m.head); - Buf.take(data, m.data); - Buf.reset(m.head); - Buf.reset(m.data); -end; -``` - -`m := {minor: 1, maxBody: max}` alone also compiles. It drops both -buffers' memory and their allocator, so the next `Buf.add` calls a -`nil` allocator and stops (A7.7, H4). - -A `Reader` can't hold the `Conn` it reads from, since no safe pointer -to a local `Conn`, or to `cl^.conn`, exists. Either the `Conn` comes -from `NEW`, and a `Client`'s 16 KB buffer can never be freed (D), or -the reader takes the connection on each call: - -``` -proc read*(var r: Reader; var c: Conn.Conn; b: []U8): (INT, ERROR); -proc readBody*(var cl: Client; b: []U8): (INT, ERROR); (* open no longer returns ^Reader *) -``` - -`parseUrl` fills a local `Url` with slices of a `Buf`, and the `Url` -dies before the `Buf` does. That is PROPOSALS' false alarm of "a record -that lives in the frame". Returning the `Url` as a result doesn't help, -since a local record may not hold a lend (7.3). The cure that compiles -copies the URL into a frame array, whose slices a local record *may* -hold: - -``` -var here: [MaxUrl]U8; hereLen: INT; u: Url; -... -try parseUrl(here[0..hereLen], u); (* frame-lent: allowed in the local u; parseUrl's s is keep *) -``` - -So a URL gets a fixed limit only to get past the rule. `cl^.scheme := -u.scheme` becomes `cl.tls := u.scheme = "https"`. The server's threads -become `Task(^Server)`, `Hello` makes its `Server` with `NEW`, and -`arg: ^U8` goes from `Handler`. A server with state keeps it in module -variables, shared by its workers with no lock unless it uses -`Lock.Guarded`. The tests that cast `Conn.state` go into an unsafe -module of their own. - -**Count.** About 2,700 lines, tests included. The fence alone -(`ADR` to `Http`'s own pointer parameters, casts): about 330 lines. -Parts B to F: `Message` and its accessors and setters about 120, the -readers and writers that use them about 40, `reset` and `open`'s copy -15, `Url` 15, `Reader` and `Client` 20, threads and the handler 10, -Webserver 8, `Server` 16, `Hello` 3. About 230 lines in all, 9%. - -**Judgement: worse.** Every field is now a call. Each header and each -body a handler makes is copied once more, and a 100,000-byte body made -in a `Buf` is copied whole. Fixed limits come in only to dodge a rule -(`MaxUrl`), and handlers lose their context. In return, "good until the -message is read again or reset", which `Http`'s header comment asks a -reader to remember, is now checked. - -**Contortions and false alarms:** `parseUrl` into a frame array; the -scheme as a BOOL; `Reader` without its `Conn`; the accessors, which -don't compile without R1. **Run-time stops in correct code:** none -found. **Real bugs caught:** none. `reset`'s copy of the `Buf`s, which -section 7.6 calls "safe by luck", is right: the copies are put back at -once. `res^.body := req^.body` in `test/Server.raz` is right by the -order `serveConn` keeps. - -### A7.3 rmacs (`src/Core.raz`, `Commands.raz`, `Text.raz`, `Mini.raz`, `Dired.raz`, `Windows.raz`) - -**What the rules reject.** - -| Line or construct | Rule | The compiler's error | -|---|---|---| -| `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` | -| `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` | -| `proc text: []U8` (`Mini`), the same through `Core.mini^.t` | 7.3 | the same | -| `proc nameAt(i: I64): []U8` (`Dired`), a slice of the module `Buf` `names` | 7.3 | the same | -| `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 | -| `Heap.heap^.free(Heap.heap, ^U8(x))` (`Core.kill`), four in `Windows` | 5.1, 5.2, D | `Heap's free is an unsafe procedure` | -| `t := ADR(w^.buf^.t)` (`Rmacs.colours`) | 5.1 | `ADR is for unsafe modules` | -| `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 | -| `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` | -| 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` | - -**Rewritten.** No procedure but the owner's own can hand out what an -owner lends, so `Core.slice` can't be written, and each of its twelve -callers names the text itself: - -``` -(* Before *) -Buf.str(ADR(Core.tmp), Core.slice(p, b)); -(* After *) -Buf.str(Core.tmp, Text.slice(Core.b^.t, p, b)); -``` - -A procedure value can't return a lend either, so `Mini.Names` changes -to write the name into a buffer it is given: - -``` -(* Before *) -Names* = proc(i: I64): ([]U8, BOOL); -proc bufferNames(i: I64): ([]U8, BOOL); -begin - if i >= numChoices then return "", false; end; - return Buf.bytes(ADR(choices[i]^.name)), true; -end; - -(* After *) -Names* = proc(i: I64; var name: Buf.Buf): BOOL; (* the i-th name, into name *) -proc bufferNames(i: I64; var name: Buf.Buf): BOOL; -begin - if i >= numChoices then return false; end; - Buf.reset(name); - Buf.str(name, Buf.bytes(choices[i]^.name)); - return true; -end; -``` - -`gather`'s loop and `commandNames` change to match: about 10 lines. A -killed buffer and a closed window are not freed. Their contents are -(`Text.done`, `Buf.done`), and the empty record, about 200 bytes, is -kept to the end of the run: - -``` -Text.done(x^.t); -Buf.done(x^.name); -Buf.done(x^.path); -(* x itself is kept, empty: part D lets no safe module free it *) -``` - -That is five lines taken out. The `Pool(Buffer)` that section 14.2 -offers would touch about 370 dereferences of `^Buffer` and `^Window`. -`Pool` can't take a `Buffer` at all anyway: `add(var p; keep x: T)` -passes `x` by value, and a `Buffer` holds owners (7.6). `Pool` would -need an `alloc(var p): Handle` that hands out a zeroed slot. - -`Text` either says `unsafe;` and carries the owner's protocol by hand -(a `LENDS` field, retiring in `room`, `ret` on `slice`: about 25 -lines), or is rebuilt on `Vec(U8)` and `Vec(Change)` (about 60 lines). -Its gap moves under a slice that is held (`moveGap`), which the rules -let pass, since it is memory-safe. That is right: today's comment, -"good until the next change", stays a comment. - -**Count.** 4,931 lines. The fence alone: about 160 (the 139 `ADR`s, -the casts, `Text`'s heading). Parts B to F: `Text` 25, the four -accessors and their 20 callers 35, `Mini.Names` 10, `colours` 7, frees -5, `len` writes 7: about 90, 2%. - -**Judgement: the same.** Twelve calls grow a little longer. -`Mini.Names` copies each name once per keystroke of ido, about 256 -small copies, which doesn't show. - -**Run-time stops in correct code.** `writeFile` holds `p := -Buf.bytes(abs)` under `defer Buf.done(abs)`, and `loadInit` holds -`s := Buf.bytes(b)` under `defer Buf.done(b)`. Section 7.3 lets a -hold go "when the procedure returns", but doesn't say whether that is -before or after its deferred statements. If after, `C-x C-w` stops -the editor every time, and so does starting it with a `~/.rmacs` -(A7.7, H5). **Real bugs caught:** none. No self- -append or kill-while-held was found. `killBuffer` and `deleteWindow` -take care with `Core.b` and `Core.selected` already. - -### A7.4 The compiler (`src/Scan.raz`, `Chunk.raz`, `Diag.raz`, `Sym.raz`, and their users) - -**Scan's name table: can be safe, and is clearer.** Today names are -three hand-grown arrays and a table, all freed and copied by hand, and -the bytes sit in 64 KB chunks that are never freed. Safe, the chunks -come from `NEW` (lasting, so their slices last), and the arrays are -`Vec`s: - -``` -var - chunk: ^[PoolChunk]U8; (* from NEW, never freed: its slices last *) - chunkUsed: INT; - names: Strs.Vec; (* import Strs := Vec([]U8) *) - hashes, table: Ints.Vec; (* import Ints := Vec(INT) *) - -proc intern*(s: []U8): INT; (* was intern(p: ^U8; n: INT), called with ADR(s[0]), LEN(s) *) -var h, i, k: INT; t, hs: []INT; p: []U8; -begin - h := hash(s); - t := Ints.all(table); - hs := Ints.all(hashes); - i := h & tableMask; - while t[i] # 0 do - k := t[i] - 1; - if (hs[k] = h) and (Strs.get(names, k) = s) then return k; end; - i := (i + 1) & tableMask; - end; - if (chunk = nil) or (LEN(s) > PoolChunk - chunkUsed) then NEW(chunk, Heap.heap); chunkUsed := 0; end; - p := chunk^[chunkUsed..chunkUsed + LEN(s)]; - COPY(p, s); - INC(chunkUsed, LEN(s)); - k := names.len; - Strs.push(names, p); (* keep: p lasts *) - Ints.push(hashes, h); (* may grow hashes: hs is retired, and not read again *) - t[i] := k + 1; - t := []; (* or grow's Ints.done(table) stops the program *) - hs := []; - if (k + 1) * 2 > tableMask then grow; end; - return k; -end; -``` - -Two things here aren't in the proposal. `Strs.get` is new: `return -Strs.all(names)[n]` is refused, since an element of an owner's lend is -lent (6.1), though what it holds was stored by `keep` and lasts (A7.10, -R4). And `t := []` before `grow` is needed only to get past `done`'s -stop. Today's `intern` checks `n > chunkLeft` and then copies `n` -bytes into a 64 KB chunk: a name longer than 65,536 bytes would -overrun it. That can't happen, since `MaxStr` is 65,536 and `MaxIdent` -is 63, so the bound holds only by the coincidence of two constants. -The safe form checks it. About 40 lines change; the scanner's buffer -stays unsafe, as section 21 suggests. - -**Chunk's grown arrays: can be safe, and grow longer.** `text`, -`rodata`, `chunks`, `fixups`, `dataFixups`, `lines` and `varNotes` -become `Buf`s and `Vec`s. `put1` becomes `Buf.add(text, U8(b & 0FFH))`, -which is clearer. But there are about 200 places in `Link`, `X64`, -`Elf`, `Gen`, `Parse` and `Item` that read `Chunk.chunks[c].adr` or -`Chunk.lines[i].at`, and each one becomes either - -``` -Chunks.all(Chunk.chunks)[c].adr := a; (* a count raised and lowered, each time *) -``` - -or a local held over the procedure, `cs := Chunks.all(Chunk.chunks)`. -The obvious mending, `proc at*(c: INT): ^Chunk` in `Chunk`, can't be -written, since it returns a lend of an owner that no parameter names -(7.3). And a held `cs` across a `newChunk` that grows the array is a -new trap. The writes through `cs` go into the retired block and are -lost, with no message, even in the debugging heap, which poisons -retired blocks for reads only (11). Today that is a use after free. -Under the proposal it is a wrong executable, and the proposal calls it -"lost, but harmless" (7.4). For a compiler it is not harmless. - -**Diag's files and messages.** `files: ^File` becomes `Vec(File)`, and -`pathOf` needs `Vec.get` (R4). `say` keeps every message for good, in -a `Buf` from `grab` that is never freed: - -``` -(* Before *) -b := ^Buf.Buf(grab(SIZE(Buf.Buf))); -Buf.init(b^, Heap.heap); -Fmt.write(b^, f, args); -return Buf.bytes(b^); - -(* After, with Buf.leak (R5) *) -var b: Buf.Buf; -Buf.init(b, Heap.heap); -Fmt.write(b, f, args); -return Buf.leak(b); (* b gives its block up for good: it lasts *) -``` - -Without `Buf.leak` the only safe form is a second copy, `Str.copy` of -the bytes and then `Buf.done`, for every message. `Sym.typeName` is the -same, and so are four `grab`-and-slice strings in `Parse`, `Item` and -`Raz`. - -**Sym's scopes.** The hash table `hashTab: ^^Obj` becomes `Vec(^Obj)`, -and `rehash` builds a new one and drops the old. `Obj`s and `Type`s -come from `NEW` and are never freed, so the 1,015 dereferences stay as -they are, as 8.1 says. Under the strict reading of 6.1, though, each -procedure that stores a pointer it is given needs `keep`: `newObj`'s -`typ`, `insert`'s `obj`, and the 17 procedures of `Item` and `Parse` -that put a `^Sym.Type` or `^Sym.Obj` parameter into a `var x: Item`. -That is about 40 headings across `src/`, and every argument is a -pointer from `NEW` already (R3 removes them). `Parse`'s `curLoop := -ADR(lp)` becomes a stack of loops in a module array, about 10 lines. - -**Count.** 14,285 lines. The fence's own list (section 2.2): about 60 -sites. Parts B to F and what the mending entails: Scan 40, Chunk 60, -the 200 accesses, Diag and the kept strings 30, Sym 20, `keep` marks -40, loops 10. About 420 lines, 3%. - -**Judgement.** Scan's table and `Diag.say` come out clearer. `Chunk` -and `Link` come out longer, and no clearer, unless R1 allows accessors. -Speed: a call, a count and a bounds check where a pointer index stood, -on the symbol lookup and code emission paths. That is not measured; an -estimate is 1 to 3% of instructions, on top of the 4.5% of 13.1 if -`Scan` goes safe as well. **Run-time stops in correct code:** -`Parse.raz:3696`, `text := Buf.bytes(s)` and then `Buf.done(s)`, would -stop at the first generic instance the compiler made, and so `make -check` would stop in its first minute. **Real bugs caught:** none, -beyond the bound in `intern` that holds by luck. - -### A7.5 The library (`Fmt`, `Opt`, `Map`, `Buf`, `Vec`, `List`, `Files`) and `examples/Sh.raz` - -**`Fmt` can't be made safe as section 5.4 says.** `format` takes -`b: ^Buf.Buf`, with `nil` for standard output, and `write` and -`eprint` pass `ADR(b)`. Without `ADR`, the `nil` must become a flag, -and `print` has no `Buf` to pass: - -``` -(* After *) -var none: Buf.Buf; (* never written: what print passes for b *) - -proc put(var b: Buf.Buf; out: BOOL; s: []U8); -begin - if out then Out.str(s); else Buf.str(b, s); end; -end; - -proc print*(f: []U8; args: []Arg); -begin - format(none, true, f, args); -end; -``` - -This is a contortion: an owner kept only to stand in for "none". -`eprint` builds its text in a `Buf` over an arena, so that a program -that doesn't call it carries no heap. Under the proposal -`Buf.init(b, Arena.allocator(ar))` is refused. `init` keeps its -allocator, so its parameter is `keep`, and the arena's allocator is -lent by the arena (8.4). So `eprint` moves to the heap and loses the -reason its comment gives. No container can take memory from an arena -in safe code. About 15 lines change. - -**`Opt` is safe, with one stop in correct code.** `left` and -`leftWidth` take `const r: Row` for `ADR(p.table[i])`, six lines. -`init` is `keep name, table`, and `scope` is `keep name`. `say` would -stop: - -``` -proc say(fd: INT; var b: Buf.Buf); -var s: []U8; n: INT; -begin - s := Buf.bytes(b); - while LEN(s) > 0 do - n := Sys.write(fd, s); - if n <= 0 then break; end; - s := s[n..LEN(s)]; - end; - s := []; (* new: else the next line stops, though s is empty and never read again *) - Buf.done(b); -end; -``` - -Every usage message and every `--help` of every program goes through -`say`. - -**`Map` marks are easy, and its uses narrow.** `put(var m; keep k: K; -keep v: V)` is one heading. `Map([]U8, V)` keys must now last, so a -key made in a `Buf` is `Str.copy`'d and never freed, or goes in -`Names(V)`. `Map(K, Buf.Buf)` can't be made at all: `put` takes `V` by -value, and an owner can't be copied. A map of strings to buffers, an -editor's "buffer by name", has no safe form but `Pool` handles. - -**The containers export what breaks them.** `Buf.len*`, `Vec.len*`, -`List.head*` and `List.Node.next*` are fields a safe module can write. -`b.len := 1 shl 40; Buf.bytes(b)` reads any memory, because `bytes` -slices `b.data`, a pointer, unchecked. `l.head := other.head; -List.clear(l)` frees another list's nodes. This is 5.3's rule 4, but -section 17 doesn't list it. Hiding the fields changes every read of -`b.len` in every program, dozens in rmacs alone, unless fields can be -exported read-only (R6). `Files.load` writes `INC(b.len, n)` after -`Buf.spare`, as `spare`'s own comment says to, so `Files` isn't safe -either until `Buf` gets a checked `took(var b; n)`. `examples/Words` -walks `order.head` and `n^.next`, three lines that become -`Names.first` and `Names.next`. - -**`examples/Sh.raz`: its arena has no safe form.** `Sh` builds each -word in a `Buf` over a module arena, keeps `Buf.bytes(b)` in the module -variable `text` and in `Command.args`, and resets the arena for each -script. Every one of those is refused: the `Buf` over the arena (keep, -8.4), `text := Buf.bytes(b)` (7.3), `c^.args[c^.n] := text` through a -pointer (6.2), `return Buf.bytes(b), true` in `find` (7.3), and `s := -script` from `run(Buf.bytes(line))` (keep). Building `argv` from spans -at `spawn` is refused too, since a local array of slices may not hold -a lend (7.3). What compiles is a bump allocator written by hand over a -module array, whose slices last: - -``` -var - pool: [1 shl 24]U8; (* the words of what is being run; a module's array lasts *) - used: INT; - -proc add(c: U8); -begin - if used = LEN(pool) then say("out of room for words", []); Rt.exit(2); end; - pool[used] := c; - INC(used); -end; - -(* in readWord, for Buf.init(b, ADR(arena.base)) ... text := Buf.bytes(b) *) -start := used; -... -text := pool[start..used]; -``` - -The rules let this pass, and that's right: `used := 0` makes old words -show new bytes, which is a matter of logic, not memory. But it shows -that the arena was refused for what it is, not for anything it does. -`ADR(p^.cmds[i])` becomes an index, and `builtin` and `start` take -`const`. The scanner's module state (`s`, `at`, `text`) goes into a -`Scanner` record passed by `var`, so that `run` needn't keep its -script. That is 45 of 387 lines, 12%. The scanner comes out clearer, -and the allocator worse: an `Arena` was one line, and this is ten. - -### A7.6 rjson's `Json` (`src/Json.raz`, `test/Suite.raz`) - -`Doc` grows its nodes by hand with `Mem.alloc` and `Mem.free`, and -copies strings into a list of chunks that `reset` frees. So `Json` -says `unsafe;` and carries the owner protocol itself: a `LENDS` field, -retiring chunks in `reset`, `ret` on `text`, `key` and `copy`. That is -about 25 lines of trusted code outside the library, and the same holds -for every program with a container of its own (`Text` in rmacs). The -audit surface grows with each one. The zero-copy design ("the text -must live as long as the document") means `parse` keeps its text. The -suite's - -``` -v := Json.parse(ADR(d), Buf.bytes(ADR(text))); (* twice *) -``` - -is refused, since a `Buf`'s bytes don't last. Such a program either -leaks each file's bytes with `Buf.leak`, which is fine for a test but -not for a server parsing request bodies, or `Json` gets a `parseCopy` -that copies the text into the document first: one copy per parse, -small next to parsing. About 40 lines change, 4%. - -### A7.7 Holes the port found in the rules - -Each of these lets unsafe code through as the proposal is written, or -leaves undecided whether correct code stops. - -- **H1. A store through a slice isn't a store that outlives.** 6.2 - lists module variables, `p^.f` and `var` parameters. It doesn't list - `s[i] := e` for a slice `s`. So `proc fill(names: [][]U8); var buf: - [8]U8; begin names[0] := buf[0..8]; end;` puts a slice of the frame - in the caller's array. `Vec.all(v)[i] := e` puts a lend in a - container the same way. The rule must say that a store through a - slice not lent by the frame alone is a store that outlives. -- **H2. A `ret` through a record that holds owners loses the owner.** - `name*(ret const m: Message; i: INT): []U8`, the accessor section - 14.2 recommends, returns a lend of `m.head`. The caller knows only - that the result is lent by `m`, which isn't an owner (7.2), so it - doesn't know whose count to raise, and it raises none. Then - `readRequest` grows `m.head`, frees the old block, and the held - slice dangles. Either the accessor is refused, and 14.2's way out - doesn't compile, or it is allowed, and the count is lost. R1 - mends it. -- **H3. The containers' exported fields** (A7.5): `Buf.len*`, - `Vec.len*`, `List.head*`, `Node.next*`, and `Files.load`'s `INC(b.len, - n)` by design. -- **H4. A literal over a live owner.** `m := {minor: 1}` is allowed - (7.6: a literal may leave an owner out). It drops the owner's block, - which is a safe leak, and zeroes its allocator, so the owner's next - growth stops. It is a trap that compiles, and the obvious rewrite of - `Http.reset` falls into it. -- **H5. The order of a hold's let-go and `defer`.** If holds are let go - after the deferred statements, every `defer Buf.done(b)` over a - local that holds `Buf.bytes(b)` stops the program. If before, a - deferred statement that reads the local reads memory still allocated, - which is fine. Section 7.3 must say "before". -- **H6. Option 2 of 14.2 breaks rule 4 of 5.3** (A7.2). An unsafe - `Http` with exported slice fields hands a safe module a slice it can - read after `Http.done`. - -### A7.8 The verdict, in numbers - -| Code | Lines | The fence alone (`ADR` to own pointers, casts) | Parts B to F | Share | Result | -|---|---|---|---|---|---| -| rnet `Http`, `Conn`, tests, `Hello` | 2,700 | 330 | 230 | 9% | worse | -| rmacs | 4,931 | 160 | 90 | 2% | the same | -| raz `src/` | 14,285 | 60 sites | 420 | 3% | Scan, Diag clearer; Chunk, Link longer | -| `lib/`: `Fmt`, `Opt`, `Map`, `Buf`, `Vec`, `List`, `Files` | 1,500 | 15 | 70 | 5% | Fmt worse; the rest the same | -| `examples/Sh.raz` | 387 | 10 | 45 | 12% | scanner clearer, allocator worse | -| rjson `Json`, `Suite` | 1,050 | 15 | 40 | 4% | the same, with a copy per parse | -| **All** | **24,850** | **about 590** | **about 895** | **4%** | | - -Where parts B to F's 895 lines come from, by rule: - -| Rule | Lines | Share | What it hits | -|---|---|---|---| -| 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` | -| 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 | -| 6.1 and 6.2 read strictly: `keep` on a pointer parameter that is stored | 60 | 7% | `Sym`, `Item`, rmacs's `Core` | -| 7.6: owners aren't copied | 30 | 3% | `Http.reset`, `open`'s `out := req^` | -| 5.3 rule 4: the containers' fields hidden | 20, or every read of `.len` | 2% | rmacs, `Files` | -| D: no `free` | 5, leaking | 1% | rmacs's buffers and windows | -| the rest: `ret` marks, `t := []`, views | 130 | 15% | everywhere, a line at a time | - -**Stops at run time in correct code: 8**, found by a search for a -local holding `Buf.bytes(b)` when `b` is done: `Opt.say`, -`Parse.raz:3696`, `examples/Elf.raz`, rmacs's `Commands` (two), -ravite's `Ravite.raz`, rnet's `Dns` (two). Five of them depend on H5. -Each is found the first time its code runs, and each is mended with one -line. But there is one in the compiler and one in the library, so -`make check` would stop the day part C came in. - -**Real bugs caught: none** in about 25,000 lines. One bound holds by -the coincidence of two constants (Scan). Every slice held across a -change of its buffer was right, by an order the code keeps. So the -rules make "right by discipline" checked. They guard tomorrow's code; -they don't mend today's. The five programs of section 1.2 were written -to show the holes. None of them was found in this code. - -**Is the pain narrow?** By lines, yes: 96% of the code is left alone, -or changes only where `STANDARDS.md` already asks it to. By kind, no. -Five of the six pieces need a redesign of the one type they are built -round. Each such type keeps a slice of a buffer in a record, or hands -one out from a procedure that isn't the buffer's own, and those are -the pieces that do I/O or hold data. Code that only computes, `Parse`'s -statements, `Item`, `Gen`, rflate's inflater, `Fmt`'s formatting, is -left alone, as section 14.1 says. - -### A7.9 Beside Rust and beside today's raz - -**Beside today's raz.** Today the six pieces compile as they are, and -their rules of lifetime are comments ("good until the buffer next -grows", "the text must live as long as the document"). Under the -proposal four of those comments become checks, and the code that -leans on them grows by about 4%. It loses three things that were -easy: a record of slices of someone else's buffer, an accessor that -returns a slice of a buffer, and a container over an arena. - -**Beside Rust.** Where a record holds slices of its *own* buffer -(`Message`, `Doc`), Rust can't do it either: a struct can't borrow -from itself, so Rust programs use spans, as here, or a crate built for -it. Where a record holds slices of *another's* buffer (`Url` of a -`Buf`, `Sh`'s `argv`, a `Doc` over a file's bytes), Rust writes -`Url<'a>` and is done; raz must copy, or use a frame array. Where a -procedure returns a slice of an owner it reaches through a global or a -pointer (`Core.slice`, `bufferNames`, `Chunk.at`), Rust writes -`&'static` or a lifetime on the result; raz can't write it at all. -Where a callback needs its context (`Server.arg`, `Conn.state`), Rust -has closures and trait objects; raz has `^U8`, which is fenced. On -the other hand, 96% of the code needs no mark at all, where a Rust -port of `Sym`, `Item` and `Parse`'s trees, with their `^Obj` and -`^Type` links everywhere, would need `Rc`, arenas with lifetimes or -indexes throughout. And Rust would reject at compile time the eight -`done`-while-held places, where this proposal stops at run time. In -short, the proposal costs much less than Rust in the code that -computes, more than Rust in the code that holds buffers, and it has -nothing for type-erased context, where Rust has a great deal. - -### A7.10 Relaxations and additions - -Each of these removes pain found above. Each says what it would cost, -and what, if anything, it weakens. - -- **R1. A lend carries its count.** An owner's lend returned from any - procedure carries the address of its owner's count, in a hidden word, - as a held local already does. Then the caller counts it on the right - owner, whoever returned it. This allows `Core.slice`, `Mini.text`, - `Dired.nameAt`, `Chunk.at`, `Http.target` and `Json.text`, mends H2, - and removes about 250 of the 450 lines of 7.3. A procedure type - must say that its result carries a count (`proc(i: I64): lent - []U8`). It costs a register on return. It weakens nothing. -- **R2. A local array or record may hold lends** (question 4 of section - 21: yes), with one hold for each owner it holds lends of, all let go - when the local is assigned whole or the procedure returns. This - allows `Url` of a `Buf`, `Sh`'s `argv`, and a local `[]Fmt.Arg` of - several `Buf`s, and removes about 60 lines. It costs a few words in - the frame. It weakens nothing. -- **R3. A pointer parameter lasts, as STANDARDS says it does** ("a - pointer, only when it is kept"). An unmarked `^T` parameter may be - stored. An owner's pointer (`Vec.add`, `Pool.at`) may not be passed - as a `^T` argument, only dereferenced at the call, `f(p^)` to a `var`. - This removes the 60 `keep` marks, and it puts the check on the rare - case, the owner's pointer, not the common one. It weakens nothing. -- **R4. `Vec.get(const v; i: INT): T` and `Vec.set(var v; i: INT; - keep x: T)`.** A copy of an element holds what was kept, and that - lasts. This mends `Scan.nameOf` and `Diag.pathOf`. Library only, - and it weakens nothing. -- **R5. `Buf.leak(var b: Buf.Buf): []U8` and `Vec.leak`.** The owner - gives its block up for good and is left empty, and the block lasts, - since no one holds what could free it. This is Rust's `Box::leak`. It - mends `Diag.say`, `Sym.typeName`, `Parse`'s and `Item`'s kept - strings, and a test's file. Library only, and it weakens nothing, - but leak-freedom, which the guarantee doesn't promise (3). -- **R6. Fields exported read-only**, Oberon-2's `len-: INT`, and - `Buf.took(var b; n: INT)`, checked against the room `spare` made. This - closes H3 and keeps every read of `b.len` as it is, while the seven - writes in rmacs become `Buf.cut`. A language change of one mark. - It weakens nothing, and without it the containers aren't safe. -- **R7. `done` with a lend held is caught when compiling where it - can be, and otherwise retires.** In one pass, the compiler knows when - a local was last assigned a lend of `b` and has not been assigned - since, so at `Buf.done(b)` it can say "`s` still holds a lend of `b`: - write `s := []` first". That turns six of the eight stops into - messages. The two through a pointer stay. For those, `done` retires - the block instead of stopping: question 3 of section 21, answered - "leak". With H5 settled as "before", the eight become none. It weakens - leak-freedom, not safety, and the debugging heap can report each - leak. -- **R8. A checked context pointer.** A type `^ANY`, which any pointer - from `NEW` converts to, and a conversion back, `^T(p)`, checked - against a type word that `NEW` writes before the record. A wrong - type stops the program, as Oberon's type guard does. This mends - `Conn.state`, `Http.Server.arg`, `Thread.spawn`'s `arg` and the - tests' casts, about 150 lines, and lets a server keep its state - without module variables shared across threads. It costs a word per - record that is ever made `^ANY`, if `NEW` is told so, and a compare - per conversion. It weakens nothing. -- **R9. Growth with a *writable* lend held stops; with a lend that - only reads, it retires.** `Vec.add` and `Buf.spare` lend for - writing, and `bytes` and `all` lend for reading. A write into a - retired block is lost with no message (A7.4); a stop says where. - `Buf.str(b, Buf.bytes(b))` still runs. This is a tightening, not a - relaxation. It costs a second count per owner, and `all` must split - in two, since today it lends for both. - -Some pain has no relaxation that keeps the guarantee: - -- **A container over an arena** (`Fmt.eprint`, `Sh`). Making it safe - needs the container to hold the arena's count for as long as it - lives: an owner holding a lend, which is a lifetime in a record, - Rust's apparatus. A module array with an index does it safely, as - `Sh`'s rewrite shows, at a fixed size. Otherwise such code stays - unsafe. -- **A record that keeps slices of its own buffer** (`Message`, `Doc`) - stays spans and accessors, in raz as in Rust. With R1 the accessors - compile, and that is all the help there is. -- **Freeing records one by one.** `Pool`, or leaking. For an editor - leaking is the plain choice, and it is safe. `Pool` needs an `alloc` - that hands out a zeroed slot, for records that hold owners. - -With R1 to R8, the port's 895 lines fall to about 400, under 2%. The -contortions left are `Fmt`'s stand-in and `Sh`'s allocator, and no -correct code stops at run time. The holes H1 to H6 are mended by -R1, R6 and two sentences in 6.2 and 7.3. diff --git a/PLAN.md b/PLAN.md index b142c23..061b5e8 100644 --- a/PLAN.md +++ b/PLAN.md @@ -1,8 +1,8 @@ # raz: the plan to 1.0 What is left before raz is 1.0, in order, by the owner's word of -2026-10-23. `PROPOSALS.md` takes nothing new; what it still holds open is -the safety thaw and the Moss work below, and nothing else is planned. +2026-10-23. raz takes no proposals; what is left is the Moss work below, +its proposals kept in the appendix, and nothing else is planned. Each step is a release, started on the owner's go-ahead; within it, one commit per piece, the report first for any change to the language. @@ -28,9 +28,10 @@ ## 2. The safety thaw: v0.23.0, then v0.24.0 The scope, by the owner's word of 2026-10-26, after reviewing -`MEM_PROPOSAL.md` whole with its appendices. raz doesn't promise memory -safety: `free` stays, so a program can always keep a pointer to what -it freed. The thaw shrinks what is undefined, and fences what can reach +`MEM_PROPOSAL.md` (in git to 2026-10-26) whole with its appendices. +raz doesn't promise memory safety: `free` stays, so a program can +always keep a pointer to what it freed. The thaw shrinks what is +undefined, and fences what can reach memory it shouldn't, so a reader can find it. What goes in: @@ -107,14 +108,15 @@ 1. Merge the branch `moss-platform-boundary`'s two plain fixes (a file's identity from `Sys.info`; a main file at the root), rebased on main. -2. `Host`, as "The compiler on another host" in `PROPOSALS.md` asks: +2. `Host`, as "The compiler on another host" in the appendix asks: five procedures, `Files.argCount`, a host chosen by staging, its tests in `sh`, not Python; rebased and merged. Moss's `RAZ_PORT.lock` then pins main. 3. What the compiler asks of `Sys`, `Rt` and `Files`, written down in `doc/compiler.md` and held by a test. 4. "A freestanding program, stated", "The assembler's instructions" and - "Implementation limits, and a compiler for a small stack". + "Implementation limits, and a compiler for a small stack", in the + appendix. 5. Release. ## 4. The hard freeze @@ -128,9 +130,8 @@ The files that served the thaws are made a record, short and true: -- `PROPOSALS.md` and `MEM_PROPOSAL.md`: what was built is in the report, - `doc/report-history.md` and git; each shrinks to a short index of what - was decided, and what was left out with its reason, or goes. +- `PROPOSALS.md` and `MEM_PROPOSAL.md`: gone, done early (2026-10-26); + what was built is in the report, `doc/report-history.md` and git. - `~/r/RAZ-GAPS.md` and each repository's `RAZ-NOTES.md` (or `RAZ.md`): closed, each saying so at its top; a gap since mended is marked. - `CLAUDE.md` (raz's and `~/r`'s): "Where things stand" cut to the @@ -148,3 +149,341 @@ No date. raz is 1.0 when use shows it: programs written against v0.26.0 for long enough that no defect is outstanding. Until then it is 0.26.x, mending defects only. + +## Appendix: the Moss work, as proposed + +The four proposals 3 builds, kept from `PROPOSALS.md` (in git to +2026-10-26) when it and `MEM_PROPOSAL.md` went: what the thaws built is +in the report, `doc/report-history.md` and git. +### The compiler on another host: `Host`, and what it asks of the library + +**Status.** Built on the branch `moss-platform-boundary` (3eded0c), +which Moss pins: there raz compiles programs, rebuilds itself byte for +byte, and builds again after a restart (moss c606069, +`docs/native-raz.md`). Waiting for the owner's word on the questions +below before it is rebased and merged. + +The host is the system the compiler runs on; the target, the system +its program will run on. Until the branch they were one, Linux, and +the compiler reached Linux outside `Sys`: `Parse.identity` read a +`struct stat` by `SYSCALL(4)` into a guessed `[18]INT`; `Raz` read +`ARGC()` and `ARGV()`, found the library through `/proc/self/exe`, +probed two loader paths for musl, and ran a program by `memfd_create` +and `execve`; `Elf` set mode 755. The branch does three things. + +**1. A file's identity from `Sys.info`** (2644329). Its `dev` and +`ino`, so the parser makes no system call of its own. A plain fix: +merge it. + +**2. A main file at the root, and a directory ending in `/`** +(3eded0c). `/Main.raz` has `/` as its directory, not `""`, and a +directory given as `lib/` doesn't make `lib//Sys.raz`. A plain fix: +merge it. + +**3. `Host`, a module of what the compiler asks of its host** +(bb03e48): `argCount`, `arg`, `libraryDir`, `preferMusl`, `canRun`, +`canLinkC`, `writeExecutable`, `prepareRun`, `execute`. `src/Host.raz` +is Linux's; Moss stages the compiler's sources with its own +`Host.raz` (27 lines: the library at `/lib`, no run, no C, no mode +bits) and its own `Sys`, `Rt` and `Files`. + +Questions before the merge: + +**a. A smaller `Host`.** Two of its nine procedures are there only +because `Raz` reads the command line by built-ins: +- `argCount` and `arg` go if the library has the count beside + `Files.arg`: a `Files.argCount()`, which Moss's `Files` gives from + `Sys.argc`. `Files.arg` is already the library's, and Moss already + replaces it. +- `preferMusl` and `canLinkC` are one question, which C library to + link against: `Host.cLibrary(): CLib` with `CLib = (none, glibc, + musl)`, or keep the two booleans. +- `canRun` goes if `prepareRun` is called while the command line is + read, before any source, so that its error is the refusal. +That leaves `libraryDir`, `cLibrary`, `writeExecutable`, `prepareRun` +and `execute`: five procedures, each a real difference between hosts. + +**b. How a host is chosen.** The branch stages: copy `src/`, put the +host's `Host.raz` in place of raz's, build. The main directory is +searched first, so `-I` alone can't replace it, which is right: a +module isn't silently replaced. The other way is a target name, as +`Sys.linux-x86_64.raz` is chosen today from fixed suffixes: a +`-os moss` that makes the suffixes `.moss-x86_64`, `.moss`, `.x86_64`, +`""`, so that `Host.moss.raz` and `Sys.moss.raz` are found beside the +generic files. That puts Moss's files in raz's tree, and raz would +then know of Moss. The proposal is to keep staging, raz knowing +nothing of any host but Linux, and to document it in +`doc/compiler.md` as the one way to build for another host. + +**c. What the compiler asks of the library, written down.** Moss's +`Sys` has 23 exported procedures against Linux's 104, and is enough. +`doc/compiler.md` should list what the compiler and the modules it +imports (`Rt`, `Mem`, `Heap`, `Lock`, `Arena`, `Out`, `Fmt`, `Buf`, +`Str`, `Bytes`, `Files`) use of `Sys`, `Rt` and `Files`, as Moss's +`docs/raz-port.md` measured it, and a test should hold it: the +compiler built against a `Sys` with only those exports. Then a change +to the compiler that reaches for one more of `Sys` is seen in raz, +not in Moss's next build. The test host on the branch +(`test/host/Host.raz`) checks the `Host` side only. + +**d. The stack.** A self-build passed in 64 KiB of stack on Linux, +but 64 nested parentheses don't, and Moss gives a stored program 1 +MiB. That is "Implementation limits, and a compiler for a small +stack", above; the merge needn't wait for it. + +**e. The tests in Python.** The branch adds `test/compiler-host.py` +(177 lines) and grows `test/library-path.py`, which came with +RAZ_PATH. raz's tests are otherwise `sh`, as a public project's +should be, needing nothing but a shell to run. The proposal is to +write both in `sh` before the merge. + +**f. Before the merge, in any case.** The system call numbers in +`Host.raz` named as constants, as `Raz` had them (`MemfdCreate`, +`MfdCloexec`, `Execve`); a comment on every procedure; the new section +of `doc/compiler.md` made as short and plain as the rest; a rebase on +main (`doc/compiler.md` and `src/Raz.raz` conflict). Moss's +`RAZ_PORT.lock` then pins a commit on main. +### A freestanding program, stated + +**Status.** Proposed 2026-10-22, collated from RAZ-GAPS.md. + +"For a kernel: three changes to the compiler" made a raz program run on +the bare machine; Moss, a kernel in raz, now boots on it. What it found +is less a missing feature than missing words: what a `-bare` program +must give the compiler, and what it may count on, are known only by +reading `Gen.entryPoint` and `Raz`. Five items, each standing alone. +The sixth thing Moss met, `jmp rax` read as a jump to a label, was a +bug, fixed in ac3c464. + +**1. The runtime ABI, written down.** A section of `doc/compiler.md`, +"A program with its own `Rt`", saying what the compiler asks of `Rt` +and what a program's start may count on: +- **Required:** `proc exit*(status: INT);`, which never returns (the + compiler puts `ud2` after its call), and + `proc fail*(what, a, b, len: INT; at: UINT; name: ^U8; rdi, rsi: UINT);`, + with the kinds of `what` as `lib/Rt.raz` gives them (0 an index, 1 a + slice, 2 an enumeration, 3 a backward slice of a pointer, 4 a nil + pointer, 5 a division by zero, 6 a stack overflow, 7 a view), named + constants in the text, not bare numbers. +- **Optional, found by name when declared:** `places`, `calls`, + `teller`, `place`, `placer` (item 5), `startProfile` and `profiler` + (never under `-bare`), `cExit` (only with C, which `-bare` refuses). +- **The entry:** `_start` runs every used module's body but `Rt`'s, + then `main`. Under `-bare` it reads nothing from the stack and aligns + nothing: the loader or boot stub enters it with the bss zeroed and + `rsp` a multiple of 16, as Linux does. +- **`main` returning:** allowed. `Rt.exit` is then called with `main`'s + result, or 0 for `proc main*`. +- **The panic hook:** `Rt.fail` is it. A kernel's `fail` prints and + halts; nothing else is needed, and no second hook is proposed. + +A test holds it: `test/run/` builds a `-bare` program against a +smallest `Rt` of `exit` and `fail` alone, run under Linux, whose +`exit` and `fail` make the system call themselves. + +Met in Moss (`docs/raz-findings.md` §2), which copied the stock +signatures. + +**Recommendation:** take; it is words and one test, and the contract +already exists. + +**2. A recipe for an interrupt's entry.** Before any attribute or +generated stub, a tested recipe in `doc/compiler.md`, beside item 1, +stating what the compiler's code may assume and so what a stub must +restore: +- **What the compiler's code uses:** System V's caller-saved + registers, `rax`, `rcx`, `rdx`, `rsi`, `rdi`, `r8` to `r11`, all of + `xmm0` to `xmm15`, and the flags; the direction flag is clear at + every call (the compiler's copies use `std` and `cld` and leave it + clear). +- **The red zone:** whether the compiler ever writes below `rsp`. Not + checked today ("For a kernel" leaves it open); it is to be checked + and the answer written down. If it never does, an interrupt needs no + IST stack for that reason. +- **The stub:** a `code` procedure per vector that pushes 0 where the + CPU pushes no error code, pushes the vector, saves the caller-saved + registers, aligns `rsp` to 16, saves the SSE state (`fxsave` or + `xsave` to an aligned area), `cld`, calls an ordinary procedure + `proc handle(vector, code: INT; frame: ^Frame)`, restores, drops the + two words and `iretq`. + +It is testable on Linux: `iretq` from ring 3 to ring 3 is allowed, so +`test/run/Interrupt.raz` builds a frame by hand, jumps to the stub, has +the handler compute with reals, and checks on return that every +register the stub promised to keep is kept. The stub needs items 3 and +"The assembler's instructions", 1 (`push` of a constant, `cld`). + +Met in Moss (`docs/raz-findings.md` §4): its handlers use only `rax` +and make no call, which is safe but no recipe. + +**Recommendation:** take; a kernel's first stub is where the calling +convention is easiest to get wrong, and a test on Linux keeps it right. + +**3. A code procedure names a procedure or a global.** In a code +procedure, a name of the module's scope, or a qualified one, that is a +procedure or a global variable stands for its address, as an operand +of three forms only: + + call fault; (* a procedure, rip-relative *) + jmp fault; + lea rax, [ticks]; (* a procedure or a global *) + +Each makes a reference to that chunk, so the linker keeps what is +named, as any call does. No other operand takes a name, and no type is +checked: a code procedure is the target's, and its author already +answers for the convention. The assembler gets the names as it gets +constants, by a function the parser hands in beside `ConstFn`. + +Moss stores `UINT(fault)` in a slot at start and calls through a +register (`docs/raz-findings.md` §5), so the slot must be filled +before the first fault, which nothing checks. + +**Recommendation:** take; three operand forms remove a hand-off that +can be forgotten, and the recipe in item 2 needs `call handle`. + +**4. A program brings its own `Rt`.** A `src/Rt.raz` beside the main +module meets `lib/Rt.raz`, and "a program has one module of each name" +refuses it, rightly. Moss copies the compiler beside an empty `lib/`. +Two ways out: +- **Staging,** as "The compiler on another host" proposes for the + compiler's own sources: copy `raz` beside a library of the program's + own. Nothing in raz changes; only words in `doc/compiler.md`. Every + freestanding project then carries a copied compiler, and its library + is all or nothing. +- **`raz -lib DIR`:** the library is `DIR`, not the one beside the + compiler. A kernel's `-lib` is a directory holding its own `Rt` and + `Sys` and, by symbolic links, whichever of raz's modules it takes + (`Str`, `Fmt`, `Buf`). The duplicate check stays as it is. On the + `Host` branch it is one line over `Host.libraryDir`; today a few + lines in `Raz.raz` and raz(1). + +The option is the smaller for its users and nearly as small in raz; +staging stays the way for the compiler on another host, where the +whole of `src/` is replaced anyway. + +**Recommendation:** take `-lib`; a few lines save every freestanding +program a copy of the compiler. + +**5. Symbols without `Rt`'s places.** Without `-s` the compiler links +`places`, `calls`, `teller`, `place` and `placer` and stops with "Rt +has no places" where `Rt` lacks one, and `-noprofile` doesn't help, so +Moss builds with `-s` and loses the symbol table a debugger reads. +Two things are tied that needn't be: the ELF's symbols and lines, for +a debugger, and the places, for `Rt` to say where a check failed. +The change: each of the five is linked only when `Rt` declares it, +`calls` with `teller` and `place` with `placer`, a pair or neither; `-s` +still strips both. A kernel then keeps its symbols for GDB and gives +`fail` the raw address, or declares `places` and decodes them itself. + +A hosted program's `Rt` is raz's, which declares all five, so no +program changes. One that writes its own `Rt` and misspells `places` +loses its places silently; item 1 lists the names. + +Met in Moss (`docs/raz-findings.md` §3). + +**Recommendation:** take; it is a test on each name in `Raz.raz` and +gives a kernel its symbols back. + +### The assembler's instructions + +**Status.** Proposed 2026-10-22, collated from RAZ-GAPS.md. + +The report leaves which instructions the assembler knows to the +implementation, and `db` gives any other. That stays. What is missing +is a rule for when an instruction joins, and the few that programs +have already written in `db`. + +**1. `push` of a constant, and `cld` and `std`.** `push imm8` and +`push imm32` (6A, 68, sign-extended to 64 bits), and `cld` and `std` +in `Plain`. The encoder already writes `cld` and `std` for the +compiler's copies; only the assembler's table lacks them. Moss's +exception stubs write all three with `db`, and every stub of +"A freestanding program, stated", 2, needs them. + +**Recommendation:** take; three entries the encoder half has, and an +interrupt stub can't be written without them. + +**2. When an instruction joins, and the SHA and shuffle ones now.** +The rule, in `doc/compiler.md` beside the assembler: an instruction +joins when a program writes it in `db`, it is a family's member the +tables already hold (a code in `PackedOps`, an entry in `Plain`), and +its bytes are checked against GNU `as` in `test/run/`, as +`AsmKernel.raz` does. Anything else stays `db`, which is the permanent +answer for an instruction no program uses twice. By that rule, now: +- `paddd`, `punpcklqdq`, `punpckhqdq` into `PackedOps` (66 0F FE, 6C, + 6D); +- `pshufb` (66 0F 38 00) and `palignr` (66 0F 3A 0F, with a byte), + two more forms, three-byte opcodes; +- `sha256rnds2` (0F 38 CB, `xmm0` implied), `sha256msg1` (0F 38 CC), + `sha256msg2` (0F 38 CD). + +Sauce's SHA-NI hash is 123 `db` lines assembled by GNU `as`, nothing +checking a byte against its mnemonic; with these it is read as written. +AES-NI, `pclmulqdq`, AVX and the rest wait for a program. (`movd` and +`movq`, `pxor`, `pshufd`, `movdqu`, `movdqa`, `pmovmskb` are there +already.) + +**Recommendation:** take; a rule stops the list growing by wish, and +eight instructions turn sauce's 123 unchecked lines into checked ones. + +**3. `raz -S`'s listing, stated.** raz(1) gives the listing's form, so +a tool may read it: +- a blank line, then a procedure's name as `Module.name:`; +- a source line: its number right-aligned in 6 columns, two spaces, + the line's text; +- an instruction: its offset in the procedure right-aligned in 14 + columns, two spaces, the instruction as the assembler would read it, + a jump within the procedure giving its target as an offset. + +Only the main module's live procedures, in the order they were made; +nothing is disassembled. A change to the form is then a change to the +manual, and rcrypto's constant-time guard (`tools/branches.sh`), which +counts conditional jumps by reading these three kinds of line, breaks +loudly instead of silently. A test in raz holds the form against a +small program's listing. + +**Recommendation:** take; it is a paragraph of raz(1) and one test, +for a form that already doesn't change. +### Implementation limits, and a compiler for a small stack + +**Status.** To investigate; nothing decided. + +The report names no implementation limits: how deep expressions, +statements, imports and generic instances may nest, how long a name or +a string may be. A compiler for a small machine that rejects a deep +nesting is then arguably not a raz compiler at all. C settles it with +its translation limits (C99 §5.2.4.1: 63 levels of nested parentheses, +15 of nested includes, and so on): every compiler must take at least +that much, and may take more. The proposal: a short section in the +report giving the least each compiler must accept, and saying that a +compiler that goes past its own limit stops with an error naming it, +never a crash. It changes the report, not the language. + +Behind it, three things in this compiler that need no change to the +report at all, so that it runs in a small stack: + +1. **Nesting.** Each level of a nested expression costs about 1 KiB + of stack. A constant expression with 64 nested parentheses fails a + 64 KiB stack and passes 256 KiB; 256 of them fail 256 KiB and pass + 1 MiB. A limit from the section above, checked in the parser, makes + the stack a program needs bounded and known. +2. **Imports.** `importModule` compiles an imported module in the + middle of the one importing it, on the same stack, so the stack + grows with the depth of the chain of imports. Ordering the modules + first and compiling them from the leaves, in a loop, keeps whole + program compilation and a stack that doesn't grow; symbol files, as + Wirth's compilers have, would do it too, but must then carry a + generic module's body. +3. **Instances.** `makeInstance` keeps the declaration under way aside + in arrays on the stack (`[MaxFwd]PType`, `[MaxFwd]Diag.Pos`, + `[MaxNames]INT`, several KiB) for every instance it nests. A list + of instances still to make, made between declarations, would keep + none. + +Not yet measured: which of these filled the stack when the stripped +compiler, given one more `-I` directory, overflowed 64 KiB building +itself, where the ordinary self-build fit. + +Met in moss (`docs/raz-port.md`): its stored programs get a guarded +64 KiB stack, and a native compiler must fit, or the stack must grow +(2026-10-22). diff --git a/PROPOSALS.md b/PROPOSALS.md deleted file mode 100644 index 7d4bee9..0000000 --- a/PROPOSALS.md +++ /dev/null @@ -1,2986 +0,0 @@ -# raz: proposals - -What the language or the library might have, met while writing raz. -None is built while the freeze holds; each waits for a later thaw, by -the owner's word, and goes into the report before any code. - -**Closed to new proposals** (owner, 2026-10-23). Nothing new is added. -What is still open here, the safety thaw and the Moss work, is the -last; once it is done the language is in a hard freeze: the language -and the library's core change only to mend a defect, or the core to -plug a very big gap, and the rest of the library grows only -conservatively. - -## Installed source libraries and RAZ_PATH - -**Status.** Approved by the owner on 2026-10-19 and implemented after -this proposal was committed and pushed. This changes the compiler's -module search paths and documents an installation convention; it adds -no language syntax or package manager. - -A library should be usable by several programs without adding it as a -Git submodule to each. Install its source modules directly in -`$HOME/.raz/lib`, including any target-specific siblings. The compiler -searches that directory automatically. It does not search subdirectories -or create the directory itself. - -`RAZ_PATH` replaces that default with a colon-separated list of module -directories. An unset variable means `$HOME/.raz/lib`; an explicitly -empty value disables user library directories. Empty entries in a list -are ignored, rather than standing for the working directory. Relative -paths are relative to the compiler's working directory. The compiler -does not expand `~` or environment variables inside a path: the shell -can expand them when setting `RAZ_PATH`. If `HOME` is unset or empty, -there is no default user library directory. - -The search is the main module's directory, each `-I` directory, the user -library directories, and finally `lib/` beside the compiler. The standard -library is always searched, even with an empty `RAZ_PATH`. Existing -target suffixes, interface checks, duplicate-module errors and the -symbolic-link exception apply to the new directories too. `-I` does not -silently override an installed module. - -For example: - -```sh -mkdir -p "$HOME/.raz/lib" -install -m644 Json.raz "$HOME/.raz/lib/Json.raz" -raz Main.raz # import Json; needs no -I -export RAZ_PATH="$HOME/.raz/lib:$HOME/work/raz-libs" -RAZ_PATH= raz -I deps/json Main.raz # an isolated dependency selection -``` - -A library's build file may provide install and uninstall tasks for its -own source files. Robbie can run those tasks, as make or a shell can; -the convention belongs to raz and needs no special robbie feature. -Dependency versions and downloads remain the project's or user's choice. - -Document this in the report's module lookup, raz(1), the README and the -compiler guide. Test the unset and empty cases, lists of directories, -paths with spaces, target-specific files and interface checks, duplicate -modules and symbolic links, and use with both compilation and `raz run`. - -## What a call does with its arguments, written at the call - -**Status.** Not approved. Drafted 2026-10-16 and reviewed twice on -2026-10-17 (the second review's findings are under "Open questions", -at the end of part 1). The owner judged the feature, and its use, not -settled: no change is made for the marks at the call, `ret` or `keep`. -It was drafted as five parts. Three of them went into report -2026-10.33 on their own, without the marks: the library's parameters -by `var` (part 2), a `const` parameter (part 4), and a variant in a -constant (part 5). What is left are the two parts not approved, kept -by their numbers. Left out of the safety thaw by the owner on 2026-10-26 -(`PLAN.md` §2). - -1. **Marks at the call** (this section): an argument for a `var` - parameter is written `var x`, and one for a `keep` parameter - `keep x`. -3. **`ret` and `keep`** (below): a heading says what a procedure does - with what it is given, and the compiler holds the body to it. - -Nothing is built unless the owner starts it. The report changes first, -as always; the documentation listed below comes with it. - -### The problem: a call hides what it does - -A heading says whether a parameter is changed, kept or lent; the call -doesn't. This line of `src/Scan.raz` reads a character: - -``` -v := utf8(cur.pos); -``` - -It also moves `cur.pos` past it, since the heading is -`proc utf8(var pos: INT): INT`. Nothing at the call says so. Pascal -and Oberon leave it so; C#'s `ref`, Swift's `&` and Rust's `&mut` -write it at the call. - -`keep` would hide its promise in the same way. Here the map keeps the -name it is given, which must outlive the call; a reader of the call -can't tell: - -``` -_ := Names.put(table, name, 1); -``` - -Today `ADR` stands in for a mark, badly. `STANDARDS.md` says `ADR` at a -call means the callee keeps what it is given, but the library takes -`^T` where it keeps nothing, so `ADR` stands at nearly every call -(`Buf.add(ADR(b), c)`), and says nothing. - -### What a procedure does with what it is given - -| Heading | The procedure | At the call | Example | -|---|---|---|---| -| no mark | reads it while the call runs, then lets go | nothing | `Str.eq(a, b)` | -| `const x` | reads the caller's variable in place, without a copy, and doesn't change it | nothing | `Opt.number(p, 1, 9)` | -| `var x` | may change the caller's variable | `var x` | `Buf.add(var b, c)` | -| `keep x` | may store it where it outlives the call | `keep x` | `Names.put(var table, keep name, keep 1)` | -| `ret x` | its results may point into it | nothing | `s := Str.trim(line[0..n])` | -| `^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)))` | - -A slice given to an unmarked parameter is a value, two words, but the -elements it points at are the caller's: the procedure may write them, -and nothing at the call says so. `Sys.read(fd, line)` fills `line`, -`COPY(d, s)` fills `d`. A slice is a view of the caller's array, and -lending it is what it is for; the table says so in a note under it. - -`var` and `const` are in the language now (report 2026-10.33); `keep` -and `ret` would come with part 3. The table, and the note, go into the report (8), raz(7) -and the tutorial as they are here. - -### The rules - -1. **`var` at the call.** An argument for a `var` parameter is written - `var` and a variable: `var b`, `var p^`, `var a[i]`, `var r.f`. - Leaving the mark out is an error; so is writing it for a parameter - that isn't `var`. This holds for every call: of a procedure, of - another module's, of a procedure value, of a generic module's - instance. -2. **`keep` at the call.** An argument for a `keep` parameter is - written `keep` and the argument, whatever its type, as `var` is: - `Counts.put(var counts, keep 5, keep 7)`. The map does keep the 5. - Where the argument can't end, an `INT` or a literal, nothing is - checked, but the mark stands. So the mark follows the heading alone: - a generic module's body reads the same in every instance, as - `Bag(T)` calling `L.push(var l, keep x)` must, and a call never - hangs on fields of a record it can't see. -3. **Both.** An argument for a `keep var` parameter is written - `keep var x`, in the heading's order. -4. **`ret`** is never written at the call. It is about the result, - which the compiler checks where it is returned or stored (part 3); - and the calls it is on, `Str.trim`, `cut` and `field`, are the most - common ones. -5. **Built-in procedures** take no marks: `INC(v)`, `DEC(v)`, - `NEW(p, a)`, `COPY(d, s)`. They are the report's own words, and - their names say what they change. `extern` procedures have no `var` - or `keep` parameters, and so take none. -6. **What follows `keep`.** `keep` is a mark, not a name, when the - token after it is a name, a number, a string or character literal, - `{`, `[`, `var`, `-`, `not` or `~`: anything that starts an - argument and can't follow a name in one. Before `(`, `^`, `.`, `,`, - `)` or an operator between two operands it is the name `keep`: - `keep(x)`, `keep^`, `keep.f` and `keep + 1` are what they are today. - An argument that starts with `(` is written without it: `keep a + b`, - not `keep (a + b)`. `keep [` is the mark before an array literal or - the empty slice, `keep []`; an array literal lives in the frame - (part 3), so a kept one is an error unless it is a constant's. -7. **Procedure types** say `const`, `var` and `keep` as headings do - (5.9), so a call through a procedure value is marked as a call by - name. -8. **`const`** is never written at the call: the procedure neither - changes nor keeps what it is given. Its argument is any expression - of the parameter's type; a variable is passed in place, and anything - else in a temporary of the statement (report section 8). - -``` -Arguments = "(" [ Argument { "," Argument } ] ")" . -Argument = [ "keep" ] [ "var" ] Expr . -``` - -Each rule looks at the call and the heading only, so a one-pass -compiler makes them as it reads the call: perhaps 40 lines, beside the -250 to 400 of part 3 (400 to 600, by the second review). - -### Examples - -**Swapping**, from the tutorial (4): - -``` -proc swap(var a, b: INT); -var t: INT; -begin - t := a; a := b; b := t; -end; - -swap(var x, var y); -``` - -**A procedure that changes a place deep in a record**, from -`src/Scan.raz`: - -``` -v := utf8(var cur.pos); (* cur.pos moves past the character *) -bigMul(var num, 10, digit); (* num changed; 10 and digit read *) -bigSub(var num, d); (* num changed; d read *) -``` - -**A buffer.** `examples/Sh.raz`'s `readWord`, today: - -``` -Buf.init(ADR(b), ADR(arena.base)); -while (at < LEN(s)) and not special(s[at]) do - ... - | 39: Buf.add(ADR(b), s[at]); INC(at); - | '$': dollar(ADR(b)); - | else: Buf.add(ADR(b), s[at]); INC(at); - end; -end; -text := Buf.bytes(ADR(b)); -``` - -and after the thaw: - -``` -Buf.init(var b, ADR(arena.base)); (* b set up; the arena is an allocator: a pointer *) -while (at < LEN(s)) and not special(s[at]) do - ... - | 39: Buf.add(var b, s[at]); INC(at); - | '$': dollar(var b); - | else: Buf.add(var b, s[at]); INC(at); - end; -end; -text := Buf.bytes(b); (* only read: no mark *) -``` - -The marks are as many as the `ADR`s were, and shorter; now they are -true. `Buf.bytes(b)` has none, and the one pointer left, -`ADR(arena.base)`, stands out as what it is. - -**Passing on what the procedure was given.** A `var` parameter is a -variable, and is marked like any other: - -``` -proc dollar(var b: Buf.Buf); -begin - ... - Buf.str(var b, Sys.env(s[start..at])); -end; -``` - -**What the program holds by pointer** is given as `p^`: - -``` -proc emit(w: ^Writer; c: U8); -begin - Buf.add(var w^.out, c); -end; -``` - -**A map that keeps its keys:** - -``` -(* import Names := Map([]U8, INT, Str.hash, Str.eq); - table: Names.Map and heap: Heap's allocator, module variables *) -proc count(name: []U8); -var k: []U8; ok: BOOL; -begin - k, ok := Str.copy(heap, name); (* a copy, on the heap *) - if ok then _ := Names.put(var table, keep k, keep 1); end; - _ := Names.put(var table, keep "main", keep 1); (* a literal never ends *) -end; - -proc lookup(name: []U8): INT; -var n: INT; found: BOOL; -begin - n, found := Names.get(table, name); (* only read: no mark *) - ... -end; -``` - -**A map that keeps nothing that can end.** The marks stand, as the -heading says, though nothing is checked: - -``` -(* import Counts := Map(INT, INT, hashInt, eqInt) *) -_ := Counts.put(var counts, keep 5, keep 7); -``` - -**A generic module calling another.** One body serves every instance: - -``` -module Bag(T); -import Mem, L := List(T); -var l: L.List; - -proc add*(keep x: T); -begin - _ := L.push(var l, keep x); -end; -``` - -**A table a procedure keeps**, a constant (report section 4), as `Sh`'s is now: - -``` -const Rows: []Opt.Row = [ - Opt.usage("", "Sh [-c script | file]"), - Opt.option("", 'c', "command", "script", "run script, not standard input")]; -... -Opt.init(var p, keep "Sh", keep Rows); -while Opt.next(var p) do ... end; -secs := Opt.number(p, 1, 600); (* number only reads: const, no mark *) -``` - -Today's `Opt.init(ADR(p), "Sh", [...])`, with the literal in the call, -is an error once `init` is `keep table`: the literal lives in the -frame, and `keep` can't say "as long as `p`" (part 3, "False alarms"). - -**A large record only read**, by `const` (report section 8), as `tools/Pretty.raz` has it now: - -``` -proc is(const sc: Scanner; s: []U8): BOOL; (* Scan's *) - -if Scan.is(sc, "-") or Scan.is(sc, "+") then ... end; -if Scan.among(Scan.text(sc), binaryWords) then ... end; -``` - -Before 2026-10.33 each of these was `ADR(sc)`; by `var` each would say -`var sc`, and none changes it. - -**A list of names a procedure keeps, passed on.** The parameter is -`keep` in turn, so the promise travels up: - -``` -(* import Seen := List([]U8) *) -proc remember(var l: Seen.List; keep name: []U8); -begin - _ := Seen.push(var l, keep name); -end; - -remember(var seen, keep "start"); -``` - -**`keep var`: a reader that keeps a slice of the caller's buffer.** - -``` -proc start(var r: Reader; keep var page: [4096]U8); -begin - r.rest := page[0..0]; - r.page := page[0..LEN(page)]; -end; - -var page: [4096]U8; (* a module variable *) -... -start(var rd, keep var page); -``` - -**A procedure value.** - -``` -type Step = proc(var s: State): BOOL; - -proc run(step: Step; var s: State); -begin - while step(var s) do end; -end; -``` - -**What stays a pointer**, and so keeps `ADR`: - -``` -NEW(node, ADR(arena.base)); (* an allocator *) -t, err := Thread.spawn(work, ^U8(ADR(job))); (* kept by the thread *) -XNextEvent(dpy, ADR(ev)); (* C *) -p := Sys.mmap(size); (* bytes, not a variable *) -``` - -**A slice's elements, lent unmarked:** - -``` -n := Sys.read(fd, line); (* fills line[0..n] *) -Str.lower(word); (* writes word's bytes *) -``` - -**`ret`, unmarked:** - -``` -s := Str.trim(line[0..n]); (* s points into line *) -key, rest, ok := Str.cut(s, "="); (* both point into s *) -``` - -### What the compiler says - -Each message names the mending, at the argument: - -``` -Sh.raz:94:21: b: write `var b`: Buf.add may change it -Sh.raz:115:23: b: Buf.bytes only reads it: no `var` -Count.raz:12:27: name: write `keep name`: Names.put keeps it -Count.raz:14:34: 7: write `keep 7`: Counts.put keeps it -Count.raz:9:27: key[0..4]: kept by Names.put, but it points into this procedure's frame -Sh.raz:60:28: [...]: kept by Opt.init, but an array literal lives in this procedure's frame: make it a constant -Pretty.raz:123:19: sc: Scan.is only reads it (const): no `var` -``` - -The compiler already says, since 2026-10.33, that a `const` parameter -can't be changed, and what to write for `ADR(b)` or `p` given to a -`var` or `const` parameter. - -### How much noise - -Measured by a search of `src/`, `lib/`, `tools/` and `examples/`, about -23,300 lines of code (rough: a search, not the compiler): - -- about 630 `ADR`s, before 2026-10.33; most were at calls to the - library, which now take `x` itself, and would take `var x`; -- about 580 calls of our own procedures with `var` parameters, unmarked - today: each gains `var`, about one line in 40; -- `keep`: a few dozen calls (`Map.put`, `List.push`, `Vec.push`, - `Opt.init`, `Opt.scope`, and procedures that pass a kept value on). - Since it follows the heading, it stands also before values that can't - end, `keep 1` in `Names.put(var table, keep name, keep 1)`: a word - each, the price of one rule for every instance; -- `const`: none at the call. - -So most of the marks stand where an `ADR` stands today. What is new is -the 580, and those are the calls, like `utf8(cur.pos)`, that change a -variable with nothing to say so. - -### `ADR` afterwards - -`ADR` stays, for the pointers `STANDARDS.md` lists: an allocator, what -may be `nil`, what the program holds by pointer already, C and memory -that is bytes, and a pointer a procedure keeps (`Thread.spawn`'s `arg`). -The marks of part 3 don't follow a pointer, so `ADR` at a call still -says "kept, or not a variable", unchecked, as now; with the library on -`var`, it is rare enough in ordinary code to be read so. - -### What the documentation gains - -The thaw is not done until each of these is: - -- **The report, `doc/raz.md`.** 8: the grammar above; "Parameters" - becomes "Parameters and arguments", with the table and its note on - slices, rules 1 to 8, and the swap and map examples; `keep` and - `ret` from part 3. 5.9: procedure types with marks. 7.3: `ret`. 10: the promise, whose - exceptions shrink to `ADR`, C, code procedures and `check off`. - 1, "A first look": its example marks its calls. Every example in the - report is marked. About two pages; the report stays under 40 (31 - now), counted by `make pdf`. -- **`doc/report-history.md`**: the version's entry, with the mending: - `ADR(x)` to `var x`, `p` to `var p^`, `var` and `keep` at each call - the compiler names. -- **raz(7)**, the language at a glance: under PROCEDURES, the table, as - a list, and one line for each of `var`, `keep` and `ret` at the call; - THE GRAMMAR IN BRIEF gains `Argument`; BUILT-IN PROCEDURES says they - take no marks. -- **The tutorial, raz-tutorial(7).** Section 4 marks `swap(var x, var y)` - and says why. A new section after 6, "WHAT A CALL DOES WITH ITS - ARGUMENTS": the table; a whole program, with its output, that counts - the words of its input in a `Map([]U8, INT)` with a `Buf`, using - `var`, `keep`, `ret` and `const`, each said in a sentence where it - stands; - then "What the compiler stops", the four mistakes of the messages - above, each with its message. Section 16, "FROM PASCAL AND C TO RAZ", - gains: Pascal's `var` is unmarked at the call, raz's is marked, as C#'s - `ref` is; C's `&x` becomes `var x` when the callee only changes it, - and stays `ADR(x)` when it keeps it. Every other example in the - tutorial is marked. Each runs under `make check`, as now. -- **Volume 2, `doc/raz-lib.md`, and raz-lib(3)**: each module's - example marked, and `keep` and `ret` where the library has them. -- **`STANDARDS.md`**: `ADR` no longer marks what is kept, `keep` does. -- **`doc/compiler.md`**: where the marks are read and checked, the - checks of part 3 and the set each value carries, with the code - before and after, and the table of lines. -- **`README.md`**: its examples marked. -- **Tests.** `conform/`: a program for each rule, run and error; - `test/err` and `test/msg`: each message above; `test/pretty`: the - marks formatted; the vim and emacs support indent and colour `var` - and `keep` at a call. -- **`sbcl/`**, the reference compiler from the report alone, follows - the report. - -### What it breaks, and the order of the work - -Every call to a procedure with a `var` or `keep` parameter: in `src/`, `lib/`, the -tools, the examples, the tests, and rmacs, ravite, rat, rlX11, rloc, -rpg and rsqlite, each when it moves its pin. The mending is mechanical, -and the compiler names it at each place. - -**BOOT first.** The release `BOOT` names can't read a marked call, and -it builds `src/` and reads `Sys` and `CAbi`. So this thaw needs a -release that reads the marks, named by `BOOT` (CLAUDE.md, "The compiler -and BOOT"), before `src/` and that part of the library can be marked: -the owner's call, and the first step. - -Then, one commit each: - -1. The report, `report-history.md`, raz(7): for review. -2. The compiler reads the marks and checks rules 1 to 8, and every - caller in this repository is marked. -3. `ret` and `keep` in headings and their checks (part 3), and the - library marked (`Str.trim`, `Map.put`, `List.push`, `Vec.push`, - `Opt.init`, `Opt.scope`, ...). -4. The tutorial, volume 2, raz-lib(3), `STANDARDS.md`, - `doc/compiler.md`, `README.md`. -5. The tests: `conform/`, `test/err`, `test/msg`, `test/pretty`, the - editors. - -The examples of parts 2 and 3 are written as the whole thaw makes -them, with the marks of part 1. - -### Open questions - -The second review, 2026-10-17, read the five parts against `src/`, -`lib/Opt.raz`, `tools/Pretty.raz` and `examples/Words.raz`. It found -the direction sound, and parts 1, 2 and 4 clearly better in `tools/` -and `Opt`, but mostly noise in `src/Parse.raz`, where `var x` stands -on nearly every call. Left open, by the owner's word: - -1. **BOOT.** A release of today's compiler can't read the marks - either, so "BOOT first" can't work as written: it takes two - releases, one that accepts every new form without requiring it, - named by `BOOT`, then one that marks `src/` and requires the marks. -2. **An error here.** Part 3's `Names.put(var table, keep buf[0..n], 1)` - lacks `keep 1`. (The others the review found were in parts 2, 4 - and 5, mended when they went into the report.) -3. **A hole in part 3's exception for `var`.** `proc fill(var r: R); - begin r.s := r.buf[0..4]; end;` passes, since `r` points where it - pointed; a caller's local `r` copied to a module variable then - points into a dead frame. Mend: the caller's variable and what its - slices point at as two places, the exception covering the second. -4. **Part 3's cost.** A local points wherever anything assigned to it - does, which needs a closure over local-to-local assignments at - `end` (`w, rest := Str.field(rest)`), and bits for locals, value - parameters and `match`'s names: 400 to 600 lines, not 250 to 400. -5. **Rule 6.** Its list contradicts itself: `keep - 1` and `keep[i]` - are expressions today, and `Sys.closeAllBut(keep: []INT)` indexes - `keep[i]`; `keep ^U8(p)` can't be marked. Proposed: decide by the - heading, which is known when the argument is read: at a `keep` - parameter a leading `keep` is the mark; elsewhere a name. -6. **`keep` before what can't end is noise**: `keep 5`, `keep "Sh"`, - and `keep k + 1`, which reads as `(keep k) + 1`. Proposed: optional - before a constant or a basic or pointer type, required where the - type carries a slice or is another module's record. It partly undoes - rule 2's "the heading alone": one rule and some noise, or less noise - and an exception. -7. **A mark that lends nothing in a plain heading**, `keep n: INT`, - costs every call a word. Proposed: a warning, but on a module - parameter's type or a procedure with a body for each target. -8. **`ret` with `const`.** `ret const` given a temporary that holds an - array would return a slice of the temporary: an error. The heading's - grammar, `Params = ["ret"] ["keep"] ["var" | "const"] ident ...`, - and the call's, a designator after `var`. (The rest of `const`'s - rules are report 2026-10.33's, section 8.) -9. **Procedure types** with fewer marks are assignable, not the same: - 5.10 must say so, for `=`, generic instances and `forward`. - `Map`'s `eq` can't take a `const` equality. -10. **False alarms to document.** A local container over a local - buffer, `Scan.init(var s, keep line[0..n])`, is refused though both - end together (a module variable, a `Buf` or the heap is the way - out); so is a store through `ADR` of a local. - -### Part 3: marking what a procedure does with what it is given: `ret` and `keep` - -#### The hole - -A procedure's locals, its value parameters and the array literals it -passes as slices live in its frame, which is gone once it returns. A -slice that still points there afterwards reads whatever the next call -put in its place, and writes into it. Section 7.3 catches the plain -case, a slice of a local returned at once: - -``` -proc short(h: Hex): []U8; (* Hex = [64]U8 *) -begin - return h[0..8]; (* an error: h is the procedure's own copy *) -end; -``` - -It can't catch the same slice once it has passed through a call, -since the caller can't see what the callee returns a slice of: - -``` -proc head(var h: Hex): []U8; -begin - return h[0..8]; (* fine: h is the caller's *) -end; - -proc short: []U8; -var h: Hex; -begin - return head(h); (* a slice of short's frame; not caught *) -end; -``` - -Nor the other way, a slice given to a procedure that keeps it: - -``` -proc remember(name: []U8); -var buf: [16]U8; -begin - ... - _ := Names.put(var table, keep buf[0..n], 1); (* the map, on the heap, keeps a slice of buf *) -end; -``` - -Section 10 leaves both undefined. The marks close them: each parameter -says what the procedure may do with what it is given, the compiler -holds the procedure's body to its heading, and a caller trusts the -heading without seeing the body. Each check needs only the procedure -it is in, so a one-pass compiler can make it. - -#### Words - -**Carrying a slice.** A type carries a slice if it is a slice, or an -array, record or variant with one in it: `[]U8`, `[4][]U8`, -`Sys.Program`, `Fmt.Arg`. `INT`, `[64]U8` and every pointer type don't. -What a pointer points at is not followed: a slice reached through a -pointer, `p^.s`, is the heap's or a module's, as far as the marks -know. - -**Where a value points.** Every value that carries a slice has, for -the compiler, a set of places its slices may point into: - -- **the frame**, this call's own: a slice of a local array, of a - value parameter's array, or an array literal used as a slice; -- **a parameter `p`**: what `p` lends. For a value parameter, that is - what its slices point at, which is the caller's business, not this - frame. For a `var` or `const` parameter whose type holds an array, - it is also the caller's variable itself: `h[0..8]` of `var h: Hex` - points into `h`. One whose type holds no array, as a `Scanner`, lends - only what its slices point at, as a value parameter does, so - `return Scan.text(n)` of a local `n: Scanner` is not frame-bound - when `n.src` isn't. -- **nowhere that ends**: module variables, constants, string literals, - and anything reached through a pointer. - -A value made from others points wherever any of them does: a slice, a -field, an element or a view of `x` points where `x` does; a record, a -variant or an array literal built from parts, wherever the parts do; a -call's result, wherever its arguments for `ret` parameters do (below). -A local variable that carries a slice points wherever anything -assigned to it anywhere in the procedure does, wherever the assignment -stands, since a loop can run a `return` after an assignment written -below it. **Frame-bound** means pointing into the frame. - -**Outliving the call.** A place outlives the call if it is a module -variable, anything reached through a pointer (`p^.f`, `p^[i]`), or a -`var` parameter of this procedure. A value stored there, or returned, -leaves the frame. - -#### No mark - -A parameter without a mark is only used while the call runs. The -procedure may read it, copy its bytes (`COPY`, `Buf.str`), keep it in -locals and pass it to other calls' unmarked or `ret` parameters. It -may not return what it points at, nor store it anywhere that outlives -the call. This is what most procedures do: `Str.eq`, `Str.find`, -`Buf.str`, `Sys.write`, `Fmt.print`, `Map.get`'s key. - -#### `ret` - -``` -proc trim(ret s: []U8): []U8; -``` - -`ret s` says: the results may point where `s` points. In the body, -returning a slice of `s` is allowed; in the caller, the result points -wherever the argument given for `s` did. - -``` -proc greet: []U8; -var line: [80]U8; n: INT; -begin - n := Sys.read(Sys.stdin, line); - Out.str(Str.trim(line[0..n])); (* fine: used here, in the frame *) - return Str.trim(line[0..n]); (* an error: frame-bound through trim's ret *) -end; - -proc word(ret s: []U8): []U8; -begin - return Str.trim(s); (* fine: points where s does, and s is ret *) -end; - -proc word2(s: []U8): []U8; -begin - return Str.trim(s); (* an error: s isn't ret here *) -end; -``` - -`ret` lends something when the parameter carries a slice, or is a -`var` or `const` parameter whose type holds an array (it lends the -caller's variable), of a procedure with a result that carries a slice. -Elsewhere, `ret n: INT`, `ret a: [4]U8` or on a procedure whose results -carry no slice, it lends nothing, and is allowed: a mark is leave to -do something, not a claim that it is done. Two cases need that. A -generic module's parameter may be any type, and a procedure with two -bodies, one for each target, has one heading: `Sys.nextEntry`'s `Dir` -holds the entry's bytes in an array on Linux, where `ret` lends them, -and a C pointer over C, where it lends nothing. - -With several results, `ret` covers them all: in `cut(ret s: []U8; -sep: []U8): ([]U8, []U8, BOOL)` both slices may point into `s`. With -several `ret` parameters, a result may point where any of them does, -and the caller takes the result as pointing where all of their -arguments do. - -#### `keep` - -``` -proc put(var m: Map; keep k: K; keep v: V): BOOL; -``` - -`keep k` says: what `k` points at may outlive the call; the procedure -may store it in a place that does. In the caller, an argument for a -`keep` parameter leaves the frame as a store would: it must not be -frame-bound, and if it points where one of the caller's own -parameters does, that parameter must be `keep` too. - -``` -(* import Names := Map([]U8, INT, Str.hash, Str.eq); - table: Names.Map and heap: Heap's allocator, module variables *) -proc count(name: []U8); -var key: [32]U8; k: []U8; ok: BOOL; -begin - _ := Names.put(var table, keep name, keep 1); (* an error: name isn't keep here *) - _ := Names.put(var table, keep key[0..4], keep 1); (* an error: frame-bound to a keep *) - _ := Names.put(var table, keep "main", keep 1); (* fine: a literal never ends *) - k, ok := Str.copy(heap, name); - if ok then _ := Names.put(var table, keep k, keep 1); end; (* fine: copied to the heap *) -end; -``` - -`keep` lends something on a parameter that carries a slice, or a -`var` parameter whose type holds an array; on another, `keep n: INT`, -it lends nothing and is allowed, as `ret` is. At the call it is -written all the same (part 1, rule 2). - -One exception keeps the common loop free of marks: a `var` parameter -may be given a value that points only where it already pointed, so -`s := s[1..LEN(s)]` with `var s: []U8` needs no `keep`. The caller's -variable is no worse off. - -#### Both, and the order - -`ret keep v: T` is both. The marks come before `var`, and each -mark covers the group it starts, so `(ret s, t: []U8)` marks both; -`(ret s: []U8; sep: []U8)` marks only `s`. `ret` and `keep` are not -reserved words: they are marks only before a parameter's name, as -`static` is a mark only in `link static;`. `proc f(ret: INT)` is a -parameter named `ret`. - -#### What the compiler checks, all of it - -In each procedure: - -1. `return e`, each result: `e` must not be frame-bound, and every - parameter it points at must be `ret`. -2. A store into a place that outlives the call, `M.x := e`, - `p^.f := e`, or `v := e` for a `var` parameter `v` or a part of it - (`v.f := e`, `v[i] := e`): `e` must not be - frame-bound, and every parameter it points at must be `keep`, but - for the exception above. `COPY` into such a place is no such store: - it copies bytes, not where they point. -3. An argument for a call's `keep` parameter, as 2. - -Checks 1 to 3 on a local variable's value wait for the procedure's -`end`, when everything assigned to it is known. - -#### Procedure values, generic modules, and the rest - -**Procedure types** carry the marks, `proc(ret s: []U8): []U8`. A -procedure with fewer `ret` and `keep` marks than a procedure type may -stand where that type is wanted, since it does less than the type -allows: a procedure without `ret` can stand where `ret` was allowed, -not the other way. `const` and `var` must match, as `var` must now -(5.9): they change how the argument is passed. - -**Generic modules.** A mark is allowed on a parameter whose type is a -module parameter, `keep v: T`, whatever `T` will be. The body is -checked in each instance: `Map(INT, INT)`'s `put` would pass without -`keep`, `Map([]U8, INT)`'s wouldn't, so the library marks its generic -modules for the instance that needs it. Calls write the marks the -heading has, in every instance (part 1, rule 2). - -**`extern` procedures** take no marks: C is outside the promise of -section 10 already. **Code procedures** take them, and are trusted: -there is no body to check. - -**`ADR`** gives a pointer, which the marks don't follow; a pointer to -a local that outlives it stays undefined, as section 10 says. So does -a slice reached through such a pointer, and a thread given a pointer -to its spawner's locals. - -#### False alarms - -The rules are sure, not exact: they reject some programs that were -right. - -- **A record that lives in the frame, filled through a pointer.** - `examples/Sh.raz` does - - ``` - Opt.init(var p, keep "Sh", keep [Opt.usage(...), Opt.option(...)]); - ``` - - `Opt.init` keeps its table in `p`, so it needs `keep table`, and - the array literal is frame-bound: an error, though `p` is a local - and dies with the literal. `keep` can't say "as long as `p`"; - saying that needs lifetimes on records, Rust's whole apparatus, which - is not proposed. The way out: the table a constant, which report - 2026-10.33 allows, as part 1's example shows. -- **A local variable used twice.** One slice variable that holds a - slice of a local buffer early on and a result to return later is - frame-bound throughout. Two variables cure it. -- **Several `ret` parameters.** A result is taken to point at all of - them, though it may point at one. - -#### What it breaks - -Every procedure, in the library or a program, that returns or keeps -what a parameter points at stops compiling until it is marked: a -thaw. In the library, by a search of the headings: `Str.trim`, -`trimLeft`, `trimRight`, `cut` and `field` (`ret`); `Map.put`, -`List.push`, `Vec.push` and `Vec.tryPush` (`keep`: they store a `T`); -`Opt.init` (`keep name` and `keep table`) and `Opt.scope` (`keep -name`), and `Sh`'s call of `init`, as above; `Sys.nextEntry` (`ret`, -lending on Linux only). Not marked: `Str.copy` (its result is the allocator's), -`Sys.env` and `readLink` (their own buffer), `Buf.str` and -`Fmt.write` (they copy), `Map.get`. In sauce, `Svec.push` and `add` -(`keep`), and what returns a slice of its argument. - -#### What it costs - -Reports: 5.9 (procedure types), 7.3, 8 (parameters), 10 (the promise, -whose exceptions shrink to `ADR`, C, code procedures and `check -off`), appendix B. The compiler: a set of the places a value points -into, carried with each value as its type is, a 64-bit set (the frame -and up to 63 parameters); the same on each local; the checks above, -and a list per procedure of the checks that wait for its `end`. -Perhaps 250 to 400 lines; no cost at run time, and little at compile -time. - -Precedent: D's `scope` and `return scope` (DIP1000) are `keep`'s -opposite and `ret`; Rust's lifetime elision reads a call's result as -`ret` does. D's experience is that the corners (fields, generics, -procedure values) take years; the narrow form here leaves record -lifetimes out, and so the first false alarm above, on purpose. - -## A minus sign after an operator - -**Status.** Not planned (owner, 2026-10-23): dropped for good; `x & (-8)` or `x & ~7` stays the spelling. - -`x & -8` and `n * -1` are errors: a unary minus belongs to the start -of a `SimpleExpr` (6), not to a factor, so after an operator it needs -parentheses, `x & (-8)`, or another spelling, `x & ~7`. This is the -report's grammar, Oberon's, and the compiler is right to refuse it; -but nearly every other language takes it, and the error ("expected an -expression, found -") surprises. - -The proposal: a factor that follows an operator may be `"-" Factor`. -The minus at the start of a `SimpleExpr` stays as it is, applying to -the first term, so no program changes meaning: `-a & b` is still -`-(a & b)`, which isn't `(-a) & b`, nor is `-a shr n` the same as -`(-a) shr n`. Only text that is an error today, `x & -8`, gets one. -The cost is that a minus means two things by where it stands, which -the report would say in a line. - -Met in tery's `aligned`, `(a + 7) & -8`. - -## Dividing 128 bits by 64 - -**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. - -`Math.mul` gives the 128-bit product of two `U64`s; there is nothing -to divide such a number back down. Forth's `UM/MOD` and `M*/`, and -any arithmetic on numbers wider than a word (a bignum, a fixed-point -product scaled back), need "this 128-bit number, given as its high -and low words, divided by a 64-bit one: the quotient and the -remainder". x86-64 does it in one instruction, `div`; a raz program -does it by a loop of 64 shifts and subtractions, or a code procedure -per target. - -The proposal, in the library: - -``` -proc div*(hi, lo, d: U64): (U64, U64); (* hi, lo divided by d: the quotient and the remainder; hi < d *) -``` - -in `Math`, beside `mul`; `hi >= d`, whose quotient doesn't fit a word, -and `d = 0` stop the program as a division by zero does. It breaks no -program, so it could come with any release, not only a thaw. - -Met in tery's `udivmod`, a loop of 64 rounds. - -## Inlining a procedure that only returns - -**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). - -Not the language's but the compiler's: a call of a procedure whose -body is `return` and an expression, as `Grep.zeros` and -`Scan.tokPos` are, made in place of the call. One pass keeps no -tree to copy, but it can read source again, as `while` reads its -condition again (`saveScan`, `restoreScan`): the arguments go to -temporaries, each evaluated once and in order, a scope names the -parameters as them, and the expression is read again from where the -procedure's begins, in its own module's scope. - -Measured by hand on the kernels: Grep with `zeros` and `lowest` -written in place is 20% faster, 0.88 times FPC `-O2`'s time where it -is 1.14 now. The compiler has 78 such procedures and the library 28; -the compiler's profile names the calls of small routines as what is -left (doc/compiler.md). - -Kept narrow: scalars passed by value, no recursion, no code -procedure (a square root has its own way), a procedure taken as a -value still called. What it costs: an inlined procedure is not in -the trap report's list of procedures, nor in gdb's backtrace, though -a failed check in it is still told at its line; 60 to 100 lines of -the budget; and, across modules, the imported module's -text kept to be read again, which is to be checked. - -More cases, from sauce (`~/r/sauce`, RAZ-NOTES.md). Its SHA-256, with -the rotation a procedure, `return (x shr n) | (x shl (32 - n))`, and -each word read by `Str.be`, ran at 52 MB/s; with both written out in -the loop, 115 MB/s, where FPC `-O2` does about 200 and `check off` -adds only 9%. Most of the gap is calls. `ror` is the narrow case -above; `Str.be` is not, a loop over its bytes, and would want a -`Str.be32` of four bytes that only returns, or the loop unrolled where -it is. A rotate of the language's own, an operator or a built-in -procedure, would serve SHA, the other hashes and checksums without -any inlining, but it is a language change, for a thaw. **Taken into -the report (2026-10.35):** the built-ins `ROL(x, n)` and `ROR(x, n)`, -by the owner's word; the compiler has them. rcrypto met the -same (its `RAZ-NOTES.md`): SHA-256 at 32 MB/s with `ror` a procedure, -80 with it written out. On 100 MB of -new files `sauce commit` takes 1.2 s against the Pascal sauce's 0.7, -and `verify` 0.95 s against 0.48: the hashing. - -## Less that is undefined - -**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`. - -Section 10 lists what isn't defined: a stale or made-up pointer, -indexing through a pointer, a slice kept after its frame is gone, a -slice of an array a call returned kept past its statement, an index -out of range under `check off;`, writing a string's bytes, a code -procedure that breaks its rules, and C. Some of these can be closed at -little cost; the rest can be fenced, so that a reader sees which -modules can reach memory they shouldn't. Four pieces, each standing on -its own, the cheapest first. - -**1. An array a call returns lives to the end of its procedure.** -Section 8 says it lives to the end of its statement. Its slot in the -frame would stay reserved for the rest of the procedure instead, as a -deferred statement's slots already do, so that `s := f('a')[0..4]` is -defined until the procedure returns; in a loop the slot holds the -latest call's array. Section 10 loses a case, and what is left of it -is a slice leaving its frame (7.3), which `ret` and `keep`, above, -would close. It breaks nothing; the cost is a frame larger by each -such call's array. - -**2. Writing a string's bytes stops the program, or changes them.** -Two outcomes instead of any: where the target has read-only memory, -the string constants are in it, and a write stops the program as a -bad address (section 10), as this compiler's already does, since they -are in rodata; where it hasn't, the write changes the constant for the -rest of the run, everywhere its bytes are shared. Which of the two is -the target's (appendix A). It breaks nothing. - -**3. A race tears no slice.** 7.6 says a variable written by one -thread while another reads it holds a value it had, or a mixture of -their bytes, and that nothing else becomes undefined. For a slice -that is a defect: a mixture of one slice's address and another's -length is indexed, checked, against the wrong length, and reaches any -memory; a variant's tag torn from its fields is the same. The mend: -a slice, a variant, or a record holding either, read or written in a -race, is the exception of section 10, said so in 7.6. A pointer, a -word on every target, tears into nothing new. This is a defect, which -the freeze allows mending. - -**4. Fencing the rest: `unsafe;`.** A module that does any of the -following says `unsafe;` after its links and its `check` line, and it -is an error to do them in one that doesn't: - -- `ADR`, and `p + i`, `p - i`, `p[i]` and `p[lo..hi]` on a pointer; -- converting an integer to a pointer or a procedure, or one pointer - or procedure type to another; -- a view, `v.(T)`, whose `T` holds a pointer, a slice or a procedure - (one to integers, reals and their arrays stays safe); -- `check off;`, `extern`, `link`, code procedures and `SYSCALL`. - -`unsafe`, like `static` in `link static;`, is a word only there. In a -program none of whose modules says it, what is left undefined is -short: a pointer used after `Heap.free` or an arena's reset gave back -what it points at, and a slice leaving its frame (7.3). The library's -modules that need it (`Rt`, `Mem`, `Heap`, `Arena`, `Bytes`, `Sys`, -`Thread`, ...) say it, as a program trusts them; `grep unsafe` lists -the rest. It breaks every module that does one of these and doesn't -say it: rmacs, ravite, the tools and ten of `src/`'s modules (by -`ADR`), each mended by one line, which -the compiler's message names. The compiler's cost is a flag on the -module, checked at each of those places. Since BOOT's release doesn't -know `unsafe;`, `src/` can't say it until `BOOT` names one that does: -for one release a missing `unsafe;` is a warning, then an error. - -Pieces 1 and 2 are small and change no program; 3 is a mend; 4 needs -a thaw. - -## Windows - -**Status.** Not planned (owner, 2026-10-23). - -A Windows target would keep volume 2 as it is: it describes the -library on a Unix target. Windows has no stable system calls, no -signals, no fork, no termios, and fds that are handles, so its `Sys` -can't be the one volume 2 gives. Appendix A's core already lets a -target leave out all of `Sys` past writing, ending the program and -getting memory: a Windows target gives the core, and what else it has -in a module of its own (`Win`), told on a page of its own beside -volume 2. Volume 1 needs at most a sentence, that `link static;` -means no C library where there are no system calls to make. The -compiler needs a PE writer and Microsoft's calling convention. - -## An enumeration's name read against the type it is given to - -**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. - -Two enumerations of a scope may share a name, and then the name alone -is an error: "the type is never taken from where the name stands" -(5.7). So a table of records, which names its enumerations on every -row, must write the type out on each row where the name is shared, -though the field says which enumeration it is: - -``` -type - MenuAction = (close, run, complete); - BlockKind = (time, run, window); - MenuKey = record sym: INT; act: MenuAction; end; - Block = record kind: BlockKind; arg: []U8; end; -const - MenuKeys: []MenuKey = [{sym: 13, act: run}]; (* an error: MenuAction.run or BlockKind.run *) - Blocks: []Block = [{kind: run, arg: "date"}]; (* and so is this *) -``` - -Adding `BlockKind`, with its `run`, broke `MenuKeys`, which had -compiled until then: a name added to one table reaches into the other. - -The proposal: where a value is given to a place whose type is an -enumeration, a name of that enumeration written alone is that name, -though another enumeration of the scope has it too. The places are the -right side of an assignment, a field of a record or variant written -with braces, a value parameter, a `return`, and the other side of a -relation with a value of the type. Everywhere else, and wherever the -rule of 5.7 names something already (a constant, a variable or a -procedure of the scope that isn't an enumeration's name), it stays as -it is. A program that compiles today means the same; only some of the -programs refused today compile, so it breaks none. - -It costs a line of 5.7, and in the compiler, a type passed down to the -lookup of a name where the parser knows it. - -Met in mosaico's `Mconfig`, where `MenuAction.run` and a status block's -kind `run` met; the block's kind was renamed `command`. - -## A slice that can't be written: `[]const T` - -**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`. - -raz has no slice whose elements can't be written. A `const` parameter -(report 2026-10.33, section 8) is shallow: the procedure can't change -the record, but it can write through a slice in it, and through a -slice it makes of an array in it. A constant's slices, and every -string literal, point at bytes whose writing "isn't defined" (5.10, -10): the compiler doesn't refuse it, and on a target with read-only -memory the program stops. Nothing in a heading says that `Str.eq` -only reads its slices and `Str.lower` writes them. - -``` -type Rule = record class: []U8; tag: INT; end; -const Rules: [2]Rule = [{class: "firefox", tag: 2}, {class: "mpv"}]; - -proc shout(const r: Rule); -begin - r.class[0] := 'F'; (* allowed today: writes the constant's bytes, undefined *) -end; -``` - -The proposal: a slice type may say its elements are read only, -`[]const T`, as a pointer type says `^VOLATILE T`. - -- Its elements can be read and sliced, and not written: no `s[i] :=`, - no `COPY` into it, no `var` argument or `ADR` of an element, no - `INC` of one. A slice of it is `[]const T` too. -- A `[]T` goes where a `[]const T` is wanted, as `U8` widens to `INT`; - never the other way. A procedure that only reads a slice takes - `[]const T`, and every caller's `[]T` still fits it: `Str.eq(a, b: - []const U8)`, `Sys.write(fd: INT; s: []const U8)`, `Out.str`. Those - changes break no program. -- A record field may be `[]const U8`, so a record, a constant's above - all, can hold slices that can't be written: `type Rule = record - class: []const U8; ... end`, and `shout` above is refused. - -What a procedure returns of its argument is the hard part. `Str.trim(s: -[]const U8): []const U8` would hand a caller with a `[]U8` back a -slice it can't write, and break the caller that does. Either such -procedures keep `[]U8` until `ret` (above) can say "of the same kind -as the argument", or they come in pairs. This is where D's `inout` and -C++'s `const` overloads went; neither is small. - -A second step, for a thaw: a string literal and a constant's slices -are `[]const U8` and `[]const T`, so that writing them is an error, -not undefined, and section 10 loses a case. It breaks every program -that keeps a literal in a `[]U8` variable or field, which is most of -them, `Opt`'s rows included; each is mended by writing `[]const U8` -where nothing writes the bytes. - -Precedent: C's `const char *`; D's `const(T)[]`; Rust's `&[T]` and -`&mut [T]`; ulam, the other language here, makes `[]T` read only and -writes `[]var T` for one that may be written, which is the safer -default but breaks every raz program. - -Costs: the report, 5.3, 5.10 and 10, and 8 for `const` parameters, -which could then read their slices as `[]const`, making `const` deep -for slices; the compiler, a flag on a slice type, as `vol` is on a -pointer, checked where an element is written, about 60 to 100 lines; -the library, its read-only slice parameters, a long list but each -change one word. - -Met in the discussion of `const` parameters (2026-10-17): "If a const -can still be written, what's the point?", and "Can records have -constant slices?" - -## For a kernel: three changes to the compiler - -**Status.** Done in v0.21.0 (2026-10-17), all three: `raz -base`, `raz -bare`, and the privileged instructions. - -Not the language's but this compiler's, kept together since they serve -one end: a raz program run on the bare machine, a unikernel, with no -operating system under it. None is needed for one: a kernel can be -made today, with a boot stub of its own that enters long mode, `db` -for the instructions the assembler lacks, and either a library of its -own beside a copy of `raz` (the library is read from beside the -compiler) or a handler for `syscall` that does what `Rt` and `Sys` ask -of Linux. Each piece below takes away one of those work-arounds, and -stands on its own. - -**1. A load address chosen at the command line.** Done (2026-10-17): -`raz -base ADDR`, a multiple of the page, the program wholly in the low -or the top 2 GB (`doc/compiler.md`, the linker). - -**2. A program with no `Rt` body.** Done (2026-10-17): `raz -bare` -reads no `argc` and `argv`, runs no body of `Rt` and gives it no -profiler. It still gives `Rt` the places, by stores alone, so that a -failed check says where it was, which the proposal had left out as -`-s` does (`doc/compiler.md`, the command line). - -**3. The privileged instructions in the assembler.** Done (2026-10-17): -`cli`, `sti`, `iretq`, `swapgs`, `lgdt`, `lidt`, `ltr`, `invlpg`, -`mov` to and from the control registers, `rdmsr`, `wrmsr`, `in`, `out`, -`wbinvd`, `xsave` and `xrstor` (`doc/compiler.md`, the assembler). - -What is still left to a kernel's own code, with all three: zeroing -the bss and a stack aligned to 16 bytes before `_start`, as Linux -gives; the boot stub, since no common loader enters an ELF64 file in long mode but -Firecracker (GRUB's Multiboot2 and QEMU's PVH enter in 32-bit mode, -and the assembler makes only 64-bit code); interrupt stubs that save -the XMM registers, since the compiler's code uses them; and, if the -compiler's code ever writes below `rsp`, which isn't yet checked, an -IST stack for each interrupt. - -Met in the question "how difficult to create a simple amd64 unikernel -in raz?" (2026-10-17). - -## `Sys.setsid`: a session of a process's own - -**Status.** Approved by the owner on 2026-10-23 and implemented in both backends. - -Library growth that breaks no program: one procedure, beside `fork`, -in `Sys.raz` (C's `setsid`) and `Sys.linux-x86_64.raz` (system call -112). - - (* A new session and process group, led by this process, with no - controlling terminal: its process id, or minus an errno (-1, - EPERM, if it leads a process group already, as a process just - forked doesn't). *) - proc setsid*: INT; - -A daemon forks, and its child calls `setsid` so that the terminal it -was started from is no longer its own: closing that terminal sends it -no `SIGHUP`, and the terminal's job control doesn't reach it. Without -it, a program can ignore `SIGHUP` and `SIGINT` (`Sys.ignore`), but -stays in the terminal's session and process group, so job control and -any other signal sent to the group still reach it. - -Met in rabble, whose daemon (its `PLAN.md`, from 0.2.0) is started by -the client with `fork` and must outlive the terminal (2026-10-21). - -## The local time zone - -**Status.** Not planned (owner, 2026-10-23): rzone answers it outside raz. - -Library growth that breaks no program: a module, `Zone`, that tells -the offset from UTC of the user's time zone at a given time, so that a -program can show times as its user's clock does. - - (* The local zone's offset from UTC, in seconds east, at the time - t (seconds since 1970 UTC), and its abbreviation ("CEST"); 0 and - "UTC" if no zone can be read. *) - proc offset*(t: I64): (INT, []U8); - -The zone is the one `TZ` names, as a file under `/usr/share/zoneinfo` -(`TZ=Europe/Madrid`) or a path (`TZ=/etc/localtime`); with `TZ` unset, -`/etc/localtime`. The file is TZif, versions 1 to 4, read once and -kept: its transitions, and the POSIX rule in its footer for the times -past the last one. A `TZ` written as a POSIX rule itself -(`CET-1CEST,M3.5.0,M10.5.0/3`) is read too. No C: the same on every -target, with or without libc, so a program's times don't change with -the target it is built for. - -Met in rabble, which shows every time in UTC, in the screen and in its -logs, since the library has no zone (2026-10-21). - -## Implementation limits, and a compiler for a small stack - -**Status.** To investigate; nothing decided. - -The report names no implementation limits: how deep expressions, -statements, imports and generic instances may nest, how long a name or -a string may be. A compiler for a small machine that rejects a deep -nesting is then arguably not a raz compiler at all. C settles it with -its translation limits (C99 §5.2.4.1: 63 levels of nested parentheses, -15 of nested includes, and so on): every compiler must take at least -that much, and may take more. The proposal: a short section in the -report giving the least each compiler must accept, and saying that a -compiler that goes past its own limit stops with an error naming it, -never a crash. It changes the report, not the language. - -Behind it, three things in this compiler that need no change to the -report at all, so that it runs in a small stack: - -1. **Nesting.** Each level of a nested expression costs about 1 KiB - of stack. A constant expression with 64 nested parentheses fails a - 64 KiB stack and passes 256 KiB; 256 of them fail 256 KiB and pass - 1 MiB. A limit from the section above, checked in the parser, makes - the stack a program needs bounded and known. -2. **Imports.** `importModule` compiles an imported module in the - middle of the one importing it, on the same stack, so the stack - grows with the depth of the chain of imports. Ordering the modules - first and compiling them from the leaves, in a loop, keeps whole - program compilation and a stack that doesn't grow; symbol files, as - Wirth's compilers have, would do it too, but must then carry a - generic module's body. -3. **Instances.** `makeInstance` keeps the declaration under way aside - in arrays on the stack (`[MaxFwd]PType`, `[MaxFwd]Diag.Pos`, - `[MaxNames]INT`, several KiB) for every instance it nests. A list - of instances still to make, made between declarations, would keep - none. - -Not yet measured: which of these filled the stack when the stripped -compiler, given one more `-I` directory, overflowed 64 KiB building -itself, where the ordinary self-build fit. - -Met in moss (`docs/raz-port.md`): its stored programs get a guarded -64 KiB stack, and a native compiler must fit, or the stack must grow -(2026-10-22). - -## `Sys.blocking`: whether a descriptor's reads and writes wait - -**Status.** Approved by the owner on 2026-10-23 and implemented in both backends. - -Library growth that breaks no program: one procedure, beside -`setBlocking`, in `Sys.raz` (C's `fcntl` with `F_GETFL`) and -`Sys.linux-x86_64.raz` (system call 72, `F_GETFL`, as `setBlocking` -already makes it). - - (* Whether reads and writes on fd wait, as they do at first: 1 if - they do, 0 if they return -11 (EAGAIN) at once, or minus an - errno. *) - proc blocking*(fd: INT): INT; - -`setBlocking` sets the flag but nothing reads it, so a library that -must make a caller's descriptor non-blocking for a while can't put it -back as it found it: it can only guess. rnet's `Tls.accept` makes the -socket it is given non-blocking for the handshake and, on failure, -makes it blocking again, as `Sys.accept` gives it; a caller that gave -it a non-blocking one gets it back changed. With `blocking`, it would -note the flag first and restore that. A test, too, can't check that a -descriptor was put back without it. - -Met in rnet, after a review of its STARTTLS (2026-10-22). - -## Base64 in `Str` - -**Status.** Approved by the owner on 2026-10-22 and implemented in -`lib/Str.raz`, with the interface below; `out` too short stops the -program at the byte it lacks, as any slice does. Decoding also rejects -padding bits that are not 0 (RFC 4648, section 3.5 allows it). - -Library growth that breaks no program: three procedures in `Str.raz`, -beside `hexVal` and `toHex`, of base64 as RFC 4648 (4) has it: its -alphabet, `A` to `Z`, `a` to `z`, `0` to `9`, `+` and `/`, and `=` to -pad the last group to four. - - (* The bytes base64 makes of n bytes: 4 for each 3, or part of 3. *) - proc base64Size*(n: INT): INT; - - (* s in base64 into out, which holds base64Size(LEN(s)) bytes at - least: the bytes written. *) - proc base64*(s, out: []U8): INT; - - (* s, base64, decoded into out, which holds LEN(s) div 4 * 3 bytes at - least: the bytes written; false if s isn't base64, its length - not a multiple of 4, a byte outside the alphabet, or padding - anywhere but at the end. *) - proc unbase64*(s, out: []U8): (INT, BOOL); - -The caller gives the room, as `Fmt` and the rest of `Str` have it, so -nothing is allocated. Decoding is strict: line breaks and missing -padding, which MIME and some programs allow, are the caller's to take -out or put back first. - -Programs each carry their own copy meanwhile: rnet's `Ws`, for the -WebSocket handshake's accept key, and `Smtp`, for AUTH PLAIN, the same -twenty lines twice in one library; flojo, for the terminal's clipboard -(OSC 52), its own fifteen. HTTP's Basic authentication and data URLs -want it as well, and want decoding too, which none of those copies -does. - -Left out: base64url (RFC 4648, 5), for JWTs, which is the same with -`-` and `_` and usually no padding; a flag, or a second pair of -procedures, if a program needs it. - -Met in rnet, whose `Smtp` copied `Ws`'s (2026-10-22); listed in -`~/r/RAZ-GAPS.md` before that, from rnet and flojo. - -## A library that says which raz it was written for - -**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`). - -0.19 moved the library from pointers to `var` and `const` parameters, -and every library pinned to an older raz stopped building: rnet, rjson, -rfetch, rj and arno needed fixes, and alba, clima and linia carried -their own JSON reader meanwhile. The errors were loud but far from the -cause: "can't use ^Buf as Buf" inside rjson, read by someone building -clima. The report says the library "grows only by what breaks no -program", and the move broke all of them. Three small pieces, none of -them syntax. - -**A deprecation step.** A change to the standard library that breaks -programs keeps the old form for one minor version beside the new, the -old one marked so that a call to it is a warning naming the new one: - - (* deprecated: Buf.add(var b, ...) *) - proc addOld*(b: ^Buf; s: []U8); - -How the mark is written is the open question: a comment the compiler -reads is a pragma in disguise; a word like `obsolete` before `proc` is -a reserved word for a rare case. The step could also be policy alone, -with no mark: the release notes list the old forms and the next -version removes them. - -**An error says whose module it is in.** An error in a module found -through `-I` or `RAZ_PATH` names the directory it came from and, if -that directory holds a file `RAZ-VERSION` (one line, `0.21`), the raz -it was written for: - - /home/luis/.raz/lib/Json.raz:41: can't use ^Buf as Buf - (a library written for raz 0.18; this is raz 0.21) - -The compiler only reads the file; it never refuses to build. A library -that has none is no worse off than today. - -**`raz --version` says its commit** when `git describe` finds no tag, -as from a shallow fetch, instead of "unknown" (rcrypto pins a commit -and always sees "unknown"). - -Met in rnet, rjson, rfetch, rj, arno, alba, clima and linia (0.19), -and rcrypto (`--version`). - -## Sys for a server - -**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. - -Library growth that breaks no program. Programs that serve sockets -(rabble's relay and daemon, dwa's broker, rdbus, awizo, arno's te -protocol) each declare a few C procedures or make system calls with -`SYSCALL` in a `.linux.raz` file, for what any server needs. Each piece -below stands alone; together they are about a dozen procedures in -`Sys.raz` and `Sys.linux-x86_64.raz`. - -- **`shutdown`.** `proc closeWrite*(fd: INT): INT;` ends this side's - writing, `SHUT_WR`, so the peer reads an end and can still answer - on the same socket (te's protocol; rabble wakes a thread waiting in - a handshake with it). Met in dwa, rabble, arno. -- **Who is at the other end.** `proc peer*(fd: INT): (Peer, INT);` - with `Peer` the address of a TCP peer (family, address bytes, port) - and, for a Unix socket, the peer's uid and pid (`SO_PEERCRED`). A - server can log who connected and a broker can check that its client - is the same user, instead of trusting a 0700 directory. Met in - rabble, dwa. -- **A pair of sockets.** `proc socketPair*(): (INT, INT, INT);` the two - ends and 0, or minus an errno. Met in rdbus's tests and rabble's - relay. -- **A send that doesn't wait.** `proc sendNow*(fd: INT; s: []U8): INT;` - (`MSG_DONTWAIT`): -11 where `send` would wait, without making reads - non-blocking too. Met in rdbus. -- **Opening without waiting.** `nonblocking` and `closeOnExec` among - `Access`. (`closeOnExec` falls away if "Sys for files and - memory" makes it the default.) Opening a fifo to write waits for a reader, and a fifo - given where a file was expected waits for a writer. Met in mosaico, - awizo, surco, raudio. -- **A fifo.** `proc makeFifo*(path: []U8; mode: INT): INT;`. Met in - awizo. -- **An owner.** `Info.uid`, `Info.gid` and `proc chown*(path: []U8; - uid, gid: INT): INT;`, so a save through rename keeps the owner and a - daemon can check that its directory is the user's. Met in dwa, - rabble. -- **Keepalive.** `proc keepAlive*(fd: INT; idle, interval, count: - INT): INT;` rather than a general `setsockopt`, whose value is a - pointer and a length of any type. Met in rabble. -- **An abstract Unix socket.** `connect` passes `2 + LEN(path)` as the - address's length when the path starts with a zero byte, so Linux's - abstract names (D-Bus's `unix:abstract=`) are reached. A fix, not a - procedure. Met in rdbus. -- **`errConnAborted`** (-103), which `accept` gives for a client gone - before it was taken. Met in rabble. - -**Waiting**, the one piece that changes a procedure's answer, and so -better as a new procedure than a change to `readyFor`: - - (* Waits up to ms milliseconds (ms < 0: as long as it takes) until - one of fds may be read or written as each of its wants says, and - sets each one's ready. The number ready, 0 on a timeout, or minus - an errno. *) - proc poll*(var fds: []Poll; ms: INT): INT; - -with `Poll = record fd: INT; read, write: BOOL; ready: BOOL; end`. -It takes as many as it is given (`readyFor` stops at 64, so dwa's -broker serves 31 editors), answers every ready descriptor in one call -(`readyOf` gives only the first, so awizo takes two rounds and rabble -rotates its clients so that the first doesn't starve the rest), gives -the place in the list, not the fd, and tells a timeout from an error -(both are -1 today). `readyFor` and `readyOf` stay, written over it. -Whole milliseconds stay too: surco rounds up, and a wait in -nanoseconds is `ppoll`, Linux's, for one program. - -Each item is listed in `~/r/RAZ-GAPS.md` under "Standard library: Sys, -files, processes". - -## Sys for running a program - -**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. - -Library growth, but two of the four change what `spawn` and `wait` -do, so they need the owner's word on whether a change of behaviour -counts as breaking. - -- **`spawn` says a program isn't there.** Today a missing program - still gives a pid, and the child exits 127, which a caller can't tell - from the program's own 127; clima, alba, sauce and raztest search - `PATH` first, about 20 lines each, and sauce still reads curl's 127 - as "cannot run curl". `spawn` searches `PATH` in the parent, as - `exec` already does, and gives -2 (ENOENT) before it forks. A - program found but failing in `execve` (not executable, a bad - interpreter) still exits 127, since only the child sees that; a - close-on-exec pipe would carry its errno back, at the cost of a pipe - per spawn. -- **Ignored signals stay ignored.** `spawn` and `exec` give the child - every signal as at first, SIG_IGN included, where `execve` keeps an - ignored one ignored: a robbie under `nohup` runs its recipes without - it, and ssh run by fdn doesn't keep SIGPIPE ignored. A - `Program.keepIgnored: BOOL`, false as today, keeps them. -- **`fds` with `tty`.** With `tty`, the pseudo-terminal is all three - files and `fds` is ignored, so dwa's background job that should read - `/dev/null` waits on a terminal nobody types to. A non-zero `fds[i]` - replaces the terminal for that file; zero keeps it. -- **`wait` without the stopped.** `wait` always asks for stopped - children (WUNTRACED), so a program waiting for `$EDITOR` loops past - Ctrl-Z (notis, fdn). `proc waitExit*(pid: INT): (INT, Status, INT);` - waits only for an end, or `wait` takes `stopped: BOOL`, which - changes its signature. - -`PATH` read empty as unset (pict) stays: the library volume says so, -and it is `execvp`'s choice. - -## An investigation: where a hot loop's time goes - -**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. - -Not a change: a measurement, whose report would say whether register -allocation, inlining (see "Inlining a procedure that only returns"), -or neither is worth its weight in the compiler. - -What is known, from rcrypto, rat and sauce: - -| Code | MB/s | Against | -|---|---|---| -| ChaCha20, `quarter` on a `var x: [16]U32` | 40 | 78 written out on sixteen locals; OpenSSL scalar 589 | -| Poly1305, arithmetic on locals, no calls | 491 | | -| AES-128 bitsliced, 115 gates on 130 local `U64`s | 23 | GHASH 180 | -| SHA-256 with `ROR` | 76 | 40 before `ROR` | - -and rat's parser, which inlines `Utf8.take` by hand because the call -costs 7 to 10 per cent. - -The steps: a `bench/` of these few kernels, each in its plain form and -its hand-tuned one; their `raz -S` read side by side, counting loads -and stores of locals, spills and calls; then the same kernel with the -generator changed by hand (a local kept in a register across a loop, a -small procedure inlined) to put a number on each. The outcome is a -page here saying which change buys what, and none is made before it. - -Listed in `~/r/RAZ-GAPS.md` as "A state in an array or behind a `var` -is slow" and "No procedure is inlined". - -## A width in `Fmt` - -**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. - -Library growth that breaks no program. `Fmt` has only `{}`, so seven -programs pad by hand: arno, rat, notis and poczta each have a -two-digit helper for times, surco writes `m:ss` and its cover files' -lower-case hashes with loops of its own, rttf writes `U+00E9` and raz's -own `Prop` a fixed-width hex name. - -The proposal: a width between the braces, and a zero before it to pad -with zeros, right-aligned: - - Fmt.print("{2}:{02}", [Fmt.int(m), Fmt.int(s)]); (* " 3:07" *) - Fmt.print("U+{04}", [Fmt.hex(0E9H)]); (* "U+00E9" *) - -A value wider than the width is written whole. A minus pads on the -right (`{-10}`), for columns of names. Zeros go after a sign: `{04}` of --7 is `-007`. Nothing else: no precision (`Fmt.real` has `places`), no -other fill, no named or numbered arguments. - -And a lower-case hexadecimal: a case `lowHex(h: U64)` beside `hex`, or -`{x}` against `{X}`, which is a second letter in the format for a thing -an argument could say. The argument is the plainer. - -`{` followed by anything but `}` or a width is printed as it stands -today, so no format changes meaning unless it already had `{2}` in it, -which printed `{2}`. - -Settled by "One exponent letter: `Fmt` writes `E`", below. - -## Selectors after a `^T(e)` conversion - -**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. - -A conversion through a pointer type's name is a designator, so -selectors follow it: with `PR = ^R` and `PU = ^U8`, `PR(ADR(r))^.b` -and `PU(ADR(r))[0..4]` compile today. The same conversion written out -is the grammar's own factor, `"^" ["VOLATILE"] Type "(" Expr ")"`, and -takes none: `^R(ADR(r))^.b` is "a conversion can't be dereferenced", -and `^U8(ADR(r))[0..4]` is "can't use ^U8 as []U8", the slice read as -part of the operand. So a program declares a pointer type, or a -variable, for one read through a C struct or one slice of raw memory. - -The proposal: that factor takes selectors, as a named conversion does. - - Factor = ... | "^" ["VOLATILE"] Type "(" Expr ")" { Selector } | ... - -`^U8(p)[0..n]` is a slice of `n` bytes from `p`; `^XMapEvent(ADR(ev))^.window` -is one field of an event. Nothing new is checked or left unchecked: the -selectors are a pointer's, as they are after `PU(p)`. A statement still -starts with a name or `try`, so `^T(x)^ := v` stays out (the report -says so already, and a view, `mem[a].(I64) := v`, writes it). What is -text with an error today gets a meaning, and nothing else changes. - -Met in znaczy, raudio, rcrypto and linia (the slice) and rx11 (the -dereference). - -## The limits of an integer type: `MIN(T)` and `MAX(T)` - -**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). - -Programs write `7FFFFFFFFFFFFFFFH` for the largest `I64` and `-10^12` -for "below anything real", and nothing ties either to its type: change -a field from `I64` to `I32` and the constant still compiles, wrong. -Oberon has `MIN` and `MAX` of a basic type for this. - -The proposal: two built-in procedures, for an integer type `T` only: - -| Call | Result | -|---|---| -| `MIN(T)` | the smallest value of `T`, an untyped constant | -| `MAX(T)` | the largest value of `T`, an untyped constant | - -`MIN(U64)` is 0, `MAX(U64)` is 18446744073709551615, `MIN(I64)` is --9223372036854775808, so the constants need the compiler's -`U64`-and-`I64` range, which constant folding already has. A name for -another type, an enumeration, a set or a real, is an error: an -enumeration has `LEN`-like answers of its own, and a real's limits -(an infinity, the largest finite) are a separate question. Two words -taken among the built-ins, which a program can't declare anyway. - -Met in mosaico, rfuzz and raudio. - -## `OFFSET(T, f)`, and `SIZE` of a field - -**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). - -A record handed to C by pointer must match C's struct byte for byte; -a field one word off is read wrong with no error. mosaico and rx11 test -their Xlib records against C's `offsetof` and `sizeof`, and today -measure an offset on a dummy variable, `INT(ADR(v.f)) - INT(ADR(v))`: -a run-time value, a variable declared for it, and pointer arithmetic -where the test means "where `f` is". rx11's `test/layout.sh` copies -each field's type out of the source text, since `SIZE` takes only a -type. - -The proposal, two additions to the built-in procedures: - -| Call | Result | -|---|---| -| `OFFSET(T, f)` | the byte offset of field `f` in the record type `T`, an untyped constant | -| `SIZE(T.f)` | the size of field `f` of the record type `T`, an untyped constant | - -`f` is one field name; a path, `OFFSET(T, a.b)`, would be the sum of -two and is left out, and so is a variant, whose cases share their -place. `SIZE` still takes no -variable: `T.f` names a type's field, not storage, so `SIZE` stays a -question about types. - -C has `offsetof`; Modula-2 and Oberon kept such things in `SYSTEM`, -and raz has no `SYSTEM`. It is constant folding of what the compiler -already knows, and it is also what a view through raw memory wants, -`mem[a + OFFSET(Hdr, len)].(U32)`, in place of a number, and what a -kernel's `code` procedures would want if their operands take constants. - -Met in mosaico and rx11. - -## The compiler on another host: `Host`, and what it asks of the library - -**Status.** Built on the branch `moss-platform-boundary` (3eded0c), -which Moss pins: there raz compiles programs, rebuilds itself byte for -byte, and builds again after a restart (moss c606069, -`docs/native-raz.md`). Waiting for the owner's word on the questions -below before it is rebased and merged. - -The host is the system the compiler runs on; the target, the system -its program will run on. Until the branch they were one, Linux, and -the compiler reached Linux outside `Sys`: `Parse.identity` read a -`struct stat` by `SYSCALL(4)` into a guessed `[18]INT`; `Raz` read -`ARGC()` and `ARGV()`, found the library through `/proc/self/exe`, -probed two loader paths for musl, and ran a program by `memfd_create` -and `execve`; `Elf` set mode 755. The branch does three things. - -**1. A file's identity from `Sys.info`** (2644329). Its `dev` and -`ino`, so the parser makes no system call of its own. A plain fix: -merge it. - -**2. A main file at the root, and a directory ending in `/`** -(3eded0c). `/Main.raz` has `/` as its directory, not `""`, and a -directory given as `lib/` doesn't make `lib//Sys.raz`. A plain fix: -merge it. - -**3. `Host`, a module of what the compiler asks of its host** -(bb03e48): `argCount`, `arg`, `libraryDir`, `preferMusl`, `canRun`, -`canLinkC`, `writeExecutable`, `prepareRun`, `execute`. `src/Host.raz` -is Linux's; Moss stages the compiler's sources with its own -`Host.raz` (27 lines: the library at `/lib`, no run, no C, no mode -bits) and its own `Sys`, `Rt` and `Files`. - -Questions before the merge: - -**a. A smaller `Host`.** Two of its nine procedures are there only -because `Raz` reads the command line by built-ins: -- `argCount` and `arg` go if the library has the count beside - `Files.arg`: a `Files.argCount()`, which Moss's `Files` gives from - `Sys.argc`. `Files.arg` is already the library's, and Moss already - replaces it. -- `preferMusl` and `canLinkC` are one question, which C library to - link against: `Host.cLibrary(): CLib` with `CLib = (none, glibc, - musl)`, or keep the two booleans. -- `canRun` goes if `prepareRun` is called while the command line is - read, before any source, so that its error is the refusal. -That leaves `libraryDir`, `cLibrary`, `writeExecutable`, `prepareRun` -and `execute`: five procedures, each a real difference between hosts. - -**b. How a host is chosen.** The branch stages: copy `src/`, put the -host's `Host.raz` in place of raz's, build. The main directory is -searched first, so `-I` alone can't replace it, which is right: a -module isn't silently replaced. The other way is a target name, as -`Sys.linux-x86_64.raz` is chosen today from fixed suffixes: a -`-os moss` that makes the suffixes `.moss-x86_64`, `.moss`, `.x86_64`, -`""`, so that `Host.moss.raz` and `Sys.moss.raz` are found beside the -generic files. That puts Moss's files in raz's tree, and raz would -then know of Moss. The proposal is to keep staging, raz knowing -nothing of any host but Linux, and to document it in -`doc/compiler.md` as the one way to build for another host. - -**c. What the compiler asks of the library, written down.** Moss's -`Sys` has 23 exported procedures against Linux's 104, and is enough. -`doc/compiler.md` should list what the compiler and the modules it -imports (`Rt`, `Mem`, `Heap`, `Lock`, `Arena`, `Out`, `Fmt`, `Buf`, -`Str`, `Bytes`, `Files`) use of `Sys`, `Rt` and `Files`, as Moss's -`docs/raz-port.md` measured it, and a test should hold it: the -compiler built against a `Sys` with only those exports. Then a change -to the compiler that reaches for one more of `Sys` is seen in raz, -not in Moss's next build. The test host on the branch -(`test/host/Host.raz`) checks the `Host` side only. - -**d. The stack.** A self-build passed in 64 KiB of stack on Linux, -but 64 nested parentheses don't, and Moss gives a stored program 1 -MiB. That is "Implementation limits, and a compiler for a small -stack", above; the merge needn't wait for it. - -**e. The tests in Python.** The branch adds `test/compiler-host.py` -(177 lines) and grows `test/library-path.py`, which came with -RAZ_PATH. raz's tests are otherwise `sh`, as a public project's -should be, needing nothing but a shell to run. The proposal is to -write both in `sh` before the merge. - -**f. Before the merge, in any case.** The system call numbers in -`Host.raz` named as constants, as `Raz` had them (`MemfdCreate`, -`MfdCloexec`, `Execve`); a comment on every procedure; the new section -of `doc/compiler.md` made as short and plain as the rest; a rebase on -main (`doc/compiler.md` and `src/Raz.raz` conflict). Moss's -`RAZ_PORT.lock` then pins a commit on main. - -## Constants built from constants - -**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). - -Three small changes to what a constant may be written with, and a defect. Each stands -alone; none changes what a program that compiles today means. - -- **A named constant as an element.** `const Y: [2]R = [X, {a: 2}]`, - with `X` a record constant, is "expected a literal of R", and so is - `[X, [3, 4]]` with `X` an array constant, and `{a: X}` for an array - field. A named integer is taken (`[N, 2]` compiles), and so is a - named array constant for a slice part (`[R1, R2]` for a `[][]INT`). - The report already allows it: the value is "a literal of constants", - and its elements may be "arrays, records and variants of these". So - this is a defect of the compiler, mended with no change to the - report: where an array, record or variant is wanted, a constant of - that type stands for its literal. Met in mgla. - **Recommendation:** take, as a defect mended. Fixed in 065335a - (2026-10-22). - -- **A literal for a slice part.** `const T: [][]INT = [[1, 2], [3]]` - is "a constant slice is a string, an array constant of its elements - or []", and so is `{r: [1, 2]}` for a `[]INT` field. Each row must be - named first, `R1: []INT = [1, 2];`, and the table written `[R1, R2]`, - or the rows flattened into one slice walked by counts, as raudio's - Sbr test does. The proposal, one clause of 4: where a slice part is - wanted, an array literal of its element type makes an array constant - of its own, with no name, as `[]` there makes the empty slice. `[]` - stays the empty slice. Met in raudio. - **Recommendation:** take, since the named rows say nothing the - literal doesn't. - -- **An `ERROR` constant named by another.** - `const Short*: ERROR = PictBase.Short;` is "an error is made from a - string", so an interface module can't pass on the errors of the - modules under it, and its callers import a second module only to - compare. The proposal, a sentence of 5.8: an `ERROR` constant whose - value is another `ERROR` constant is that same error, not a new one, - and `Short = PictBase.Short` holds. Only a string makes a new error, - as now. Met in pict. - **Recommendation:** take, since the alternative is a second import - on every caller. - -- **A comma after the last element.** `[a, b,]` is "expected an - expression", so a table written one row a line, by hand or by a - program, treats its last row apart, and adding a row changes two - lines. The proposal, in the grammar: - - | "[" [ Expr { "," Expr } [ "," ] ] "]" - | "{" [ Element { "," Element } [ "," ] ] "}" - - for array, record and set literals alike; not for calls, parameter - lists or `match` labels. `Pretty` keeps the comma where a literal - runs over lines and drops it where it fits on one. Met in rtui. - **Recommendation:** take, since a generated table is the common case - for literals this long. - -## A record's procedure field that takes the record - -**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. - -A record that carries its own callback can't give the callback the -record: - -``` -type Lines = record each: proc(var r: Lines; s: []U8); n: INT; end; - (* "Lines isn't declared" *) -``` - -Only the base type of a pointer may name a type declared later (4), so -the callback takes `^Lines` and is called with `ADR(l)`, which by -`STANDARDS.md` says the callee keeps it, and it doesn't. Met in znaczy. - -The proposal, a clause of 4: the type of a parameter or result of a -procedure type may also name a type declared later in the same `type` -section. A procedure value is an address whatever its signature, so -the record's size doesn't depend on it; a call through the field -comes after the section, when `Lines` is whole. Nothing that compiles -today changes. In the compiler, the pointer's forward reference -reused where a signature is read in a `type` section. - -**Recommendation:** take, since the workaround puts a false `ADR` at -every call. - -## A `match` arm names its case as everywhere else - -**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). - -An arm takes a case written alone, or with its type when the type is -the module's own (`| K.a:`). An imported case can't be written as -everywhere else outside its module: - -``` -import Xml; -... -if x.kind = Xml.done then ... end; (* qualified here *) -match x.kind of -| Xml.done: ... (* "Xml isn't a case of Xml.Kind" *) -| Xml.Kind.text: ... (* the same *) -| done: ... (* taken: a name this module otherwise hasn't *) -``` - -The same holds for a variant's cases (`| Ev.circle(r):`). Met in -rslack, rxml and fraco. - -This is the complement of "An enumeration's name read against the type -it is given to": an arm already reads a bare name against the matched -type. The proposal, a sentence of 7.4: an arm on an enumeration or a -variant names its case alone or as it is written anywhere else, with -its type, its module, or both (`done`, `Kind.done`, `Xml.done`, -`Xml.Kind.done`), and a qualified name must be a case of the matched -type. The bare form stays, so nothing breaks. A wrong qualified name -says so: "Ev.dot isn't a case of Xml.Kind". - -**Recommendation:** take, since the natural spelling is refused with a -message that doesn't say what to write. - -## Two warnings - -**Status.** Approved by the owner on 2026-10-23 and implemented in `Parse` and `Scan`. - -Compiler warnings, which are the implementation's own (10, appendix -A): no change to the report, and `-Werror` builds break only where the -text is in fact doubtful. - -- **A relation of `BOOL`s beside `and` or `or`.** In raz the relations - bind tighter than `and` and `or`, so - `(b[i] = 0) # (i >= 2) and (i < 9)` is - `((b[i] = 0) # (i >= 2)) and (i < 9)`. It was meant the Pascal way, - and a test passed for the wrong reason. The warning: an `=` or `#` - whose operands are `BOOL`s, written unparenthesised as an operand of - `and` or `or`: - - a # b and c is (a # b) and c: put the # of two BOOLs in parentheses - - Comparing integers is untouched, so `i < n and a[i] # 0` stays - quiet. Met in rcrypto. - **Recommendation:** take, since the slip is silent and the fix is a - pair of parentheses. - -- **`\0` before a digit.** `"\01"` is a zero byte and `1`; a reader who - knows C reads one octal byte. Moss's keyboard table, - `"\0\01234567890-="`, cost a bug. The warning, in a string or a - character where `\0` is followed by `0` to `7`: - - \0 is a zero byte and the digit after it is itself: write \x00 to keep them apart - - Met in moss (and dwa's tests have the same text, in a comment). - **Recommendation:** take, as a few lines in `Scan` for a bug already - paid for. - -## A `BOOL` as an integer: `INT(b)` - -**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). - -Moved here from the list of what to leave out, because three programs -met it and one of them for a reason an `if` can't serve. 6.7 says -there is no conversion between `BOOL` and integers, left out until -needed. Programs now write `8 + Ord(b)` as an `if` (raudio, surco's -Lyrcheck). Constant-time code needs a comparison as a mask with no -branch: rcrypto rebuilds each test from byte differences, -`INT((d - 1) shr 31)`, since an `if` would branch on a secret. - -The proposal, one row of 6.7's table: - -| From | To | Result | -|---|---|---| -| `BOOL` | integer | 0 for `false`, 1 for `true` | - -`U64(a = b)` is 0 or 1, and `0 - U64(a = b)` the mask. Only this way: -no integer to `BOOL` (`x # 0` says it). In a constant it folds. The -compiler has the comparison's `setcc` already, so it is computed -without a branch; the report doesn't promise that (no word of it says -anything of time), but this compiler does it. - -**Recommendation:** take, since Oberon has `ORD(b)` and a constant-time -mask has no other plain spelling. - -## Counting bits: `CLZ`, `CTZ` and `POPCOUNT` - -**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). - -raz has `ROL` and `ROR` (report 2026-10.35) but nothing that counts -bits, so programs loop. raudio's Rice decoder finds the one bit that -ends a unary code by shifting until it meets it (`Bitio.unary`); oku's -`Grid.count` asks `d in s` for each of nine digits to learn how many a -set holds. The library meets the same three times in `Bytes`: `highest` -is a loop, the lowest set byte is found by a multiply, and `count` sums -bits by a multiply, each with a paragraph to explain it. Oberon has -none of these; C compilers, Go (`math/bits`), Rust and Zig all do, as -one instruction each on every machine raz targets. - -The proposal: three built-in procedures, beside `ROL` and `ROR` in 6.8. - -| Call | Result | -|---|---| -| `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 | -| `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` | -| `POPCOUNT(x)` | the number of one bits in `x`, an `INT`; `x` of an unsigned integer type, or a set, whose members it counts | - -The width is the type's, as for `ROL`: `CLZ(U8(1))` is 7, `CLZ(U64(1))` -is 63. Defining 0 rather than leaving it undefined, as C does, costs a -test where the machine's instruction doesn't give the width (x86-64's -baseline `bsr` and `bsf`); `lzcnt`, `tzcnt` and `popcnt`, which the -compiler's assembler already knows, are newer than the baseline, so -the compiler emits `bsr` or `bsf` with a test, and the multiply that -`Bytes` uses for `POPCOUNT`, unless the target says the instructions -are there. A set goes to `POPCOUNT` and not to `LEN`, which already -means a fixed number of elements and would read as the size of the -set's type. - -Why three and not one: `CLZ` is what reads a code from the top bit -down (Rice, Golomb, UTF-8's lead byte, a log base 2), `CTZ` what walks -the members of a bit mask from the bottom, and `POPCOUNT` what counts. -Each can be written from another only in a way that needs a comment. -Three words among the built-ins, which a program can't declare anyway. -It breaks nothing. - -Met in raudio, oku and the library's own `Bytes`. - -**Recommendation:** take; three one-instruction built-ins replace loops -and multiplies that each need a paragraph. - -## The bytes of a variable or a slice: `BYTES(x)` - -**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). - -A view, `v.(T)`, reads one value from bytes, and can't be sliced, -since it has no address (6.9). So a program that has words and wants -their bytes takes an unchecked pointer: raudio writes a `[]I32` of -samples to a file through `p := ^U8(PTR(s))` and `p[0..LEN(s) * 4]` -(`Ao.bytesOf`); surco's Engcheck reads a file into a `[]I32` the same -way; rcrypto wipes each hash state through `p := ^U8(ADR(c)); -RcBytes.wipe(p[0..SIZE(Ctx)])`, with a `p` that says nothing. "Selectors -after a `^T(e)` conversion" makes the last one expression, -`^U8(ADR(c))[0..SIZE(Ctx)]`, but it stays unchecked: the length is -written by hand and nothing ties it to `c`. - -The proposal: one built-in procedure. - -| Call | Result | -|---|---| -| `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 | - -``` -n := Sys.write(fd, BYTES(samples)); (* samples: []I32 *) -n := Sys.read(fd, BYTES(words)); (* fills words: []I32 *) -RcBytes.wipe(BYTES(c)); (* c: Ctx, all of it *) -``` - -`T` must be a type a view may take (6.9): integers, reals, pointers, -and records and arrays of these alone, the types for which any bytes -are a value. So writing through the slice can make nothing mean -nothing, which is why a `BOOL`, a set, an enumeration, a slice, a -variant or a procedure, or a record holding one, is an error. The -slice is checked as any slice is; its length comes from the type, not -from the program. A variable given to `BYTES` follows the rules for a -slice of it: a local's bytes can't be returned (7.3); a `const` -parameter, a view and a volatile variable are errors, as `ADR` of them -is; a string constant is an error, as writing its bytes isn't defined. -The bytes are in the target's order (appendix A), as a view's are. - -It is `PTR` and `SIZE` made one checked expression, about 30 lines in -the compiler. It breaks nothing. With "Filling bytes: `Bytes.fill`", below, an array -of words is zeroed as `Bytes.fill(BYTES(a), 0)`. - -Met in raudio, surco and rcrypto. - -**Recommendation:** take; it replaces an unchecked pointer and a -hand-written length with one checked expression. - -## Filling: `FILL(d, x)` - -**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. - -`COPY` copies and `NEW` zeroes, but nothing sets the elements of an -array or a slice already in hand. rttf clears each glyph's raster a -byte at a time (`clear`), its `Pgm` the same for an image, a -`Buf.spare` slice is cleared by a loop, and raudio zeroes a `[576]F32` -with a loop or a helper. Pascal has `FillChar`, C `memset`. - -rat fills with a value that isn't zero, on its hottest path: each -pixel row of a cell's background is `U32` pixels of the cell's colour, -some 4 million pixels for a full redraw of a 3440 by 1440 window. The -loop for it was most of `Draw.paint`'s time, itself 81 per cent of -rat's on full redraws, as its counter had lost its register to -`paint`'s busier variables; moved into a procedure of its own it has -one, and rat's time on full redraws fell by 30 per cent. Even then a fill does better: -libc's `wmemset`, against the loop with its counter in a register, -fills runs of 10 `U32`s in 0.6 of the time, and of 4 million in a -third. A `Bytes.fill(s: []U8; b: U8)`, as this proposal first was, -can't serve it: a colour's four bytes differ. - -The proposal: one built-in procedure, a statement, as `COPY` is. - -| Call | Result | -|---|---| -| `FILL(d, x)` | sets every element of `d`, an array or a slice of elements of type `T`, to `x`, a value of `T` | - -``` -FILL(w^.band[row..row + w^.cellW], U32(l.bg)); (* a row of pixels *) -FILL(window, 0.0); (* window: [576]F32 *) -FILL(raster, 0); (* raster: []U8 *) -``` - -`d` is written as `COPY`'s destination is, and `x` is assigned to each -element as by `:=`. An element of one, two, four or eight bytes is -stored with `rep stos` of that width, or with moves when there are -few, as `zeroBytes` does; any other is stored once and copied forward -from there. A zero of any type is `rep stosb`, as `NEW`'s zeroing is. - -It breaks nothing, and leaves `Bytes.fill` out: a slice of bytes is -filled as any other. It is not a wipe: an optimizer may leave out a -fill that nothing reads after, as it may any write (7.6). Its size in -the compiler is not yet measured. - -Met in rttf, raudio and rat. - -**Recommendation:** take; one statement for a loop every buffer-handling -program writes, as fast as the machine fills, for any element type. - -## `COPY` forwards unless it must go back - -**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. - -`COPY` is right when its two sides overlap (6.8), and the compiler -makes it so by copying backwards whenever the destination is above -the source (`Gen.copySlice`): `std`, `rep movsb` down from the last -byte, `cld`. That is right, but it goes backwards for every copy to a -higher address, overlapping or not, and a backward `rep movsb` gets -none of the processor's fast copying: it moves a byte at a time. Ten -million copies between the two halves of one `[4096]U32`, never -overlapping: - -| Elements | Down | Up | -|---|---|---| -| 10 `U32`s | 66 ms | 510 ms | -| 1000 `U32`s | 390 ms | 9,800 ms | - -rat meets it drawing a scaled font: each pixel row of a cell is copied -to the rows under it, a higher address in the same image, for every -cell drawn. - -The proposal, the compiler's alone, as the report already says what -`COPY` does: copy backwards only when the destination starts inside -the source (`rsi < rdi < rsi + rcx`, one more comparison), and -forwards otherwise. A backward copy that must be made could go by -words, eight bytes at a time down to the last few, rather than by -`rep movsb`. - -It breaks nothing: no program can tell, but by its time. - -Met in rat. - -**Recommendation:** take; one comparison in `copySlice` for a copy up -to eight times faster at ten elements and twenty-five at a thousand. - -## A slice of a `const` parameter, returned - -**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. - -7.3 says a slice of a `var` parameter, of a module variable, or of -what a pointer points at may be returned, and says nothing of a -`const` one. rimap's `proc sectionOf(const p: Part): []U8; begin -return p.section[0..p.sectionLen]; end;` compiles and works, but the -report doesn't promise it, so rimap leaves its callers to slice the -field themselves. - -A `const` parameter is the caller's variable read in place (8), as a -`var` one is, so its slice is the caller's, not this procedure's -frame. When the argument isn't a variable it is a temporary of the -caller's statement, and a slice of it kept past that statement is -already the exception of section 10. The rule only has to say so. - -The proposal, 7.3's sentence: - -> A slice of a `var` or `const` parameter, of a module variable, or of -> what a pointer points at may be returned: none of them is this -> procedure's frame. For a `const` parameter given a temporary, the -> slice lives to the end of the caller's statement (section 8). - -Only the report changes; the compiler already accepts it. It breaks -nothing. Whether the caller may write through the slice it gets back -is the question of "A slice that can't be written: `[]const T`", which -this doesn't settle. - -Met in rimap. - -**Recommendation:** take; a sentence promises what the compiler already -does. - -## What wiping can't reach, said in appendix A - -**Status.** Approved by the owner on 2026-10-23, with the twelfth thaw. In the report, 2026-10.36 (appendix A); no code. - -A wipe through `^VOLATILE U8` is never left out (7.6), but it writes -only what the program can name. A spilled register, a statement's -temporary, a value parameter's copy and an array a call returned are -the compiler's, and stay in memory after the procedure returns, until -something else writes there. rcrypto found that its wipes can't reach -them, and nothing in the report says they exist. C has the same limit -and says nothing either; OpenSSL's `OPENSSL_cleanse`, which rnet's -`Tls.wipe` calls, wipes only what it is given. - -The proposal: a paragraph in appendix A, among what an implementation -says of itself, and no feature. - -> **Copies.** A procedure's frame may hold copies of its variables -> that the program can't name: registers saved to it, temporaries of -> its statements, its value parameters, and arrays its calls return. -> This implementation leaves them where they are when the procedure -> returns; they last until the stack is used again. A wipe (7.6) -> reaches only the variables it is given. A secret is best kept in -> one variable, passed by `var` or `const` or by pointer, never by -> value, and wiped there. - -Zeroing a frame on return, by a word on the procedure or a flag, was -weighed and left: it costs every call of such a procedure a write of -its frame, and still misses registers and the kernel's copies of a -thread's state. It breaks nothing. - -Met in rcrypto. - -**Recommendation:** take; a paragraph says a limit every program that -wipes must know. - -## Sys for files and memory - -**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. - -Library growth, but the last item changes what `open` does, so it -needs the owner's word on whether that counts as breaking. Each item -stands alone; each is in both `Sys.raz` (the C library) and -`Sys.linux-x86_64.raz` (system calls). - -- **A file mapped to be read.** `mapFile` maps to read and write, - shared, so a file opened only to read (a dictionary that isn't the - user's to write) can't be mapped: `mmap` fails with EACCES. znaczy - makes the system call itself in a `Zmap.linux.raz` (30 lines), and - raudio's Inmem does the same. - - (* The first size bytes of the file fd, which may be open only to - read, mapped to be read only: writing there stops the program. - nil if it can't be; munmap gives them back. *) - proc mapRead*(fd, size: INT): ^U8; - - C's `mmap` with `PROT_READ` and `MAP_PRIVATE`; system call 9 with - the same. Met in znaczy, raudio. **Recommendation:** take, two - programs carry a Linux-only file for it. - -- **Memory that can't be touched.** A test that puts its input against - a guard page, so that a read one byte out of range stops it, calls - `SYSCALL(10, ...)` itself and is tied to Linux; raudio's Inmem grows - a large mapping readable a step at a time, so that the bytes never - move. - - (* Lets the pages from p, size bytes from a page boundary, be read - and written as read and write say; neither, and touching them - stops the program. 0, or minus an errno. *) - proc protect*(p: ^U8; size: INT; read, write: BOOL): INT; - - C's `mprotect`; system call 10. With `mmap` it serves raudio's - reserve too: map the most it will hold, `protect` it all to neither, - and open it as it fills. Met in rttf, raudio. **Recommendation:** - take, the one portable way to a guard page. - -- **Files closed in a program exec starts.** `pipe`, sockets and - `memFile` are closed across `exec`; a file `open` gives is not, so a - fifo mosaico holds reaches every program it starts, unasked, and it - calls `keepOnExec(fd, false)` after each open. `openMode`, `open`, - `openRead` and `create` would pass `O_CLOEXEC`, and their comments - say "closed in a program exec starts" as `pipe`'s does; - `keepOnExec(fd, true)` keeps one open. `spawn`'s `fds` are unchanged, - since `dup2` in the child clears the flag. This makes the - `closeOnExec` access in "Sys for a server" unneeded (`nonblocking` - stays). A program that hands an opened file to an exec'd one by its - number, without `fds`, must then say `keepOnExec`. Met in mosaico. - **Recommendation:** take, one rule for every descriptor Sys makes. - -## Files: what programs write over Sys - -**Status.** Approved by the owner on 2026-10-22 and implemented in `lib/Files.raz`, all three; `Files.write` is written over `writeAll`. - -Library growth that breaks no program. Each is portable, written in -`Files.raz` over procedures `Sys` already has, so neither backend nor -Moss's `Sys` grows. - -- **Writing all of it.** A `write` may be short (a pipe, a socket) or - broken by a signal, and each program carries its loop; `Files.write` - has one, but only for a whole file it creates. - - (* Writes all of s to fd, again after a short write or a signal: - 0, or minus the errno of the write that failed. *) - proc writeAll*(fd: INT; s: []U8): INT; - - `Files.write` is then written over it. Met in surco (Sjournal), and - the loop is in most programs that write to a pipe. - **Recommendation:** take, the loop every writer to a pipe needs. - -- **A path made absolute and plain.** surco makes `-r` and a playlist - absolute with an `extern` to C's `realpath(3)`; dwa's - `Docs.canonical` does `setWorkDir`, `workDir` and `setWorkDir` back, - which is wrong with threads. - - (* Adds to b the absolute path of the file at path, with no ".", - "..", or symbolic link in it: 0, or minus an errno (-2, ENOENT, - if a part of it isn't there). *) - proc realPath*(path: []U8; var b: Buf.Buf): INT; - - About 40 lines over `workDir`, `linkInfo` and `readLink`, with a - bound on links followed (-40, ELOOP). Met in surco, dwa. - **Recommendation:** take, two programs and the workaround is wrong. - -- **Removing a tree.** A sauce clone cut short leaves - `.sauce-clone`, since removing a tree is a walk of `openDir`, - `remove` and `removeDir`; a test that makes a directory to work in - has the same walk to clean up. - - (* Removes the file at path and, if it is a directory, all within - it, without following a symbolic link: 0, or minus the first - errno. *) - proc removeTree*(path: []U8): INT; - - Over `openDir`, `entryKind`, `linkInfo`, `remove` and `removeDir`, - about 30 lines. Met in sauce. **Recommendation:** take, easy to get - wrong (a link to a directory followed) and wanted by every test with - a scratch directory. - -## Sys for signals and the process - -**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`. - -Library growth that breaks no program. The first three are in both -`Sys` backends; the last is in `Rt`. - -- **Whether a signal is ignored.** A program started in the - background or under `nohup` starts with some signals ignored, and - should leave those alone, as a shell does, rather than `handle` or - `catch` them. `handle` and `ignore` don't say what was there, so - robbie asks the kernel through `rt_sigaction` in an `Rsig.linux.raz`. - - (* Whether the signal sig does nothing now, as ignore(sig, true) - or the program that started this one left it. *) - proc ignored*(sig: INT): BOOL; - - C's `sigaction` with no new action; system call 13 the same. - Independent of `keepIgnored` in "Sys for running a program", which is - about the child. Met in robbie. **Recommendation:** take, any - program that takes SIGINT or SIGHUP should ask it first. - -- **An environment variable unset or empty.** `env` gives `""` for - both, but `TZ` unset means `/etc/localtime` and `TZ=` means UTC, so - alba and rzone walk `envAt` themselves. - - (* The value of the environment variable name and true, or "" and - false if it isn't set. *) - proc findEnv*(name: []U8): ([]U8, BOOL); - - `env` stays, written over it. Met in alba, rzone, surco. - **Recommendation:** take, three programs walk `envAt` for it. - -- **How many processors.** `raztest -j` would default to it, as - `make -j$(nproc)` does, and defaults to 1; rayo makes - `SYSCALL(204)` itself. - - (* The number of processors this program may run on, at least 1. *) - proc processors*: INT; - - C's `sched_getaffinity` and `CPU_COUNT`; system call 204, counting - the bits. Moss's gives 1. Met in raztest, rayo. - **Recommendation:** take, two programs and no portable way without it. - -- **How the program ends, for `atExit`.** A procedure `Rt.atExit` - registered can't tell an end by `exit(0)` from a failed check or - `Rt.stop`, so surco's log can't note a crash. - - (* The status exit was given, while the procedures atExit - registered run; 0 before. *) - proc exitStatus*: INT; - - `Rt.exit` sets it before running them. A failed check and `stop` - both end with 2, which is enough to note a crash. Met in surco. - **Recommendation:** take, three lines and nothing else can say it. - -## Numbers in the library - -**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. - -### An unsigned decimal reader: `Str.toU64` - -Library growth that breaks no program. `Str.toInt` stops at the largest -`I64`, so a `U64` written by `Fmt.uint`, such as a `Rand.seed` read back -from `$PROP_SEED`, needs a loop of its own (raz's own `Prop.decimal`). -`toHex` already gives a `U64`; decimal should too: - - (* s as a decimal number, digits only; false if it isn't one, or a - U64 can't hold it. *) - proc toU64*(s: []U8): (U64, BOOL); - -No sign: a `-` is no `U64`, and a `+` nobody writes. `Opt.number` -stays on `toInt`. - -Met in raz's `Prop`. - -**Recommendation:** take; it is the reader for what `Fmt.uint` writes. - -### `ABS`, and `min`, `max` and `clamp` of integers - -**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. - -Library and language growth that breaks no program. `Math` is `F64` -only and there are no built-ins, so rat writes `min` and `max` in Draw, -Font, Layout and Shapes, `abs` in Shapes and `clamp` in Rat; raudio's -Tags and rabble's Remote the same; mgla and fraco each write a 4-line -`abs` of an `F64`. - -The proposal, in two parts. A built-in, as Oberon has it, for every -numeric type, since one name serves integers and reals and no -procedure can: - -| Call | Result | -|---|---| -| `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 | - -And three procedures in `Math`, of `INT`, the type that indexes and -counts: - - (* The smaller of a and b. *) - proc min*(a, b: INT): INT; - (* The larger of a and b. *) - proc max*(a, b: INT): INT; - (* x, or lo if it is below lo, or hi if it is above hi. *) - proc clamp*(x, lo, hi: INT): INT; - -`MIN` and `MAX` are taken for a type's limits ("The limits of an -integer type"), so these are lower-case procedures, not built-ins. -`Math`'s opening line then says "and `min`, `max` and `clamp` of -`INT`". Left out: the same of `F64`, which no program asked for. - -Open: `ABS` touches the report (6.8's table), so it may move to -the language proposals, beside `MIN(T)` and `MAX(T)`. - -Met in rat, raudio, rabble, mgla, fraco. - -**Recommendation:** take; five programs write the same four lines. - -### `Math.tanh` - -Library growth that breaks no program. `Math`'s header leaves the -hyperbolic functions out "until a program needs them"; mgla soft-clips -its mix with tanh, written `1 - 2/(exp(2x)+1)`, which loses every digit -near 0. - - (* The hyperbolic tangent of x, from -1 to 1. *) - proc tanh*(x: F64): F64; - -fdlibm's, over a private `expm1` (which `Math.pow` and `exp` already -come close to). `sinh` and `cosh` stay left out, as the header says, -until a program needs them. - -Met in mgla. - -**Recommendation:** take; the header's own rule says when, and mgla is it. - -### Rounding a half to even: `Math.roundEven` - -Library growth that breaks no program. `Math.round` takes a half away -from 0, as C's `round` does: `round(2.5)` is 3.0. Pascal's `Round`, and -IEEE 754's default, take it to the even one, 2.0, and a program that -must give Pascal's numbers (alba's, raudio's `Sbr`) writes its own, -where the case of `x + 0.5` rounding up is easy to get wrong. - - (* The whole number nearest x; a half to the even one, as IEEE 754's - default and Pascal's Round have it. *) - proc roundEven*(x: F64): F64; - -Met in alba and raudio. - -**Recommendation:** take; two programs, and the edge cases are subtle. - -### The fewest digits that read back: `Fmt.short` - -Library growth that breaks no program. `Fmt.real(x, places)` writes a -fixed number of places; nothing writes a real as briefly as it can be -written and still read back as itself. arkusz carries 150 lines for it -(`Afmt`: base-10^9 big numbers, and the halves to the neighbouring -`F64`s); fraco writes its own decimals for a deep zoom's centre, which -needs up to 17 places; alba prints coordinates. - -A case of `Arg`: - - (* r in the fewest digits that Math.toReal reads back as r; with an - exponent below 1E-4 and from 1E15 on, as real writes one. *) - short(r: F64); - -The result is unique (Steele and White; Ryu's answer). It costs a -correctly rounded conversion, so about arkusz's 150 lines, moved into -`Fmt`; `Fmt.real` keeps its own fast path. - -Left out: arkusz's exact 17-digit expansion (`sci(x, digits)`), which -`short` makes unneeded for the round trip, and rounding the 17-digit -text again as Pascal's `Str` does, which gives `45.1603` for -`Fmt.real(45.16025, 4)` where the binary value, below the half, gives -`45.1602`: that is Pascal's double rounding, not a fault in `Fmt`. - -Met in alba, arkusz and fraco. - -**Recommendation:** take; three programs, and the hard part is the -library's to do once. - -### One exponent letter: `Fmt` writes `E` - -**Status.** Approved by the owner on 2026-10-22 and implemented in `lib/Fmt.raz`. - -A change to output. `Fmt.real` writes `1.50e17`; the language reads a -real's exponent as `E` only (report section 2), so a value a program -prints can't be pasted into code (rayo). `Math.toReal` reads both. - -The proposal: `Fmt` writes `E`, as the report's own numbers are -written, `1.50E17`. Reading `e` in the compiler instead would add a -spelling to the report. A test that compares printed exponents changes -by one letter; raz's own `Fmt` test is one. - -This settles the open question in "A width in `Fmt`". - -Met in rayo. - -**Recommendation:** take; one letter for the language and its library. - -## Memory, Buf and Vec - -**Status.** Proposed 2026-10-22, collated from RAZ-GAPS.md. - -### An allocator that stops when memory runs out: `Heap.sure` - -**Status.** Approved by the owner on 2026-10-22 and implemented in `lib/Heap.raz`. - -Library growth that breaks no program. `Buf` and `Vec` stop the program -when the allocator has no room; `NEW(p, Heap.heap)` and `Mem.alloc` -give `nil`, so rat checks and stops in about a dozen places. A -procedure that allocates or stops can't be written for every `T`, but -an allocator can, and `NEW` is already generic: - - (* The heap, but running out of memory stops the program, as - Buf.add does, instead of giving nil: for NEW where nil would be - a bug nobody checks for. *) - sure*: ^Mem.Allocator; - -`NEW(p, Heap.sure)` then gives a `p` or stops, with `Rt.trace`. Its -`free` is the heap's. Ten lines, and nothing new to learn. - -Met in rat. - -**Recommendation:** take; one variable makes every `NEW` safe without a -check at each. - -### Freeing back to a mark: `Arena.mark` and `Arena.release` - -**Status.** Approved by the owner on 2026-10-23 and implemented in `lib/Arena.raz`. - -Library growth that breaks no program. `Arena` frees only everything at -once, so fdn's recursive walk, which makes a few strings per entry, -gives each back to the heap by hand. An arena that goes back to where -it stood gives one line per level: - - (* Where ar stands now, for release. *) - proc mark*(const ar: Arena): INT; - - (* Everything allocated from ar since mark m freed at once; a mark - past where it stands stops the program. *) - proc release*(var ar: Arena; m: INT); - -A mark is the arena's `used`, so each is a line. `reset` is -`release(ar, 0)`, and stays for its name. - -Met in fdn. - -**Recommendation:** take; two lines in `Arena` replace a free per string. - -### Inserting and removing in the middle of a `Vec` - -**Status.** Approved by the owner on 2026-10-23 and implemented in `lib/Vec.raz`. - -Library growth that breaks no program. dwa's edit takes lines out and -puts others in by resizing around a `COPY` by hand, twice, where the -overlapping copy's direction is the thing to get wrong. - - (* n zero elements opened at i, those from i on moved up; i from 0 - to v.len. Stops the program, as push does, if there is no room. *) - proc insert*(var v: Vec; i, n: INT); - - (* The n elements from i taken out, those after them moved down; - i + n at most v.len. *) - proc remove*(var v: Vec; i, n: INT); - -`insert` gives zeros, as `add` and `resize` do, for the caller to fill -in `all(v)[i..i + n]`. Left out: a `tryInsert`, until a program wants -one. - -Met in dwa; any editor's lines, and a list kept in order, want it. - -**Recommendation:** take; it is the one `Vec` operation that is easy to -get wrong by hand. - -## Strings, base64 and text for C - -**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`. - -### A slice of a C string, and a C string of a slice - -Library growth that breaks no program. C gives a `^U8` ending in a zero -byte (an X resource's value, a class hint's name), which awizo counts -by hand to make a `[]U8`. The other way, a path for C's `open` or -`realpath` must be followed by a zero, which callers copy into a -`[PathMax + 1]U8` by hand. - - (* The bytes at p up to its zero byte, not copied; "" for nil. *) - proc fromC*(p: ^U8): []U8; - - (* s copied into out with a zero byte after it, for C: out holds - LEN(s) + 1 bytes at least. *) - proc toC*(s, out: []U8): ^U8; - -`toC` gives `PTR(out)`, so the call reads as what C is given: -`C.realpath(Str.toC(path, room), ...)`. `out` too short stops the -program, as a slice does. Left out: a `CStr` type, which would say in -a signature that a zero follows; that is a language question, and -`Sys` takes `[]U8` already. - -Met in awizo and surco; every binding to a C library meets both. - -**Recommendation:** take; the two ends of every C call that takes or -gives text. - -### Base64 in another alphabet, unpadded - -Library growth that breaks no program. `Str.base64` has RFC 4648's -section 4 alphabet, padded. Section 5's, `-` and `_` and no padding, is -PKCE's and JWTs', and IMAP's modified UTF-7 is `,` for `/`, unpadded: -roauth carries 13 lines over `Str.base64`, rimap 40 of hand-packed -6-bit letters. "Base64 in `Str`" left this out until a program needed -it; two do. - - const - (* The alphabets of RFC 4648, sections 4 and 5. *) - Base64* = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - Base64Url* = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; - - (* s in base64 with the 64 letters of alphabet into out, which - holds base64Size(LEN(s)) bytes at least, padded with = if pad: - the bytes written. *) - proc base64With*(s, out, alphabet: []U8; pad: BOOL): INT; - - (* s decoded as base64With wrote it, into out, which holds - (LEN(s) + 3) div 4 * 3 bytes at least: the bytes written; false - as unbase64 says, or, without pad, for a length that leaves one - letter over. *) - proc unbase64With*(s, out, alphabet: []U8; pad: BOOL): (INT, BOOL); - -`base64` and `unbase64` become `base64With(s, out, Str.Base64, true)` -and stay, for the common case. rimap passes its own alphabet. - -Met in roauth and rimap. - -**Recommendation:** take; two programs, and the existing proposal named -this as the way to grow. - -### Formatting into a caller's slice: `Fmt.into` - -Library growth that breaks no program. `Fmt.write` goes only to a -`Buf`, which needs an allocator, so a library with no heap (rxml, for -"... on line 12"; rttf and magma are the same kind) joins pieces by -hand with `Str.fromInt`. `Buf` says the core has no heap to assume; -`Fmt` should then work without one. - - (* f formatted into out as write formats it: the bytes written, and - false if out was too short and the text is cut there. *) - proc into*(out: []U8; f: []U8; args: []Arg): (INT, BOOL); - -Cut short, not stopped: the length of formatted text isn't known -before, as base64's is. Inside, `put` writes to a target that is a -`Buf`, a slice, or standard output, in place of today's `^Buf.Buf` or -`nil`. - -Met in rxml. - -**Recommendation:** take; it makes `Fmt` usable in the no-heap core -`Buf` itself is written for. - -## `Opt` - -**Status.** Approved by the owner on 2026-10-23 and implemented in `lib/Opt.raz`, both. - -### A negative number as an operand - -A change to what `Opt` reads, for scopes it can't hurt. `alba -33.87 -151.21` is "unknown option -3", and `--` changes the command line the -user types, so alba reads its arguments by hand and loses `Opt`'s help -and mistakes. - -The proposal: in a scope with no option whose letter is a digit, a -word of a `-` and then a digit is an operand, and so ends the options -as any operand does. A scope that gives a digit a letter (`head -5` -style) reads it as today. No new procedure; the library volume's list -of rules gains a line. - -Met in alba. - -**Recommendation:** take; one rule, no interface, and it lets a numeric -program keep `Opt`. - -### A mistake in the operands, with the synopsis: `Opt.misuse` - -Library growth that breaks no program. `Opt.fail` writes the program's -sentence alone, for "no command; see keep -h". The one that adds the -synopsis lines, as `Opt`'s own mistakes and `refuse` do, is the private -`mistake`, so raztest's "no tests named", a mistake in the operands, -comes without the usage a user needs. - - (* The program's own mistake, written as Opt's are, with the - scope's synopsis lines after it, and status 2. *) - proc misuse*(const p: Parser; text: []U8); - -It is `mistake` with `text` as its one argument. A flag on `fail` -would read worse at the call. - -Met in raztest. - -**Recommendation:** take; three lines, and no workaround without -copying the table's synopsis by hand. - -## A freestanding program, stated - -**Status.** Proposed 2026-10-22, collated from RAZ-GAPS.md. - -"For a kernel: three changes to the compiler" made a raz program run on -the bare machine; Moss, a kernel in raz, now boots on it. What it found -is less a missing feature than missing words: what a `-bare` program -must give the compiler, and what it may count on, are known only by -reading `Gen.entryPoint` and `Raz`. Five items, each standing alone. -The sixth thing Moss met, `jmp rax` read as a jump to a label, was a -bug, fixed in ac3c464. - -**1. The runtime ABI, written down.** A section of `doc/compiler.md`, -"A program with its own `Rt`", saying what the compiler asks of `Rt` -and what a program's start may count on: -- **Required:** `proc exit*(status: INT);`, which never returns (the - compiler puts `ud2` after its call), and - `proc fail*(what, a, b, len: INT; at: UINT; name: ^U8; rdi, rsi: UINT);`, - with the kinds of `what` as `lib/Rt.raz` gives them (0 an index, 1 a - slice, 2 an enumeration, 3 a backward slice of a pointer, 4 a nil - pointer, 5 a division by zero, 6 a stack overflow, 7 a view), named - constants in the text, not bare numbers. -- **Optional, found by name when declared:** `places`, `calls`, - `teller`, `place`, `placer` (item 5), `startProfile` and `profiler` - (never under `-bare`), `cExit` (only with C, which `-bare` refuses). -- **The entry:** `_start` runs every used module's body but `Rt`'s, - then `main`. Under `-bare` it reads nothing from the stack and aligns - nothing: the loader or boot stub enters it with the bss zeroed and - `rsp` a multiple of 16, as Linux does. -- **`main` returning:** allowed. `Rt.exit` is then called with `main`'s - result, or 0 for `proc main*`. -- **The panic hook:** `Rt.fail` is it. A kernel's `fail` prints and - halts; nothing else is needed, and no second hook is proposed. - -A test holds it: `test/run/` builds a `-bare` program against a -smallest `Rt` of `exit` and `fail` alone, run under Linux, whose -`exit` and `fail` make the system call themselves. - -Met in Moss (`docs/raz-findings.md` §2), which copied the stock -signatures. - -**Recommendation:** take; it is words and one test, and the contract -already exists. - -**2. A recipe for an interrupt's entry.** Before any attribute or -generated stub, a tested recipe in `doc/compiler.md`, beside item 1, -stating what the compiler's code may assume and so what a stub must -restore: -- **What the compiler's code uses:** System V's caller-saved - registers, `rax`, `rcx`, `rdx`, `rsi`, `rdi`, `r8` to `r11`, all of - `xmm0` to `xmm15`, and the flags; the direction flag is clear at - every call (the compiler's copies use `std` and `cld` and leave it - clear). -- **The red zone:** whether the compiler ever writes below `rsp`. Not - checked today ("For a kernel" leaves it open); it is to be checked - and the answer written down. If it never does, an interrupt needs no - IST stack for that reason. -- **The stub:** a `code` procedure per vector that pushes 0 where the - CPU pushes no error code, pushes the vector, saves the caller-saved - registers, aligns `rsp` to 16, saves the SSE state (`fxsave` or - `xsave` to an aligned area), `cld`, calls an ordinary procedure - `proc handle(vector, code: INT; frame: ^Frame)`, restores, drops the - two words and `iretq`. - -It is testable on Linux: `iretq` from ring 3 to ring 3 is allowed, so -`test/run/Interrupt.raz` builds a frame by hand, jumps to the stub, has -the handler compute with reals, and checks on return that every -register the stub promised to keep is kept. The stub needs items 3 and -"The assembler's instructions", 1 (`push` of a constant, `cld`). - -Met in Moss (`docs/raz-findings.md` §4): its handlers use only `rax` -and make no call, which is safe but no recipe. - -**Recommendation:** take; a kernel's first stub is where the calling -convention is easiest to get wrong, and a test on Linux keeps it right. - -**3. A code procedure names a procedure or a global.** In a code -procedure, a name of the module's scope, or a qualified one, that is a -procedure or a global variable stands for its address, as an operand -of three forms only: - - call fault; (* a procedure, rip-relative *) - jmp fault; - lea rax, [ticks]; (* a procedure or a global *) - -Each makes a reference to that chunk, so the linker keeps what is -named, as any call does. No other operand takes a name, and no type is -checked: a code procedure is the target's, and its author already -answers for the convention. The assembler gets the names as it gets -constants, by a function the parser hands in beside `ConstFn`. - -Moss stores `UINT(fault)` in a slot at start and calls through a -register (`docs/raz-findings.md` §5), so the slot must be filled -before the first fault, which nothing checks. - -**Recommendation:** take; three operand forms remove a hand-off that -can be forgotten, and the recipe in item 2 needs `call handle`. - -**4. A program brings its own `Rt`.** A `src/Rt.raz` beside the main -module meets `lib/Rt.raz`, and "a program has one module of each name" -refuses it, rightly. Moss copies the compiler beside an empty `lib/`. -Two ways out: -- **Staging,** as "The compiler on another host" proposes for the - compiler's own sources: copy `raz` beside a library of the program's - own. Nothing in raz changes; only words in `doc/compiler.md`. Every - freestanding project then carries a copied compiler, and its library - is all or nothing. -- **`raz -lib DIR`:** the library is `DIR`, not the one beside the - compiler. A kernel's `-lib` is a directory holding its own `Rt` and - `Sys` and, by symbolic links, whichever of raz's modules it takes - (`Str`, `Fmt`, `Buf`). The duplicate check stays as it is. On the - `Host` branch it is one line over `Host.libraryDir`; today a few - lines in `Raz.raz` and raz(1). - -The option is the smaller for its users and nearly as small in raz; -staging stays the way for the compiler on another host, where the -whole of `src/` is replaced anyway. - -**Recommendation:** take `-lib`; a few lines save every freestanding -program a copy of the compiler. - -**5. Symbols without `Rt`'s places.** Without `-s` the compiler links -`places`, `calls`, `teller`, `place` and `placer` and stops with "Rt -has no places" where `Rt` lacks one, and `-noprofile` doesn't help, so -Moss builds with `-s` and loses the symbol table a debugger reads. -Two things are tied that needn't be: the ELF's symbols and lines, for -a debugger, and the places, for `Rt` to say where a check failed. -The change: each of the five is linked only when `Rt` declares it, -`calls` with `teller` and `place` with `placer`, a pair or neither; `-s` -still strips both. A kernel then keeps its symbols for GDB and gives -`fail` the raw address, or declares `places` and decodes them itself. - -A hosted program's `Rt` is raz's, which declares all five, so no -program changes. One that writes its own `Rt` and misspells `places` -loses its places silently; item 1 lists the names. - -Met in Moss (`docs/raz-findings.md` §3). - -**Recommendation:** take; it is a test on each name in `Raz.raz` and -gives a kernel its symbols back. - -## The assembler's instructions - -**Status.** Proposed 2026-10-22, collated from RAZ-GAPS.md. - -The report leaves which instructions the assembler knows to the -implementation, and `db` gives any other. That stays. What is missing -is a rule for when an instruction joins, and the few that programs -have already written in `db`. - -**1. `push` of a constant, and `cld` and `std`.** `push imm8` and -`push imm32` (6A, 68, sign-extended to 64 bits), and `cld` and `std` -in `Plain`. The encoder already writes `cld` and `std` for the -compiler's copies; only the assembler's table lacks them. Moss's -exception stubs write all three with `db`, and every stub of -"A freestanding program, stated", 2, needs them. - -**Recommendation:** take; three entries the encoder half has, and an -interrupt stub can't be written without them. - -**2. When an instruction joins, and the SHA and shuffle ones now.** -The rule, in `doc/compiler.md` beside the assembler: an instruction -joins when a program writes it in `db`, it is a family's member the -tables already hold (a code in `PackedOps`, an entry in `Plain`), and -its bytes are checked against GNU `as` in `test/run/`, as -`AsmKernel.raz` does. Anything else stays `db`, which is the permanent -answer for an instruction no program uses twice. By that rule, now: -- `paddd`, `punpcklqdq`, `punpckhqdq` into `PackedOps` (66 0F FE, 6C, - 6D); -- `pshufb` (66 0F 38 00) and `palignr` (66 0F 3A 0F, with a byte), - two more forms, three-byte opcodes; -- `sha256rnds2` (0F 38 CB, `xmm0` implied), `sha256msg1` (0F 38 CC), - `sha256msg2` (0F 38 CD). - -Sauce's SHA-NI hash is 123 `db` lines assembled by GNU `as`, nothing -checking a byte against its mnemonic; with these it is read as written. -AES-NI, `pclmulqdq`, AVX and the rest wait for a program. (`movd` and -`movq`, `pxor`, `pshufd`, `movdqu`, `movdqa`, `pmovmskb` are there -already.) - -**Recommendation:** take; a rule stops the list growing by wish, and -eight instructions turn sauce's 123 unchecked lines into checked ones. - -**3. `raz -S`'s listing, stated.** raz(1) gives the listing's form, so -a tool may read it: -- a blank line, then a procedure's name as `Module.name:`; -- a source line: its number right-aligned in 6 columns, two spaces, - the line's text; -- an instruction: its offset in the procedure right-aligned in 14 - columns, two spaces, the instruction as the assembler would read it, - a jump within the procedure giving its target as an offset. - -Only the main module's live procedures, in the order they were made; -nothing is disassembled. A change to the form is then a change to the -manual, and rcrypto's constant-time guard (`tools/branches.sh`), which -counts conditional jumps by reading these three kinds of line, breaks -loudly instead of silently. A test in raz holds the form against a -small program's listing. - -**Recommendation:** take; it is a paragraph of raz(1) and one test, -for a form that already doesn't change. - -## `Doc` for a library's pages - -**Status.** Approved by the owner on 2026-10-23 and implemented in `tools/Doc.raz`, both. - -`tools/Doc.raz` writes raz-lib(3) from `lib/`, and other libraries -have started to use it for their own pages. Two changes let them. - -**1. A comment that heads a group of constants.** A comment just -before `const`, `type` or `var`, on lines of its own, is the group's: -`Doc` writes it once, before the group's declarations, as it writes a -module's own comment, and each declaration keeps the comment just -before it as now. Today `section` reads past the keyword and drops it -(checked: each constant then shows alone), so mosaico's `Mxlib` has a -comment line for each of its 237 constants where one before each group -would halve the file. In mdoc the group's comment is filled text before -the literal display; in plain text, the comment as written. - -**Recommendation:** take; a few lines in `section` keep a comment the -standards already ask for. - -**2. `Doc man` writes the modules, not the page.** Today it writes -raz-lib(3)'s `.Dd`, `.Dt`, NAME, DESCRIPTION and SEE ALSO, fixed in the -tool, and a `Date` constant in `Doc.raz` dated by hand. The change: -`Doc man Module.raz ...` writes only what is now between `.Sh MODULES` -and `.Sh SEE ALSO`; raz's `Makefile` puts the head and tail around it -from `doc/raz-lib.head` and `doc/raz-lib.tail` (or one file with a -marker line), and the date lives with the page, not the tool. rcrypto's -`tools/man3.sh`, which cuts Doc's page between the two `.Sh` lines and -sets its own around it, then just wraps it, as raz does. Title, name -and description from the command line were the other way; three -options to replace two small files is the larger. - -**Recommendation:** take; it makes `Doc man` serve any library, and -`Doc.raz` loses its fixed text and its date. - -## Left out - -What the collation of 2026-10-22 recommended leaving out, each with its -reason; it is marked "Not planned" in `~/r/RAZ-GAPS.md`. - -**Status.** Confirmed by the owner on 2026-10-23, but for the exported -array, parked with `[]const T`. - -### The language - - -- 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. -- 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. -- 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. -- No type of its own for an array — a one-field record keeps two hashes apart, as it keeps generic arrays (owner's idiom). -- 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. -- 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). -- An exported variable can't be assigned from outside — Oberon's read-only export; a setter shows who writes. -- 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. -- `I32` doesn't widen to `INT` — `INT` may be 16 bits (5.1), so the widening would not hold everywhere. -- Common words are reserved — settled. -- 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. -- Every string a record keeps is freed by hand — no collector; an `Arena` per record frees all of them at once. -- 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. -- 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. -- 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. - -### Bits and bytes - - -- **`Buf` gives memory back unwiped.** — a program with secrets sizes - its `Buf` with `Buf.room` and calls `Tls.wipe(Buf.bytes(b))` before - `Buf.done`, as roauth does; a wipe in the library would duplicate - rnet's `Tls` backends. -- **No hash but FNV, and no wipe the compiler can't drop.** — hashing - and wiping go through rnet's `Tls` backends (`Tls.sha256`, - `Tls.wipe`); `Ws`'s SHA-1 and the two 8-line wipes in `Smtp` and - `Imapnet` move to `Tls` in rnet, and raz gains nothing. - -### Sys and Files - - -- No reserving address space — `mmap` of the most it will hold, then - `protect`, serves raudio; `MAP_NORESERVE` alone is not worth a - procedure. -- `Sys.openDir` gives no order — sorting the names is a few lines with - `Sort`, in the one program. -- No glob — one program (robbie), and which wildcards it takes is that - program's choice; a `*` over `openDir` is about 40 lines. -- A signal noted just before a `wait` doesn't break it — already - answered: `catch` SIGCHLD with the others and wait in `ready` on - catch's fd (child, signal or deadline at once), then `wait(pid, - false)`; `ignore(sig, false)` gives a caught signal its default back. - Worth a paragraph in the library volume (written there), not a procedure. -- No word from the kernel when a file changes — inotify is Linux's, - with no match in the C backend's other systems or Moss; a 300 ms - look serves. -- No sleep a signal breaks into — `ready(-1, ms)` is that sleep for - `handle`, and `ready` on catch's fd for `catch`. -- No sockets but streams and datagrams to addresses — netlink and HCI - are Linux's, for one program. -- No user's name — the password database with NSS needs the C - library, which mosaico links anyway. -- `Sys.rawMode` doesn't flush typed-ahead input — keys typed ahead are - usually meant for the program; flushing would lose them. -- No positional read (`pread`, `fadvise`) — `seek` then `read` serves - the one program; `fadvise` is a hint, fine as a `SYSCALL`. -- No `madvise` in `Sys` — `munmap` then `mmap` gives pages back. - -### Numbers, strings, memory and Opt - - -- No fixed-capacity string — one program, a record of a length and an array, three lines. -- `Math.toReal` refuses `.5` and `5.` — it reads reals as the language writes them, and arkusz's 3-line `withZeros` serves its one user. -- `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. -- `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. -- `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. -- `Opt` carries no completion words — completion is concha's, one program, and the table would grow for every user. -- A zero `Buf` or `Vec` isn't usable — deliberate: the core assumes no heap, and `init` says which allocator. -- Joining texts into a kept `[]U8` costs a `Buf` and a copy — `Str.join` then `Str.copy` is two calls, for one program. -- Case is ASCII only — Unicode case maps are large tables for one program; rrem has them. -- `Vec` gives no pointer to an element already in it — `Nodes.all(v)[k].next := m` already sets a field in place. -- No lenient base64 reader in `Str` — mail's junk is rmime's to handle; its 30 lines serve the one reader that meets it. -- `Check.int` takes `I64` — an `I32` widening to `I64` is the language's question, and one call site converts. -- `Rand` has no shuffle — `Rand` isn't generic, and Fisher and Yates over `below` is four lines. Confirmed by the owner, 2026-10-22. -- `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. - -### Freestanding programs and tools - - -- `Doc` fills a list. Done (owner, 2026-10-23), by lazy continuation: a - line starting with `- ` at a comment's margin begins a bullet, the - lines at the margin after it continue it, and a blank line or code - ends it, so an indented line is still code. diff --git a/README.md b/README.md index 94e4328..758f5e1 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,6 @@ | `conform/` | The conformance suite: what every implementation must do | | `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 | | `test/` | This compiler's own tests, and the scripts that run them | -| `PROPOSALS.md` | What the language might have, waiting for a later thaw | ## Building @@ -307,9 +306,10 @@ defect, and the library grows only by what breaks no program. A library change that must break programs keeps the old form for one minor version beside the new; the release notes list the old forms, and the next -version removes them. Wishes -wait in `PROPOSALS.md`, for a later thaw; v0.6.0 was one, for a -language anyone can build again from its report. +version removes them. Thaws, by the owner's word, changed it since; +the last, for safety, was v0.24.0. After the Moss work (v0.25.0) it is +frozen hard: no more thaws, the language mended only where it does +other than the report says. ## Not here diff --git a/doc/compiler.md b/doc/compiler.md index 2607fc0..93f8a90 100644 --- a/doc/compiler.md +++ b/doc/compiler.md @@ -941,8 +941,8 @@ ## Inlining a procedure that only returns A call of a procedure whose body is only `return e`, with no locals, -is made in place of the call, as PROPOSALS.md's "Inlining a procedure -that only returns" has it. One pass keeps no tree to copy, but it can +is made in place of the call, as the proposal "Inlining a procedure +that only returns" had it. One pass keeps no tree to copy, but it can read source again, as `while` reads its condition again: `body` notes such a procedure (`onlyReturns`), keeping in its `Obj` an `Inline` (`Sym.raz`): the scanner's state at the `return`, its file, whether diff --git a/src/README.md b/src/README.md index c5ccbba..0bfea20 100644 --- a/src/README.md +++ b/src/README.md @@ -110,7 +110,7 @@ same; whether the compiler built from this is slower for it is for the speed test of step 4 to say. A `const` parameter (a hint that the callee won't change it, so that the caller may pass its address) - would be a language change: it is in `../PROPOSALS.md`. (It came in + would be a language change. (It came in report 2026-10.33; since v0.20.0, built by v0.19.0, which has it, the routines that every program's compile goes through take their `Item` as `const`, measured, as `doc/compiler.md` says.)