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.
Table of contents
Section titled “Table of contents”- Overview
- Program structure
- Types
- Variables and globals
- Pointers and conversions
- Slices and the iterating
for - Functions
- Control flow
- Expressions and operators
- Structs, classes, interfaces and enums
- Memory and
new - Modules and import
- Attributes,
declareand external linking - Conditional compilation, constants and macros
- Compiler builtins
- Standard library
- Testing
- Command line
- Limitations
Overview
Section titled “Overview”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:
*Tis unchecked; array indexing is bounds-checked by default (--safety=checked) and can be switched off with--safety=unchecked. - No garbage collector, no exceptions.
Program structure
Section titled “Program structure”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, ormainCRTStartupon Windows) is generated by the compiler. It calls_xl_initAll, which runs every@initfunction, then the@entryfunction, then_xl_finiAll, which runs every@finifunction in reverse order, and exits with thei32that@entryreturns (0 when it returns nothing). Without an@entryfunction the build fails (E0739). On Linux and macOS the entry receivesargcandargvwhen it takes them; on Windows an@entrywith parameters isE0755. -
shared:@entryis optional and takes no parameters (E0755)._xl_initAllis registered as the load hook and runs before@entrywhen the library is loaded (ELF.init_array, Mach-O__mod_init_func)._xl_finiAllis the unload hook (ELF.fini_array, Mach-O__mod_term_func). Windows DLLs get neither hook yet. -
staticandobj: no entry code, and an@entryfunction isE0754._xl_initAlland_xl_finiAllare weak exported symbols: the host calls_xl_initAllonce before it uses the library, and_xl_finiAllonce after. -
@entrymarks the program’s entry function, at most one per program (E0753for a second). Its form is@entry fn name() -> i32or@entry fn name(argc: i32, argv: **u8) -> i32; the return type may be omitted (exit status 0).argcis the number of arguments, andargvholdsargcC strings followed by a NULL pointer, with the program path first. On Windows the arguments come from the registeredargsrole; a Windows executable whose@entrytakes parameters and has noargsrole isE0755, as is the argument form in a shared library. Any other parameter list, a generic function or a method isE0752. -
@initmarks 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. -
@finimarks a module-level teardown function with the same form and rules as@init. It runs after@entry, in the reverse of the@initorder. 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,@finior@entryfunction, or using its name as a value, is errorE0727.@initand@finion a class method, on a generic or non-function item, or on a function with parameters or a return type areE0729. A bodyless@init fn boot();is the parser’s errorE0002. -
The entry symbols (
_start,mainCRTStartup) and_xl_initAllare compiler-owned: a userexport(c),@mangleordeclarethat uses one of these names isE0726. -
Without an
@entryfunction no entry stub is emitted. Building such a file as an executable (--emit=exe, and thereforexl run) isE0739; library modules are built with--emit=obj,--emit=staticor--emit=shared.--emit=ir,bcandheaderdo not raiseE0754. -
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.
Strings
Section titled “Strings”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.
Variables and globals
Section titled “Variables and globals”Locals are declared with local; the type is written after a colon:
local i: i32 = 0local buf: [u8; 64] // no initializerlocal q: *Point = &plocal n = 3 // type inferred from the initializerlocal 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 = 10global 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 = 7const GREETING = "hi" // strconst TABLE: [u8; 4] = "abc" // copied bytes, zero-paddedEvery 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.
Pointers and conversions
Section titled “Pointers and conversions”&xtakes an address,*pdereferences,p.fieldreaches a field through a pointer or a value,p[i]indexes a pointer or an array.nilis 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 < 3is(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 needsas. - An
unsafe { ... }block allows implicit integer conversions that change signedness when the target is the same width or wider, and unsigned to float (stillW0601); narrowing always needsas. - Arithmetic on fixed-width integers wraps (
u + 10withu: u8 = 250gives 4). Division by zero and out-of-range array indexes call the registeredpanicunder--safety=checked.
Slices and the iterating for
Section titled “Slices and the iterating for”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 arraylocal mid: []i32 = buf[1..5] // elements 1..4local tail: []i32 = buf[4..] // to the endlocal head: []i32 = buf[..2] // from the startlocal v: []mut i32 = buf[1..5] // writable view of a local arrayv[0] = 100 // writes buf[1]
for x in all { ... } // x: *i32, points into buffor x, i in all { ... } // i: usize, the indexfor 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 notconst; otherwise it is[]T. Slicingstror[u8; N]yields astr. .lenis the number of elements and.ptrthe data pointer (*T). Indexing is bounds-checked under--safety=checked. Writing an element (s[i] = v) needs a[]mut T: on a read-only[]Tit isE0716(“cannot write through a read-only slice”). A[]mut Telement is a place; a[]Telement reads through the view.[]mut Tmarks a writable view only. It is what a read-only[]Tmust be upcast to in order to write; the reverse ([]mut Tto[]T) is implicit and free.mutis not an aliasing or lifetime guarantee: two views of the same bytes may exist.- A
for x in selement is a pointer into the storage, so nothing is copied andx.field = vwrites the owner. The bound is read once, before the first turn.break,continueand a label behave as in the otherforforms. 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 anexport(c)boundary (C has no fat pointer).
Functions
Section titled “Functions”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 voidfn 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)anddeclarefunctions cannot be overloaded (E0405). An@entryfunction can be overloaded: the entry is the one marked, not the name. Non-virtual methods of one class may overload each other;virtual/overridemethods 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
i64and 2 for any other integer type; an untyped float literal costs 1 forf64and 2 forf32; a string literal costs 0 forstr, 1 for*u8and 2 for[u8; N];nilcosts 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 isE0403; no available overload isE0404and 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 isE0403. - 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 beexported). 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 isE0704. Importers see the alias as the target’s function. - Variadic parameters: a function whose last parameter is written
..nametakes 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 likecount<i32, i32>), and the instance has one parameter per argument. Inside the body,name.lenis the argument count,for a in name { ... }is unrolled once per argument withatyped as that argument,breakandcontinuework in it, and..namein 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 beexport(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. (
syscallis the one builtin with a variable argument count.) - A function with a return type must end every path in
return, otherwiseE0764. A path also ends at an endless loop (while truewithoutbreak), at a call of a-> neverfunction, and at aswitchthat covers every variant and ends each arm. -> neverdeclares a function that does not come back (an exit, an endless loop,panic). Its body must not reach its end and cannotreturn(E0764,E0765); the code after a call of it is unreachable.neveris only a return type: a parameter, local or field of typeneverisE0765.- 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 onelocal:local (q, r) = divMod(7, 3)bindsqto element 0 andrto 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)thendm.0); a number written right after.is always a position, sot.0.1reads 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 fnmakes a function visible to importers;export(c) fnadditionally keeps the C symbol name unmangled. Names are mangled by default (--mangle=nonedisables it).export(c)anddeclarefunctions 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 afn(...)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
implblocks (see below);selfis the first parameter. - Naming convention: types
PascalCase, functions, variables and fieldscamelCase.
Control flow
Section titled “Control flow”if cond { ... } else if other { ... } else { ... }
while cond { ... }do { ... } while condfor local i: i64 = 0; i < 10; i++ { ... }for local i := 0; i < 10; i++ { ... } // type inferred from the initializerfor i in 0..10 { ... } // upper bound exclusive, evaluated oncefor 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.
forhas 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 fromloup to but not includinghi, andfor name in lo..=hi { }includeshi. 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, sofor i in 0..limit()works without a writtenas. 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 ...), andbreak outer/continue outerleave or advance that loop.- The iterating
for(for x in s,for x, i in s) walks a[T; N], a[]T, a[]mut Tor astr. The element is a pointer into the storage (*T, so nothing is copied andx.field = vwrites the owner); overstr, whose bytes are read-only, the element is the byte itself (u8). The index is ausizeand comes second (for x, i in s), never first. It lowers to a plain index loop, reads the bound once, and takes a label,breakandcontinuelike the other loops. A struct or class is iterable when it hasfn next(self: *T) -> Option<E>(it is its own iterator) orfn iter(self: *T) -> IwhereIhasnext;for x in vthen binds the payload of eachSomeand stops atNone.Vec<T>is iterable this way and yields*T. switchworks on integers, bools and enums, has no fallthrough, and abreakinside it leaves the enclosing loop. Without a subject (switch { case x < 0 { } case x == 0, y == 0 { } default { } }) eachcaselistsboolconditions; the first arm with a true condition runs, the conditions of later arms are not evaluated, and a comma between conditions means “or”.defer stmtruns when the enclosing block is left; see defer.md.cond ? a : bis the conditional expression.
try / catch
Section titled “try / catch”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 thetrybody, at any call depth, continues in thecatchblock after thedeferstatements and drops of every frame in between have run, innermost first. The program goes on after thecatch. - Leaving the body normally, or with
return,breakorcontinue, skips thecatch. A panic inside thecatchgoes to the next enclosingtry;panic(e)rethrows. epoints into a buffer owned by thetry(255 bytes plus NUL); copy it to keep it past thecatch.- A panic with no enclosing
tryis 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 theunwindrole. Without the roletryisE0501. See Known limitations for the limits (foreign frames, Windows).
Expressions and operators
Section titled “Expressions and operators”- 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 twostrvalues byte by byte (equal length and equal bytes);<and the other orderings do not apply tostr(E0709). On a struct or class operand a comparison calls the type’s operator function with both operands’ addresses:a == bisoperator==(&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 offn ==,fn !=,fn <,fn <=,fn >andfn >=is a pointer (fn ==(a: *T, b: *T) -> bool, orfn ==(self, other: *T)in a class); a by-value one isE0779.!=follows from==, and>,<=,>=follow from<, when the type does not define them. e?propagates a failure.eis an enum of two variants: a success carrying one value and a failure carrying at most one (Ok(T)/Err(E), orNone/Some(T); found by shape, no name is special).e?is the success value, or, wheneis the failure, an earlyreturnof 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 isE0762. A droppable value crosses?by move, and the enclosingdeferstatements and drops run on the early return like on anyreturn.?is hoisted: the statement it is in runs theeof 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, acasecondition of a subject-lessswitchonly when the earlier arms did not match, and a loop condition (while,do-while, C-stylefor) on every test, before the test. Adeferbody has no function to return from when it runs, so?there isE0761. 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 : 1is a ternary,f()? - 1andf()? * 2propagate, and inc ? f()? - 1 : 0the:belongs to the outer ternary, sof()?propagates. Any other?starts the ternaryc ? a : b.- Struct literal:
Point { x: 1, y: 2 }. Array literal:[1, 2, 3]. - Calls:
f(a, b), method callsobj.method(a), macro callsname!(...). &etakes the address of a place. Wheneis a value instead (&make()), the value is stored in a hidden local before the statement runs and&eis that local’s address; the local lives, and is dropped, like alocalat that point of the block. A void value, or&eof a value inside adeferbody, isE0709; bind the value to a local first.- An array’s
.lenis its constant lengthNasusize; the array is not evaluated, so.lenof an array with side effects (make().len) isE0709. sizeOf(T),alignOf(T)andoffsetOf(T, field)are compile-time constants.Tis any type, slices included (sizeOf([]i32),alignOf([]mut u8)); a type is valid only as their argument, never as a value.offsetOftakes a struct or class.
Structs, classes, interfaces and enums
Section titled “Structs, classes, interfaces and enums”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
structholds data only (no methods). The default layout is xlang’s own;@repr(c)selects C layout. - A
classhas fields, methods, single inheritance (class Dog : Animal) and a vptr;virtualmethods are overridden withoverride. A*Dogconverts to*Animalwithas. - An
interfaceis a set of method signatures. A value of interface type is a fat pointer (data pointer plus table);impl Interface for Typeprovides the methods, and a value of that type passes where the interface is expected. Interfaces are nominal: without theimplthe use is errorE0504. 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 errorE0760(a dangling fat pointer); it is an error, never a warning, and--allow/@allowcannot silence it. Allocate the object withnewand return that pointer, which converts to the interface:local p := new CProvider()thenreturn p. The caller owns the heap object and frees it withdelete. The check coversreturn(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.Greenand converted to integers withas. - A value enum (
enum Name: T { A, B = 5 }) names constants.Tis an integer, float, bool or*u8; a member without= valueis 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: Tand no= valuemembers (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(E0751for a wrong count,E0706for 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 acasemoves 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 isE0758, and an array of one isE0759. - 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, soResult<i32, MyErr>andResult<String, MyErr>are different types with their own tag, union and payload structs. A variant is constructed asE.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 isE0756. A variant without data is writtenResult.Noneand 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 }whosedatais a union of one struct per variant, sosizeOf(Expr)andalignOf(Expr)work. switchon 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-valuematch. 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 isE0720.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 itscaseand name every value, and everycasemust name variants of that same enum (E0749for acasethat names no variant at all,E0757for acasethat names a variant of a different enum). Withoutdefaultevery variant needs acase(E0750), and a variant named twice isE0709. 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 methodsfn name<U>(...)of a class declare type parameters. Globals,constanddefinecannot 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 isE0724. 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 expressionName<...>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, soid<(i32, i32)>(x)andmk<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 (i32ori64,f64,str). A parameter that stays unknown isE0724. 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 expectedfn(...)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 (notvirtual,override,initordrop) 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 operationTlacks costs nothing until it is used with thatT. A generic method cannot bevirtualoroverride(E0730), cannot be overloaded (E0405), and is supported only in a class: a generic method of animplor aninterfaceisE0733. A genericimplnames its type parameters in the target and the interface, as inimpl<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, areE0731. An error inside an instance is reported at the generic declaration, followed by onein instantiation ofnote per enclosing instance, at most 8. Nesting of type arguments beyond 64 levels isE0725. 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,E0722otherwise) andfn drop(self)(a destructor; at most one, no parameters besidesself, no return type, not virtual,E0722otherwise).T(args)builds a new object: it is zeroed, its vptr is set andinitruns on it. A class with aninitcannot be built withT { ... }(E0723); a class without one keeps the field literal. In a classinit,self.f = von a droppable field is a raw store: the field holds zeroed memory there, so the old value is not dropped. A derived class whoseinitexists runs the base classinitthat takes no arguments first; if the base has constructors but none without arguments, the derivedinitisE0722. - A class needs drop when it has a
dropmethod, 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 withdefer. The drop runs the userdropbody, 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 isE0766(see Classes). - Moving: a droppable local used by value (a
localinitializer, the right side of an assignment, a by-value argument including constructor arguments, areturnvalue, a field initializer of a field literal ornew) is moved, and its drop is cancelled. Moving a field, an element or*pby value isE0720; 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) isE0780, and so is a use reached by a path that moved it, such as afterif 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*Tallocated withnew. An array whose element type needs drop is alsoE0721, as a local, parameter, struct or class field, or global, because arrays do not drop their elements (E0759instead when the element type is a payload enum that needs drop). A droppable element belongs in aVec<T>, which drops its elements when it is dropped. new T(args)gets memory from the registeredallocfunction and constructs in it;new(p) T(args)constructs in the memoryppoints at and allocates nothing.delete pruns the drop of the pointee when it needs drop, then releases the memory through the registeredfreefunction. There is no explicit-allocator form ofdelete; to release memory from another allocator, call__builtin_dropand that allocator’sfreeyourself.
Memory and new
Section titled “Memory and new”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.
Modules and import
Section titled “Modules and import”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 namespaceimport "std/mem" as memfrom "std" import print, String // selective importimport print, String from "std" // same, other orderfrom "std" import print as say // renameimport * from "std" // bring every export inimport * as sys from "std/sys" // namespace aliasRe-exports:
export * from "memory"export * from "memory" except strlenexport * 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, isE0711. - Only
exported declarations are visible to importers. - A namespace import binds one name (
import "std"bindsstd); its members are writtenstd.print(...),std.Result<i32, Error>,std.Result.Ok(v)and, for a class,std.String()orstd.Vec<i32>().--import stdloads 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), andxlpasses the installed one (or the onexlang.local.toml,$XLANG_STDor--std=<dir>names); see The xl tool.- An import of
NAMEorNAME/subresolves inside the directory of the module root-M NAME=DIR;xladds one root per package. Other paths are relative to the importing file.
Attributes, declare and external linking
Section titled “Attributes, declare and external linking”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) -> i32declare fn helper(x: i32) -> i32 // resolved at link time from another object- A
declared function not defined in the compilation producesW0301. It uses the C calling convention (see Functions). - Native libraries are used only where the OS requires them (the Windows
std/sys/windows.xlimports from ntdll, kernel32 and bcrypt,std/sys/sock.xlfrom ws2_32, andstd/tls/truststore.xlfrom crypt32). On Windows the linker driver generates import libraries from the@librarydeclarations; Linux and macOS programs are linked with no libraries at all (@libraryhas no effect there). - Prefer the raw
syscall(nr, args...)builtin to a library call. Imports of OS libraries stay instd/sys/behind#if os == "...". - Other attributes:
@repr(c)(C layout),@allow(CODE)(silence a warning for the item). --emit=headerwrites a C header for exported items;--emit=static|shared|objproduce 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,#ifndefand#error; the condition is a normal expression. Inactive regions are only lexed. - Predefined names:
os,arch,pointerWidth,endian,debug,optLevel, andfeatureXxxfor each stdlib feature.-D NAME[=VALUE]and-U NAMEset or remove user definitions. define NAME = expris a compile-time constant.define f(x: expr) { ... }defines a hygienic macro; parameter kinds areexpr,type,ident,blockanditems. A macro is invoked asf!(...). There is no stringification.staticAssert(cond)fails the build whencondis false.
Compiler builtins
Section titled “Compiler builtins”The global namespace holds only a closed list of builtins plus registered names:
syscall(nr, args...): raw system call; arguments are integers or pointers; returnsi64(negativeerrnostyle). The maximum argument count is checked against the target.__builtin_atomicLoad,__builtin_atomicStore,__builtin_atomicXchg,__builtin_atomicCas,__builtin_atomicAddand__builtin_fence. The memory order is a compile-timeMemoryOrdervalue (MemoryOrder.acquire,MemoryOrder.release, …).__builtin_asm("...", out(reg) x, ...): inline assembly.sizeOf,alignOf,offsetOf,staticAssert,nil.__builtin_needsDrop<T>(): a compile-timebool, true whenTneeds 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 anif, only the taken branch is lowered, so the other branch may use operationsTdoes not have (if __builtin_needsDrop<T>() { return v.clone() }).__builtin_drop(p): runs the drop glue of the pointee ofp; nothing when the pointee needs no drop.__builtin_read(p): the value stored atp, copied out with no move and no drop. The caller owns the copy, solocal v = __builtin_read(p)givesvits own drop when its type needs drop; the place keeps its bytes and its owner.__builtin_write(p, v): a statement that storesvatpwithout dropping the old value. A droppablevis moved in, so its drop is cancelled. As a value it isE0709. These two are the raw moves a container needs for its slots; they are unchecked, like*p.- Registered
panic,allocandfreenames.
print, alloc-style helpers, memcpy, assert and the rest are stdlib functions that must be imported.
Standard library
Section titled “Standard library”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).
Testing
Section titled “Testing”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.
Command line
Section titled “Command line”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|cleanxl lc install|update|list|usexl std install|update|list|usexl 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.
Limitations
Section titled “Limitations”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).