radlang
radlang is a compiled programming language built from scratch in Rust,
targeting native machine code via LLVM 20. It was designed for rapid API
endpoint development. Source files use the .rad extension.
This document is a language reference and user guide. For compiler
architecture and contributor-facing details, see .claude/CLAUDE.md.
Building and running
Install a release from a checkout with tools/install/install-release.sh (macOS
arm64, Linux x86_64 and arm64; needs LLVM 20 and clang). It builds the
single-file compiler (runtime embedded), installs it into ~/radlang, links
~/.local/bin/radlang, and keeps the previous release: --rollback switches
back, --dry-run builds and checks without installing. The installed compiler
needs no RADLANG_RUNTIME. The commands below use a compiler built from source.
# Build the compiler (Ubuntu/Debian — see .claude/CLAUDE.md for other platforms)
LLVM_SYS_201_PREFIX=/usr/lib/llvm-20 cargo build --release
# Scaffold an offline project with a pinned stdlib package
./target/release/radlang new myapp --template app
# Other templates: cli, api, web, lib, gui, mcp
# Compile and run a file directly
./target/release/radlang run hello.rad
# Compile to a native binary (defaults to output/release/<name>)
./target/release/radlang build hello.rad -o hello
./hello
# Remove generated .rlc files and output artifacts for the current project
./target/release/radlang clean
# Compile a namespace file as a precompiled library (also happens automatically
# for every src/namespace/*.ns.rad file when you run/build)
./target/release/radlang lib mylib.ns.rad -o mylib.rlc
# Package every compiled namespace library into one distributable archive
./target/release/radlang export -o mylib.rlp
# Format a source file (prints to stdout)
./target/release/radlang fmt hello.rad
# Run a test file
./target/release/radlang rtest feature.test.radradlang run compiles to output/debug/, links, executes, then deletes
the temporary binary. radlang build links to a kept binary, by default
under output/release/. radlang rtest compiles in test mode (no
main required), links with the test runtime, and prints pass/fail
results.
Environment variables for builds:
| Variable | Effect |
|---|---|
RADLANG_MARCH=<cpu> |
Compile for that CPU (native, x86-64-v3, …). Off by default so binaries run on any CPU of the target; native can crash on an older machine. |
RADLANG_FP_STRICT=1 |
Same as project.fp: strict: no fused multiply-add, bit-reproducible floating point. |
RADLANG_NO_LINE_TABLE=1 |
Locate errors with per-statement bookkeeping instead of the link-time line table (see Error handling). |
RADLANG_LLD=<path> |
Linux: the ld.lld to link with (default: the one on PATH). |
RADLANG_DUMP_IR_DIR=<dir> |
Write each module’s LLVM IR there (for compiler bug reports). |
RADLANG_LIB_JOBS=n |
Libraries compiled at once (see Namespace libraries below). |
Runtime settings
The runtime: mapping in config.yaml bakes runtime defaults into an executable:
runtime:
dbReaders: 3
dbBusyMs: 5000
dbJournal: wal
log: info
shutdownMs: 5000
cooperativeBudget: 0
handleReport: falseAn environment variable, where the setting defines one, overrides the baked
value. Settings are read lazily by their runtime subsystem; the existing
memory: settings and project.cores keep their configuration paths.
Unknown runtime keys, duplicate keys, and invalid value types are compile errors.
Library objects do not install their own settings: the executable’s configuration
applies before namespace initializers run.
The runtime table in compiler/runtime/core/rt_config.c defines the supported
keys and their policies. After changing that table, regenerate the compiler’s
schema with python3 tools/dev/gen-rt-config.py; --check detects a stale schema.
See runtime configuration, async scheduling and process lifecycle for settings and limits.
Entry point
Every program needs a fn main(). There is no top-level statement
execution outside of it. (Test files using test "..." { } blocks do not
need a main.)
fn main() {
sys.output("Hello, world!")
}main() can call itself recursively like any other function.
Comments
// a single-line comment
/// a doc comment (attached to the next fn, type, or ns declaration)
/* a block comment — may span multiple lines; not nestable */Doc comments document the declaration below them, including namespace
members and functions in a type body. Editor hover (radlang lsp) shows
the declaration’s signature followed by its doc comment rendered as
Markdown, for functions, types, namespaces, namespace members and type
methods, and for members of imported namespaces and .rlc/.rlp libraries
(which keep function and type docs in their metadata). A namespace’s member
listing shows each member’s doc as /// lines above its signature.
/// Converts **Celsius** to Fahrenheit.
fn toF(float c): float { return c * 1.8 + 32.0 }Comments (of either kind) are only valid where a statement or item may start — as their own line, standing between other statements/declarations. They cannot appear in the middle of an expression or statement (`5 /* x */
- 3` does not parse) — same restriction as line comments already had, just now shared by block comments too.
A character outside strings and comments that starts no token ($, a backtick, a
non-breaking space) is a compile error at its line and column:
Parse error (3:23): unexpected character '$'. A byte-order mark at the
start of a file is ignored.
Inside a string interpolation ("{a $}") such a character is skipped and
reported as a warning at its line and column; the program still compiles.
Automatic semicolon insertion
Semicolons are optional. A newline after a statement-ending token acts as an implicit semicolon, so this:
int x = 5
sys.output(x.toString())is equivalent to:
int x = 5;
sys.output(x.toString());Caveat: ) is one of the tokens that triggers ASI on a following newline.
A brace-less control-flow body written across two lines
(if (cond)\nstatement) will have a stray semicolon inserted after the
), breaking the body. Keep brace-less forms on one line, or use { }.
Primitive types
int // i32
uint // u32
long // i64
float // f64
decimal // f128 (software float)
byte // u8
string
char
bool
void
null
num // numeric supertype (f64 under the hood); widens/narrows with
// any other numeric type in both directions
var // inferred: resolves to the value's concrete type at compile
// time (declarations, globals, and fn params alike); only a
// value whose type cannot be determined statically falls back
// to the dynamic i64 slot (see Limitations) Declarations
Type comes before name, JS/TS-style is not used for variables (only for function return types — see Functions):
int age = 25
const string name = "Tim"
var x = 42A bare declaration with no initializer gets a zero/empty default:
string greeting // ""
int count // 0
bool active // false
User u // every field defaulted recursively Safe mode
#safe as the first line of a file requires explicit constructors for
every declaration and forbids mixed-type (var[]) lists:
#safe
int x = Int(5)
string name = Str("Tim")The constructor requirement applies to a bare literal only — a function
call’s result (User u = User("Tim", 30)) doesn’t need wrapping, since
the call’s own signature already provides the type safety a constructor
would otherwise exist to add.
Note: #safe is only honored from the entry file — a #safe directive
in an imported file is silently ignored. If any file in the import graph
declares #safe, the entire compiled program runs in safe mode.
Operators
+ - * / % ** // arithmetic (** is exponent, right-associative)
== != < > <= >= // comparison
&& || ! // logical (&&/|| short-circuit: right side skipped if result is determined)
& | ^ ~ << >> // bitwise AND, OR, XOR, NOT, left-shift, right-shift (integers only)
?? // nullish coalescing: a ?? b returns a's inner value if non-null, else b
cond ? a : b // ternary conditional (right-associative; chainable)
i++ i-- // increment/decrement
i += n i -= n i *= n i /= n // compound assign++, -- and the compound assignments also take a field, a list element or
a namespace variable as their target (o.inner.count += 1, xs[i]++,
store.hits -= 1). Such a target is read twice, so it cannot contain a call
(xs[next()] += 1 is a compile error: assign the index to a variable first).
The ternary cond ? a : b evaluates to a when cond (which must be bool)
is true, else b. It is right-associative, so it chains cleanly for
multi-way selection:
string grade = score >= 90 ? "A"
: score >= 80 ? "B"
: score >= 70 ? "C"
: "F" // parses as a ? : (b ? : (c ? : d))Both branches must have compatible types; two numerics widen to the wider
(x > 0 ? 1 : 2.5 is float), and T with null yields T?.
Arithmetic between an integer type (int, uint, long, byte) and a
floating type (float, decimal, num) has the floating type, in either
order, and is computed in floating point: with long a = 5, a / 1000.0 is
the float 0.005. Between two floating types the result has the left
operand’s type. A decimal result is not implicitly a float
(float f = d * 1.0 with decimal d is a type error).
Floating-point multiply-add within one expression (a * b + c, c + a * b,
a * b - c, c - a * b) compiles to a fused multiply-add where the CPU has
one, rounded once instead of twice, as C compilers do by default
(-ffp-contract=on). The one exception is a plain variable accumulating into
itself (x = x + a * b), which stays a separate multiply and add because a
fused operation on the loop-carried chain is slower; an element or field
accumulator (acc[i] = acc[i] + d * a[c]) is fused. Results can therefore
differ from a two-rounding computation in the last bit. To turn it off for a
project, set fp: strict under project: in config.yaml (1.40.32): every
product is then rounded before the add, whatever the shape of the expression,
for results that reproduce bit for bit across shapes and against languages that
do not contract. Without it, give the product its own statement
(float p = d * a[c] then acc[i] = acc[i] + p): separate statements are never
fused. Math functions the runtime implements in C (math.matmul, the
quantized math.dotQ* kernels) keep their own rounding either way.
Integer arithmetic (+ - * / %) whose operands have different widths
(byte 8, int/uint 32, long 64 bits) takes the type of the place it is
going to: a declaration, an assignment, a struct field or constructor
argument, a list element, a function argument or a declared return type.
With int i = 2000000000 and long big = 3000000000:
long a = i + big // 5000000000: computed in long
int c = i + big // 705032704: computed in long, then truncated to int
long t = i * 2 + by // a wider target widens every operand first (no int overflow)
int k = 5
k += big // compound assignment takes k's type (truncates)A target wider than the expression has every integer operand widened (by its
own signedness) before the operations; a narrower one keeps the wide result
and truncates it. With no declared target (var x = i + big, interpolation,
a comparison operand, .toString()) the expression has the wider operand’s
type in either order, so var x = i + big is a long. An integer literal
operand does not count (b + 1 keeps b’s type) unless it does not fit an
unsigned operand (see below), and two operands of the
same width keep the left operand’s type (uint + int is uint, int + uint
is int).
An operation with an unsigned operand (byte, uint) is unsigned, unless the
other operand is a wider signed type: then the unsigned value fits in the
wider type, so the operation (including /, % and comparisons) is signed,
with the unsigned operand zero-extended and the signed one sign-extended.
| Operands (either order) | Type with no declared target | Signedness |
|---|---|---|
byte and int |
int |
signed |
byte and long |
long |
signed |
uint and long |
long |
signed |
uint and int |
left operand’s type | unsigned |
byte and uint, uint and uint |
uint (left for same width) |
unsigned |
So long -20 / uint 10 is -2 and long -1 < uint 5 is true, while int -1 < uint 5 compares unsigned and is false. A declared target wider than the
expression computes it signed in the target type (long d = i / b with
int -20, byte 10 is -2).
An integer literal beside a byte or uint adapts to it only when it fits
that type’s range. A literal that does not fit (a negative one such as -1
or (-1), or one above the range such as 300 beside a byte) keeps a type
of its own, and the rules above apply: beside a byte it is an int (a
long when it does not fit int), so the operation is a signed int one;
beside a uint it is a long, so the operation is computed signed in long
and no uint compares below a negative literal. With byte b = 10 and
uint u = 10:
b > -1 // true (signed int comparison)
b * -2 // -20, an int
b < 300 // true; 300 is not narrowed to a byte
u > -1 // true (computed in long)
u + -1 // 9, a long
b - 20 // 246: 20 fits a byte, so this is byte arithmeticAn int variable holding -1 is not a literal and keeps the same-width rule
(int -1 < uint 5 is false). Assigning or passing a negative literal to an
unsigned target is unchanged: byte e = -1 is 255 and uint f = -1 is
4294967295.
String + concatenates. String ==/!= compare contents (not pointer
identity). String ordering (</>/<=/>=) has not been verified for
the same content-vs-pointer correctness.
?? requires the left operand to be a nullable type T? and returns T.
The right operand must match the inner type:
int? maybeCount = getCount()
int count = maybeCount ?? 0Numeric literals accept scientific notation (3e3, 1.5e-2, 2E+6).
Integer literals can be hexadecimal (0xFF, 0XC3) or binary (0b1010), with
_ separators between digits (0xFFFF_0000). A literal above the signed range
keeps its 64-bit pattern (0xFFFFFFFFFFFFFFFF is -1); one wider than 64 bits
is a compile error.
A numeric literal automatically widens to fit a wider declared type
(long l = 9000000000), and arguments widen at call sites too
(fn(long) f; f(5) coerces the 5).
Control flow
// if / else
if x > 0 { sys.output("positive") } else { sys.output("non-positive") }
// brace-less bodies (single statement, single line — see ASI caveat above)
if (x > 0) sys.output("positive")
// while
while count < 10 { count++ }
// C-style for (bare `i` is implicitly int)
for (i = 0; i < 10; i++) { sys.output("tick") }
// for-in over a list, a range, a comprehension or any call that returns a list
for (string name in names) { sys.output(name) }
for (int x in [1..10]) { if (x == 3) { continue }; total = total + x }break and continue work in every loop. A C-style loop is for index
arithmetic and early exits; to transform, filter, build or add up a list, the
list forms are shorter and usually faster (see
Choosing a loop form).
// match expression — subject requires parens; arms use =>
// patterns: int/string/bool literals, type names (union narrowing, including
// dotted namespace types such as svc.Account), enum members
// (Color.green), _ wildcard
string result = match (x) {
1 => "one"
2 => "two"
_ => "other"
}match is an expression: arms must produce values of a unifying type, and a
_ wildcard arm is required unless the subject is a union type with all
members covered by type-name patterns. The arms’ types join: a null arm makes
the result nullable, and integer arms of different widths widen (1.40.33):
var c = match (v) {
0 => 5
_ => null // c is int?
}
sys.output(c ?? 0)
fn pick(int v): long? {
return match (v) {
1 => 10
_ => null
}
} Functions
fn add(int a, int b): int {
return a + b
}
// Omitting the return type infers it from the first value-returning `return`
// in the body (top-level named functions only — not namespaced functions,
// not anonymous closures)
fn getName() {
return "Tim" // inferred as : string
}The return type uses a colon suffix (: not ->). Both type name and
name: type parameter syntaxes are accepted:
fn greet(string name, int age): string { ... }
fn greet(name: string, age: int): string { ... } // also validFunctions are hoisted — a function may call another defined later in the file.
Function values and closures
var double = fn(int x): int { return x * 2 }
double(21) // 42
fn(int): int square = someFn // explicit fn-typed variable, callable
var cube = service.cube // function value with an inferred typeAssigning a named or namespace function to a bare fn variable
(fn get = service.get) is a compile error: declare its type
(fn(): T get = service.get) or use var. A function value refers to the
function; each call runs it again.
A var/fn(...):-typed variable holding a function literal is a real,
callable value backed by a closure structure in the traced heap.
Closures fully support capturing outer-scope variables, and they can safely cross call boundaries (e.g. be returned from a function or passed as an argument). The environment struct containing captured variables is managed by the traced heap and stays live while the closure is reachable.
fn makeAdder(int x): fn(int): int {
return fn(int y): int { return x + y }
}
var add5 = makeAdder(5)
sys.output(add5(10).toString()) // 15A closure created in a loop body captures that iteration’s loop variable: in
for (int i = 0; i < 3; i++) { fns.add(fn(): int { return i }) } the three
closures return 0, 1 and 2 (as with a for-in item). A write to i in the
body, or from a closure called there, still carries over to the step.
A captured list or Map is shared, not copied: changes the closure makes are
visible to the code that captured it and to every other reference to it, and
the other way round. That holds for a list captured directly, through a
captured variable, or inside a captured struct, including after the closure
is returned or stored and outlives the function that created the list.
fn collector(string[] into): fn(string): void {
return fn(string s): void { into.add(s) }
}
string[] seen = []
var add = collector(seen)
add("a")
sys.output(seen.length()) // 1A function value read from a list by index can be called directly:
handlers0.
Arrow functions
When the body is a single expression, an arrow function is the short form. The
parameters are parenthesized and typed, and the body’s value is the result, so
no return is written:
fn square(int x) => x * x // named; the return type is inferred
fn greet(string name) => "Hello, {name}!"
var inc = (int x) => x + 1 // anonymous
var add = (int a, int b) => a + b
var typed = fn(int x): int => x * 2 // with an explicit return type
int base = 100
int[] shifted = [1, 2, 3].map((int x) => x + base) // captures work as in any closurex => x + 1 and (x) => x + 1 do not parse, and neither does a block body
((int x) => { ... }): when you need statements, write the full
fn(int x): int { ... } form. Arrow functions are what you pass to map,
where, reduce and the other list methods (see
Choosing a loop form).
Piping values: .pipe
x.pipe(f) calls f(x), so a sequence of single-argument steps reads
left to right instead of inside out:
fn parse(string s): int { return Int(s) }
fn double(int n): int { return n * 2 }
int n = parse("21").pipe(double) // double(parse("21")) == 42
string s = "hi".pipe(text.shout).pipe((string t) => t + "?")
int total = scores.pipe((int[] v) => v.sum())f can be a named function, a namespace function (text.shout), a closure
variable or a lambda (captures work as usual). It must take exactly one
parameter, which must accept the receiver’s type; the result has f’s return
type, so each step can change the type. Anything else is a compile error.
Design note: .pipe is compiler sugar, not a runtime method. The analyser
types x.pipe(f) as f’s return type, and codegen rewrites it to the call
f(x), so it costs exactly one ordinary call. It is synchronous: piping a
Future is a compile error (await it, or use .resolve(cb), first). User
members win: if a struct has its own fn-typed field named pipe,
value.pipe(arg) calls that field, and a namespace function ns.pipe(...)
is an ordinary namespace call.
Function overloading
Multiple functions can share the same name in the same scope, provided they differ in arity or parameter types. The analyser resolves the call by picking the best match in a two-pass (arity-then-type) strategy:
fn describe(string s): string { return "string: " + s }
fn describe(int n): string { return "int: " + n.toString() }
sys.output(describe("hello")) // string: hello
sys.output(describe(42)) // int: 42Overloads also work inside namespaces. A namespace function (or a type-body
method, or a generic function’s copy) calls an overloaded member of its own
or an enclosing namespace by its bare name, and the arguments pick the
overload, also in a compiled library. A member import
(import { describe } from "lib") brings every overload of the name in, when
one namespace declares them all. If no overload matches, a compile-time error
is raised.
Nullable types and optional parameters
Append ? to any type to make it nullable:
string? name = null // explicit null
int? count // defaults to null (not 0)
string? label = "hello" // non-null nullableA T? variable holds either null or a value of type T. Passing T?
where a T is expected is a compile error in safe mode unless the value
has been narrowed.
Null narrowing
Inside an if (x != null) { ... } block, x is treated as its inner
type T and can be used without unwrapping:
string? s = maybeGet()
if (s != null) {
string lower = s.lower() // s is string here, not string?
}A narrowed variable stays narrowed while it is assigned values of its inner
type (s = "b", s = s + "!"). Assigning null or a nullable value ends
the narrowing: s is string? again from that statement on, until another
check narrows it. A loop that may assign it such a value (or a value whose
type is only known inside the loop) ends the narrowing before the loop
starts. A local that a closure assigns is not narrowed once that closure has
been written, and inside a closure body a narrowed local is read as its
declared nullable type, since the closure may run after the variable changes.
The same check on a field path (h.f, h.a.b) narrows that path when its
root h is a local variable or parameter. It works wherever a local narrows:
the then-branch of != null, the else-branch of == null, each conjunct of
an && chain, a ternary, and the rest of the block after an early return
(if (h.f == null || h.g == null) { return }):
if (order.note != null) {
sys.output(order.note.upper()) // order.note is string here
}
if (order.address.city == null) {
return
}
ship(order.address.city) // string from here onThe narrowing of a path ends at the first assignment to its root, because a
field write h.f = v assigns h (it is h = { ...h, f: v }). Any =,
compound assignment or ++/-- on h or on any field under it ends the
narrowing of every path under h from that statement on, as does declaring
a new variable named h. The value on the right of a write is read first, so
h.f = h.f + "!" inside the branch is fine. A loop that assigns h anywhere
ends the narrowing before the loop starts. Closures capture locals by
reference, so a root that a closure assigns is not narrowed once that closure
has been written, and narrowed paths do not carry into a closure body.
Calls do not end a narrowing (structs are passed by value, and a function
cannot reach its caller’s locals), except a call of a type-body method that
changes its receiver (h.clear()), which assigns h. Inside a method, paths
under me (@f, me.f) narrow the same way.
A null check never narrows a global (module-level) variable, a namespace
variable (bare v inside its namespace or qualified ns.v), or a field path
rooted at one (conf.user.name), in any of the forms above: any call may set
it to null. Using it as T inside the check is the ordinary nullable type
error, with a hint. Copy it to a local first, and check the local:
string? name = "a"
fn clear() { name = null }
if (name != null) {
clear()
sys.output(name.length()) // should be an error: name may be null again
}
var n = name
if (n != null) {
clear()
sys.output(n.length()) // n is string here; clear() cannot change it
}As of 1.40.52 the compiler does not report the first case: it narrows the global and
the program crashes when clear() has set it to null (v1/bugs.md). Always copy a
global to a local before the check.
A const global or namespace variable cannot change, so a check on it does
narrow it.
A narrowed read is still the declared T? for the null operators, which
then know the answer: inside if (s != null), s ?? "d" is s (the
fallback is type-checked but never evaluated), s != null is true and
s == null is false. This holds for narrowed locals, parameters and field
paths (if (q.min != null) { lo = q.min ?? 0.0 }). ?? on a value declared
without ? stays a compile error.
Optional and default parameters
A nullable parameter is optional at the call site — the callee receives
null if the argument is omitted. Default-valued parameters work the same
way with a fallback expression instead of null:
fn describe(string? label) {
if (label != null) { sys.output("label: " + label) }
}
describe() // label = null
describe("hello") // label = "hello"
fn greet(string name = "world"): string {
return "hello " + name
}
greet() // "hello world"
greet("Tim") // "hello Tim"Rules:
- Required parameters must come before optional ones (both nullable and default-valued params count as optional).
T?declarations are exempt from safe mode’s constructor requirement —nullis itself always valid for a nullable type.
Custom types
Structs
type User = { string name, int age }
const User u = User("Tim", 30) // explicit constructor
const User u2 = { "Tim", 30 } // inferred constructor
u.name // field access, including chained (req.body.name)
sys.output(u) // {"name":"Tim","age":30}
u.toString() // same JSON renderingA bare User u declaration recursively defaults every field. Nested
struct fields default and render correctly too.
Assign a field with x.f = v. Structs are values, so this updates the struct
held by that variable, list element or enclosing field — u.age = 31,
order.address.city = "Leeds", users[i].name = "Ann" — and not copies
of it made earlier (passing a struct to a function passes a copy).
x.f = v is shorthand for x = { ...x, f: v }; in list[i].f = v the
index expression is evaluated twice, so keep it free of side effects.
Methods in a type body
A fn written inside a struct’s type body is a method of that type and is
called on a value with v.name(args). Inside it, me is the receiver and
@name is its field name (exactly me.name):
type Acc {
int total
int[] items
fn add(int n): int {
@total += n // reads and writes a field of the receiver
@items.add(n)
return @total // or me.total
}
fn twice(): int {
return add(1) + add(1) // a bare call names a sibling method: me.add(1)
}
fn reset() {
me = Acc(0, []) // replaces the whole receiver
}
}
Acc a = Acc(0, [])
a.add(5) // 5
a.total // 5: the change reaches `a`
a.twice() // 13: add(1) returns 6, the second add(1) returns 7, 6 + 7me reads like any struct value (me.f, me.inner.n, passed on as an
argument, returned, compared, captured by a closure written in the method)
and is written with the usual field assignments: me.f = v, me.f += n,
me.n++, me.inner.n += 1, or me = Acc(0, []) to replace the whole
value. @name is the same thing in a shorter spelling and stands wherever
me.name does: an expression, a call argument, a condition, an assignment
target (@total += n, @count++, @a.b = 1, @list[i] = v), a call
(@items.add(x), or @cb(x) for a function-typed field) and a string
interpolation ("{@total}"). The two spellings mix freely and the formatter
prints whichever was written. @ names fields only: a sibling method is
called bare, and @add(1) is an error that says so. A field is only reached
through me or @: a bare total in a method is an undefined variable
error that says to write @total (or me.total). me and @name outside a
method are errors, and me cannot be the name of a variable, parameter,
field, function or type. this is not special: inside a method it is just an
undefined name, and the error says that this is me in radlang.
A method that changes me (directly, or by calling a method that does)
stores the receiver back when it returns, so the change is seen by whatever
the call was made on: a variable or parameter, a field path (h.acc.add(1)),
a list element (xs[i].add(1), where i is evaluated again for the store, as
in xs[i].f = v), a global or namespace variable (bank.vault.add(1)), or
me inside another method. A receiver that is a temporary (make().add(1),
m.get(k).add(1)) is changed and then dropped. The usual copy rules still
hold: a struct argument, a for-in item and a value returned from a function
or map are copies, so calling a method on them changes the copy. A method that
throws leaves its receiver as it was. const Acc a = ...; a.add(1) is an error
when add changes me. A call of such a method ends any null narrowing of
paths under the receiver’s variable, like an assignment to it.
A bare call inside a method resolves to, in order: a parameter or local of
the method (a closure variable), a sibling method of the type, then module
scope (functions of the namespace and the program). A bare variable name
reaches the variables of the type’s namespace and the program’s globals. A closure written in the
method captures me (and so @name) like any local: changes it makes while the method runs
are stored back, and one that outlives the call keeps the method’s own copy.
Methods work on top-level and namespace types (shop.Cart k; k.total(5),
parameter types are those of the type’s namespace), on generic types (each
instantiation, Box<int>, gets its own copy of the methods), on any receiver
expression (a call result, a list element, a narrowed nullable), and on the
types of a compiled library or package when the importer calls them. A
generic type of a compiled library or package (lib.Box<int>, or Box<int>
imported by member) brings its methods too: the instantiation made in the
importing program gets checked copies, which reach the library’s private
functions, types and variables as the library’s generic functions do. (A
library compiled before the receiver was spelled me must be rebuilt with
radlang lib -f; loading it says so.) On
v.name(..) a field of function type with the same name wins over the
method; inside a method a bare call of such a name is an error (write
@name(..) or me.name(..) for the field). A [controller] type’s methods are called
by the HTTP server: me there is the handler’s own copy of the controller
instance, and changes to it last for that call only.
Anonymous structs
An anonymous (untyped) struct can be created inline without a prior type
declaration. The shape is inferred from the field names and initializer types:
var point = { x: 10, y: 20 }
var user = { name: "Tim", age: 30, active: true }
// Shorthand: omit the value when a local has the same name as the field
string name = "Tim"
int age = 30
var obj = { name, age } // same as { name: name, age: age }
// Mixed
var mixed = { name, count: 3 }
sys.output(point.x.toString()) // field access works normallyAnonymous structs are typed by their shape. They work for local use but
cannot cross function boundaries typed as a named struct — use type
declarations when the struct needs to be passed to or returned from functions.
A literal can copy another struct with ... and override fields. Assigned to
a declared struct type, it takes that type, so an override may be null for a
nullable field (T? f):
type Rec { string id, string? summary, int n }
Rec r = Rec("a", "s", 1)
Rec cleared = { ...r, summary: null } // also valid in `x = {...}`, `list[i] = {...}`,
// and `return {...}` from a fn returning Rec / Rec?A literal passed where a struct parameter is expected (a function argument,
or an argument to a function-typed struct field such as net.fit(xs, ys, { epochs: 400 })) is built as that struct by field name, with omitted fields
defaulted. For a field of a struct from a library, the parameter type is the
one the library declared, so the program does not need to import its name.
A null override needs a declared target type: var q = { ...r, summary: null }
is a compile error (the literal has no type for the field), and overriding a
non-nullable non-string field with null is a type mismatch.
Unions
type Status = string | int
Status s = "active"
if s is string { sys.output("string!") }is checks are implemented at runtime via a type tag stored alongside the
value. Inside an if s is T block, s is fully narrowed — method calls
and field access on the narrowed type work correctly:
type Value = string | int
Value v = "hello"
if v is string {
int len = v.length() // v treated as string here
sys.output(len.toString())
}The static analyser may still emit a warning for method calls on a union-typed variable inside a narrowing block, but the code compiles and runs correctly. A local variable can be used to silence the warning:
if v is string {
string s = v // assign to typed local — no further warnings
sys.output(s.upper())
} Enums
enum Color { red, green, blue } // string enum: members read as their names
enum Status { active = 1, inactive = 2 } // int enum: an int member makes every member an int
enum Level { low, mid = 10, high } // bare int members count up: 0, 10, 11
Color c = Color.green
c == "green" // true
fn describe(Color c): string { return "colour " + c }
describe(Color.red)
describe("blue") // a plain value of the underlying type is acceptedAn enum type is its underlying string or int: a member reads as its value,
an enum-typed variable or parameter holds that value and can be used anywhere
the underlying type can (concatenation, arithmetic, comparisons, match), and
it accepts any value of the underlying type, not only members.
A match arm can name a member (Color.green => ..., Status.active => ...)
or use the underlying literal ("green" => ...); both compare by value. A
dotted pattern that is not a member of an enum is a compile error.
An enum declared inside a namespace is named with the namespace:
Shapes.Kind, Shapes.Kind.square. Public namespace enums are part of the
namespace’s compiled library, so a program importing the library can use them;
priv enum keeps one inside the library.
Dynamic values (any)
any is a truly dynamic, runtime-tagged value — an open union whose tag set
is fixed by the runtime rather than a member list. Any concrete value can be
implicitly wrapped into any, and it is narrowed back out with is or match
(never a direct assignment, exactly like a union member):
any x = "hello"
any n = 42
any[] mixed = [1, "two", true] // heterogeneous list
if (x is string) { sys.output(x.upper()) }any holds scalars, strings, lists, closures, Future, and
struct-shaped values — user structs, Date, and Error. A boxed struct
carries a hidden type id so distinct struct types stay distinguishable:
type User = { string name, int age }
type Order = { int id, string item }
fn describe(any v): string {
return match (v) {
User => "user " + v.name
Order => "order " + v.item
int => "int " + v.toString()
string => "str " + v
_ => "other"
}
}
any u = User("Ada", 36)
sys.output(describe(u)) // "user Ada"
sys.output(u) // renders the struct
sys.output(json.from(u)) // {"name":"Ada","age":36}Both if (v is T) and match (v) narrow the value in their body, so field and
method access on the matched type work. Calling a method on an un-narrowed
any is a compile error — narrow first. any is distinct from var: var
resolves to a concrete static type where it can, whereas any always carries a
runtime tag. In #safe mode, wrapping requires the explicit Any(expr)
constructor.
Generics
radlang supports generic struct types and generic functions using a
C#/TypeScript-style <T> syntax. Generics are resolved at compile time
via monomorphization (generating concrete copies of structs or functions
for each distinct set of type arguments used).
Generic structs
type Box<T> = { T value }
type Pair<A, B> = { A first, B second }
Box<int> bi = Box(99)
Pair<int, string> pr = Pair(7, "seven")Generic type parameters can be used within struct fields. In safe mode,
constructor calls require explicit type wrapping (e.g., Box<int>(99) or
Box(99) if inferred).
A constructor without <...> infers its type arguments from its arguments
wherever it appears — nested (Box(Box(5)) is a Box<Box<int>>), as a list
element, an argument or a return value. In a declaration the annotation
decides instead (Box<float> f = Box(9) is a Box<float>), and the
arguments are checked against it as for any struct: Box<int> b = Box("s")
and Box<int>("s") are errors (struct 'Box<int>' field 'value' expects int, got string). Arguments that name no type argument (Box(null), Box([]))
take the instantiation the constructor is checked against: a declaration,
return type, parameter, field or assignment target. With none of those
(var b = Box(null)) it is an error asking for the type arguments.
Instantiations
nest freely, including a closing >>: Box<Pair<int, Box<string>>> b.
A type annotation may nest up to 64 levels (each generic argument, [],
?, map or fn level counts one); deeper is a compile error, type nesting too deep. The same limit stops a generic that instantiates itself with an
ever larger type argument (grow<T> calling grow<Box<T>>).
Generic functions
fn identity<T>(T x): T {
return x
}
fn unbox<T>(Box<T> b): T {
return b.value
}
fn makeBox<T>(T val): Box<T> {
Box<T> b = Box(val)
return b
}
int x = identity<int>(7)Generic functions can accept and return generic type parameters as well as
generic struct instances. Type arguments can be written inside <...>
(e.g. identity<int>(7)) or inferred from the arguments, including generic
struct arguments: unbox(b) with b a Box<int> calls unbox<int>.
A single capital letter used as a parameter type without a <...> list
(fn first(T[] xs): T) is an implicit type parameter, unless a type of that
name is declared in the function’s namespace, an enclosing namespace or at the
top level: then it names that type (type U = Account | Other and
fn kind(U u) take a U, and calls are checked against it).
Generic functions must be declared at the top level (or as a namespace member) — see the nested named function limitation below.
A generic function belongs to the namespace that declares it: a.wrap<T>,
b.wrap<T> and a top-level wrap<T> are three functions. A bare wrap(x)
calls the current namespace’s, then an enclosing namespace’s, then the
top-level one. Its body uses the namespace’s functions, variables and types
unqualified, like any other member. A generic function exported from a
compiled library is instantiated in the importing program; its copy reads and
writes the library’s own namespace variables (initialized by the library) and
calls the library’s private functions, as the library’s other functions do.
This holds for import { wrap } from "lib" as well, and for a member import
from a package (import { wrap } from pkg), which also brings in what the
body names in the package. The variables stay unexported: code outside the
library’s namespaces still cannot name them, and a namespace const cannot
be assigned from a copy’s body any more than from elsewhere.
A generic function’s body is checked once per instantiation, with the type
arguments substituted, in the scope of its declaration (its namespace’s
variables, not the caller’s locals). A body that is invalid for some type
argument is a compile error at its position in the body, naming the
instantiation: with fn getX<T>(T v): int { return v.x }, getX(Q("a"))
reports in fn getX<Q>: 'Q' has no field 'x' (a namespace’s generic function
is named by its namespace: in fn box.wrap<Q>). An error in a template from a
compiled library is reported at the call that instantiates it.
Destructuring
int [good, better, best] = scores // positional
int [a, ...rest] = scores // rest binding, must be last
int [, , best] = scores // sparse skip
string { name } = u // struct field destructureValidated at compile time: declared element/field types must match the
real ones, and ...rest must be the final element.
Lists
string[] names = ["Alice", "Bob"]
int[] scores // default: empty
int[10] primes // sized: 10 elements, all 0
int[] oneToFive = [1..5] // range: both ends inclusive
names[0] // index access
names[0] = "Ann" // index assignment
names.add("Carol") // mutates in place
names.remove("Bob") // mutates in place,
// removes first value match
names.removeAt(0) // -> T, removes by index and returns it
names.pop() // -> T, removes and returns the last
names.clear() // removes every element
string[] merged = names.combine(other) // -> T[], new list with all elements
// of both; does not mutate either
names.join(", ") // -> string, any element type
names.length() // -> int, works on any list
// including chained results
names.indexOf("Alice") // -> int, first index of value, -1 if absent
names.contains("Alice") // -> bool
names.first() // -> T, first element (undefined if empty)
names.last() // -> T, last element (undefined if empty)
names.reverse() // -> T[], new reversed copy; does not mutate
names.slice(1, 3) // -> T[], elements [1, 3) as a copy
names.map((string s) => s.upper()) // -> new list, one result per element
names.where((string s) => s != "Bob") // -> new list of the elements kept
names.iter(fn(string s): void { sys.output(s) }) // -> void, side effects only
ages.reduce((int acc, int a) => acc + a, 0) // -> left fold from a seed
ages.sort() // -> new sorted list; see Sorting belowmap, where and iter also accept fn(T item, int index) callbacks, and
every list-building form (map, where, comprehensions, ranges) is described
under Choosing a loop form.
add, contains and indexOf take a value of the element type and combine
a list of the same element type: a value of another type is a compile error,
as it is for list[i] = v (bool[] given a string, A[] given a B). A
number widens as in a declaration (longs.add(1), floats.contains(2)), and
an anonymous struct literal of a matching shape is accepted
(points.add({ x: 1, y: 2 })).
A list is shared, never converted, so a list value must already have the
declared element type: long[] wide = ints is a compile error (int[] and
uint[] are interchangeable, as are float[], decimal[] and num[]). A list
literal or a range is built with the element type of the place it is written
in: a declaration, an assignment (xs = [1, 2], box.vals = [1..n],
rows[0] = [1, 2]), an argument (sum([1, 2]) for a long[] parameter), a
return value, a struct field (Box([1, 2]), { vals: [1, 2] }) and the
argument of add or combine. This holds at any depth
(long[][] rows = [[1, 2], [3..5]]).
Ranges and comprehensions
[start..finish] builds an inclusive integer list. The direction follows the
bounds, the bounds are any integer expressions, and the element type is int
(long if either bound is long):
int[] up = [1..5] // [1, 2, 3, 4, 5]
int[] down = [5..1] // [5, 4, 3, 2, 1]
int[] indexes = [0..<n] // 0 .. n-1: n elements, none when n == 0Because the direction follows the bounds, [0..n - 1] with n == 0 is
[0..-1], two elements counting down. Use the half-open [start..<finish]
for “n times” and index loops: it counts up, leaves finish out and is empty
when finish <= start ([2..<5] is [2, 3, 4]; [5..<2] is empty).
for (int i in [0..<xs.length()]) compiles to the same counted loop as
for (int i = 0; i < xs.length(); i++).
[expr for (T x in source) where cond] builds a list from any list or range.
where is optional and runs first, so it guards the expression
([100 / x for (int x in xs) where x != 0] never divides by zero). The
element type is the type of expr:
int[] squares = [x * x for (int x in nums)]
int[] evens = [x for (int x in nums) where x % 2 == 0]
string[] labels = ["n" + x.toString() for (int x in nums) where x > 4]
float[] prod = [a[i] * b[i] for (int i in [0..a.length() - 1])] // index form
string[] cats = [p.name for (Pet p in pets) where p.kind == "cat"]A range or a comprehension is an ordinary list: it can be indexed, iterated
with for (int x in [1..10]), nested as the source of another comprehension, or
given a method ([1..4].map(...)).
Parallel forms
map, where, iter and reduce take an optional trailing thread count that
runs the callback on a pool of OS threads; parallel(fn, n) is an alias for
the parallel map:
int[] big = nums.map((int x) => x * x, 4) // 4 threads
int[] some = nums.where((int x) => x % 2 == 0, 2)
int total = nums.reduce((int acc, int x) => acc + x, 0, 4) // R must equal T
int[] alias = nums.parallel((int x) => x + 1, 3)map, where and parallel keep the element order; iter does not. The
callback runs on a worker thread, so it must be synchronous and should not write
to shared outer state. The exception is counting: in a callback written as a
closure literal in the call, ++, --, +=, -=, *= and /= on a captured
or global number (int, long, uint, byte, float, decimal) are atomic,
so hits++ counts every element. A plain assignment (x = x + 1), a string or
list update, and a callback passed by name or through a variable are not
synchronized: the last writer wins. A parallel reduce needs an associative combiner and an
accumulator of the element type. Starting the pool costs tens of microseconds,
so a thread count only pays off when the callback does real work per element
(see Choosing a loop form); with a trivial callback the
sequential form is faster at every size.
Sorting
sort() returns a new list and leaves the receiver alone; the other forms:
int[] a = unsorted.sort() // ascending
int[] b = unsorted.sort(true) // descending
int[] c = unsorted.sort((int p, int q) => q - p) // comparator: <0, 0, >0
Pet[] d = pets.sortBy((Pet p) => p.age, true) // key extracted once; desc flag optional
unsorted.sort({ inPlace: true, threads: 4 }) // mutates the receiverFor integer lists math.sort.radix, .count, .timsort, .intro and .pdq
return sorted copies. The sort is stable.
Choosing a loop form
radlang has several ways to walk or build a list, and they do not cost the
same. The figures below were measured on radlang 1.34.7 (Apple M1 Max) and
compare whole-operation time with the C-style for (int i = 0; ...) version of
the same task, at 16, 10,000 and 1,000,000 elements. Rows that a later release
changed say so, with that release’s measurement. The method, the raw tables and
the caveats are in
list-idioms-benchmark.md; later
measurements are in v1/perf-log.md.
| To do this | Write | Compared with the C-style loop |
|---|---|---|
| Build a list from an index or a formula | [0..n - 1], [f(i) for (int i in [0..n - 1])], xs.map(...), or int[n] out filled by index |
Since 1.40.36 and 1.40.41 a loop that only adds to a fresh list (T[] out = [] or List<T>(cap), then for or while with out.add(...), an optional if) is folded into the comprehension and runs as fast (829 -> 65 us). A sized list filled in order folds too (1.40.47). An add loop that does other work per element is still about 20 times slower |
| Transform every element | xs.map((T x) => ...) or [... for (T x in xs)] |
As above: the comprehension, map and a plain add-only loop are equally fast, and so are arrow, fn literal and named callbacks |
| Keep some elements | xs.where((T x) => ...) or [x for (T x in xs) where ...] |
about 5 times faster than if plus add |
| Add up a list | xs.sum(), for (int x in xs) or an index loop |
the same speed (within a few percent) |
| Fold with your own function | a loop, xs.sum(), or reduce with an arrow reducer |
A read-only arrow reducer over a pipeline or a range is inlined (1.40.11, 3.5 times faster) and a string-building reduce appends in place (1.40.17). A named or capturing reducer still costs one call per element |
| Run a function for its effects | for (T x in xs) or xs.iter(fn(T x): void { ... }) |
the same speed (iter is 3 times slower at 16 elements) |
| Filter, then map, then add up | xs.where(...).map(...).sum() or [... for ... where ...].sum() |
One pass, no intermediate lists (1.40.10, 1.40.19); ending in reduce folds the same way |
| Matrix times vector | a helper that dots one row, called from rows.map(...), a comprehension or a for over rows |
8 to 9 times faster than nested m.rows[i][j] loops through a struct field. An inner row.map((x, i) => x * v[i]).sum() fuses into one loop (1.40.46, 2.3 times faster) |
| Join values into text | xs.map(...).join(",") or a comprehension then .join(","), or s += x on a local string in a loop |
Since 1.40.44 join over a comprehension or map chain writes the text directly, without the intermediate list (4.8 times faster; numbers and interpolations are formatted in place, 1.40.45). Appends to a local string are in place while nothing else holds it; passing, storing or copying s inside the loop makes each later append copy the text, which is quadratic |
| Visit the characters or bytes of a string | for (byte b in s.toBytes()), for (string c in s.chars()), s.count("a"), or an index loop with charAt |
for (string c in s.chars()) walks the string without building a list (1.40.35). An index loop bounded by s.length() (in the condition, or int n = s.length() before it) no longer rescans: s.charAt(i) == "c" compares one byte (1.40.34, 1.40.42; 100,000 characters in 45 us, about 5 times the toBytes loop) |
Visit the values of a Map |
for (string v in m.values()) |
2.4 to 2.7 times faster than going through m.keys() and m.get(k) |
| Join two lists | a.combine(b) |
8 to 25 times faster than two add loops; acc = acc.combine([x]) on a local list appends in place, as fast as add, unless acc is passed, stored or copied inside the loop |
Why the differences. map, where, iter and comprehensions are expanded
into one tight loop with no per-element call and no capacity check, which the
compiler can vectorize. An add loop checks the capacity and calls into the
runtime for memory bookkeeping on every element; filling a sized list
(int[n] out) by index avoids both. Sequential reduce is the exception to the
rule that the list methods are free: its function is called through a pointer
for each element, which blocks inlining and vectorizing. A for over a list and
an index loop cost the same. Counted range loops (for (int i in [0..<n]), or
[0..n - 1]) compile to the same loop as for (int i = 0; i < n; i++) (measured
equal on 1.40.25); prefer the half-open [0..<n], which is empty when n is 0,
where [0..n - 1] would walk 0 and -1. List<T>(n) saves only the regrowth, about 20 percent
from 10,000 elements up.
When a loop indexes lists that are fields of a struct, copy the lists into
locals before the loop (float[] a = d.a): in the measurements that made a dot
product 20 percent faster and a matrix loop 9 to 17 times faster.
Parallel forms (a thread count as the last argument) cost about 35 microseconds
per call to dispatch, so they win only when the sequential call would take well
over 100 microseconds: for example a callback that does about a microsecond of
work, on 200 or more elements. With 0.85 microseconds of work per element,
10,000 elements ran 2 times faster on 2 threads, 3.7 times on 4 and 5 times on
8; at 16 elements the same call was 3.5 times slower. With a trivial callback
(x * 2 + 1) the parallel map lost at every size, by 20 to 30 times at 100,000
elements, because the sequential loop already runs at memory speed. Write the
sequential form first and add a thread count only after measuring.
Sorting: xs.sort() on numbers is the fast path. A comparator whose body is one
return that only reads values (sort((int a, int b) => a - b),
sort((Person x, Person y) => x.age - y.age), or a named function such as
fn byAge(Person a, Person b): int { return a.age - b.age } passed as
sort(byAge)) is evaluated inside the sort loop; any other comparator is called
once per comparison. sortBy calls its key
function once per element, then sorts the keys (int, long and float keys by
radix). On 10,000 integers the inline comparator is about 13 times slower than
sort() and sortBy about 4 times; use them for structs and custom orders, not
for plain numbers. A comparator’s result counts by its sign, so a float or
long difference works too.
List helpers
These return new values and never mutate the receiver:
int[] xs = [3, 1, 3, 2]
xs.sum() // -> 9; same type as the elements
xs.unique() // -> [3, 1, 2]; first occurrences, in order
xs.take(2) // -> [3, 1]; the first n elements
xs.skip(2) // -> [3, 2]; everything after the first n
xs.chunk(3) // -> [[3, 1, 3], [2]]; T[][]
xs.flatMap(fn(int n): int[] { return [n, n * 10] }) // -> [3, 30, 1, 10, 3, 30, 2, 20]
pets.groupBy((Pet p) => p.kind) // -> map[string, Pet[]]sum()works on numeric lists (int,uint,long,byte,float,decimal,num) and returns the element type:int[]sums toint,long[]tolong,float[]tofloat. Integer sums wrap on overflow like+. An empty list sums to0. Any other element type is a compile error.unique()keeps the first occurrence of each value and drops later repeats. It works on numbers, bools and strings and compares with==: strings by content,0.0equals-0.0, andNaNnever equals anything (everyNaNis kept). Other element types are a compile error.take(n)returns the firstnelements andskip(n)everything after them. Counts clamp:n <= 0takes nothing / skips nothing, andnpast the end takes the whole list / skips everything.chunk(n)splits the list into consecutive lists ofnelements; the last one holds the remainder. An empty list gives[].n <= 0throws a catchableError("list.chunk size must be positive, got <n>").flatMap(f)callsf(which must return a list) on each element and concatenates the results in order. Usemapwhenfreturns one value.groupBy(f)returns amap[string, T[]]from each keyfreturns to the elements with that key. Keys appear in first-seen order and each group keeps the elements’ original order. Map keys are strings, sofmust return astring(convert numbers with.toString()).
Elements are copied shallowly, as with slice: a list of lists or structs
shares the inner values.
Lists can also be created with the List constructor:
var ids = List<int>() // empty int[]
var names = List<string>(1000) // empty string[] with room for 1000 elements
int[] scores = List() // element type taken from the contextList<T>()is an emptyT[], like a typed[].List<T>(capacity)is also empty (length()is 0);capacityonly reserves room so the firstcapacity.add()calls don’t reallocate. A negative capacity throws a catchableError.List()takes its element type from where it is used: a declared variable (int[] xs = List()), a parameter (count(List())), a return value or a struct field.var xs = List()has no element type to take and is a compile error; writeList<T>().List(capacity)without a type argument is an error too.
A program that defines its own List function or type keeps it: List(...)
then calls the user’s definition.
A sized list declaration creates a list of that length, filled with default
values (unlike List<T>(capacity), which stays empty):
int[10] primes // 10 elements, all 0; primes.length() == 10Lists are managed values in the traced heap, with real amortized-growth
mutation. .map()’s result type follows the
closure’s own declared return type, not the input list’s element type, so
type-changing maps work.
Lists are passed by reference: a function that calls .add() on a list
parameter changes the caller’s list. Returned lists are copies unless the
function built them itself. Returning namespace state, a parameter, a struct
field, or a local that aliases one of those gives the caller its own shallow
copy, so a getter cannot hand out mutable access to priv storage. Lists
created in the function (literals, [] plus .add(), map/where/slice
results, other calls) are returned without copying. The copy is shallow:
elements that are themselves lists are still shared. Maps follow the same
rule: a returned Map or map[K, V] the function did not build (including
the receiver a chained .set returns) is a copy with its own entries.
ns store {
priv int[] items = [1, 2]
fn all(): int[] { return items } // caller gets a copy
}
fn main() {
int[] mine = store.all()
mine.add(3) // store's items are unchanged
}A var[] literal whose elements share one type resolves to that type
(var[] xs = [1, 2] is an int[]). A literal with mixed element types
(var[] xs = [1, "a", 2.5]) resolves to any[]: each element carries its
runtime tag, as in an explicit any[] (see Dynamic values). Safe mode
(#safe) rejects a mixed var[]; write any[] there.
A closure literal passed to map, where or iter may return from
anywhere in its body, including inside an if, a loop or a try; the
return ends that call of the closure only. A literal whose only return
is its last statement is expanded in place with no call per element; one
with a return in a nested block is called as a closure.
Using scopes
using { } creates a lexical scope. It does not dispose managed values or
guarantee that their memory is reclaimed when the block exits. Managed values
remain live while reachable and are reclaimed later by the traced collector:
using {
string[] big = loadLargeDataset()
// ... process big ...
} // the lexical scope ends hereusing fn marks a function with the existing scoped-memory syntax. It does
not force collection on return; values created by the function remain live
while reachable:
using fn processRequest(HttpRequest req): HttpResponse {
string[] parts = req.body.split(",")
// parts remain reachable until no longer used
return HttpResponse(200, "done", { "Content-Type": "text/plain" })
}The compiler’s existing escape rules for using { } remain in force. They
constrain value flow; they are not a promise of prompt memory reclamation. An
explicit resource binding, described below, has a different purpose: it calls
close() at scope exit.
Resource bindings — using (T t = expr) { }
A second form binds a disposable resource whose close() runs
automatically on every exit from the block — normal fall-through,
return/break/continue, and a throw unwinding past it (exception-safe,
like C#’s using / try-with-resources):
using (TcpConn conn = tcp.connect("example.com", 80)) {
conn.write("GET / HTTP/1.0\r\n\r\n")
string reply = conn.read()
// conn.close() runs here — even if read() throws
}T must be a type with a close() method: TcpConn, TcpServer,
WebSocket/Socket, SseStream, SseClient, Channel, HttpServer, or a
database Database, or a RegEx. Unlike the lexical scope form using { }, the
resource form deterministically closes t; it does not restrict escapes,
and other values may leave the block freely. Nested resource blocks dispose
innermost-first. Collection may later reclaim managed values, but does not
replace explicit resource disposal.
String methods
s.length() // -> int, bytes (O(n): see below)
s.utf16Length() // -> int, UTF-16 code units
s.isEmpty() // -> bool
s.upper() // -> string
s.lower() // -> string
s.capitalize() // -> string; first letter upper-cased
s.trim() // -> string (strips ASCII whitespace from both ends)
s.trimStart() // -> string
s.trimEnd() // -> string
s.reverse() // -> string
s.repeat(3) // -> string; also "ab" * 3 or 3 * "ab"
s.contains("x") // -> bool
s.replace("a", "b") // -> string (replaces ALL occurrences)
s.replace("a", "b", 1) // -> string; at most 1 replacement
s.split(",") // -> string[]
s.split(",", 3) // -> string[]; at most 3 pieces — the final piece holds
// the unsplit remainder (delimiters included).
// limit <= 0 means unlimited.
s.chars() // -> string[]; one entry per code point
s.lines() // -> string[]; keeps a trailing "" when s ends in "\n"
s.startsWith("http") // -> bool
s.endsWith(".json") // -> bool
s.indexOf("x") // -> int; first byte index of substring, -1 if absent
s.indexOf("x", from) // -> int; first match at or after byte `from` (index in s)
s.lastIndexOf("x") // -> int; last byte index, -1 if absent
s.count("x") // -> int; non-overlapping occurrences
s.charAt(n) // -> string; single-character string at byte index n;
// empty string if out of bounds (O(n), see below)
s.slice(start, end) // -> string; substring from byte index start (inclusive)
// to end (exclusive); clamps to string length
s.substring(start) // -> string; from byte index start to the end
s.substring(start, n) // -> string; n bytes from start (a length, not an end)
s.padStart(n, "0") // -> string (target length, pad string — both
// required, validated at compile time)
s.padEnd(n, "0") // -> string
s.toInt() // -> int; s.toLong() -> long; s.toFloat() -> float
s.toBytes() // -> byte[]
s.toString() // -> string (identity)bool.toString() is also supported and returns "true" or "false".
length(), slice(), indexOf() and charAt() count bytes, not characters.
A string carries no stored length, so length() and charAt(i) both walk it
(about 2 us per call on a 100 KB string). A loop that calls either one per
iteration is therefore quadratic. Read the length once into a local
(int len = s.length()), and for per-character work iterate
for (string c in s.chars()) (code points) or for (byte b in s.toBytes())
(bytes, the cheapest form) instead of indexing with charAt.
Also: s.replace("a", "b", n) replaces only the first n occurrences,
s.slice(start) runs to the end, s.substring(start[, length]),
s.lastIndexOf("x"), s.count("x"), s.repeat(n). The argument count and
types of string, number, list (length, first, last, reverse, pop,
join) and Map methods are checked at compile time: "hello".startsWith("h", 3)
is an error that shows the signature (fn startsWith(string prefix): bool), as is
a missing argument such as xs.join() or n.min().
String interpolation
string name = "Tim"
sys.output("Hello {name}, you are {age + 1} next year")Plain "{expr}" inside a double-quoted string, no prefix needed. Escape
literal braces with \{ / \}. Nested string/char literals inside the
embedded expression are handled correctly; a // comment inside an
embedded expression is not — a } inside such a comment would close the
interpolation early. For text full of braces (JSON payloads, fixtures), use
single-quoted raw strings ('...', where { is always literal) or build
the text with json.from({...}) instead of writing it by hand.
Single-quoted raw strings may span lines. “Raw” disables interpolation;
backslash escapes still work: \' embeds an apostrophe, \\ a backslash,
\n a newline, \r a carriage return, and \t a tab. \", \{, and
\} are also accepted; other backslash sequences are preserved literally.
So '\n' inside a multi-character raw string is a newline, not a backslash and
an n; write '\\n' for the two characters.
A single character such as 'x' or '\'' is a char literal.
string kernel = '
// The group\'s shared memory
kernel void run() { /* braces are literal */ }
'Escape apostrophes inside embedded source, including comments: an unescaped
' ends the raw string. A likely apostrophe inside a word is diagnosed at
that quote; a missing closing quote is diagnosed at the opening quote.
Numeric methods
n.toString() // -> string
n.abs() // -> same type; for float uses llvm.fabs
n.round() // -> same type; no-op on integers, llvm.round on float
n.floor() // -> same type; no-op on integers, llvm.floor on float
n.ceil() // -> same type; no-op on integers, llvm.ceil on float
n.round(2) // -> same type; rounded to 2 decimal places (also floor/ceil)
n.min(other) // -> same type
n.max(other) // -> same type
n.toInt() // -> int (a float saturates at the int range)
n.toLong() // -> long
n.toFloat() // -> float
n.toByte() // -> byte; wraps (300.toByte() is 44)
n.toBytes() // -> byte[]; little-endian (int, uint, long, byte)
x.toFixed(2) // -> string; "3.14" (an int works too: 3.toFixed(2) is "3.00")
x.toShortest() // -> string; shortest text that round-trips
n.toHex(4, true) // -> string; "0x00ff" (width and prefix are optional)Works on int/uint/long/float/decimal/byte/num.
Date
A built-in type, modeled as a one-field struct (internally { long ms },
milliseconds since the Unix epoch). All getters are local-time based.
long ms = Date.now() // current epoch ms, as a long
long us = Date.now.micro() // current epoch microseconds, as a long
long nanos = Date.now.nano() // current epoch nanoseconds (macOS: microsecond precision)
Date d = Date.new() // current date/time, as a Date
Date d2 = Date() // same as Date.new()
Date d3 = Date(0) // from an existing ms timestamp
Date d4 = Date("2026-05-17") // parsed from a string
d.getTime() // -> long, ms since epoch
d.getFullYear() // -> int
d.getMonth() // -> int, 0-11 (JS convention)
d.getDate() // -> int, day of month
d.getDay() // -> int, day of week, 0 = Sunday
d.getHours() // -> int
d.getMinutes() // -> int
d.getSeconds() // -> int
d.toString() // -> string, locale-formatted
d.toLocaleDateString() // -> string, same formatting
d.format("YYYY-MM-dd") // -> string, custom format template
sys.output(d) // same locale-formatted renderingDate(dateString) tries, in order: the exact shape toString() produces,
%Y-%m-%dT%H:%M:%S, %Y-%m-%d %H:%M:%S, then a bare %Y-%m-%d. A
date-only string is parsed as local midnight (not UTC midnight, unlike
JS), to stay consistent with every other Date getter being local-time. A
string matching none of these formats throws a catchable Error
(invalid date string: '...').
d.format(template) tokens
| Token | Output |
|---|---|
YYYY |
4-digit year |
MM |
2-digit month (01-12) |
dd |
2-digit day of month |
HH |
2-digit hour (00-23) |
mm |
2-digit minutes |
ss |
2-digit seconds |
zzz |
3-digit milliseconds |
UTC getters (getUTCFullYear() … getUTCSeconds()), toISOString(),
diff(other) (milliseconds) and addMs … addYears (each returns a new Date)
are available; see builtins. Not implemented:
calendar-component construction (Date(year, month, day)) and comparison operators
(<, >) on Date values (compare getTime()).
Error handling
throw Error("Not found", 404)
try {
int result = riskyOp()
} catch (Error e) {
sys.output(e.message) // string
sys.output(e.code) // int
}Running out of memory raises an Error with code 507 and a message that
starts with out of memory:; without a handler the program prints a memory
report and exits with status 71 (see Runtime memory).
Implemented via setjmp/longjmp (not LLVM landingpad unwinding):
throwing from a called function correctly unwinds to a try in the
caller, nested try/catch and rethrow from inside a catch both work, and
an uncaught throw prints radlang: uncaught exception: <message> with its
location and exits with status 1 (from radlang run too).
The location names the function and line that raised the error:
radlang: uncaught exception: list index out of bounds: index 7, length 3
location: main() (line 6)It is the raise site even when the error crossed an await (an async task’s error
reports the task’s line), and native crashes (radlang: fatal error) and the
out-of-memory message (at fn:line) use the same lookup. Since 1.40.52 locations come
from a line table built when the program links, so generated code does no
bookkeeping per statement. Libraries built before 1.40.52 report their caller’s line
until they are rebuilt. RADLANG_NO_LINE_TABLE=1 at build time switches back to the
older per-statement bookkeeping (a little slower); cross-compiled builds always use it.
Maximum nesting depth for try/catch is 64 frames.
Namespaces
ns greeter {
fn hello(string name): string {
return "Hello, " + name
}
}
fn main() {
sys.output(greeter.hello("Tim"))
}Namespaces can nest (outer.inner.f()) and hold types as well as
functions, including dotted type names (Types.User) and call-style
construction (Types.User("Tim", 30)).
Inside a namespace a bare type name means the namespace’s own type, else an
enclosing namespace’s. Signatures keep that meaning outside: in
ns outer { type Account {..} ns inner { fn make(): Account {..} } },
outer.inner.make() returns an outer.Account, and a parameter
fn(Account): string of a function in ns svc takes a
fn(svc.Account): string. A type argument follows the same rule:
Box<Mailbox> written in ns mailA is Box<mailA.Mailbox>, a different type
from Box<mailB.Mailbox>.
A generic type declared in a namespace is that namespace’s type on every path:
inside ns mailA { type Crate<T> { T v } }, Crate<int>(1), the inferred
Crate(2), a Crate<int> annotation, return type, field or list element all
name mailA.Crate<int>, which is what a caller outside writes
(mailA.Crate<int>(1) or mailA.Crate(1)). Two namespaces that each declare
a Crate<T> have distinct types, and a top-level Crate<T> is a third.
Inside a namespace, a nested namespace is reached by its own name: in
ns outer { ns inner { fn f() {..} } }, inner.f(), inner.T, inner.count
and inner.deep.g() written in outer (or in another namespace nested in
outer, such as a sibling of inner) mean outer.inner.f() and so on. The
nearest enclosing namespace with a child of that name wins. A name that already
means something else keeps that meaning: a local, parameter or loop variable,
a member of an enclosing namespace, a top-level namespace, import, function,
variable or type, and the built-in namespaces (json, sys, …).
Inside a namespace, a bare call or function value f names the namespace’s
own f when it has one, else the nearest enclosing namespace’s f, and
only then a top-level f: in ns store { fn clear() {..} fn run() { clear() } }
the call is store.clear() even when the program also has a top-level
fn clear(). Overloaded and generic siblings resolve the same way, as do
the copies of a compiled library’s generic functions made in the importing
program. A local variable or parameter named f wins over all of them.
Namespace variables are read as ns.name and assigned as ns.name = value
(also outer.inner.name = value), from inside or outside the namespace; inside
it the bare name works too. A priv variable can only be assigned from its own
namespace. Variables of a namespace compiled into a library (.rlc) are not
visible outside it: give the library functions to read and change them.
Protected vs. open
p ns config {
fn get(string key): string { ... }
}p ns name { ... } on a namespace’s first declaration makes it
protected: closed for modification, open for extension. A later ns name { ... } block (same file or, via import, another file) may add new
members but redefining an existing member is a compile error. Without
p, the namespace is open: later blocks can freely add or override
members, with the last-compiled definition winning. p is only legal on
a namespace’s first declaration and is not a reserved word elsewhere
(int p = 5 is fine).
Private members
ns math {
priv fn square(int n): int { return n * n }
fn sumOfSquares(int a, int b): int {
return math.square(a) + math.square(b)
}
}priv fn / priv type marks a namespace member as private to the file it
is declared in. Private members are accessible to sibling members within
the same namespace (same file), but are stripped before the namespace is
exported via any import form. Calling a private member from an importing
file produces a compile error (“namespace has no function ‘…’”).
sys is a reserved identifier. It cannot be used as a namespace name,
variable name, function name, parameter name, or type name. Any attempt
to shadow it produces a compile error. The builtin sys.* methods are
compiler intrinsics, not a real ns sys block.
Other built-in namespace names, including db, fs, gpu, and math,
are reserved too. See the complete reserved identifier list
before choosing local or declaration names.
Imports
import greeter from "greeter" // whole namespace, accessed
// as greeter.hello(...)
import { User, Status } from "types" // destructure specific
// members into top-level scope
import { // the member list may span lines
User, // (one name per line, comments and a
Status, // trailing comma are fine)
} from "types"
import * from "utils" // wildcard — every member of
// every namespace in that file
import "utils" // shorthand for import * from "utils"The file extension is optional. When omitted, the resolver tries .rlp,
.rlc, .ns.rad, then .rad, in that order. It checks the importing
file’s directory, the project root, the configured lib directory, and each
configured include project (including its root, lib/, and namespace source
directory). Explicit extensions are honored. Import cycles are detected and
rejected; diamond imports (two files importing the same third file) are
deduplicated rather than double-defined. import is top-level only —
not valid inside a function or namespace body.
A type imported by name is the namespace’s type, not a copy: after
import { Account } from "acct" and import acct from "acct", Account and
acct.Account are one type and mix freely (acct.Account a = Account(..),
fn f(): acct.Account { return Account(..) }). Same-named types of different
namespaces are different types even when their fields match: inside
ns ledger, a bare Account is ledger.Account when ledger declares one,
and passing, assigning or returning an acct.Account (or an imported
Account from acct) where a ledger.Account is expected is a type error
naming both types. A top-level type Account and a namespace’s own
Account are different types in the same way, whatever their fields:
acct.take(Account(..)) with a top-level Account is a type error.
A value declared outside the namespace keeps its type inside it: with a
top-level type Account and fn open(): Account, inside ns ledger (which
declares its own Account) var a = open() and open().address read the
top-level type, and Account a = open() is a type error naming
ledger.Account and the top-level Account.
A member imported by name brings in the types its signature and fields
name (parameters, return type, struct fields, the signature of a
function-typed field), under their bare names, so import { area } from "geo" lets area({ width: 3, height: 4 }) convert the literal to the
SizeOptions that area takes, and SizeOptions can be written too. This
is the same for a source file, a .rlc library and a package (.rlp); a
dependency that is missing or names two different types is left out, and a
private type or enum stays in its namespace (see Private members).
A member imported by name keeps its namespace’s types: after
import { open } from "acct", open returns acct.Account (also when
acct itself is not imported), so inside ns ledger
Account a = open("x") is a type error naming ledger.Account and
acct.Account, while var a = open("x") and passing a on to another
acct member work. The same holds for any function or variable whose
declaration names an imported Account. A library whose source imports a
type by name exports it as that namespace’s type, so a consumer can mix the
library’s results with acct.Account. Fields follow the same rule (a field
of an imported struct keeps its namespace’s type), and the bare and the
qualified spelling are one type in unions, lists, nullables, is checks,
match arms, generic arguments (Box<Account> is Box<acct.Account>) and
map key and value types (map[string, Account] is
map[string, acct.Account], also as map[string, Account[]] or
map[string, Box<Account>]). An anonymous struct literal ({ address: "a", port: 1 })
still converts to any struct type whose fields it fits.
Namespace libraries (.ns.rad / .rlc)
A .rlc (radlang library collection) file packages one or more
namespaces as compiled native code. Consumers import a .rlc exactly
like a .rad source file — the resolver handles both transparently.
Namespace source files always use the .ns.rad suffix and live in
<src>/namespace/ (e.g. src/namespace/log.ns.rad). radlang build
and radlang run automatically compile every .ns.rad file found there
into <lib>/<name>.rlc before building your program — a plain
import "log" in src/main.rad is enough; you don’t need to run
radlang lib yourself for anything living in src/namespace/.
A library is rebuilt only when its inputs changed, by content, not by
timestamp. Its inputs are:
- its source and extension files, and every source it imports (source imports are compiled into the consumer, so a body edit rebuilds the libraries that import it);
- the packages it uses;
- the profile,
config.yamland the compiler itself.
A fresh checkout or a branch switch rebuilds nothing whose content is unchanged.
Built libraries are also kept in a cache shared by every project and
checkout. When a library’s exact inputs were built before, by another worktree
or before an edit was undone, lib: <name> (cached) copies it instead of
compiling.
The cache lives in ~/Library/Caches/radlang/libs on macOS and
$XDG_CACHE_HOME/radlang/libs (or ~/.cache/radlang/libs) elsewhere:
RADLANG_LIB_CACHE=<dir>moves it, andRADLANG_LIB_CACHE=offturns it off.RADLANG_LIB_CACHE_MBcaps its size (default 4096; the least recently used entries go first).RADLANG_LIB_CACHE_VERIFY=1compiles anyway and reports any library that differs from its cached build.
The lib dir ("lib" by default) is build output only —
never put .ns.rad source there; it won’t be treated as importable
even if present, and build/run will warn about it.
radlang lib (no arguments) runs this same compile step for every file it
finds under src/namespace/, rebuilding only what changed; radlang lib --force rebuilds everything. Given a single file it compiles just that one:
radlang lib mylib.ns.rad -o mylib.rlcLibraries that don’t import each other compile in parallel, each in its own
compiler process: a library starts as soon as every library it imports has
been written. This applies to build, run, rtest, lib and export,
cross targets included. The output is the same as a one-at-a-time build: the
lib: <name> lines and any diagnostics print in dependency order, and a
failing build reports the error the one-at-a-time build would stop at. A
.rlc is written to a temporary file and renamed, so a failed compile never
leaves a partial library behind. Libraries that don’t depend on the failing
one and were already compiling are kept, so the next build may rebuild fewer
of them. The number of libraries compiled at once is, in order of precedence:
| Setting | Meaning |
|---|---|
RADLANG_LIB_JOBS=n |
At most n at once. 1 compiles one at a time inside the radlang process, exactly as before parallel builds. A value that isn’t a whole number of at least 1 prints a warning and the default is used. |
build.libJobs: n in config.yaml |
The same, for one project. |
| default | The number of CPU cores, at most 8. |
A library file must not define main(). Private members (priv fn,
priv type, priv const) are not visible to consumers. The private functions, constants and variables a public generic
function’s body uses are carried for its copies only.
Outside the namespace that declares it, a private type or enum cannot be
named by its qualified name, the same rule priv fn and priv variables
follow (the namespace itself and extensions of it are inside; a nested
namespace is outside). With ns g5 { priv type Hid { int n } }, these are
each 'Hid' is private to namespace 'g5': g5.Hid h, a parameter, return
type or struct field of type g5.Hid (also inside g5.Hid[], g5.Hid?,
map[string, g5.Hid], a union and Box<g5.Hid>), g5.Hid(9),
x is g5.Hid, a g5.Hid match arm and json.parse<g5.Hid>; a private
enum’s g5.Mode.A likewise. Values of the type that the namespace’s public
functions return stay usable through inference (var h = g5.make(), h.n,
passing h back, a var list of them), a public function may name the type
in its signature, and the namespace’s own code, generic functions’ copies
included, names it freely. A compiled library carries its private types and
enums so that a consumer gets the same error as from a source import.
A member import (import { make } from "g5", from a source file, a .rlc or
a package) whose members use a private type leaves that type in its
namespace: the imported members keep using it (their signatures, their
generic templates, which may write it bare or as g5.Hid, inference and
anonymous literals that take it), but the importer cannot write it, bare or
qualified (Hid h, Hid(9), Box<Hid>, Mode.A are each the same error).
An importer that declares its own Hid means its own type. The compiled object code and type metadata are both embedded
in the single .rlc file, so no separate header or manifest is needed.
Public namespace const declarations are exported through .rlc and .rlp:
settings.MODE reads the library’s initialized storage from either a program
or another namespace. Member imports such as import { MODE } from "settings"
also work and preserve the constant binding. Initializers still execute once;
importing a constant does not copy or rerun its initializer. Lists/objects keep
the existing shallow-constant semantics. Ordinary mutable namespace variables
are not exported; expose them through getter functions. (The library’s
generic functions, instantiated by the consumer, still reach them, see
Generic functions.)
Libraries built before constant metadata support must be rebuilt with
radlang lib; re-export packaged .rlp artifacts and rebuild consumers too.
Older libraries remain readable but do not expose constants they never recorded.
Packages (.rlp)
radlang export collects every .rlc in the configured lib directory into a
single .rlp archive. Each .rlc remains intact inside the package, so all
namespaces, nested namespaces, interfaces, metadata, and native objects remain
available to consumers:
radlang export -o stdlib.rlpWithout -o, the package is written to
output/package/<project.name>.rlp.
Libraries are compiled per platform, so a package used by iOS or Android apps
also needs those builds. radlang export --target <target> (ios,
ios-simulator, android, linux-x86_64) compiles the namespaces for that
target and writes output/package/<target>/<project.name>.rlp, beside the host
package (android writes android-arm64/). Consumers keep a single
packages: entry pointing at the host .rlp; when it is installed into their
lib/, the per-target builds next to it are installed into lib/<target>/,
and radlang build --target … links them. A package without the build a
target needs fails that build with an error saying so. Export with the same
radlang version the consumers build with: libraries carry its ABI.
radlang export # output/package/mylib.rlp
radlang export --target ios # output/package/ios/mylib.rlp
radlang export --target ios-simulator # output/package/ios-simulator/mylib.rlp
radlang export --target android # output/package/android-arm64/mylib.rlpEach library records the radlang version that built it. radlang packages
lists the packages in config.yaml with that version for the host build and
for every target build found beside it, so a target package left behind by an
older compiler is visible:
radlang packages
stdlib 1.0.0
host: built with radlang 1.34.5 (../stdlib/output/package/stdlib.rlp)
ios: built with radlang 1.34.0 (this is 1.34.5) (../stdlib/output/package/ios/stdlib.rlp)radlang build prints one note: line for a package built by a different
minor version. It is information only: a package is rejected only when its
runtime ABI differs.
Place the package in the project root, configured lib/, or an included
project, then use normal imports:
import rtest from "stdlib"When both stdlib.rlp and stdlib.rlc exist, .rlp wins. Packages may
contain multiple libraries and their namespaces are merged, including dotted
namespace extensions.
Package dependencies are nestable in config.yaml; radp owns installing and
selecting the matching package version:
packages:
r_stdlib:
path: "../stdlib/output/package/r_stdlib.rlp"
version: "1.*"
web:
version: "*"Omitting version means the latest available version. Version selectors may
be exact (1.2.3) or use wildcards (1.*, 1.2.*, *). Once installed,
the package can be imported by symbol name: import rtest from r_stdlib.
String paths remain available for local/source imports.
Built-in sys namespace
sys.output(value) // print to stdout with a trailing newline;
// accepts any type: numerics, bool, string,
// lists, structs, Date
sys.error(value) // print to stderr with a trailing newline
sys.input() // block for one line of stdin; returns it
// as a string with the trailing newline stripped
sys.input("prompt: ") // same, printing a prompt first (no newline)
sys.exit(code) // terminate the process with exit code
sys.env("HOME") // read an environment variable; returns ""
// if not set
sys.env("KEY", "VAL") // set environment variable
sys.sleep(ms) // pause execution for ms milliseconds
sys.args() // -> string[]; command-line arguments,
// argv[0] excluded
sys.cwd() // -> string; current working directory
sys.pid() // -> int; current process ID
sys.platform() // -> string; "darwin", "linux", or "windows"
sys.arch() // -> string; "arm64" or "x86_64"
sys.hostname() // -> string; machine hostname
sys.cores() // -> int; number of online logical CPU cores
sys.home() // -> string; user's home directory
sys.tmp() // -> string; system temporary directory
sys.sleepAsync(ms) // -> Future<void>; non-blocking timer for use
// with await inside an async fn (see Async)
sys.cli(cmd) // -> Future<int>; executes a shell command in the
// background via worker pool
sys.spawn(exe, args) // -> Future<int>; spawns a child process with args
// directly, bypassing the shell
sys.blockOn(future) // -> T; run the scheduler until the Future<T>
// resolves, then return its value (see Async)sys is a reserved identifier — it cannot be used as a namespace name,
variable name, function name, or parameter name. The built-in methods are
compiler intrinsics, not a real ns sys block, and there is no
user-facing way to extend them.
Built-in math namespace
Mathematical functions and constants. All functions accept and return
float. Integer arguments are automatically widened.
Constants
math.PI // 3.14159...
math.E // 2.71828...
math.TAU // 6.28318... (2*pi) Functions
math.random() // -> float; uniformly in [0, 1) — auto-seeded per run
math.sqrt(x) // -> float
math.abs(x) // -> float
math.floor(x) // -> float
math.ceil(x) // -> float
math.round(x) // -> float
math.log(x) // -> float; natural log (ln)
math.log2(x) // -> float
math.log10(x) // -> float
math.sin(x) // -> float
math.cos(x) // -> float
math.tan(x) // -> float
math.tanh(x) // -> float; hyperbolic tangent
math.exp(x) // -> float; e raised to x
math.pow(base, exp) // -> float
math.min(a, b) // -> float
math.max(a, b) // -> float
math.clamp(x, lo, hi) // -> float; clamps x to [lo, hi]
math.seed(n) // -> void; seeds the underlying rand() sequenceNote: math.random() uses rand(), auto-seeded once at process start from
the clock and pid (before any user code runs), so the sequence differs
between runs by default. Call math.seed(n) — anywhere before the first
math.random() call — to force a specific, repeatable sequence instead
(e.g. for tests or replays); it overrides the automatic seed. Unlike the
old extern fn escape hatch (removed from the language; see Known
limitations), math.seed is a real compiler intrinsic — it doesn’t grant
general C access, it just wraps srand() specifically.
Note: math.min/math.max always return float regardless of input
types, unlike the numeric instance methods .min()/.max() which return
the same type as the receiver.
Built-in fs namespace
File system operations. Paths are resolved relative to the current working directory unless absolute.
Reading files
string? text = sys.blockOn(fs.readText("data.txt")) // null if not found
string? syncText = fs.readTextSync("data.txt")
byte[] bytes = sys.blockOn(fs.readBytes("data.bin"))
byte[] syncBytes = fs.readBytesSync("data.bin")fs.readText and fs.readBytes run on the async worker pool and return
futures. Use await inside an async fn or sys.blockOn from synchronous
code. The *Sync variants perform the blocking operation directly.
readText resolves to a nullable string? — always check for null before
using the result.
Writing files
bool ok = sys.blockOn(fs.writeText("out.txt", content))
bool ok2 = sys.blockOn(fs.appendText("log.txt", line))
bool ok3 = sys.blockOn(fs.writeBytes("out.bin", data))
bool ok4 = sys.blockOn(fs.appendBytes("out.bin", data))
bool syncOk = fs.writeTextSync("out.txt", content)
bool syncAppend = fs.appendTextSync("log.txt", line)
bool syncBytes = fs.writeBytesSync("out.bin", data)
bool syncAppendBytes = fs.appendBytesSync("out.bin", data)The unsuffixed write operations return Future<bool> and run on the async
worker pool. The *Sync operations return bool directly. All indicate
success or failure rather than throwing.
File info
bool exists = fs.exists("config.json")
FileInfo info = fs.stat("config.json")
// info.exists bool
// info.isFile bool
// info.isDir bool
// info.size int (bytes)
// info.modified long (epoch ms)
// info.created long (epoch ms)
// info.permissions int (octal mode) Directory operations
string[] entries = fs.listDir("/tmp") // filenames only (no . or ..)
string[] full = fs.listDirFull("/tmp") // full absolute paths
bool ok = fs.mkdir("output/logs") // creates parent dirs (mkdir -p)
bool removed = sys.blockOn(fs.delete("temp.txt")) // unlink or rmdir
bool syncRemoved = fs.deleteSync("temp-sync.txt")
string[] paths = sys.blockOn(fs.walk("src"))
string[] syncPaths = fs.walkSync("src")
DirEntry[] entries = sys.blockOn(fs.readDirInfo("src"))
DirEntry[] syncEntries = fs.readDirInfoSync("src")DirEntry contains the child’s full path and a FileInfo value in info.
walk recursively visits descendants; readDirInfo reports immediate
children with metadata.
Rename, copy, and temporary paths
bool renamed = sys.blockOn(fs.rename("old.txt", "new.txt"))
bool copied = sys.blockOn(fs.copy("new.txt", "backup.txt"))
string tempFile = sys.blockOn(fs.tempFile())
string tempDir = sys.blockOn(fs.tempDir())
bool syncRenamed = fs.renameSync("old.txt", "new.txt")
bool syncCopied = fs.copySync("new.txt", "backup.txt")
string syncTempFile = fs.tempFileSync()
string syncTempDir = fs.tempDirSync()The unsuffixed operations run on the async worker pool and return futures;
their Sync twins perform the blocking operation directly.
Watching a path
fs.watch("config.json", fn(string changedPath): void {
sys.output("changed: " + changedPath)
})The callback is scheduled on RadLang’s microtask queue after the path’s existence, size, or modification time changes. An active watch consumes one shared async worker while waiting.
Path utilities
fs.basename("a/b/c.rad") // -> "c.rad"
fs.dirname("a/b/c.rad") // -> "a/b" (returns "." if no directory component)
fs.extension("c.rad") // -> ".rad" (empty string if none)
fs.resolve("../config") // -> absolute path via realpath()
fs.join("output", "file") // -> "output/file" Built-in json namespace
JSON parsing and serialization. JSON is read into a declared type, or into a
Map when an object’s keys aren’t known in advance. (JsonNode, the parser’s
tree type, is internal: naming it, untyped json.parse(s) and the old
json.get/json.at/json.getString/json.keys/… calls are compile errors.)
Parsing
// Typed parse — converts directly to a radlang type
User u = json.parse<User>('{"name":"Tim","age":30}')
int n = json.parse<int>("42")
bool ok = json.valid(text) // well-formed JSON? (json.parse<T> throws if not)json.parse<T> supports: primitive types (int, float, bool,
string), Map, named struct types, lists of those, and generic
instantiations like json.parse<Box<int>>(...). A nullable field
(int? exp) is null when its key is missing.
Objects with unknown keys
Map m = json.parse<Map>(body)
string name = m.get("name") // a string member is its text
int age = json.parse<int>(m.get("age")) // any other member is its JSON
Map geo = json.parse<Map>(m.get("geo")) // nested objects parse again
string[] keys = m.keys() // in document orderA missing key reads as "" (m.has(key) tells them apart); anything but an
object parses to an empty map.
Serialization
string s = json.from(value) // serialize any radlang value to a JSON stringSerialization supports: int, long, float, bool, string, null,
structs (as {"field":value,...}), lists (as [elem,...]), and Map (an object
whose values are JSON strings). json.fromExact(value) writes floats in the
shortest form that reads back to the same value (json.from rounds them).
Built-in http namespace
The http namespace provides outbound HTTP client capabilities. The
httpserver namespace provides an inbound HTTP server. They are separate
reserved identifiers.
Outbound client (http.*)
All client methods use libcurl. The unsuffixed methods are asynchronous and
return Future<HttpResponse>; use await in an async fn or use the ...Sync
twins for blocking calls.
HttpResponse r = await http.get("https://example.com/api")
HttpResponse r = await http.delete("https://example.com/item/1")
// Methods with a body:
HttpResponse r = await http.post("https://example.com/api", body, "application/json")
HttpResponse r = await http.put("https://example.com/api", body, "application/json")
HttpResponse r = await http.patch("https://example.com/api", body, "application/json")
// Full control with custom headers:
string[] headers = ["Authorization: Bearer token", "Accept: application/json"]
HttpResponse r = await http.request("GET", url, headers, "")The blocking equivalents are http.getSync, http.deleteSync, http.postSync,
http.putSync, http.patchSync, and http.requestSync, with the same
arguments and a direct HttpResponse return.
Note: http.post, http.put, and http.patch currently ignore the
contentType argument. Use http.request when you need to set a custom
Content-Type or other request headers.
HTTP server (httpserver.*)
HttpServer server = httpserver.serve(8080, "127.0.0.1") // explicit loopback; omitted address defaults to 0.0.0.0
// Register route handlers (closures are supported — they can capture variables)
server.get("/hello", fn(HttpRequest req): HttpResponse {
return HttpResponse(200, "hello world", { "Content-Type": "text/plain" })
})
server.post("/echo", fn(HttpRequest req): HttpResponse {
return HttpResponse(200, req.body, { "Content-Type": "text/plain" })
})
server.put("/item", fn(HttpRequest req): HttpResponse { ... })
server.delete("/item", fn(HttpRequest req): HttpResponse { ... })
server.patch("/item", fn(HttpRequest req): HttpResponse { ... })
// CORS support
server.enableCORS()
server.allowOrigins(["https://example.com"])
server.allowHeaders(["Content-Type", "Authorization"])
server.allowMethods(["GET", "POST", "OPTIONS"])
// Start the server
server.listen() // blocking — runs the accept loop on the current thread
server.start() // non-blocking — runs accept loop in a detached thread
// Shut down
server.close()Route matching is exact — no path parameters or wildcards. CORS preflight
OPTIONS requests are handled automatically when enableCORS() is called.
Request and response types
type HttpRequest = {
string method,
string path,
string query,
string body,
string headers
}
type HttpResponse = {
int status,
string body,
string contentType
}req.headers holds the full raw header block. To read a single header by name
(case-insensitive), use req.header(string name):
string token = req.header("Authorization")Route params (:id segments, see below) are read the same way with
req.param(string name).
Database
The db namespace provides database connectivity. SQLite is always available;
MySQL is available when libmysqlclient is installed (auto-detected at build time).
database.md is the full reference; this is the
outline. Every example below was run on 1.40.26 against sqlite://:memory:.
Schema declaration
A schema block maps a struct to a database table. Its name must end in Tbl;
the row type it reads into is Db plus the name without Tbl (UsersTbl reads
DbUsers). Fields go one per line, with no comment inside the body:
schema UsersTbl<"users"> [snakeLower] {
[pk] int id
string firstName
["email_addr"] string email
int? age
}<"table_name">— override the table name (default: the schema name as-is)[snakeLower]/[snakeUpper]— convert camelCase field names to snake_case columns["col_name"]before a field — per-field column name override[pk]before a field — the primary key (required forupdateanddelete)T?field types — nullable columns; reads returnnullwhen the column is SQL NULL
Connection
Database conn = db.connect("sqlite://./mydb.db") // or sqlite://:memory:
Database conn = db.connect("mysql://user:pass@host:3306/dbname")
conn.migrate(UsersTbl) // create or extend the table
conn.close()db.connect throws Error on failure. Wrap in try/catch to handle connection errors.
Read and write
Each call has an async form (read, insert, update, delete, query: await it
in an async fn) and a blocking ...Sync twin:
conn.insertSync(UsersTbl, { id: 1, firstName: "Tim", email: "tim@example.com", age: 30 })
conn.updateSync(UsersTbl, { id: 1, firstName: "Timothy" }) // the [pk] field picks the row
DbUsers[] users = conn.readSync(UsersTbl)
DbUsers[] later = await conn.read(UsersTbl) // inside an async fn
conn.deleteSync(UsersTbl, 1) // the row whose pk is 1 Raw query
string[][] rows = conn.querySync("SELECT first_name, age FROM users")
for (string[] row in rows) {
sys.output(row[0] + " is " + row[1])
}Returns every row as a string[]. Useful for ad-hoc queries, DDL, or joins across schemas.
Query builder
DbUsers[] adults = conn.selectSync().from(UsersTbl).where("age > 18").orderBy("first_name").limit(10)where and orderBy take SQL, so they name columns (first_name), not fields.
Update and delete through the builder with the blocking chain; without .where()
they apply to every row:
?UsersTbl changes = { firstName: "Timothy" }
conn.selectSync().from(UsersTbl).where("id = 1").update(changes)
conn.selectSync().from(UsersTbl).where("age < 18").delete() Partial types (?Type)
A ?Type declaration is a compile-time-validated subset of a named struct or schema:
?UsersTbl changes = { firstName: "Tim" }All field names in the literal must exist in the base type. Bind a partial to a
variable before passing it: a ?T { ... } literal is not accepted inline as an
argument. See database.md for column projection.
Async and await
Functions declared async fn run as cooperative coroutines on a single-threaded
scheduler. Calling one spawns a coroutine that starts executing immediately
(eager execution) and yields a Future of the declared return type; the body
runs until it completes or reaches its first await on an unresolved future.
async fn fetchAnswer(): int {
await sys.sleepAsync(100) // suspends this coroutine; others keep running
return 42
}
async fn doubled(): int {
int a = await fetchAnswer() // await another async fn
return a * 2
}
fn main() {
var f = doubled() // Future; body already running
int result = sys.blockOn(f) // run the scheduler until resolved (the compiler warns: in
// a server or a long program, make the caller async and `await`)
sys.output(result) // 84
}Rules and behaviour:
await expris only legal inside anasync fnbody. The operand must be a future; the expression’s value is the future’s payload.mainis synchronous.sys.blockOn(future)is the on-ramp: it drives the scheduler until the future resolves and returns its value. The compiler warns that it is unsafe anywhere else: it blocks every other request and coroutine on the thread until the future settles, so inside async code useawait.- Concurrency is cooperative and single-threaded — coroutines only interleave
at
awaitpoints, so there are no data races on shared values. - Each coroutine has its own stack and exception-handler state. Suspended coroutine stacks and saved exception state remain collector roots while the coroutine can resume, keeping its live values intact.
sys.sleepblocks the whole process; useawait sys.sleepAsync(ms)inside async code.
Future combinators
async fn page(string url): string { ... }
async fn load(): string {
// Wait for several futures; results come back in input order.
string[] pages = await Future.all([page("/a"), page("/b"), page("/c")])
// Take whichever settles first.
string fastest = await Future.race([page("/mirror1"), page("/mirror2")])
// Bound a wait; on expiry a catchable Error with code 408 is thrown.
try {
string slow = await page("/slow").timeout(2000)
} catch (Error e) {
sys.output(e.message) // "future timed out after 2000 ms"
}
return fastest
}
var job = load()
job.cancel() // true: job was still pendingFuture.all(Future<T>[] futures): Future<T[]>resolves once every input has resolved, with the values in input order (not completion order). If an input rejects, it rejects as soon as the first rejection happens, with that error; other inputs keep running. An empty list resolves to[]. OverFuture<void>[]it is aFuture<void>.Future.race(Future<T>[] futures): Future<T>settles like the first input to settle: its value, or its error. An empty list rejects withError("Future.race needs at least one future"). The other inputs keep running.future.timeout(int ms): Future<T>settles likefutureif it settles withinmsmilliseconds; otherwise it rejects with code408and the messagefuture timed out after <ms> ms. A negativemscounts as 0. The original future keeps running.future.cancel(): boolsettles a pending future as rejected with code499(future cancelled) and returnstrue; on an already-settled future it does nothing and returnsfalse. Everyone awaiting it (await,sys.blockOn, combinators) stops waiting and gets that error;.resolvecallbacks do not run.
Combinator results are ordinary futures: they can be awaited, passed to
sys.blockOn, given .resolve callbacks, nested in other combinators, and
cancelled. A combinator holds its inputs (and their results) alive until its
own result is released.
What cancellation stops, exactly:
- An
async fnor async closure is cancelled cooperatively. If it is parked in anawait, thatawaitthrows the cancellation error inside the task right away (during thecancel()call), so itstry/catchblocks run and it unwinds. Every laterawaitin the task throws the same error, so cleanup code must not rely on awaiting. If it is inside a blocking intrinsic instead (a socket read, a channel receive), it stops at its nextawait. Its eventual return value is discarded. - A
sys.sleepAsyncfuture’s timer is disarmed. A task stopped while awaiting a sleep that nothing else references disarms that timer too. - Work already handed to the worker pool or the network (
http.*,fs.*,db.*,sys.cli, …) runs to completion and its result is discarded; cancel does not abort it. - Cancelling a combinator does not cancel its inputs, and a timeout or race does not cancel the futures it stopped waiting for. Cancel those explicitly:
var slow = page("/slow")
try {
string body = await slow.timeout(500)
} catch (Error e) {
slow.cancel()
}Current limitations (Phase 1):
async fnmay be declared in a namespace. Anasync fncannot be overloaded (a compile error): give each one its own name.- Filesystem content I/O (
fs.read*,fs.write*,fs.append*) and database base operations are asynchronous; use the*Syncfilesystem/database variants when blocking behavior is required.sys.sleepAsyncand these worker-backed operations are suspension sources alongside awaiting another async fn. - An error thrown inside an async fn rejects its future;
awaitandsys.blockOnrethrow it as a catchableError. - A coroutine’s result stays alive while a Future, caller, or other runtime owner can reach it. When those references disappear, the traced collector can reclaim the result and its reachable graph.
Test framework
radlang has a built-in test runner. Test blocks are declared at the top
level of a .test.rad file:
test "adds two numbers" {
int result = add(2, 3)
if result != 5 {
throw Error("expected 5, got " + result.toString(), 1)
}
}
test "handles empty string" {
string s = ""
if s.length() != 0 {
throw Error("expected 0 length", 1)
}
}Each test block runs in isolation inside its own setjmp frame. A
throw inside a test is caught and recorded as a failure — the remaining
tests still run. Run with:
radlang rtest feature.test.rad # explicit file
radlang rtest # no argument: the tests under paths.tests in config.yamlOutput:
testing feature.test.rad...
[FAIL] handles empty string: Assertion failed: expected 0 length (expected 0, got 5)
↳ test/feature.test.rad:12:6
1/2 tests passedThe rtest command exits with code 1 if any test fails, 0 if all
pass. A test file does not need a main().
How test binaries are built and run
When rtest is given more than one file it builds the test binaries a batch at
a time, several at once, while no test is running. Then it runs the batch:
files that can be shown to be pure in-process computation run several at once,
and every other file runs alone, one at a time, in file order. Results are
always reported in file order, and the output, counts and exit code are the
same as running the files one by one.
A file runs concurrently only when its source, and every source file it imports, does none of the following; anything not shown safe runs alone.
- Use a side-effecting built-in namespace:
fs,http,httpserver,db,tcp,websocket,sse,gui,syn,gpu,native,ratelimit,multipart(or a resource type they create, such asHttpServerorDatabase). - Use
sysother thansys.output,sys.blockOnandsys.args(so nosys.sleep,sys.exec,sys.service,sys.worker,sys.env). - Read the clock or time anything:
now,Date(...),Date., or a name containingsleeportimeout. - Import something that cannot be shown safe: an import that does not resolve, or a compiled library or package member that carries no effects record and has no source next to it (see below).
A compiled library does not need its source for this. radlang lib,
radlang build and radlang package record the same facts, taken over the
library’s own sources and everything they import, in the library’s metadata
(effects, absent from libraries built by earlier compilers), and a package
keeps the record of each member. rtest reads that record for an imported
library, or for the members of a package that the import names (all of them for
* or a bare import), so a test that imports only libraries with an empty
record can run concurrently. A library built by an older compiler has no record:
it is read from its source when the project has the .ns.rad, and otherwise its
tests run alone until the library is rebuilt (radlang packages shows which
compiler built each one). An older stdlib package is still accepted for the
members rtest, collections, validate and cryptoutil.
Two line comments in a test file override the scan for that file:
// rtest: serial always run this file alone
// rtest: parallel this file is safe to overlap (you have checked it)| Setting | Meaning |
|---|---|
RADLANG_TEST_JOBS=n |
Build at most n test binaries at once (default: the number of CPU cores, at most 8), and run at most n safe tests at once. 1 builds each file inside the radlang process just before running it and runs everything serially. |
RADLANG_TEST_RUN_JOBS=n |
Run at most n safe tests at once (default: RADLANG_TEST_JOBS). 1 keeps builds parallel and runs every file alone. |
RADLANG_RTEST_TRACE=1 |
Print wall times to stderr: each build batch, each concurrent run, each file’s build and run time, and why each file was classified serial. |
RADLANG_RT_CACHE=<dir> |
Where compiled runtime objects are kept. off compiles the runtime sources again for every link. |
--verbose runs one file at a time, with live output.
A development checkout links test binaries (and builds without a prebuilt
runtime.a) from the runtime’s C sources. Each source is compiled once and its
object kept in ~/Library/Caches/radlang/rt-objs on macOS and
$XDG_CACHE_HOME/radlang/rt-objs (or ~/.cache/radlang/rt-objs) elsewhere. An
object is reused only while the compiler, the flags, the source and every
header it includes are unchanged, so an edited runtime file is recompiled on
the next link. Objects unused for 30 days are removed.
Where compile time goes
RADLANG_TIMINGS=1 prints one line per finished compile phase to stderr, for
build, run, lib and rtest:
timing: resolve 3.5 ms
timing: analyse 1.0 ms
timing: codegen 8.4 ms
timing: verify 1.3 ms
timing: object 108.2 ms
timing: link 540.1 msresolve reads and merges the sources, analyse type-checks, codegen builds
the LLVM module, verify checks it, write-ir and object write the .ll file
and the optimized object, and link produces the binary. Library and test
builds that run in worker processes print their own lines. The setting changes
nothing else.
Tests are not part of release builds
radlang build (the optimized, release profile) ships no test code. Inline
test "..." { } blocks in the entry file are removed before analysis, so they are
not compiled into the binary and cannot fail the build; *.test.rad files are never
compiled into a build, and intf declarations in them are not added to the
project-global interface set. radlang rtest runs tests and sees all of that. The
debug profile (radlang run) still type-checks inline test blocks so mistakes
surface while you develop. Namespace libraries compiled for a release build follow
the same rule; a standalone radlang lib file.rad uses the debug profile and keeps
them.
Stdlib libraries
These namespace libraries ship in the stdlib package that radlang new vendors
into a project (their source is in libraries/stdlib/). Import them by name from
"stdlib".
Log
import Log from "stdlib"
Log.Logger logger = Log.create("./app.log")
logger.info("server started")
logger.debug("debug details")
logger.warn("something looks off")
logger.error("something went wrong")Log.create(path) opens or creates the log file and returns a Logger
struct. Each method appends a timestamped line (YYYY-MM-dd HH:mm:ss level message) to the file and echoes it to stdout. Throws Error if the file
cannot be written.
Timer
import Timer from "stdlib"
long start = Timer.now() // current epoch ms as long
long elapsed = Timer.elapsed(start) // ms since start
string label = Timer.elapsedMs(start) // "42ms"Timer.now() wraps Date.now(). timer.sleep(ms) is not yet implemented in the stdlib library; use sys.sleep(ms) directly for pausing execution.
Platform support
Windows is not supported. Linux, Intel macOS, iOS and Android runtime execution
gates remain unverified; a successful build alone is not target acceptance.
The runtime uses stackful coroutines (async/await; a register-only context
switch on arm64 and x86_64, POSIX ucontext elsewhere), setjmp/longjmp
exception handling, and a traced heap. Use a verified host target for now.
Known limitations
Language:
- A named function may be declared inside another function’s body, but a
generic one (
fn foo<T>(...)) cannot: it reports “unexpected token: Lt”. Use a top-level generic function, orvar handler = fn(...) { }for a local closure. - Named top-level functions (
fn handler(...)) do not capture outer scope — usevar handler = fn(...) { }for closures that reference outer variables. - For real boxed/tagged dynamic values use
any(see Dynamic values), which carries a runtime tag and safely holds scalars, strings, lists, closures, and structs.varis different: it resolves to the value’s concrete type at compile time (a fn withvarparams is specialized per call site), but a value whose type cannot be determined statically (avarpassed on to anothervarparam) falls back to an untaggedi64and cannot safely hold a string or struct. A mixedvar[]literal resolves toany[](rejected under#safe).
Types and methods:
http.post/put/patchignore thecontentTypeargument; usehttp.requestfor full header control.- Route matching on
httpserveris exact — no path parameters or wildcards.
Methods that do not exist: lists have no .filter() (use where or a
comprehension), .find()/.findIndex() (use indexOf), .min() or .max().
A list method’s callback goes first: xs.reduce(fn combine, seed),
xs.map(fn, threadCount); a non-function where the callback belongs is a
compile error.
Memory:
- Managed values live in one traced heap. A value remains alive while reachable from program state, a closure, a pending Future, a coroutine, or a runtime owner. Unreachable values, including cycles, can be reclaimed.
- A thread-private nursery handles young values. Young collection traces the current thread’s nursery and roots; full collection traces the whole heap. Stores into older or global state and transfers to other threads publish referenced values before they become visible.
- Scope exit, function return and
using { }do not promise that managed memory is immediately reclaimed. Keep long-lived lists, Maps, globals and caches limited to values the program still needs. A stale pointer-looking value in a conservatively scanned stack or native region may retain an object longer than expected. - Suspended coroutines and saved exception-handler state remain roots while they can resume. A Future’s result stays alive while the Future or another runtime owner can reach it.
- Use
using (Resource value = ...)orclose()for deterministic disposal of native resources. Garbage collection is a safety net for managed values, not a substitute for closing sockets, files, databases or handles. - Memory limits raise a catchable
Errorwith code 507. See Runtime memory for accounting and target status. - Maximum exception nesting depth is 64 frames.
Compiler/tooling:
#safemode is only honored from the entry file — a#safedirective in an imported file is silently ignored.- Return types use
:syntax only —->is not supported and will produce a parse error. This applies to named functions, anonymous closures, and function type declarations. - A Zed extension ships with the compiler at
editors/zed/: syntax highlighting, format-on-save (radlang fmt), and an LSP (radlang lsp) with diagnostics and hover. Hover only resolves one member-access level deep (receiver.member); chained access (a.b.c) falls back to no info. - Packages are
.rlparchives listed underpackages:in config.yaml (radlang add --pathinstalls a local one);import { name } from "stdlib"reads one. A package import needs a project:radlang newvendors the stdlib package intolib/and lists it in config.yaml. A single.radfile outside a project cannot import stdlib. - Built-in namespaces:
sys,cfg,math,fs,json,xml,regex,hash,crypto,compress,http/httpserver,db,tcp,websocket,sse,multipart,ratelimit,gpu,gui,syn,native(see builtins); the stdlib package adds libraries such asrtest,logandlayout. There is no way to call arbitrary libc functions — theextern fnescape hatch was removed from the language; only the fixed set of intrinsics above is reachable.