Files
rexlang/docs/11-cheatsheet.md
Your NameandClaude Opus 5.5 15da1e2379 Add a package manager: rex init/add/remove/get/update/deps
Packages come from git (a registry can be added later; a bare version in
rex.toml is reserved for it). rex.toml [deps] names them, rex.lock pins exact
commits, and run/build/check/test download what is missing. `import json`
reads the package's json.rex; package files get `@json...` module keys so they
never mix with the project's own files. Newest tag of the same major version
wins when packages disagree. The language server reads downloaded packages.
Docs: docs/14-packages.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 10:30:11 +01:00

157 lines
5.5 KiB
Markdown

# 11. Cheatsheet
## Basics
```rex
var x = 1 // changeable; type inferred
var y: float = 2 // with a type
const MAX = 100 // fixed
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)`. Literals: `1_000` `0xff` `0b1010` `0o755`.
Bits: `a & b` `a | b` `a ^ b` `~a` `a << n` `a >> n` (`&` `<<` `>>` bind like `*`; `|` `^` like `+`).
## Control flow
```rex
if a > b { } else if a == b { } else { }
for i in 0..10 { } // 0..9
for i in 0..10 step 2 { }
for x in list { }
for i, x in list { }
for k, v in map { }
for cond { }
for { break }
match v { 1 => a, _ => b }
```
## Functions
```rex
func add(a, b: int): int { return a + b }
func f(): (int, error) { return 1, nil }
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
```rex
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
```rex
var m = {"a": 1} var e: map[string, int] = {}
var e2 = map[string, int]{}
m["b"] = 2 // add or replace
m["b"] += 1 // missing key counts as zero
m["a"] // value; stops if missing
m.has("a") m.get("a") // bool, value-or-nil
m.get_or("z", 0) m.len() m.keys() m.values() m.remove("a")
```
## Strings
```rex
s.len() s.upper() s.lower() s.trim() s.split(",") s.lines() s.fields()
s.replace(a, b) s.repeat(n) s.contains(x) s.starts_with(x) s.ends_with(x)
s.index_of(x) s.to_int() s.to_float() s[1..4] s[2..] s[..3]
["a", "b"].join("-")
```
## Characters
```rex
var c = 'a' '\n' 'é' // one character, single quotes
c == 'a' c < 'z' // compare
c.is_digit() c.is_letter() c.is_alnum() c.is_space() c.is_upper() c.is_lower()
c.upper() c.lower()
int(c) char(97) string(c) "{c}" // number <-> char, char -> text
for c in s { } for i, c in s { } // walk a string; i = byte position
s[i] // the char starting at byte i
```
## Structs and enums
```rex
struct P {
name: string
x, y: float
func move(dx: float) { x += dx } // mutation is inferred
}
var p = P{name: "a"} // or positional: P{"a", 0.0, 0.0}
enum E {
A
B(n: int)
}
E.B(3) match e { A => 1, B(n) => n }
```
## Errors and nil
```rex
error("message {x}") err != nil return 0, nil
var v: int? = nil if v != nil { v } if v == nil { return }
```
## Sharing
```rex
var a = shared T{...} var b = a // same value, two owners
var w = weak a w.upgrade() // shared T? (nil if gone)
```
## Generics and interfaces
```rex
func first[T](xs: []T): T { return xs[0] }
func big[T: Ordered](a, b: T): T { ... } // Ordered, Number, or an interface
struct Stack[T] { items: []T } Stack[int]{}
interface Shape { area(): float } // follow it by having the methods
var s: Shape = Circle{1.0}
```
## Files
```rex
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)
// rex.toml in the top folder: imports count from there, in every file
import os // built-in: os math time rand
import json // a package: `rex add git.joji.li/joji/json` (see chapter 14)
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
import "raylib.h" { InitWindow } // only these names, used bare
import "foo.h" link "foo" // when pkg-config doesn't know it (libfoo.so)
var f = stdio.fopen("x.txt", "r") // C pointers: compare with nil, close them yourself
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 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)
Packages: `rex init` · `rex add git.host/owner/name[@v1.2.0]` (or `../folder`) · `rex remove name` · `rex update [name]` · `rex get` · `rex deps`
## 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 ·
a failed `assert` · shifting by a negative amount · `insert`/`remove` out of range.