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:
1 parent
910bde692a
commit
300d767124
28 files changed
+1373
-65
No files matched your search
@@ -77,6 +77,51 @@ Rules worth remembering:
|
||||
- A number literal adapts to the type it is used with (`var b: u8 = 5`).
|
||||
- Dividing by zero stops the program with a clear message.
|
||||
- Converting a float to an integer cuts off the decimals.
|
||||
- Whole numbers can be written in hex, binary or octal: `0xff`, `0b1010`, `0o755`.
|
||||
`_` may separate digits: `1_000_000`.
|
||||
|
||||
### Bits
|
||||
|
||||
For flags, colors, hashes and file formats, whole numbers have bit operators:
|
||||
|
||||
| | | |
|
||||
|--|--|--|
|
||||
| `a & b` | and | bits set in both |
|
||||
| `a \| b` | or | bits set in either |
|
||||
| `a ^ b` | xor | bits set in one but not the other |
|
||||
| `~a` | not | every bit flipped |
|
||||
| `a << n` | shift left | same as `a * 2ⁿ` (bits pushed out are lost) |
|
||||
| `a >> n` | shift right | same as `a / 2ⁿ`, rounding down |
|
||||
|
||||
Each has an assignment form too: `&= |= ^= <<= >>=`.
|
||||
|
||||
```rex
|
||||
const BOLD = 0b001
|
||||
const ITALIC = 0b010
|
||||
const UNDERLINE = 0b100
|
||||
|
||||
func main() {
|
||||
var style = BOLD | UNDERLINE
|
||||
print(style & ITALIC != 0, style & UNDERLINE != 0)
|
||||
style ^= BOLD // switch bold off
|
||||
print(style)
|
||||
|
||||
var color: u32 = 0xff8800
|
||||
var red = color >> 16 & 0xff
|
||||
var green = color >> 8 & 0xff
|
||||
print(red, green, 1 << 10, ~0)
|
||||
}
|
||||
```
|
||||
```text
|
||||
false true
|
||||
4
|
||||
255 136 1024 -1
|
||||
```
|
||||
|
||||
- `&` and the shifts bind like `*`, `|` and `^` like `+`, so `x & 1 == 0` means `(x & 1) == 0`.
|
||||
- They work on whole numbers only (`int`, `u8`, ...). For `bool` use `&&` and `||`.
|
||||
- Shifting by the number's width or more gives 0 (or -1 for `>>` of a negative number);
|
||||
shifting by a negative amount stops the program.
|
||||
|
||||
## Strings
|
||||
|
||||
|
||||
@@ -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)
|
||||
@@ -30,6 +30,68 @@ func main() {
|
||||
61
|
||||
```
|
||||
|
||||
### More list methods
|
||||
|
||||
```rex
|
||||
func main() {
|
||||
var xs = [5, 3, 9]
|
||||
xs.insert(0, 7) // put 7 at position 0; the rest move up
|
||||
print(xs)
|
||||
print(xs.remove(1), xs) // take out the item at position 1 and get it
|
||||
print(xs.contains(9), xs.index_of(9), xs.index_of(4))
|
||||
xs.sort()
|
||||
print(xs)
|
||||
xs.reverse()
|
||||
print(xs)
|
||||
xs.clear()
|
||||
print(xs, xs.len())
|
||||
}
|
||||
```
|
||||
```text
|
||||
[7, 5, 3, 9]
|
||||
5 [7, 3, 9]
|
||||
true 2 -1
|
||||
[3, 7, 9]
|
||||
[9, 7, 3]
|
||||
[] 0
|
||||
```
|
||||
|
||||
| | |
|
||||
|--|--|
|
||||
| `xs.push(v)` / `xs.pop()` | add at the end / take the last one |
|
||||
| `xs.insert(i, v)` | put `v` at position `i` (`i` may be `xs.len()`, the end) |
|
||||
| `xs.remove(i)` | take out the item at `i` and give it back |
|
||||
| `xs.clear()` | remove everything |
|
||||
| `xs.contains(v)` / `xs.index_of(v)` | is it there? / its first position, or `-1` |
|
||||
| `xs.reverse()` | turn the list around |
|
||||
| `xs.sort()` | smallest first (numbers, `char`s, strings A-Z) |
|
||||
| `xs.sort_by(less)` | your own order: `less(a, b)` says whether `a` goes before `b` |
|
||||
|
||||
`contains` and `index_of` work where `==` does (numbers, strings, `char`, `bool`, enums
|
||||
without data). For structs, sort with `sort_by`:
|
||||
|
||||
```rex
|
||||
struct Player {
|
||||
name: string
|
||||
score: int
|
||||
}
|
||||
|
||||
func main() {
|
||||
var ps = [Player{"ann", 30}, Player{"bob", 50}, Player{"cy", 30}]
|
||||
ps.sort_by((a, b) => a.score > b.score) // highest first
|
||||
for p in ps {
|
||||
print(p.name, p.score)
|
||||
}
|
||||
}
|
||||
```
|
||||
```text
|
||||
bob 50
|
||||
ann 30
|
||||
cy 30
|
||||
```
|
||||
|
||||
Sorting is **stable**: items that compare equal keep their order (ann stays before cy).
|
||||
|
||||
Facts:
|
||||
- An empty list needs a type: `var xs: []int`.
|
||||
- Going outside the list (`nums[9]`) or popping an empty list stops the program with a message.
|
||||
|
||||
@@ -42,6 +42,26 @@ func main() {
|
||||
- Every file has its own names, so two files can both define `helper`.
|
||||
- Import loops and missing files are errors. An error message names the file it is in.
|
||||
|
||||
## Bigger projects
|
||||
|
||||
When a project has several folders, put an empty file named `rex.toml` in its top folder.
|
||||
Every import is then counted from that folder, in every file, wherever the file sits:
|
||||
|
||||
```text
|
||||
Klein/
|
||||
rex.toml
|
||||
engine/engine.rex
|
||||
game/app/main.rex
|
||||
```
|
||||
|
||||
```rex
|
||||
import engine.engine // the same line works in game/app/main.rex and in any other file
|
||||
```
|
||||
|
||||
Rex finds the nearest `rex.toml` above the file you run (and above each file you open in an
|
||||
editor). Without one, imports are counted from the folder of the file you run, as above. With
|
||||
one, even a file next to your main file is imported with its full path (`import game.app.util`).
|
||||
|
||||
## Built-in modules
|
||||
|
||||
Import them like your own files: `import os`.
|
||||
@@ -79,6 +99,33 @@ func main() {
|
||||
|
||||
`time.now()` gives seconds as a float. `time.sleep(seconds)` waits.
|
||||
|
||||
### rand
|
||||
|
||||
| | |
|
||||
|--|--|
|
||||
| `rand.int(a, b)` | a whole number from `a` up to, **not including**, `b` (like `a..b`) |
|
||||
| `rand.float()` | a number from 0 up to, not including, 1 |
|
||||
| `rand.seed(n)` | start from a fixed point: the same seed gives the same numbers every run |
|
||||
|
||||
Without `rand.seed`, every run gives different numbers.
|
||||
|
||||
```rex
|
||||
import rand
|
||||
|
||||
func main() {
|
||||
var die = rand.int(1, 7) // 1 to 6
|
||||
print(die >= 1 && die <= 6)
|
||||
var hit = rand.float() < 0.25 // true one time in four
|
||||
print(hit == true || hit == false)
|
||||
}
|
||||
```
|
||||
```text
|
||||
true
|
||||
true
|
||||
```
|
||||
|
||||
Not for passwords or keys: it is fast, not secure.
|
||||
|
||||
### Strings
|
||||
|
||||
`upper lower trim split lines fields replace repeat contains starts_with ends_with
|
||||
@@ -104,6 +151,44 @@ xxx hello a+b
|
||||
|
||||
A list of strings can be joined: `["a", "b"].join("-")`.
|
||||
|
||||
## Testing
|
||||
|
||||
`assert(condition)` stops the program when the condition is false, with the line it is on.
|
||||
Add a message as a second argument: `assert(n > 0, "n is {n}")`.
|
||||
|
||||
Write tests as functions whose names start with `test_`, in any `.rex` file. They take
|
||||
nothing and return nothing, or an `error` (a returned error fails the test).
|
||||
|
||||
```rex
|
||||
func add(a, b: int): int {
|
||||
return a + b
|
||||
}
|
||||
|
||||
func test_add() {
|
||||
assert(add(2, 2) == 4)
|
||||
assert(add(-1, 1) == 0, "adding opposites")
|
||||
}
|
||||
|
||||
func test_parse(): error {
|
||||
var n = "42".to_int()?
|
||||
assert(n == 42)
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
`rex test` runs the tests in every `.rex` file in this folder and the folders below it
|
||||
(or `rex test file.rex`, `rex test folder`):
|
||||
|
||||
```text
|
||||
ok calc.rex: test_add
|
||||
ok calc.rex: test_parse
|
||||
|
||||
2 passed, 0 failed
|
||||
```
|
||||
|
||||
Every test runs on its own, so one that fails (or stops with a panic) doesn't stop the rest.
|
||||
What a failed test printed is shown under it. A file's `main` is not run by `rex test`.
|
||||
|
||||
## A program that reads input
|
||||
|
||||
```rex
|
||||
|
||||
+21
-5
@@ -5,14 +5,15 @@
|
||||
var x = 1 // changeable; type inferred
|
||||
var y: float = 2 // with a type
|
||||
const MAX = 100 // fixed
|
||||
x += 1 // also -= *= /= %=
|
||||
x += 1 // also -= *= /= %= &= |= ^= <<= >>=
|
||||
print("x is {x}", y) // interpolation with { }
|
||||
```
|
||||
|
||||
## Types
|
||||
`int float bool char string error` · sized: `i8 i16 i32 u8 u16 u32 u64 f32` · `[]T` list ·
|
||||
`map[K, V]` map · `T?` optional · `shared T` · `weak T` · `func(A, B): R` function.
|
||||
Convert numbers with `float(x)`, `int(x)`, `u8(x)`.
|
||||
Convert numbers with `float(x)`, `int(x)`, `u8(x)`. Literals: `1_000` `0xff` `0b1010` `0o755`.
|
||||
Bits: `a & b` `a | b` `a ^ b` `~a` `a << n` `a >> n` (`&` `<<` `>>` bind like `*`; `|` `^` like `+`).
|
||||
|
||||
## Control flow
|
||||
```rex
|
||||
@@ -35,6 +36,8 @@ var n, err = f()
|
||||
var n = f()? // inside a function that returns error
|
||||
var g = func(x: int): int { return x * 2 }
|
||||
var h = x => x * 2 // where the type is known
|
||||
defer f.close() // runs when the block ends (last defer first)
|
||||
defer { ... }
|
||||
```
|
||||
|
||||
## Lists
|
||||
@@ -42,6 +45,9 @@ var h = x => x * 2 // where the type is known
|
||||
var xs = [1, 2, 3] var e: []int
|
||||
xs.push(4) xs.pop() xs.len()
|
||||
xs[0] xs[0] = 9 xs[1..3]
|
||||
xs.insert(i, v) xs.remove(i) xs.clear() xs.reverse()
|
||||
xs.contains(v) xs.index_of(v) // -1 if missing
|
||||
xs.sort() xs.sort_by((a, b) => a.age < b.age) // stable
|
||||
```
|
||||
|
||||
## Maps
|
||||
@@ -116,10 +122,19 @@ var s: Shape = Circle{1.0}
|
||||
import utils // utils.rex next to this file
|
||||
import tools.fs // tools/fs.rex, used as fs.name
|
||||
import ..shared // ../shared.rex (...x = two folders up)
|
||||
import os // built-in: os math time
|
||||
// rex.toml in the top folder: imports count from there, in every file
|
||||
import os // built-in: os math time rand
|
||||
pub func f() {} // visible to other files
|
||||
```
|
||||
|
||||
## Testing
|
||||
```rex
|
||||
assert(x > 0) assert(x > 0, "x is {x}") // stops the program if false
|
||||
func test_add() { assert(add(1, 2) == 3) } // `rex test` runs every test_ function
|
||||
func test_load(): error { ... } // a returned error fails the test
|
||||
rand.int(1, 7) rand.float() rand.seed(42) // import rand; 1..6, 0..1
|
||||
```
|
||||
|
||||
## C libraries
|
||||
```rex
|
||||
import "zlib.h" // zlib.crc32(...), zlib.Z_OK, types like zlib.gzFile
|
||||
@@ -130,8 +145,9 @@ lib.fill(buf, n) // T* parameters take a variable or a list
|
||||
```
|
||||
|
||||
## Commands
|
||||
`rex run f.rex args…` · `rex build f.rex -o out` · `rex check f.rex` · `rex emit-c f.rex` · `rex fmt path` (`--check` to only report) · `rex lsp` (editor server) · `rex header x.h [word]` (what a C header offers)
|
||||
`rex run f.rex args…` · `rex build f.rex -o out` · `rex check f.rex` · `rex test [path]` · `rex emit-c f.rex` · `rex fmt path` (`--check` to only report) · `rex lsp` (editor server) · `rex header x.h [word]` (what a C header offers)
|
||||
|
||||
## Things that stop the program (exit code 2)
|
||||
Divide by zero · list index/slice out of range · `pop` on an empty list · reading a missing
|
||||
map key with `m[k]` · using a `nil` or gone `weak` value · calling a `nil` function or interface.
|
||||
map key with `m[k]` · using a `nil` or gone `weak` value · calling a `nil` function or interface ·
|
||||
a failed `assert` · shifting by a negative amount · `insert`/`remove` out of range.
|
||||
+2
-2
@@ -12,13 +12,13 @@ These notes teach it from zero. Read them in order, or jump to the
|
||||
| 1 | [First steps](01-first-steps.md) | Running a program, `print`, `main` |
|
||||
| 2 | [Values and types](02-values-and-types.md) | `var`, `const`, numbers, strings |
|
||||
| 3 | [Control flow](03-control-flow.md) | `if`, `for`, `match` |
|
||||
| 4 | [Functions](04-functions.md) | Parameters, results, closures |
|
||||
| 4 | [Functions](04-functions.md) | Parameters, results, closures, `defer` |
|
||||
| 5 | [Lists and maps](05-lists-and-maps.md) | Collections |
|
||||
| 6 | [Structs and enums](06-structs-and-enums.md) | Your own types, methods |
|
||||
| 7 | [Errors and nil](07-errors-and-nil.md) | `error`, `?`, `T?` |
|
||||
| 8 | [Memory](08-memory.md) | Copies, `shared`, `weak` |
|
||||
| 9 | [Generics and interfaces](09-generics-and-interfaces.md) | Code that works for many types |
|
||||
| 10 | [Files and the standard library](10-modules-and-stdlib.md) | `import`, `os`, `math`, `time` |
|
||||
| 10 | [Files and the standard library](10-modules-and-stdlib.md) | `import`, `os`, `math`, `time`, `rand`, tests |
|
||||
| 11 | [Cheatsheet](11-cheatsheet.md) | Everything on one page |
|
||||
| 12 | [A real program](12-calculator-walkthrough.md) | A calculator, split over five files |
|
||||
| 13 | [C and C++ libraries](13-c-libraries.md) | `import "raylib.h"`, your own C code |
|
||||
|
||||
Reference in new issue
Block a user