Skip to content

xlang Language Reference

This document describes the syntax, types, module system and compiler-provided features of xlang as implemented today. Source files use the extension .xl. The standard library lives in std/ and is written in xlang itself; the compiler gives no special treatment to names inside it.


  1. Overview
  2. Program structure
  3. Types
  4. Variables and globals
  5. Pointers and conversions
  6. Slices and the iterating for
  7. Functions
  8. Control flow
  9. Expressions and operators
  10. Structs, classes, interfaces and enums
  11. Memory and new
  12. Modules and import
  13. Attributes, declare and external linking
  14. Conditional compilation, constants and macros
  15. Compiler builtins
  16. Standard library
  17. Testing
  18. Command line
  19. Limitations

xlang is a low-level, statically typed language compiled with LLVM. There is no libc and no C runtime: the compiler knows only the language, the CPU primitives and a closed list of builtins, and everything else (printing, memory allocation, memcpy, threads, sockets, HTTP, TLS) is ordinary xlang code in std/.

Design points:

  • Direct control: raw pointers, syscall, inline assembly and atomics are part of the language; higher-level APIs are opt-in imports.
  • Generics on functions, structs, classes, interfaces, aliases and class methods (no constraints).
  • Safety: *T is unchecked; array indexing is bounds-checked by default (--safety=checked) and can be switched off with --safety=unchecked.
  • No garbage collector, no exceptions.

A .xl file contains top-level declarations only: fn, global, struct, class, interface, impl, enum, type, define, import/from, export * from re-exports, macro invocations and calls such as staticAssert(...). Declarations end at a line break; a semicolon is not used. Comments are // line, /* block */ and /// doc.

from "std" import print
struct Point { x: i32, y: i32 }
global counter: i64 = 0
export fn add(a: i32, b: i32) -> i32 {
return a + b
}
@entry fn main() -> i32 {
local p: Point = Point { x: 1, y: 2 }
print("hello\n")
print(add(p.x, p.y) as i64)
print("\n")
return 0
}

Entry points are declared with attributes, and the compiler generates the process start-up from them. The attributes @entry, @init and @fini are the only names the compiler reads for start-up and teardown. What is generated depends on what is built (--emit=):

  • exe: the OS entry symbol (_start, or mainCRTStartup on Windows) is generated by the compiler. It calls _xl_initAll, which runs every @init function, then the @entry function, then _xl_finiAll, which runs every @fini function in reverse order, and exits with the i32 that @entry returns (0 when it returns nothing). Without an @entry function the build fails (E0739). On Linux and macOS the entry receives argc and argv when it takes them; on Windows an @entry with parameters is E0755.

  • shared: @entry is optional and takes no parameters (E0755). _xl_initAll is registered as the load hook and runs before @entry when the library is loaded (ELF .init_array, Mach-O __mod_init_func). _xl_finiAll is the unload hook (ELF .fini_array, Mach-O __mod_term_func). Windows DLLs get neither hook yet.

  • static and obj: no entry code, and an @entry function is E0754. _xl_initAll and _xl_finiAll are weak exported symbols: the host calls _xl_initAll once before it uses the library, and _xl_finiAll once after.

  • @entry marks the program’s entry function, at most one per program (E0753 for a second). Its form is @entry fn name() -> i32 or @entry fn name(argc: i32, argv: **u8) -> i32; the return type may be omitted (exit status 0). argc is the number of arguments, and argv holds argc C strings followed by a NULL pointer, with the program path first. On Windows the arguments come from the registered args role; a Windows executable whose @entry takes parameters and has no args role is E0755, as is the argument form in a shared library. Any other parameter list, a generic function or a method is E0752.

  • @init marks a module-level boot function: @init fn boot() { ... } with no parameters, no return type and a body. It runs before @entry, in this order: the stdlib group first, then the user group. Within a group the order is a depth-first post-order over the import statements, taken in the order they appear: a module’s imports run before the module, and each module runs once. In a cycle, a module reached again while it is still being visited is skipped, so the module that was entered first in the cycle runs last among the modules of that cycle.

  • @fini marks a module-level teardown function with the same form and rules as @init. It runs after @entry, in the reverse of the @init order. In a shared library it runs at unload; in a static library or object file the host calls _xl_finiAll. Each attribute is optional, and a library may use either one alone.

  • Calling an @init, @fini or @entry function, or using its name as a value, is error E0727. @init and @fini on a class method, on a generic or non-function item, or on a function with parameters or a return type are E0729. A bodyless @init fn boot(); is the parser’s error E0002.

  • The entry symbols (_start, mainCRTStartup) and _xl_initAll are compiler-owned: a user export(c), @mangle or declare that uses one of these names is E0726.

  • Without an @entry function no entry stub is emitted. Building such a file as an executable (--emit=exe, and therefore xl run) is E0739; library modules are built with --emit=obj, --emit=static or --emit=shared. --emit=ir, bc and header do not raise E0754.

  • Entry stubs exist for Linux and macOS on x86_64 and aarch64, and for Windows on x86_64.


Syntax Description
i8, i16, i32, i64 Signed integers
u8, u16, u32, u64 Unsigned integers
isize, usize Pointer-sized signed / unsigned integers
f32, f64 Floating point
bool true / false
void No value (the return type of a function without ->)
never Return type only: the function does not come back (-> never)
*T Pointer to T (*u8, *Point, *void)
fn(A, B) -> R Function pointer
[T; N] Fixed-size array; N is a compile-time constant
(A, B, ...) Tuple: the elements in order, laid out like @repr(c); () is the empty tuple
str Built-in read-only view { ptr: *u8, len: usize }; it never owns its bytes
[]T, []mut T A non-owning slice: a fat pointer { ptr: *T, len: usize }, the same two words as str. []mut T is the writable view (same layout, mut is a permission). See Slices and the iterating for
Name A struct, class, interface or enum

There is no owned string type in the language; String lives in the standard library. A single byte is written as a byte literal b'a' (see Strings). type Name = T declares a transparent alias.

