radlang — Best practices

This guide is opinion, not compiler law. The toolchain accepts many layouts and styles; the ones here are the defaults that keep a radlang project consistent, its main readable, and its diffs small. It has two parts:

For the language reference see the Overview; for the defined edge-case behavior (overflow, division by zero, bounds) see Semantics.


Part 1 — Project conventions

Project layout

radlang new <name> creates the default app starter. Choose another with --template cli|api|web|lib|gui|mcp; see new projects. The default shape is:

myapp/
├── config.yaml            # project metadata, paths, pinned package version
├── AGENTS.md
├── README.md
├── .gitignore             # generated RLCs, output/, .radenv
├── src/
│   ├── main.rad           # fn main(); omitted by the lib starter
│   └── namespace/
│       └── app.ns.rad
├── test/                  # *.test.rad files
└── lib/
    └── stdlib.rlp          # vendored package; no loose stdlib RLC copies

Keep the executable entry point in src/main.rad and reusable code under src/namespace/. Namespace sources auto-compile to ignored lib/*.rlc outputs on build/run. Import a local namespace with import "app"; import a packaged namespace with import { mcp } from stdlib using its configured package name. Library starters use radlang lib and radlang export instead of run.

config.yaml

The scaffold writes a minimal config; grow it as needed. The paths block tells the compiler where things live, so the CLI’s file-less forms (radlang run, radlang rtest) just work:

project:
  name: "myapp"
  version: "0.1.0"
  cores: 1            # HTTP prefork workers; omit for CPU count, 1 disables

paths:
  build: "output"
  lib: "lib"
  src: "src"
  tests: "test"
  namespace: "src/namespace"

packages:
  stdlib:
    path: lib/stdlib.rlp
    version: "1.0.0"

env:
  PORT: 8085

Read these values at runtime through the compiler-injected cfg namespace — cfg.name, cfg.env("PORT"), cfg.buildDir. See Project config.

Keep secrets out of config.yaml. The config.yaml env: block is baked into the binary and recoverable with strings, so it is for non-secret defaults only. Put passwords, API keys, and tokens in a gitignored .radenv instead — it loads at run time (not baked) and overlays the config defaults, so cfg.env("API_TOKEN") still returns it. See Project config.

File naming — kebab-case.type.rad

Name files in kebab-case with a .type.rad suffix, never underscores or PascalCase. The middle token labels what the file is:

db-service.ns.rad     // a namespace (library)
chat-room.ns.rad      // a namespace (library)
uid.test.rad          // a test / scratch harness
main.rad              // the entry point (no type token)

So user-store.ns.rad, not user_store.rad or UserStore.rad.

For variables and parameters, avoid the reserved built-in namespace names. Use conn for a database connection and weightsBuffer for a GPU buffer; db is reserved regardless of the value’s type.

Keep intrinsics behind a service namespace

Built-in namespaces (db, fs, http, crypto, …) are powerful but low-level. When one is used in more than one place or carries setup — a connection, a handle, a base URL — wrap it in a purpose-named namespace with intention-revealing methods and call that from main. Keep the raw intrinsic out of main.rad.

// src/namespace/user-store.ns.rad
type User { string name, int age }

ns UserStore {
    priv User[] users = []

    fn add(string name, int age): void {
        users.add(User(name, age))
    }

    fn count(): int {
        return users.length()
    }
}
// src/main.rad
import "user-store"

fn main() {
    UserStore.add("Ada", 36)
    UserStore.add("Alan", 41)
    sys.output("users: {UserStore.count()}")   // main reads as domain steps
}

The connection string, schema wiring, and any backend swap then live in one file; main stays declarative; and the seam is easy to stub in tests. A one-off script calling a single intrinsic doesn’t need this — reach for the wrapper when setup or reuse appears. (This mirrors the Conventions section of the overview.)

Tests

Put tests in test/ as *.test.rad files. A test file needs no main — it is a set of test "name" { } blocks. Import the bundled rtest helper for assertions:

// test/user-store.test.rad
import { rtest } from "stdlib"

test "count reflects adds" {
    rtest.assertEq(2 + 2, 4, "arithmetic")
    rtest.assert("radlang".startsWith("rad"), "prefix check")
}

rtest gives you assert(cond, name), assertEq(actualInt, expectedInt, name), and assertStr(actualStr, expectedStr, name). Run the suite by pointing rtest at the directory — it finds every *.test.rad recursively:

radlang rtest test/

CLI workflow

Command Does
radlang new <name> --template app Scaffold a project; choose any bundled template
radlang run Compile + run src/main.rad (debug profile)
radlang build Compile a release binary to output/release/
radlang rtest test/ Compile + run every test block under a path
radlang fmt <file> Print canonical formatted source to stdout

run and build default to src/main.rad from config.yaml, so you rarely pass a file. Run fmt before committing to keep diffs to real changes.


Part 2 — Language style guide

Naming

Kind Convention Example
Types (struct, union, enum) PascalCase type UserAccount { }
Functions & variables camelCase fn totalPrice(), var itemCount
Namespaces PascalCase for services, lowercase for utilities ns UserStore, ns greeter
Constants camelCase const const int maxRetries = 3
Enum members camelCase enum Color { red, green }
Files kebab-case (see Part 1) user-store.ns.rad

Prefer var for obvious locals; name types at the boundary

Use var when the initializer already makes the type obvious, and write the explicit type at API boundaries (parameters, return types, fields) where it documents intent:

fn priceWithTax(float price, float rate): float {
    var tax = price * rate          // obviously float — let it infer
    return price + tax
}

Always write return

radlang has no implicit last-expression return. A trailing expression in a function or closure body is not the return value — you must write return on every path, and the compiler rejects a function that can finish without one:

fn triple(int n): int {
    return n * 3        // required — `n * 3` alone would return 0
}

A newline right after return ends the statement, so keep the returned expression on the same line (or end the line on an operator / wrap in parens).

The exception is the arrow form, whose single expression is the result: fn triple(int n) => n * 3, (int x) => x * 3 (see Arrow functions).

Control-flow bodies: one line, or braces

A brace-less control-flow body must stay on one line — ASI inserts a stray semicolon if you split if (cond)⏎body across two lines. When a body needs more than one line, always use braces:

if ready { start() }                 // ok — one line, no braces

if ready {                           // ok — multi-line, braced
    prepare()
    start()
}

Error handling — throw Error, catch at the boundary

Signal failure with throw Error(message, code); the throw unwinds to the nearest enclosing try. Let errors propagate through the internals and catch them once at the boundary (a request handler, main) where you can actually respond:

fn loadPort(string raw): int {
    if raw == "" {
        throw Error("PORT is not set", 500)
    }
    return Int(raw)
}

fn main() {
    try {
        int port = loadPort(cfg.env("PORT"))
        sys.output("listening on {port}")
    } catch (Error e) {
        sys.output("startup failed: {e.message} ({e.code})")
    }
}

Don’t wrap every call in its own try — that scatters recovery logic and buries the happy path. One try at the level that owns the response is usually right.

Nullable + ?? for defaults, narrow with a guard

Model “might be absent” with a nullable type and supply a fallback with ?? rather than sentinel values. Inside an if (x != null) guard, x narrows to its inner type:

fn label(string? name): string {
    string shown = name ?? "anonymous"     // default without a null-check ladder
    return "user: {shown}"
}

match for dispatch

Use match (subject) { } for multi-way dispatch instead of an if/else ladder; arms are newline-separated and _ is the catch-all:

fn describe(int n): string {
    return match (n) {
        0 => "zero"
        1 => "one"
        _ => "many"
    }
}

Iterate with list forms; keep the C-style loop for index work

radlang has ranges, comprehensions and list methods, and they are usually both shorter and faster than a hand-written for (int i = 0; i < n; i++) that fills a list. Write the loop you mean:

int[] indexes = [0..n - 1]                               // inclusive range
int[] squares = [x * x for (int x in nums)]              // comprehension
int[] evens = [x for (int x in nums) where x % 2 == 0]   // filter in the comprehension
string[] upper = names.map((string s) => s.upper())      // map
int[] big = nums.where((int x) => x > 100)               // where
int total = nums.sum()                                   // sum
int chained = nums.where((int x) => x % 2 == 0).map((int x) => x * 3).sum()

The arrow lambda (Type param) => expr is the concise callback. The parameter must be parenthesized and typed ((n) => ... and n => ... do not parse) and the body is one expression; for statements, or a return before the last line, write fn(int x): int { ... } or pass a named function.

What the 1.34.7 measurements say (details in list-idioms-benchmark.md):

  • Build lists with map, where, comprehensions and ranges, not with add in a loop. From 10,000 elements up they are 20 to 33 times faster; at 16 elements still 6 to 12 times. If you have to fill by index, size the list first (int[n] out).
  • Do not worry about the callback spelling. Arrow, fn literal and named function are the same speed, and map, where, iter, comprehensions and for (T x in xs) are all as fast as a hand-written loop.
  • Add up with sum() or a loop, not reduce. Sequential reduce calls its function once per element and is 8 to 24 times slower; a where and map chain should end in .sum() (2.5 times one loop) rather than .reduce(...) (6 times).
  • To count, use for (int i in [0..<n]). It compiles to the same loop as for (int i = 0; i < n; i++) (measured equal on 1.40.25) and is empty when n is 0, where [0..n - 1] would walk 0 and then -1. Use for (T x in xs) to visit elements.
  • Copy list fields into locals before an index loop (float[] a = d.a).
  • Accumulating with combine. out = out.combine(more) on a local list that nothing else holds grows out in place. Once the list is also passed, stored, returned, aliased or captured by a closure, the next combine copies the whole list again (and a loop of them is quadratic). out.add(x), a presized List<T>(n) or a comprehension never copies.
  • Strings. length() walks the string, so read it once before a loop. charAt(i) is constant time on long strings made by concatenation, join, repeat, slice or substring, and walks other strings. Scan with for (byte b in s.toBytes()) or for (string c in s.chars()). Building text in a loop with s = s + x, s += x or s = "{s}{x}" on a local string appends in place while nothing else holds s; passing s to a function, storing it or assigning it to another variable inside the loop makes the next append copy the whole text again. map or a comprehension followed by join(",") is the other linear way.
  • Maps. m.values() is about 3 times faster to iterate than m.keys() plus m.get(k).
  • Thread counts (map(f, 4), reduce(f, 0, 4), parallel) cost about 35 microseconds per call. Add one only for expensive callbacks (about a microsecond of work per element or more, over a few hundred elements) and after measuring; with a trivial callback they are slower at every size.
  • Sorting. sort() and sort(true) are the fast path for numbers. For structs, sortBy((Person p) => p.age) extracts each key once and sorts the keys (about 4 times sort() on integers); a comparator that only reads fields, as an arrow ((Person x, Person y) => x.age - y.age) or a named one-line function, runs inside the sort loop (about 13 times). A comparator that calls a function costs a call per comparison.

A closure literal may return from anywhere in its body; one whose only return is its last statement is expanded in place with no call per element. See Known limitations for what lists and strings do not have.

When to reach for a namespace

Put related functions and their shared state behind a namespace once they form a unit — a service (UserStore), a group of pure helpers (greeter), or anything wrapping an intrinsic (Part 1). A standalone helper called from one place can stay a top-level fn; promote it to a namespace when it grows state or a second caller. Mark internal members priv so the namespace’s surface is only what callers should touch.

Methods: @field for the receiver’s fields

Behaviour that belongs to one struct reads best as a method in its type body. Inside it @total is the receiver’s field (exactly me.total) and me is the whole receiver; call sibling methods bare. Use @name for field access and keep me. for when the receiver itself is passed or replaced:

type Counter {
    int total

    fn add(int n): int {
        @total += n
        return @total
    }

    fn reset() { me = Counter(0) }
}

Do not name anything me (variables, parameters, fields, functions, types). See Methods in a type body.

Memory: let loops and calls clean up after themselves

Managed value memory follows reachability. Local scope exit does not promise that memory is immediately reclaimed; values remain live while referenced by a local, global, closure, pending Future, coroutine, or runtime owner. Unreachable values, including cycles, are reclaimed by the traced collector. A thread-private nursery collects young values, and full collection traces the whole heap. Stores and cross-thread transfers publish the values they expose.

  • Keep only values the program still needs. Replace or drop references held by long-lived lists, Maps, globals, and caches when their contents are no longer useful; a reference left in a live owner keeps its reachable graph alive.
  • Keep callbacks and captures intentionally small when work is repeated. A closure retained by a list, Map, Future, or service remains reachable for as long as that owner does.
  • In parallel list calls, return results or write them to an explicitly owned destination. Worker results are transferred back to the caller before the call completes.
  • Use using (Resource value = ...) or close() for deterministic native resource disposal. Garbage collection is a safety net for managed values, not a substitute for closing sockets, files, databases, or other native handles.
  • For memory tests, assert a workload-appropriate bound and collect explicitly when a deterministic snapshot is required. sys.memory() and RADLANG_MEM_REPORT=1 expose current accounting.

Guard memory in tests with rtest.memoryBytes() and rtest.assertMemoryBelow(...), and cap a program with memory.limitMB in config.yaml (see docs/runtime/memory.md). Running out of memory raises an Error with code 507 that a try can catch.

Format before you commit

radlang fmt is the single source of truth for layout — indentation, spacing, the canonical type Name { } struct form. Run it (or wire it into a pre-commit hook) so style never shows up in review.