Add bit operators, defer, list methods, rand, assert and rex test

- Bit operators & | ^ ~ << >> and their op= forms (Go precedence),
  plus hex, binary and octal literals (0xff, 0b1010, 0o755)
- defer stmt / defer { ... }: runs when the block ends, last first,
  also on return, ?, break and continue
- List methods insert, remove, clear, contains, index_of, reverse,
  sort and sort_by (stable merge sort)
- rand module: int(a, b), float(), seed(n)
- assert(cond[, msg]) and `rex test`, which runs each test_ function
  in its own process
- rex.toml marks a project's top folder: imports count from there
- Docs, formatter, LSP completions and editor grammars updated

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Your NameandClaude Opus 5.5 committed 2026-11-12 23:30:05 +01:00
1 parent 910bde692a
commit 300d767124
28 files changed
+1373 -65

No files matched your search

+47
View File
@@ -129,4 +129,51 @@ func main() {
11
```
## `defer`: clean up at the end
`defer` puts a line aside and runs it when the block it is in ends, however it ends: at the
closing `}`, at a `return`, at a `?` that passes an error up, or at `break` / `continue` in a
loop. Use it to keep the cleanup right next to the thing that needs it.
```rex
func process(name: string): error {
print("open", name)
defer print("close", name) // runs last, whatever happens below
if name.ends_with(".tmp") {
return error("{name}: skipped")
}
print("work on", name)
return nil
}
func main() {
var err = process("a.txt")
err = process("b.tmp")
print(err)
}
```
```text
open a.txt
work on a.txt
close a.txt
open b.tmp
close b.tmp
b.tmp: skipped
```
- Several `defer`s run in reverse: the last one written runs first (close in the opposite
order you opened).
- `defer { ... }` runs a whole block.
- The deferred code sees the variables as they are **when it runs**, not when `defer` was written.
- In a loop body, it runs at the end of every round.
- `return`, `?` and `break` can't be used inside the deferred code itself: it runs while
the block is already finishing.
- It is most useful with things you must close by hand, like files from C libraries:
```rex
var f = stdio.fopen(path, "r")
if f == nil { return error("can't open {path}") }
defer stdio.fclose(f)
```
Next: [Lists and maps](05-lists-and-maps.md)