Integer literals may be decimal, hexadecimal (0xff) or octal (0o644, for file modes); a leading 0 alone stays decimal, so 0644 is six hundred forty-four. Float literals look like 1.5 or 1.5e3; one that does not fit in an f64 (1e999) is an error, never infinity. Escapes in string literals include \n, \0 and \x1b.

A string literal takes its type from the place it is written in:

Context Type Bytes live in Mutable
expected *u8 (or an enum over *u8) *u8 .rodata, NUL-terminated no; writing through it is undefined behavior
expected [u8; N] [u8; N] copy, zero-padded the array yes
anything else, including no expected type str .rodata, with a trailing NUL that is not in len no

local buf: [u8; 8] = "Jones" copies the bytes into the array; a literal longer than N is error E0717. A str literal’s len is the number of decoded bytes, so "Jo\0nes".len is 6. The str fields are ptr (type *u8) and len (type usize); both are read-only. s[i] reads one byte and, under --safety=checked, panics when i >= len. Assigning through a str (s[i] = x, s.len = n) is error E0716. == and != are not defined on str; use eq from the standard library (import eq from "std/str"). A str converts to *u8 only through .ptr; as cannot convert it either.

A byte literal b'x' is a single u8 constant, so it needs no as in a byte context: if c == b')' { }. Printable characters, the escapes \n \t \r \0 \\ \' \" and \xHH all work, and a byte above 127 is written only as b'\xHH'. Exactly one byte goes between the quotes; b'ab' is an error. b followed by anything other than a quote is still an ordinary identifier.

A slice is a view of bytes, never a copy: s[a..b] yields the str that starts at byte a and has length b - a. Both bounds are optional (s[a..] runs to the end, s[..b] starts at 0, s[..] is the whole thing), and both are usize-compatible integer expressions. The base is a str or a [u8; N]; an array’s storage is borrowed, so a write through the array is visible through the view, and the array must outlive the view just as a str’s bytes must. Under --safety=checked both bounds are checked at run time and a start past the end or an end past the length panics; on a constant-length array a constant end past the length is error E0701. Slicing anything else (a *u8, an [i32; N]) is E0709, and a slice is a value, so assigning to it (s[0..1] = "x") is E0716 like any other str write.

The std/str module provides eq, fromC (view of a NUL-terminated C string), fromParts (view of n bytes at a pointer) and view (checked sub-range, no copy). Functions that return text return an owned String instead: slice, trim, trimStart, trimEnd, split (returns Vec<String>), replace, replaceAll, repeat. A str view does not keep its bytes alive; the owner of the bytes must outlive it.


Locals are declared with local; the type is written after a colon:

local i: i32 = 0
local buf: [u8; 64] // no initializer
local q: *Point = &p
local n = 3 // type inferred from the initializer
local m := 3 // same, written with `:=`

local x := expr is the short form of local x = expr: the type is inferred from the initializer and there is no type to write. The initializer is mandatory and must have a value, so local x := is an error, a void expression is E0708, and nil cannot be inferred. A type and := cannot be combined — local x: T := expr is an error; write local x: T = expr or local x := expr. local x: T still declares without an initializer. The same forms work in the for initializer (for local i := 0; i < n; i++).

Globals use global with a mandatory type. Their initializer must be a compile-time constant; without one the global is zero-initialized:

global counter: i64 = 10
global table: [i32; 4]
global banner: *u8 = "xlang"

A const is a named compile-time constant that cannot be written. It is allowed at module level (with export) and as a statement in any block. The type is optional; without it, the type is the default type of the literal value (integers i32, or i64 when the value does not fit; floats f64; bool; strings str). A module-level const without a type must have a literal value. The initializer must be a compile-time constant: literals, arithmetic and casts on them, define constants, arrays and struct literals of such values, and &global. Reading another variable or const in an initializer is error E0715.

const LIMIT: i32 = 7
const GREETING = "hi" // str
const TABLE: [u8; 4] = "abc" // copied bytes, zero-padded

Every const is emitted as read-only data. Assigning to a const, or to an element or field of one, is error E0716. &LIMIT is allowed and yields an ordinary pointer; writing through it is undefined behavior. A block-level const is visible only in its block; it cannot be deferred.

Assignment is target = value and target op= value for + - * / % & | ^ << >>. The value is computed in full before the target is written, so p = V(p.x + 1, p.y) and p = P { x: p.y, y: p.x } read the old p. x++ and x-- are statements, not expressions.


  • &x takes an address, *p dereferences, p.field reaches a field through a pointer or a value, p[i] indexes a pointer or an array.
  • nil is the null pointer.
  • Conversions are explicit with as: x as i64, p as *u8, (addr as usize), n as *void. A < after the type name of a cast opens type arguments (x as Box<i32>, p as *Node<T> == nil) only when a > closes them with type tokens alone and no operand (a name, a literal, (, [, self, !, ~, a closure) follows that > on its line; otherwise the < compares the cast value: x as Idx < 3 is (x as Idx) < 3.
  • Implicit conversions: same-signedness integer widening only. A signed integer converting to a float warns (W0601). Unsigned to signed (and the reverse) is an error (E0601). Narrowing always needs as.
  • An unsafe { ... } block allows implicit integer conversions that change signedness when the target is the same width or wider, and unsigned to float (still W0601); narrowing always needs as.
  • Arithmetic on fixed-width integers wraps (u + 10 with u: u8 = 250 gives 4). Division by zero and out-of-range array indexes call the registered panic under --safety=checked.

A slice is a non-owning view: a data pointer and a length, laid out exactly like str (ptr at offset 0, len at offset 8, sizeOf([]T) == sizeOf(str)). It never owns its bytes and needs no drop.

local buf: [i32; 6] = [1, 2, 3, 4, 5, 6]
local all: []i32 = buf[..] // whole array
local mid: []i32 = buf[1..5] // elements 1..4
local tail: []i32 = buf[4..] // to the end
local head: []i32 = buf[..2] // from the start
local v: []mut i32 = buf[1..5] // writable view of a local array
v[0] = 100 // writes buf[1]
for x in all { ... } // x: *i32, points into buf
for x, i in all { ... } // i: usize, the index
for b in "abcd" { ... } // str walks bytes, b: u8
  • The brackets hold a range: [..], [lo..hi], [lo..], [..hi] (upper bound excluded). Slicing a non-byte array or an existing slice yields a slice of its element type. A slice is writable ([]mut T) only when the owner is a writable place and not const; otherwise it is []T. Slicing str or [u8; N] yields a str.
  • .len is the number of elements and .ptr the data pointer (*T). Indexing is bounds-checked under --safety=checked. Writing an element (s[i] = v) needs a []mut T: on a read-only []T it is E0716 (“cannot write through a read-only slice”). A []mut T element is a place; a []T element reads through the view.
  • []mut T marks a writable view only. It is what a read-only []T must be upcast to in order to write; the reverse ([]mut T to []T) is implicit and free. mut is not an aliasing or lifetime guarantee: two views of the same bytes may exist.
  • A for x in s element is a pointer into the storage, so nothing is copied and x.field = v writes the owner. The bound is read once, before the first turn. break, continue and a label behave as in the other for forms. The form is a compiler lowering to an index loop, not a method call.
  • A slice cannot be a field of an @repr(c) struct and cannot cross an export(c) boundary (C has no fat pointer).

A method name may be a keyword (fn delete(self, url: *String) in a class, interface or impl body, called as c.delete(&url)): after fn in a type body and after . only a name can stand. A free function name is still an identifier.

fn name(a: i32, b: *u8) -> i64 { ... }
fn log(msg: *u8) { ... } // no `->` means void
fn apply(f: fn(i32) -> i32, v: i32) -> i32 { return f(v) }
  • Overloading: functions may share a name when their parameter types differ. Defining the same parameter types twice is E0401. registered functions, export(c) and declare functions cannot be overloaded (E0405). An @entry function can be overloaded: the entry is the one marked, not the name. Non-virtual methods of one class may overload each other; virtual/override methods cannot (E0405).
  • A call picks the overload with the lowest total argument cost: an exact type costs 0; an untyped integer literal costs 1 for i64 and 2 for any other integer type; an untyped float literal costs 1 for f64 and 2 for f32; a string literal costs 0 for str, 1 for *u8 and 2 for [u8; N]; nil costs 1 for a pointer; integer widening costs 1; wrapping a value in an interface costs 1; an integer to float conversion costs 2; other conversions cost 3. An argument that does not convert makes the overload unavailable. A tie is E0403; no available overload is E0404 and lists the signatures. Each non-literal argument of an overloaded call is lowered once, before the candidates are compared, with no expected type; only the chosen overload’s arguments are converted to its parameter types.
  • A function name used as a value is chosen by the expected fn(...) type. Without one, an overloaded name is E0403.
  • Overloaded functions are named with their parameter types in the link name, even under --mangle=none.
  • A function alias gives another name to a function: fn out = io.print (module level, may be exported). It stands for the whole overload set of its target, calls resolve exactly as calls to the target, and taking it as a value follows the rule above. Aliases may chain; a cycle is E0704. Importers see the alias as the target’s function.
  • Variadic parameters: a function whose last parameter is written ..name takes any number of arguments. The pack is fixed at compile time: each call instantiates the function for the argument types of that call (HIR names it like count<i32, i32>), and the instance has one parameter per argument. Inside the body, name.len is the argument count, for a in name { ... } is unrolled once per argument with a typed as that argument, break and continue work in it, and ..name in a call forwards the arguments to another pack function.
  • A pack is not a value: using it bare, indexing it, or spreading it outside a call is an error (E0735, E0738, E0737). A function has at most one pack, and it must be last (E0734). A pack cannot be export(c), declare, virtual, override, generic, or a class or interface method (E0736).
  • A call considers a pack function only when no non-pack overload of that name has as many parameters as the call has arguments; otherwise the fixed-arity overload is chosen.
  • There are no default arguments. (syscall is the one builtin with a variable argument count.)
  • A function with a return type must end every path in return, otherwise E0764. A path also ends at an endless loop (while true without break), at a call of a -> never function, and at a switch that covers every variant and ends each arm.
  • -> never declares a function that does not come back (an exit, an endless loop, panic). Its body must not reach its end and cannot return (E0764, E0765); the code after a call of it is unreachable. never is only a return type: a parameter, local or field of type never is E0765.
  • A function may return a tuple to give back several values at once: fn divMod(a: i64, b: i64) -> (i64, i64) { return (a / b, a % b) }. A tuple can be taken apart in one local: local (q, r) = divMod(7, 3) binds q to element 0 and r to element 1, with the element types taken from the tuple and the right-hand side evaluated once. The elements can also be read one by one with .0, .1, … (local dm: (i64, i64) = divMod(7, 3) then dm.0); a number written right after . is always a position, so t.0.1 reads element 1 of element 0. A tuple a tuple used as a place is assignable element by element (dm.0 = 5). The elements are laid out in order like @repr(c), so (A, B) and (B, A) are different types. () is the empty tuple: a distinct value with no fields. A tuple of plain values is copied by value; a tuple with an element that needs drop needs drop itself, moves like a class and drops its elements in reverse order.
  • export fn makes a function visible to importers; export(c) fn additionally keeps the C symbol name unmangled. Names are mangled by default (--mangle=none disables it).
  • export(c) and declare functions follow the target’s C calling convention (System V AMD64, AAPCS64, Microsoft x64), so an @repr(c) struct passed or returned by value lands in the registers or memory a C compiler uses. Every other function passes a struct as the address of a copy. Their signatures take only C types (E0302), and one that passes a struct by value cannot be a fn(...) value (E0778), because a call through a pointer uses the xlang convention. Integers narrower than 32 bits are widened by the caller in both conventions.
  • Methods belong to classes and impl blocks (see below); self is the first parameter.
  • Naming convention: types PascalCase, functions, variables and fields camelCase.

if cond { ... } else if other { ... } else { ... }
while cond { ... }
do { ... } while cond
for local i: i64 = 0; i < 10; i++ { ... }
for local i := 0; i < 10; i++ { ... } // type inferred from the initializer
for i in 0..10 { ... } // upper bound exclusive, evaluated once
for i in 0..=10 { ... } // upper bound inclusive: runs for 0 through 10
outer: for i in 0..5 {
for j in 0..5 {
if j == 3 { continue outer }
if i == 3 { break outer }
}
}
switch v {
case 1, 2 { return 10 }
case Color.Red { return 1 }
default { return -1 }
}
defer cleanup(p)
  • Conditions need no parentheses; bodies always use braces.
  • for has three forms. for init; cond; step { } is the C-style loop; any of the three parts may be left out (for ; cond; step, for init; ; step, for init; cond; { }), and leaving out the condition makes an infinite loop. for name in lo..hi { } counts from lo up to but not including hi, and for name in lo..=hi { } includes hi. A range loop evaluates both bounds once, before the first iteration, so changing them in the body does not move the end. The loop variable’s type is the bounds’ integer type; an untyped integer literal on one side takes the type of the other, so for i in 0..limit() works without a written as. A reversed range (5..2) is empty and runs zero times. for name in pack { } unrolls a parameter pack; see the variadic rule under Functions. Every form takes an optional label (outer: for ...), and break outer / continue outer leave or advance that loop.
  • The iterating for (for x in s, for x, i in s) walks a [T; N], a []T, a []mut T or a str. The element is a pointer into the storage (*T, so nothing is copied and x.field = v writes the owner); over str, whose bytes are read-only, the element is the byte itself (u8). The index is a usize and comes second (for x, i in s), never first. It lowers to a plain index loop, reads the bound once, and takes a label, break and continue like the other loops. A struct or class is iterable when it has fn next(self: *T) -> Option<E> (it is its own iterator) or fn iter(self: *T) -> I where I has next; for x in v then binds the payload of each Some and stops at None. Vec<T> is iterable this way and yields *T.
  • switch works on integers, bools and enums, has no fallthrough, and a break inside it leaves the enclosing loop. Without a subject (switch { case x < 0 { } case x == 0, y == 0 { } default { } }) each case lists bool conditions; the first arm with a true condition runs, the conditions of later arms are not evaluated, and a comma between conditions means “or”.
  • defer stmt runs when the enclosing block is left; see defer.md.
  • cond ? a : b is the conditional expression.
try {
work()
} catch e { // `e: *u8`, the panic message; `catch { }` without a name is allowed
handle(e)
}
  • A panic (explicit, or a compiler check such as division by zero or an array bound) raised inside the try body, at any call depth, continues in the catch block after the defer statements and drops of every frame in between have run, innermost first. The program goes on after the catch.
  • Leaving the body normally, or with return, break or continue, skips the catch. A panic inside the catch goes to the next enclosing try; panic(e) rethrows.
  • e points into a buffer owned by the try (255 bytes plus NUL); copy it to keep it past the catch.
  • A panic with no enclosing try is fatal and runs nothing. There are no typed errors.
  • The compiler gives functions that own cleanups a landing pad and keeps their locals in memory (they are not inlined); the walker is stdlib (std/runtime/unwind) behind the unwind role. Without the role try is E0501. See Known limitations for the limits (foreign frames, Windows).

  • Arithmetic: + - * / %. Bitwise: & | ^ ~ << >>, with Go-style precedence (& << >> bind like *, | ^ like +). A shift count of at least the bit width gives 0 (>> of a negative signed value gives -1).
  • Comparison: == != < <= > >=. Logical: && || ! (short-circuit). == and != also compare two str values byte by byte (equal length and equal bytes); < and the other orderings do not apply to str (E0709). On a struct or class operand a comparison calls the type’s operator function with both operands’ addresses: a == b is operator==(&a, &b), so comparing never moves or drops a value, and a temporary operand (make() == a) lives in a hidden local like &make(). Every operand parameter of fn ==, fn !=, fn <, fn <=, fn > and fn >= is a pointer (fn ==(a: *T, b: *T) -> bool, or fn ==(self, other: *T) in a class); a by-value one is E0779. != follows from ==, and >, <=, >= follow from <, when the type does not define them.
  • e? propagates a failure. e is an enum of two variants: a success carrying one value and a failure carrying at most one (Ok(T) / Err(E), or None / Some(T); found by shape, no name is special). e? is the success value, or, when e is the failure, an early return of the failure from the function. The function must return an enum of the same shape whose failure carries the same type, with no conversion (E0763); ? on any other value is E0762. A droppable value crosses ? by move, and the enclosing defer statements and drops run on the early return like on any return. ? is hoisted: the statement it is in runs the e of its ? (in the order written) and the early return before its other operands. An operand that runs only on some paths keeps its ? on that path: the right side of && and || runs its ? only when the left side does not decide the result, a ?: branch only when it is chosen, a case condition of a subject-less switch only when the earlier arms did not match, and a loop condition (while, do-while, C-style for) on every test, before the test. A defer body has no function to return from when it runs, so ? there is E0761. A ? written against its operand and followed by a closing token or a binary operator (f()?;, f()? + 1) propagates. A ? against its operand followed by a token that may also start an operand (-, *, &, a name, a literal) is a ternary only when its own : follows at the same bracket level before the expression ends there (a line break outside brackets, ,, ; or a closing bracket): c? -1 : 1 is a ternary, f()? - 1 and f()? * 2 propagate, and in c ? f()? - 1 : 0 the : belongs to the outer ternary, so f()? propagates. Any other ? starts the ternary c ? a : b.
  • Struct literal: Point { x: 1, y: 2 }. Array literal: [1, 2, 3].
  • Calls: f(a, b), method calls obj.method(a), macro calls name!(...).
  • &e takes the address of a place. When e is a value instead (&make()), the value is stored in a hidden local before the statement runs and &e is that local’s address; the local lives, and is dropped, like a local at that point of the block. A void value, or &e of a value inside a defer body, is E0709; bind the value to a local first.
  • An array’s .len is its constant length N as usize; the array is not evaluated, so .len of an array with side effects (make().len) is E0709.
  • sizeOf(T), alignOf(T) and offsetOf(T, field) are compile-time constants. T is any type, slices included (sizeOf([]i32), alignOf([]mut u8)); a type is valid only as their argument, never as a value. offsetOf takes a struct or class.

struct Rect { w: i32, h: i32 }
interface Shape { fn area(self) -> i32 }
impl Shape for Rect {
fn area(self) -> i32 { return self.w * self.h }
}
class Animal {
legs: i32
virtual fn sound(self) -> i32 { return 1 }
}
class Dog : Animal {
tail: i32
override fn sound(self) -> i32 { return 2 }
}
enum Color: i32 { Red, Green = 5, Blue } // underlying type defaults to i32
enum Expr { // payload enum: each variant carries its own values
Num(i64)
Neg(*Expr)
Add(*Expr, *Expr)
Nil
}
fn eval(e: Expr) -> i64 {
switch e {
case Expr.Num(n) { return n }
case Expr.Neg(x) { return -eval(*x) }
case Expr.Add(a, b) { return eval(*a) + eval(*b) }
case Expr.Nil { return 0 }
}
return 0
}
  • A struct holds data only (no methods). The default layout is xlang’s own; @repr(c) selects C layout.
  • A class has fields, methods, single inheritance (class Dog : Animal) and a vptr; virtual methods are overridden with override. A *Dog converts to *Animal with as.
  • An interface is a set of method signatures. A value of interface type is a fat pointer (data pointer plus table); impl Interface for Type provides the methods, and a value of that type passes where the interface is expected. Interfaces are nominal: without the impl the use is error E0504. An interface value borrows its object and owns nothing, so returning one whose object is a local, a parameter, a temporary or a part of one is error E0760 (a dangling fat pointer); it is an error, never a warning, and --allow/@allow cannot silence it. Allocate the object with new and return that pointer, which converts to the interface: local p := new CProvider() then return p. The caller owns the heap object and frees it with delete. The check covers return (directly, or inside a ternary, tuple or struct literal); it does not follow an interface stored in a variable or a field first.
  • Enum members are accessed as Color.Green and converted to integers with as.
  • A value enum (enum Name: T { A, B = 5 }) names constants. T is an integer, float, bool or *u8; a member without = value is the previous integer plus one (the first is 0), and a non-integer enum needs a value on every member (E0705).
  • A payload enum has at least one member written Name(T1, T2, ...). It has no : T and no = value members (E0747), and its tag is the position of the variant. A variant is built like a call, Expr.Add(a, b), with exactly its number of values, each converted to the payload type at its position; a variant without data is a plain value, Expr.Nil (E0751 for a wrong count, E0706 for an unknown member). The payload types may be any type, including pointers to the enum itself and a class that needs drop: the enum’s drop glue drops the payload of the live variant when the enum is dropped, and binding a payload in a case moves it out. A droppable payload makes the enum itself need drop, so the same places that refuse a droppable class refuse it: a global or a struct field of such an enum is E0758, and an array of one is E0759.
  • A payload enum may be generic: enum Result<T, E> { Ok(T) Err(E) }, and its payload types may name the enum’s own type parameters. Each use with concrete type arguments creates one instance of the whole enum, so Result<i32, MyErr> and Result<String, MyErr> are different types with their own tag, union and payload structs. A variant is constructed as E.Variant(...), and for a generic enum the target type must be known where the value is created: Result.Ok(1) takes its type arguments from the type the surrounding expression expects (local r: Result<i32, MyErr> = Result.Ok(1)); without that type the enum is E0756. A variant without data is written Result.None and takes its type from the expected type in the same way.
  • A payload enum is a value: it is copied like a struct. Its size is the tag plus the largest payload, not the sum of the payloads. It is a struct { tag, data } whose data is a union of one struct per variant, so sizeOf(Expr) and alignOf(Expr) work.
  • switch on a payload enum matches variants: case Expr.Add(a, b) { } binds the payload values to the names (in order; _ ignores one) and the names are visible in that case only. A switch on a value it owns (a local, a by-value parameter, a temporary) gives the payload to an arm that binds a droppable value: the switched-on value is consumed on entry, every payload value of the variant (_ included) becomes a local of the arm, and each is dropped at the end of the arm unless it is moved out, like Rust’s by-value match. A temporary that no arm takes is dropped when the switch ends. A switch on a place (switch *p, switch self.f) only lends the payload: the bindings are views, and moving one is E0720. case Expr.Add, Expr.Nil { } matches several variants without binding anything; a bare variant name matches whatever it carries. A binding pattern must be alone in its case and name every value, and every case must name variants of that same enum (E0749 for a case that names no variant at all, E0757 for a case that names a variant of a different enum). Without default every variant needs a case (E0750), and a variant named twice is E0709. A droppable payload is owned by the enum and dropped only while its variant is live.
  • Generics: fn name<T, U>(...), struct Name<T>, class Name<T>, interface Name<T>, enum Name<T>, type Name<T> = ... and methods fn name<U>(...) of a class declare type parameters. Globals, const and define cannot have them (E0724). Each use with concrete type arguments creates an instance: the declaration is copied with its type parameters replaced, then checked and lowered like any other declaration. A generic struct, class, interface or alias named without arguments is E0724. Type arguments are written in type positions (Pair<Pair<i32, i32>, str>), after a name in expressions (max<i64>(a, b), Pair<i32, str> { a: 1, b: "x" }) and after a method name (obj.apply<i32>(f)). In an expression Name<...> is a generic argument list only when everything up to the closing > is type tokens (names, primitive types, *, ., ,, array and slice brackets, tuple parentheses, fn(...) -> R, so id<(i32, i32)>(x) and mk<fn(i32) -> i32>() work) and that > is followed by (, {, ), ], ,, ; or the end of the line; otherwise < is a comparison. Arguments of a generic call or method call are inferred from the argument types; untyped literals use their default types (i32 or i64, f64, str). A parameter that stays unknown is E0724. A generic function named without a call (local f: fn(i32) -> i32 = identity<i32>) takes its arguments from the written list or, when none are written, from the expected fn(...) type. A generic method is instantiated per class instance and per argument list; a generic class may have generic methods of its own (class Box<T> { fn map<U>(self, f: fn(T) -> U) -> Box<U> }). A plain method of a generic class instance (not virtual, override, init or drop) is checked and lowered only when the program calls it or takes its address, like a C++ class template member, so a method that needs an operation T lacks costs nothing until it is used with that T. A generic method cannot be virtual or override (E0730), cannot be overloaded (E0405), and is supported only in a class: a generic method of an impl or an interface is E0733. A generic impl names its type parameters in the target and the interface, as in impl<T> Iter<T> for Cell<T>; each of them must be a direct argument of the target (E0732), and the impl is instantiated for each instance of the target that exists. Concrete impls may name interface arguments (impl Iter<i32> for Ticker). Two impls that give the same interface for the same type, after the arguments are filled in, are E0731. An error inside an instance is reported at the generic declaration, followed by one in instantiation of note per enclosing instance, at most 8. Nesting of type arguments beyond 64 levels is E0725. There are no constraints: a body is checked only for the types it is instantiated with.
  • A class may declare fn init(self, params...) (a constructor; overloadable, no return type, E0722 otherwise) and fn drop(self) (a destructor; at most one, no parameters besides self, no return type, not virtual, E0722 otherwise). T(args) builds a new object: it is zeroed, its vptr is set and init runs on it. A class with an init cannot be built with T { ... } (E0723); a class without one keeps the field literal. In a class init, self.f = v on a droppable field is a raw store: the field holds zeroed memory there, so the old value is not dropped. A derived class whose init exists runs the base class init that takes no arguments first; if the base has constructors but none without arguments, the derived init is E0722.
  • A class needs drop when it has a drop method, or a field or base class that needs drop. Such values are move-only. A local or by-value parameter that needs drop is dropped when its block ends (or the function returns), in last-in first-out order together with defer. The drop runs the user drop body, then the drop of each field that needs drop in reverse declaration order, then the base class drop. A class with a vptr drops through vtable slot 0, so deleting a derived object through a base pointer runs the derived drop; without a vptr, a drop through a base pointer that would skip a derived drop is E0766 (see Classes).
  • Moving: a droppable local used by value (a local initializer, the right side of an assignment, a by-value argument including constructor arguments, a return value, a field initializer of a field literal or new) is moved, and its drop is cancelled. Moving a field, an element or *p by value is E0720; take its address instead. A temporary passes its ownership on. A moved local holds no value until it is assigned again: any use of it after the move (reading it, &x, a field, a write into a field, moving it again) is E0780, and so is a use reached by a path that moved it, such as after if c { take(x) } or on the next iteration of a loop that moves it. Assigning the whole local (x = make()) owns it again; a path that moves it and then leaves (return, break) does not affect the code after it. A droppable temporary used as a method receiver lives until the end of its block; a discarded one is dropped after its statement.
  • A class that needs drop cannot be a struct field or a global (E0721); use a class field, or a *T allocated with new. An array whose element type needs drop is also E0721, as a local, parameter, struct or class field, or global, because arrays do not drop their elements (E0759 instead when the element type is a payload enum that needs drop). A droppable element belongs in a Vec<T>, which drops its elements when it is dropped.
  • new T(args) gets memory from the registered alloc function and constructs in it; new(p) T(args) constructs in the memory p points at and allocates nothing. delete p runs the drop of the pointee when it needs drop, then releases the memory through the registered free function. There is no explicit-allocator form of delete; to release memory from another allocator, call __builtin_drop and that allocator’s free yourself.

The compiler does not know allocators. It knows two registered functions: new T { ... } calls the function registered as alloc with the size and alignment of T, and returns *T (nil when that function returns nil, with nothing written). delete p calls the function registered as free. new(p) T { ... } is placement: p is a pointer to memory you already have, and the compiler allocates nothing (E0709 when p is not a pointer). Without a registered alloc, new T is error E0501; without a registered free, delete p is E0501.

The stdlib registers alloc and free functions when the default-allocator feature is on (the default). They forward to currentAllocator, a plain exported global of std/mem whose type is the Allocator interface (alloc(self, size: usize, align: usize) -> *void / free(self, p: *void), ordinary stdlib code, not a builtin). A program changes where memory comes from either by assigning currentAllocator (for example in an @init function) or by registering its own alloc and free. free(p) from std/mem/mem frees through currentAllocator. malloc/free/memcpy are not builtins: they are stdlib code (std/mem/mem, std/mem/memory).

register(role) decl makes a declaration global and exported under a role. The roles are panic (fn(msg: *u8) -> never; the compiler’s failure paths call it), alloc (fn(size: usize, align: usize) -> *void) and free (fn(p: *void) with no return type), and args (fn(argc: *i32) -> **u8: writes the argument count through argc and returns the argument vector; the Windows entry stub calls it after _xl_initAll because Windows passes one command-line string; the stdlib registers it in std/runtime/args). A declaration that does not fit its role is E0503. register(start) is an unknown-role error (E0503).

Registrations of the same role override by group: the stdlib (the default) is replaced by a user registration of the same role, a user registration is never replaced by the stdlib, and two registrations of one role in the same group are E0502. A user alloc must be paired with a user free, because the stdlib free forwards to currentAllocator; the compiler does not check the pairing.

String and Vec<T> allocate through currentAllocator, not through the registered alloc.


A module path "x" resolves to x.xl or x/index.xl. std and std/x come from the stdlib root; a path that starts with a dependency’s repository path ("github.com/user/repo", "github.com/user/repo/sub") comes from that installed package (see Packages); other paths are searched from the importing file’s directory, then the root file’s directory.

import "std" // module as a namespace
import "std/mem" as mem
from "std" import print, String // selective import
import print, String from "std" // same, other order
from "std" import print as say // rename
import * from "std" // bring every export in
import * as sys from "std/sys" // namespace alias

Re-exports:

export * from "memory"
export * from "memory" except strlen
export * as sys from "sys"
export { sysClockSeconds, sysRandom } from "sys"
  • Modules may import each other. Every module of the program loads before any import or export is resolved, so a cycle is legal. A name that reaches an importer only through an export * loop, and that no module in the loop exports, is E0711.
  • Only exported declarations are visible to importers.
  • A namespace import binds one name (import "std" binds std); its members are written std.print(...), std.Result<i32, Error>, std.Result.Ok(v) and, for a class, std.String() or std.Vec<i32>(). --import std loads a module without binding any name.
  • Two exports or imports of the same name are an error; the same entity reaching a module by two paths is warning W0401.
  • import "std" gives the whole standard library. The compiler has no stdlib of its own: it is a module root like any package (xlc -M std=<dir> --import std), and xl passes the installed one (or the one xlang.local.toml, $XLANG_STD or --std=<dir> names); see The xl tool.
  • An import of NAME or NAME/sub resolves inside the directory of the module root -M NAME=DIR; xl adds one root per package. Other paths are relative to the importing file.

declare prefixes any declaration that is defined somewhere else. @library("name") names a native OS library for a declared function:

@library("ntdll") declare fn NtTerminateProcess(handle: i64, status: i32) -> i32
declare fn helper(x: i32) -> i32 // resolved at link time from another object
  • A declared function not defined in the compilation produces W0301. It uses the C calling convention (see Functions).
  • Native libraries are used only where the OS requires them (the Windows std/sys/windows.xl imports from ntdll, kernel32 and bcrypt, std/sys/sock.xl from ws2_32, and std/tls/truststore.xl from crypt32). On Windows the linker driver generates import libraries from the @library declarations; Linux and macOS programs are linked with no libraries at all (@library has no effect there).
  • Prefer the raw syscall(nr, args...) builtin to a library call. Imports of OS libraries stay in std/sys/ behind #if os == "...".
  • Other attributes: @repr(c) (C layout), @allow(CODE) (silence a warning for the item).
  • --emit=header writes a C header for exported items; --emit=static|shared|obj produce a static archive, shared library or object.

See Linking for how objects are linked.


Conditional compilation, constants and macros

Section titled “Conditional compilation, constants and macros”
#if os == "linux" && arch == "x86_64"
define SYS_WRITE = 1
#elif os == "macos"
define SYS_WRITE = 0x2000004
#else
#error "unsupported target"
#endif
#ifdef featureDefaultAllocator
...
#endif
  • Directives are #if, #elif, #else, #endif, #ifdef, #ifndef and #error; the condition is a normal expression. Inactive regions are only lexed.
  • Predefined names: os, arch, pointerWidth, endian, debug, optLevel, and featureXxx for each stdlib feature. -D NAME[=VALUE] and -U NAME set or remove user definitions.
  • define NAME = expr is a compile-time constant.
  • define f(x: expr) { ... } defines a hygienic macro; parameter kinds are expr, type, ident, block and items. A macro is invoked as f!(...). There is no stringification.
  • staticAssert(cond) fails the build when cond is false.

The global namespace holds only a closed list of builtins plus registered names:

  • syscall(nr, args...): raw system call; arguments are integers or pointers; returns i64 (negative errno style). The maximum argument count is checked against the target.
  • __builtin_atomicLoad, __builtin_atomicStore, __builtin_atomicXchg, __builtin_atomicCas, __builtin_atomicAdd and __builtin_fence. The memory order is a compile-time MemoryOrder value (MemoryOrder.acquire, MemoryOrder.release, …).
  • __builtin_asm("...", out(reg) x, ...): inline assembly.
  • sizeOf, alignOf, offsetOf, staticAssert, nil.
  • __builtin_needsDrop<T>(): a compile-time bool, true when T needs drop. Written with the type argument in angle brackets because a type cannot be an argument expression. When it (or its !) is the whole condition of an if, only the taken branch is lowered, so the other branch may use operations T does not have (if __builtin_needsDrop<T>() { return v.clone() }).
  • __builtin_drop(p): runs the drop glue of the pointee of p; nothing when the pointee needs no drop.
  • __builtin_read(p): the value stored at p, copied out with no move and no drop. The caller owns the copy, so local v = __builtin_read(p) gives v its own drop when its type needs drop; the place keeps its bytes and its owner.
  • __builtin_write(p, v): a statement that stores v at p without dropping the old value. A droppable v is moved in, so its drop is cancelled. As a value it is E0709. These two are the raw moves a container needs for its slots; they are unchecked, like *p.
  • Registered panic, alloc and free names.

print, alloc-style helpers, memcpy, assert and the rest are stdlib functions that must be imported.


All of it is in std/; import "std" or from "std" import name brings it in, and from "std/<module>" import name imports one module. Each area has an index.xl that re-exports its parts, so from "std/str" import trim and from "std/str/string" import trim both work. The pages under Standard library give the API of each area; this table is the map.

Area Contents
std/io print, println, fprint(fd, ...), fprintln(fd, ...), eprint, eprintln. Each takes str, *u8, i64, u64, f64, bool or *String, or a format string followed by any number of arguments (..args). print adds no newline and println adds one \n. Output is written straight to the fd and makes no allocator calls. f64 prints with six decimals
std/io/fs, std/io/dir, std/io/stat whole-file helpers, directory listing (fsListDir) and file status
std/str/fmt {% raw %}The placeholder engine: {} takes the next argument, {{ and }} print braces, and a count mismatch panics with format: N placeholders, got M arguments in "TEXT". sprintf, format (both return a String), fmtAppend(*String, ...), snprintf(buf, cap, fmt, ...) -> usize, and toString for the scalar types. fmtEmit(sink, fmt, ..args) is the shared engine{% endraw %}
std/str/str the str view helpers: eq, fromC, fromParts, view (no copy), find, contains, startsWith, endsWith, toU64, toI64 (decimal only; false on overflow or junk)
std/str/compare compare(a, b) -> i32, equalIgnoreCase, containsAny, isSpace, globMatch(pattern, text) (* and ?, no escapes)
std/str/string String, an owned growable byte string on currentAllocator (init, length, asStr, cstr, at, slice, find, push, append, equals, clone, clear, reserve, toLowerAscii, toUpperAscii), plus the text-returning functions slice, trim, trimStart, trimEnd, split, replace, replaceAll, repeat. It frees itself when dropped
std/collections Vec<T>, a growable array on currentAllocator (length, capacity, isEmpty, reserve, get, first, last, set, push, pop, insert, remove, swapRemove, truncate, clear). It drops its elements and frees itself when dropped. An index past the end panics
std/mem memcpy, memmove, memset, memcmp, strlen; the Allocator interface, the default Heap, the exported global currentAllocator and the registered alloc/free functions
std/math integer and float helpers (abs, min, max, sqrt, trig), big/bigint/bignum/bigdiv for fixed-width big integers and Montgomery arithmetic, and the geometry types Vec2, Vec3, Vec4, Rect, Mat2, Mat3, Mat4, Quaternion, Transform
std/time calendar dates and time zones (std/time/date, std/time/tzif)
std/random entropy, CSPRNG, PRNG, UUIDs and short identifiers
std/encoding hex, base32, base58, base64, base85, base91, csv, der, pem/pemwrite, utf8, punycode/idna, json (read-only flat lookups) and jsonfull, cbor/cborread, msgpack, protobuf, toml
std/checksum crc, adler, fnv
std/compress deflate and inflate
std/crypto hash/ (SHA-1, SHA-2, SHA-3, MD4, MD5, BLAKE2, HMAC and the MAC interface), cipher/ (AES modes, AES-GCM, ChaCha20-Poly1305, Salsa20), kdf/ (HKDF, PBKDF2, scrypt), kex/ (X25519, X448), sig/ (RSA, ECDSA, Ed25519, Ed448), x509/ (certificates, CRL, CSR, SPKI, keys, verification), plus ct for constant-time comparison
std/tls TLS 1.2 and 1.3 client and server, the trust store and the IANA names
std/net dns and the wire protocols under net/proto/ (IP, DHCP, NTP, MQTT, SOCKS5, STUN, syslog, DNS transport)
std/http the server Engine, routes and groups, middleware, Context, multipart, URL parsing, and an HTTP client
std/auth JWS, JWT, OAuth and AWS SigV4
std/cloud an S3 client
std/semver semantic version parsing and comparison
std/thread threads and Mutex/Cond/RwLock/Once
std/os process control
std/cpu, std/gpu, std/hw CPU feature flags, GPU device discovery, and hardware facts from the OS
std/sys the native OS layer: env, per-OS raw calls (linux, macos, windows), sock and uring. Not for user code; reach it through the areas above
std/runtime panic (the registered panic), unwind (panic unwinding and the registered unwind, what try/catch run on) and args (the entry’s argc/argv on Windows)
std/testing the test framework

Stdlib features are plain definitions that become featureXxx constants for #if: -DfeatureDefaultAllocator=true registers the default alloc and free (xl always passes it; a program that registers its own allocator leaves it out by calling xlc directly).


A test file is a program named *.test.xl; it fails when its exit status is not 0 (xl run math.test.xl). It uses std/testing:

from "std/testing" import Suite, T, suiteInit, test, suiteRun, expectEq
fn addWorks(t: *T) { expectEq(t, 1 + 2, 3) }
@entry fn main() -> i32 {
local s: Suite
suiteInit(&s)
test(&s, "add works", addWorks)
return suiteRun(&s)
}

Matchers are typed functions (expect, expectTrue, expectEq, expectEqUInt, expectEqStr, expectNear, expectGt, expectNil, …). There is no discovery and no chained matcher syntax. The repository’s own end-to-end programs live in test/e2e/, and the language unit suites in test/unit/; see Testing.


xl run [flags] [file.xl] [args...]
xl build [flags] [file.xl] [objects...]
xl check [flags] [file.xl]
xl env [--json] [file.xl]
xl pkg add|install|update|remove|list|clean
xl lc install|update|list|use
xl std install|update|list|use
xl self-update [--check] [--force]

xl is documented in The xl tool. The flags of build, check and run are the compiler’s: -o, --emit exe|obj|ir|bc|header|static|shared, --check, -D/-U, --target <triple>, -O0..3, -g, --cpu, --mangle xl|none, --safety checked|unchecked, -M NAME=DIR, --import SPEC, --layout-scheme, --layout-history, --dump-layout [Type], --layout-record, --dump-ast, --dump-hir, --dump-mir, --incremental, --cache-dir, --print-cfg, --context N, --context-errors N, --context-warnings N, --allow/--deny/--warn-all/--allow-all, --diag-format text|json, --diag-log FILE, --diag-log-level all|warn|error, --color auto|always|never (xlc --help).

Diagnostics have codes: E for errors, W for warnings (for example E0501, W0402); xlc --explain CODE prints the long explanation, and warnings are controlled with --allow, --deny and @allow.


Open decisions and intentional incompleteness are recorded in Known limitations (nested tuple destructuring, no generic constraints, no TLS older than 1.2, and so on).