Core Language
Semicolons are optional. GX accepts
;at the end of statements but does not require them.
Types
Scalars
i8, i16, i32, i64
u8, u16, u32, u64
f16, f32, f64
bool, str (fat string: {ptr, len}), char
char and bool are scalar values: characters compare with ==, !=,
<, <=, >, >= (ch >= '0' && ch <= '9'), and booleans with == and
!=.
A char and a one-byte integer (u8, i8, c_char, c_uchar) convert to
each other without a cast. Indexing a str gives a byte (u8), so it goes
straight into a char variable or a char parameter:
fn is_digit:bool(c: char) { return c >= '0' && c <= '9' }
var c: char = s[0]
if (is_digit(s[i])) { }
var b: u8 = 'A' // 65
A wider integer needs the cast: (char)n.
Half precision (f16)
f16 is a 16-bit IEEE 754 floating-point type — the half of every
shading language. It trades range and precision (~3 significant decimal
digits) for 2-byte storage, which is what makes it the type you
reach for when preparing data for the GPU: vertex attributes, weights,
and large buffers where halving the element size halves bandwidth.
const HALF_PI:f16 = 3.140625 // nearest binary16 value to pi
struct Vertex { // 6 bytes — packs tight for a GPU buffer
x: f16
y: f16
z: f16
}
Arithmetic on f16 promotes to f32 (the same rule C applies to
_Float16), so intermediate results are computed at full single
precision and only the stored value is narrowed back to half:
var a: f16 = 1.0
var b: f16 = 4.0
var mid: f16 = (a + b) * 0.5 // a+b is f32; the result narrows to f16
Backend representation. On the C backend f16 lowers to the C
compiler’s native _Float16 when it is available (clang, gcc 12+) and
to float otherwise (e.g. the bundled TCC — still correct, but 4-byte
storage). On the LLVM backend it is always true half. See
examples/54_f16.gx for a full walkthrough.
Vectors & Matrices
vec2, vec3, vec4
mat2, mat3, mat4
All are f32-based value types defined at the language level. See Vectors and Matrices below.
Pointers
var p:*i32;
fn log_text(text:const *char) { } // `const *T` is a parameter type
Arrays
Fixed-size Arrays
var arr:i32[4] = {1, 2, 3, 4};
The size is a number, a top-level integer const, or a constant expression
of those:
const GRID_W = 16
const GRID_H = 8
struct Row { tiles: i32[GRID_W] }
var cells:i32[GRID_W];
cells[GRID_W - 1] = 7;
var grid:i32[GRID_W * GRID_H];
var edges:f32[GRID_W + 1];
A size expression may use integer literals, top-level integer consts, the
operators + - * / % << >>, unary minus and parentheses. It must come out
positive. Anything else (a variable, a function call, a float) is a compile
error: “Array size must be a compile-time integer constant”.
A const declared inside a function cannot be used as an array size.
Dynamic Arrays
Dynamic arrays (array<T>) auto-initialize on declaration — no .init() call needed:
var nums:array<i32>;
nums.push(10);
nums.push(20);
defer nums.free();
You can also initialize with values, just like fixed arrays:
var scores:array<i32> = {95, 82, 74, 88, 91};
var names:array<str> = {"Afan", "Sanela", "Ajdin"};
Indexing Dynamic Arrays
a[i] and a.at(i) are the same element access. Both work for reading and writing:
var nums:array<i32> = {5, 6, 7};
nums[1] = 60; // write
nums[2] += 1;
var first = nums[0]; // read — same as nums.at(0)
var pts:array<Point>;
pts.push(Point{1.0, 2.0});
pts[0].x = 9.0; // assign through an element
var p:*Point = &pts[0]; // valid until the next push
Both forms are bounds-checked. An index outside 0..len-1 stops the program:
panic: index 5 out of bounds (len 3)
The index expression is evaluated exactly once, so a[i++] advances i by one. The checks stay in at every -O level; pass --unchecked to remove them.
Iterating Arrays
Both fixed and dynamic arrays support for-each:
var data:i32[3] = {10, 20, 30};
for (var x in data) {
print("{x}\n");
}
var items:array<str> = {"a", "b", "c"};
for (var item in items) {
print("{item}\n");
}
Dynamic Array Methods
| Method | Description |
|---|---|
.push(val) | Append element |
a[i] / .at(i) | Bounds-checked element access, for reading and writing |
.len() | Current length |
.cap() | Current capacity |
.sort() | Sort (i32, u32, i64) |
.clear() | Remove all elements |
.remove_swap(i) | O(1) remove (swaps with last); no-op on an empty array |
.remove_shift(i) | O(n) remove (preserves order); no-op on an empty array |
.free() | Free backing memory |
Collect Expressions
Build a dynamic array from a filtered loop:
var data:i32[6] = {5, 12, 3, 18, 7, 20};
var big = for (x in data) where (x >= 10) collect x;
// big is array<i32> containing {12, 18, 20}
big.free();
The source can be a fixed array, a slice, an array<T> or a Chunks<T>
(also as a struct field). The result is an array<T> of the source’s element type and must
be freed.
Elements that never move
A push that grows an array<T> moves its elements to a new buffer, so a
pointer to one is valid only until the next push. A Chunks<T> keeps its
elements in blocks of equal size and adds a block when the last is full;
nothing already in it moves, and &c[i] stays valid for the life of the
container:
var parts: Chunks<Particle>
defer parts.free()
parts.push(spark)
var first = &parts[0]
for (i = 1:10000) { parts.push(spark) }
first.x = 2.0 // still the first particle
c[i], for, where and collect work as on an array, and so do
push, len, clear, free, init(&a) and Chunks<T>(allocator = &a).
A block holds about 4 KB, so an index costs a shift and a mask more than an
array’s. What needs the elements in one piece is not there: a Chunks is
not a slice, and has no sort, remove_swap or remove_shift. clear()
keeps the blocks for the next pushes.
Containers as Parameters
An array<T> or a map<K,V> can be a function parameter. Without out the
function may read it; with out it works on the caller’s container, and the
caller passes it with &, as for every out parameter.
fn total:i32(a: array<i32>) { // read-only
var t = 0
for (i = 0:a.len() - 1) { t += a[i] }
return t
}
fn squares(out a: array<i32>, n: i32) { // writes to the caller's array
a.clear()
for (i = 1:n) { a.push(i * i) }
}
fn count:i32(m: map<str, i32>) { return m.len() }
fn put(out m: map<str, i32>, k: str, v: i32) { m.set(k, v) }
fn main() {
var a: array<i32>
squares(&a, 4)
print("{total(a)}\n") // 30
a.free()
}
- A read-only container can be indexed, asked for
len(),cap(),get()andhas(), iterated, and passed on to another read-only parameter. Changing it is a compile error:push,set,clear,remove,sortandfree, a write to an element (a[i] = v,a[i].x = v,a[i]++), and handing it or one of its elements to anoutparameter. - Inside the function an
outcontainer is used like a local one (a.push(v),a[i] = v). To pass it on to anotheroutparameter, write&aagain. - A container field is passed the same way:
total(mesh.ids),squares(&mesh.ids, 4). - Nothing is copied in either case: a read-only parameter shares the caller’s buffer, which is why it must not be changed or freed.
- A channel is always
out(out c: chan<T>, passed with&c): a channel is shared between its users, never copied. - A read-only container given to a slice parameter (
[]T) is not checked: a slice’s elements are writable. - A function still cannot return a container; fill an
outparameter. - A function-pointer type cannot name a container parameter yet
(
fn(array<i32>):i32).
The errors say what to write:
error: Argument 1: an 'out' parameter takes the address: pass it with '&'
error: Argument 1: this parameter is not 'out': pass the array<i32> itself, without '&'
error: Cannot call 'push' on a read-only parameter. Add 'out' to the parameter to allow modification.
error: Cannot write to read-only parameter 'a'. Add 'out' to the parameter to allow modification.
error: Argument 1: read-only parameter 'a' cannot be passed to an 'out' parameter. Add 'out' to it to allow modification.
error: A channel parameter must be 'out': a channel is shared, not copied. Write 'out c: chan<T>' and pass it with '&'.
Hash Maps
Hash maps (map<K,V>) provide key-value storage with O(1) average lookup. They auto-initialize on declaration — no .init() call needed:
var scores:map<str, i32>
scores.set("alice", 95)
scores.set("bob", 82)
defer scores.free()
print("alice: {scores.get("alice")}\n") // 95
print("has bob: {scores.has("bob")}\n") // true
print("len: {scores.len()}\n") // 2
Key Types
Maps support two categories of keys:
- String keys (
str) — hashed by content using FNV-1a - Integer/enum keys (
i32,u64, enum types, etc.) — hashed by raw bytes
// String-keyed
var names:map<str, i32>
// Integer-keyed
var lookup:map<i32, str>
A map<str, V> owns a copy of its keys. .set() copies the bytes of a new key into the map, so the key stays valid even when the string it was built from is gone. This matters for keys made by interpolation, which live in a temporary buffer:
var ids:map<str, i32>
defer ids.free()
for (i = 0:9) {
ids.set("item{i}", i) // the map keeps its own copy of "item0", "item1", ...
}
print("{ids.get("item7")}\n") // 7
The copies are released by .remove(), .clear() and .free().
Hash Map Methods
| Method | Description |
|---|---|
.set(k, v) | Insert or update a key-value pair |
.get(k) | Get value by key (returns zero-value if missing) |
.has(k) | Check if key exists |
.remove(k) | Remove a key-value pair |
.len() | Number of entries |
.clear() | Remove all entries (keeps memory) |
.free() | Free backing memory |
Iterating Maps
Destructured (two variables):
for (var name, score in scores) {
print("{name}: {score}\n")
}
Entry-based (single variable with .key / .value):
for (var entry in scores) {
print("{entry.key}: {entry.value}\n")
}
Both forms support where filtering:
for (var k, v in scores) where (v >= 80) {
print("{k} passed with {v}\n")
}
for (var e in scores) where (e.value >= 80) {
print("{e.key} passed with {e.value}\n")
}
Note: Iteration order is hash-order, not insertion-order.
Implementation
Under the hood, map<K,V> is an open-addressing hash table with linear probing:
- 70% load factor — automatically grows and rehashes when exceeded
- Power-of-2 capacity for fast modulo (
h & (cap-1)) - Tombstone-based deletion to preserve probe chains
// Grow/rehash is automatic
var m:map<i32, i32>
for (i = 0:99) {
m.set(i, i * i) // grows as needed
}
print("m[50] = {m.get(50)}\n") // 2500
m.free()
Vectors
GX has built-in vector types for 2D, 3D, and 4D math — no imports needed:
| Type | Components | Layout |
|---|---|---|
vec2 | x, y | 2 × f32 |
vec3 | x, y, z | 3 × f32 |
vec4 | x, y, z, w | 4 × f32 |
Construction
var a:vec2 = vec2{1.0, 2.0};
var b:vec3 = vec3{1.0, 2.0, 3.0};
var c:vec4 = vec4{1.0, 2.0, 3.0, 4.0};
Component Access
var v:vec3 = vec3{1.0, 2.0, 3.0};
var px:f32 = v.x; // 1.0
var py:f32 = v.y; // 2.0
v.z = 5.0; // set z component
Arithmetic
Vector arithmetic uses standard runtime helpers:
var a:vec3 = vec3{1.0, 2.0, 3.0};
var b:vec3 = vec3{4.0, 5.0, 6.0};
var d:f32 = dot(a, b); // dot product → f32
var c:vec3 = cross(a, b); // cross product → vec3
String Conversion
Vectors support .str() and work in string interpolation:
var v:vec3 = vec3{1.0, 2.0, 3.0};
print("v = {v}\n"); // v = vec3(1, 2, 3)
Matrices
GX has built-in matrix types for 2D, 3D, and 4D transforms:
| Type | Layout | Column type |
|---|---|---|
mat2 | 2 × 2 | vec2 |
mat3 | 3 × 3 | vec3 |
mat4 | 4 × 4 | vec4 |
All matrices are column-major (col[N] of vecN), matching OpenGL conventions.
Construction
var m:mat4 = identity_mat4(); // built-in identity constructor
Column Access
var m:mat4 = identity_mat4();
var first:vec4 = m.col[0]; // first column
var tx:f32 = m.col[3].x; // translation X
Indexing returns the matching vector type: mat4.col[i] → vec4, mat3.col[i] → vec3, mat2.col[i] → vec2.
String Conversion
Matrices support .str() and string interpolation:
var m:mat2;
print("m = {m}\n"); // mat2([1,0], [0,1])
For transform helpers (
perspective,look_at,rotation, etc.), see Math Module.
Operators
Arithmetic
+, -, *, /, %
Comparison
==, !=, <, <=, >, >=
Operands are numbers, enums, bool or char; strings compare with == /
!=; pointers compare with each other and with null. Arithmetic or
comparison on a whole struct or array is a compile error.
Two integers of different types compare as they do in C. Types narrower
than 32 bits become i32, the wider operand decides the type, and at equal
width the unsigned type wins. So u64 > -1 is false, because -1 becomes
the largest u64, while u16 > i8 compares the actual values.
Logical
&&, ||, !
Bitwise
Bitwise operators work on integer types (i8–i64, u8–u64):
| Operator | Description | Example |
|---|---|---|
& | Bitwise AND | flags & mask |
| | Bitwise OR | flags | FLAG_READ |
^ | Bitwise XOR | a ^ b |
~ | Bitwise NOT | ~mask |
<< | Left shift | 1 << 4 |
>> | Right shift | val >> 8 |
var flags:u32 = 0;
var FLAG_READ:u32 = 1 << 0;
var FLAG_WRITE:u32 = 1 << 1;
flags = flags | FLAG_READ;
if (flags & FLAG_READ) {
print("readable\n");
}
var low_byte:i32 = 0xABCD & 0xFF; // 205 (0xCD)
var high_byte:i32 = (0xABCD >> 8) & 0xFF; // 171 (0xAB)
Hex literals are supported: 0xFF, 0xABCD.
Compound Assignment
+=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
var x:i32 = 10;
x += 5; // x = 15
x <<= 2; // x = 60
x &= 0xFF; // x = 60
Increment / Decrement
++ and -- work as both prefix and postfix operators:
var i:i32 = 0;
i++; // postfix: evaluates to 0, then i = 1
++i; // prefix: i = 2, evaluates to 2
i--; // postfix: evaluates to 2, then i = 1
Ternary Operator
condition ? then_value : else_value
var x:i32 = 10;
var abs:i32 = x >= 0 ? x : -x;
var label:str = x > 5 ? "high" : "low";
Precedence (low to high)
=,+=,-=,*=,/=,%=,&=,|=,^=,<<=,>>=(assignment, right-associative)? :(ternary)||&&|^&==,!=<,<=,>,>=<<,>>+,-*,/,%- Unary:
-,!,~,&(address-of),*(deref),++,--
Constants
Declare compile-time constants with const. The type can be inferred or explicitly annotated:
const PI = 3.14159265358979;
const TAU = PI * 2.0;
const SCREEN_WIDTH = 1920;
const MAX_ENTITIES:i32 = 1024;
const BUFFER_SIZE:i64 = MAX_ENTITIES * 64;
Constant Folding
The compiler evaluates constant expressions at compile time. Supported operations:
- Arithmetic:
+,-,*,/,% - Bitwise:
&,|,^,~,<<,>> - Comparison:
==,!=,<,<=,>,>= - Logical:
&&,||,! - Unary:
-,~,! - References to other constants
- Casts and ternary expressions
const FLAG_READ = 1;
const FLAG_WRITE = 2;
const FLAG_EXEC = 4;
const FLAG_ALL = FLAG_READ | FLAG_WRITE | FLAG_EXEC; // folded to 7
const IS_WIDE = SCREEN_WIDTH > 1000; // folded to true
const NEG_ONE = -1;
const NOT_FLAG = ~FLAG_READ; // folded to -2
Scope
Constants work at both global and local scope:
const GLOBAL_MAX = 100; // global
fn main() {
const LOCAL_HALF = GLOBAL_MAX / 2; // local
print("{LOCAL_HALF}");
}
Assignment Protection
Assigning to a constant is a compile error:
const X = 10;
X = 20; // ERROR: Cannot assign to constant
C Output
- Global constants emit as
static const type name = value; - Local constants emit as
const type name = value;
The transpiler emits the folded literal value, not the original expression tree.
Const Arrays
Constants can hold fixed-size arrays of any type. The size may be given
explicitly or inferred from the initializer with []:
const PRIMES:i32[5] = { 2, 3, 5, 7, 11 };
const COLORS:str[] = { "red", "green", "blue" }; // size inferred to 3
const FIB:i64[] = { 1, 1, 2, 3, 5, 8, 13, 21 };
Inference removes the need to keep the bracketed length in sync with the initializer — useful for word lists, lookup tables, and other long literals where a manual count would be error-prone.
C backend output: static const ec_str COLORS[3] = { ... }; (size baked in
at compile time, no runtime overhead). JS backend output: const COLORS = ["red", "green", "blue"]; (length is intrinsic to the JS array).
Size inference currently applies to global-scope const arrays. Inside a
function body, give the size explicitly: const X:i32[3] = { 1, 2, 3 };.
Defer
The defer statement schedules cleanup code to run when the enclosing block exits:
defer print("cleanup\n");
defer nums.free();
- Multiple defers execute in LIFO (last-in, first-out) order; a function
may have any number of them, in statement (
defer f();) or block (defer { ... }) form - Defers run before
returnstatements — return values are preserved - Block-scoped: defers in an
iforforbody run when that block ends
Allocators
GX provides three built-in allocator types for explicit memory management without new/delete:
Arena
A bump allocator: fast allocation, freed all at once. An arena is a chain
of blocks. init(size) makes the first one; a full block gets a successor
twice its size, or the size of an allocation that does not fit.
var arena:Arena;
arena.init(4096);
defer arena.destroy();
var p:*Point = arena.alloc(Point);
p.x = 3.14;
var m = arena.mark(); // the arena's position, an i64
var tmp = arena.alloc(Point);
arena.reset_to_mark(m); // back to the mark
arena.reset(); // back to the start
reset() and reset_to_mark(m) keep every block, so a frame that runs
again in the same arena takes no memory from the system after the first
frames. Marks are values, and they nest. Memory goes back to the system
only when the program says so:
trim()frees the blocks after the one in use: after areset(), all but the firstcompact()empties the arena and makes it one block the size of its high-water mark, so a steady frame then runs in one blockdestroy()frees everything
block_count(), total_allocated() (the position) and
high_water_mark() show how much the arena grew. An arena that was never
given init makes its first block at its first allocation.
Two more ways to start an arena:
init_buffer(buf)puts it on the caller’s memory, au8[N]or a[]u8. It never touches the heap, and a full arena stops the program with the numbers (“arena full: 8192 bytes, asked 1024 more”).init_buffer(buf, true)lets heap blocks follow the bufferinit_virtual(size)reservessizebytes of addresses (64 GB when 0) and commits memory 1 MB at a time as it is used. The arena is one range, so nothing in it moves: an array alone in it grows in place and&a[i]stays valid.reset()keeps the memory,trim()gives back what is past the position,destroy()the whole range. It needs a 64-bit target
A function that allocates takes the arena as out a: *Arena; through a
pointer without out only mark() and the numbers can be read.
Pool
Fixed-size slot allocator — O(1) alloc and free, ideal for uniform objects:
var pool:Pool;
pool.init(Point, 256); // 256 slots of sizeof(Point)
defer pool.destroy();
var p:*Point = pool.alloc(Point);
pool.free(p);
pool.reset(); // free all slots
A pointer into a pool says nothing about whether its slot was freed and
taken again by another object. A Handle<T> does: it holds the slot’s
index and a generation, and the generation changes each time the slot is
freed. It is the usual way for one game object to refer to another:
struct Target {
who: Handle<Enemy>
}
var h = pool.handle(e) // e: *Enemy from pool.alloc(Enemy)
if (pool.has(h)) {
pool.get(h).hp -= 10 // *Enemy
}
pool.free(h) // the same as pool.free(e)
pool.get(h) of a handle whose slot was freed stops the program, so a
stale handle never reads the object that took its slot. pool.has(h) asks
first. A declared Handle<T> that was never set matches nothing, and
pool.reset() makes every handle stale. Handles compare with == and
!=; they are not numbers, and a Handle<Enemy> is not a
Handle<Bullet>. Freeing a slot twice stops the program too.
FreeList
Variable-size allocator with free-list coalescing:
var fl:FreeList;
fl.init(65536);
defer fl.destroy();
var p:*Point = fl.alloc(Point);
fl.free(p, Point); // must specify type for size
fl.reset();
- All allocators use
defer allocator.destroy()for cleanup alloc(T)returns*T— the type argument determines size and alignment- The memory returned by
alloc(T)is zeroed, also after areset()or apool.free(), so every field starts at its zero value (and container fields start as valid empty containers) - No garbage collection — explicit
freeor bulkreset/destroy
The heap’s numbers
The heap has numbers too. heap.total_allocated() is the bytes in use,
heap.high_water_mark() the most there ever were, and heap.alloc_count()
the allocations so far. Read the count before and after a frame to see
whether the frame allocates:
var before = heap.alloc_count()
update(&world)
if (heap.alloc_count() != before) { print("the frame allocated\n") }
They count what the runtime takes from the heap: containers, arena blocks,
pools and free lists. A C library that calls malloc itself is not
counted. On the JS backend the three are 0.
A build with -g also keeps each allocation with the line that made it.
At exit it prints what is still allocated, largest first:
memory not freed at exit: 208 bytes in 4 allocations
main.gx:16: 144 bytes in 3 allocations
main.gx:11: 64 bytes in 1 allocation
An array that grew is reported at the push that grew it last. Memory freed a second time, through a copy of a container, stops the program at the line of the second free. A program that panics prints no report.
Containers in an allocator
An array<T> or a map<K,V> takes its memory from the heap unless it
names an arena or a free list. The name goes in the declared type, the way
a channel names its capacity:
var frame: Arena
frame.init(65536)
var visible: array<i32>(allocator = &frame)
var names: map<str, i32>(allocator = &frame)
A container that already exists, such as a struct field, gets one with
.init: mesh.faces.init(&frame). init leaves the container empty and
does not free what it held. A map’s tables and the copies of its str
keys come from the same allocator.
In an arena, free() gives nothing back, and the array that made the
arena’s last allocation grows where it is: pushing into one array at a
time uses its final size, not the sum of every buffer it had. After
reset() the arena’s memory is the next frame’s, so a container in it
starts again with .init(&frame). A Pool has one slot size and is not a
container’s allocator. A channel names its allocator beside its capacity:
chan<Job>(capacity = 64, allocator = &a).
A result that must outlive the arena it was built in is copied out with
clone:
var kept = visible.clone(heap) // the elements, and a map's keys, in the heap
frame.reset() // kept is intact
An element that is itself a container is copied shallowly; a struct that needs more copies its fields itself.
Using a container after its arena was reset, or went back to a mark before
it, stops the program: “panic: an array used after its arena was reset”.
The check is in every build that keeps bounds checks, so at every -O
level; --unchecked removes it with them. It covers push and the map
methods; indexing is not checked.
A default allocator for a block
with sets the allocator for every container in a block that names none:
var g_frame: Arena
fn frame() {
with (&g_frame) {
var visible: array<i32> // from g_frame, at its first push
var names: map<str, i32> // from g_frame, at its first set
update(&visible, &names)
}
g_frame.reset() // all of this frame at once
}
When the block ends, by its end, return, break or continue, the
allocator before it is back. Blocks nest, and the default is per thread.
A container takes its allocator at its first allocation, so one declared
before the block and first filled inside it is in the block’s arena.
heap names the heap and ignores any default around it:
var cache: array<Mesh>(allocator = heap) outlives the frame.
with (none) { ... } stops the program at any allocation inside, with the
line of the block, which checks a loop that must not allocate. Outside a
with, the default is the heap, as it always was.
Strings built inside with on an arena or a free list come from it too:
"{x}", +, .upper(), .lower(), .replace() and .repeat(). Such
a string is not overwritten 16 string operations later, and lives until
the allocator is reset. One built with "{x}" or + in one expression
may be up to 64 KB; the methods have no limit. Every string built in the block
counts, also one that is only printed, so a long loop in the block grows
the arena. Under with (heap), with (none) and outside any with,
strings use the scratch ring as before.
The threads of a par for are not inside the with of the thread that
started the loop, and an arena is not shared between threads. Give each
thread its own:
var arenas: Arena[16]
par for (i = 0:n - 1) with (&arenas) {
var cells: array<f32> // from this thread's arena
...
}
Thread k takes arenas[k], so the array needs one arena per thread of the
loop. The loop checks this before any thread starts: with more threads than
arenas it stops the program and names the first thread that has none. Set
GX_THREADS when the arenas are fewer than the hardware threads. Without
with, a par for inside a with block whose default is an arena stops
the program at the first allocation on another thread and names the fix.
Code that takes no heap memory
@no_heap fn promises that a function takes no memory from the heap, and
the compiler checks it:
@no_heap fn update(out frame: *Arena, out world: *World) {
with (frame) {
var visible: array<i32> // from the frame arena
...
}
}
Inside, a container needs memory the program chose (an allocator in its
type, or a with block around it), heap is refused, and an arena starts
on the program’s memory with init_buffer(buf), since init takes its
first block from the system. A @no_heap function calls only @no_heap
functions. A C function is one when its binding says so,
@no_heap extern fn sinf:f32(x: f32); @no_heap alone on a line marks
every function of a file, as the math, random and time modules are.
gx main.gx --no-heap checks every function of the program as @no_heap
and builds the runtime and every C file of it without malloc, calloc,
realloc and free: a C library that still calls them fails to link, so
the binary is the proof. Strings need nothing; they use a fixed ring.
Running out of memory stops the program with what was asked: a push,
set, arena block or alloc(T) never fails silently, and a full Pool
or FreeList does the same instead of returning null.
Swizzle Operations
Reorder, duplicate, or extract components from vector types:
var v = vec3{1.0, 2.0, 3.0};
var a = v.xy; // vec2(1, 2)
var b = v.zyx; // vec3(3, 2, 1)
var c = v.xx; // vec2(1, 1)
- Valid components:
x,y,z,w(must exist on the source type) - Length 1 →
f32, length 2 →vec2, length 3 →vec3, length 4 →vec4 - Components can repeat:
v.xx,v.xxy
Implicit Widening
GX allows safe widening conversions automatically:
- i8 → i16 → i32 → i64
- u8 → u16 → u32 → u64
- f16 → f32 → f64
Example:
var x:i32 = 100;
var y:i64 = x; // OK
var f:f32 = 3.14;
var d:f64 = f; // OK
Widening goes by size, so a same-size conversion (i32 → u32) is also
implicit. Integer constants convert to any integer type their value
fits:
var a:i8 = 100; // OK — the constant fits
var b:u8 = 200; // OK
var c:u8 = 300; // ERROR — out of range
var big:i64 = 70000;
var d:u8 = big; // ERROR — narrowing a variable needs a cast
var e:u8 = (u8)big; // OK
Narrowing conversions require explicit casts — with one more exception:
initializing a variable that is explicitly annotated f16 accepts a
wider float literal directly, since the annotation already states the
intent (the same way shading languages accept half h = 1.0;):
var h:f16 = 3.14159; // OK — narrows into the annotated f16
var g:f32 = 3.14159265358979; // ERROR — f64 literal, no f32 annotation rescue
Casting
var x:f32 = 3.14;
var i:i32 = (i32)x;
The target can be any scalar type, including the C types ((c_int)n,
(c_size)len) and cstr ((cstr)byte_ptr, since v0.8.7). Pointer casts are
written (*T)expr.
An enum or a type alias is a target too: (Kind)n, or (al.Kind)n for one
from a module. A name in parentheses could also be a grouped expression, so
a cast to a type of your own, and every pointer cast, needs its operand
right after the ) on the same line: a name, a call, a number, a string or
null. (Kind)(n + 1) does not compile; put the sum in a variable first.
Sizeof
sizeof(T) returns the size in bytes of a type or expression as i64. Maps directly to C’s sizeof operator.
// Built-in types
var s1:i64 = sizeof(i32); // 4
var s2:i64 = sizeof(f64); // 8
var s3:i64 = sizeof(vec3); // 12
// User-defined types (via expression)
var p:Point = Point{1.0, 2.0};
var s4:i64 = sizeof(p); // 8 (two f32 fields)
// In expressions
var buf_size:i64 = 100 * sizeof(f32);
// Array types: the element count may be a constant expression
var s5:i64 = sizeof(f32[64]); // 256
var s6:i64 = sizeof(Point[MAX + 1]);
Enums
enum Direction {
North
South
East
West
}
- Stored as
i32internally - Members separated by newlines (commas optional)
- Supports explicit values:
North = 0
Explicit values follow C numbering: a member with = value gets that value, and a member without one is the previous member plus 1 (the first member defaults to 0).
enum Kind { KA KB = 5 KC } // 0, 5, 6
enum Flag { FRead = 1 FWrite = 2 FExec = 4 } // bit flags
var perms:i32 = (i32)FRead | (i32)FExec; // 5
Struct Fields
A struct or union field can be any of the types below, not only scalars, pointers and other structs:
| Field type | Example |
|---|---|
| Dynamic array | verts: array<vec3> |
| Dynamic array of pointers | parts: array<*Mesh> |
| Hash map | index: map<str, i32> |
| Template instance | bounds: Pair<f32> |
Fixed array sized by a const | weights: f32[MAX_WEIGHTS] |
| Slice | view: []i32 |
| Function pointer | on_change: fn(i32):i32 |
const MAX_WEIGHTS = 8
#type T
struct Pair { first: T second: T }
struct Mesh {
verts: array<vec3>
index: map<str, i32>
parts: array<*Mesh>
bounds: Pair<f32>
weights: f32[MAX_WEIGHTS]
view: []i32
on_change: fn(i32):i32
}
fn mesh_add(out m: *Mesh, name: str, v: vec3) {
m.verts.push(v) // first push allocates
m.index.set(name, m.verts.len() - 1)
}
fn main() {
var m: Mesh // no allocation
mesh_add(&m, "origin", vec3{0.0, 0.0, 0.0})
mesh_add(&m, "tip", vec3{0.0, 1.0, 0.0})
m.verts[1].y = 2.0
print("{m.verts.len()} {m.index.get("tip")}\n") // 2 1
m.verts.free()
m.index.free()
}
The zero value is a valid empty container. A zero-initialized struct, whether it is a local, a global, an element of a fixed array or memory from arena.alloc(T), holds empty arrays and maps. Nothing allocates until the first push or set, and there is no hidden constructor.
- Copying a struct copies the container header and shares the buffer, the same as copying an
array<T>variable - You still call
.free()on each container yourself - Changing a container through a read-only pointer parameter is a compile error, both a modifying method (
push,set,clear,remove,sort,free, …) and a write to an element (g.pts[i] = v); mark the parameterout(see Out Parameters) - A container field can be passed to a function on its own: see Containers as Parameters
- A pointer to a container (
*array<T>) is not supported as a field; store the container itself - Structs can be declared in any order: a struct may embed one that is declared later in the file
Alignment
@align(N) before a struct, on the same line, makes the struct start at a
multiple of N wherever it is, and makes its size a multiple of N. SIMD loads
want 32 or 64 bytes, a mapped GPU buffer often 256:
@align(64) struct Particle {
pos: vec3
vel: vec3
}
N is a power of two up to 4096. A local, a global, an element of a fixed
array, arena.alloc(T), pool.alloc(T) and the elements of an array<T>,
a map<K,V> value or a chan<T> all keep it. In C the struct gets
__attribute__((aligned(N))), so a C header that declares the same struct
the same way agrees with it.
A struct with @align is not a field of another struct yet; keep it in its
own variable, array or container, or point to it.
Unions
Unions allow multiple fields to share the same memory — only one field is valid at a time. They map directly to C union types.
union IntFloat {
i: i32
f: f32
}
Type Punning
Reinterpret raw bits between types:
var pun: IntFloat;
pun.i = 1065353216; // IEEE 754 bits for 1.0
print("{pun.f}\n"); // 1.0
Tagged Union Pattern
Pair an enum tag with a union for safe variant storage:
enum ValueKind { IntVal FloatVal StrVal }
union ValueData {
i: i32
f: f32
s: str
}
struct Value {
kind: ValueKind
data: ValueData
}
fn run() {
var v: Value;
v.kind = IntVal;
v.data.i = 42;
}
Extern Unions
For C interop, declare external unions:
extern union my_c_union {
value: i32
bytes: u8[4]
}
- Same field syntax as structs:
name: Type - All fields overlap in memory (size = largest field)
- Supports pointers, arrays, nested structs
- Compiles to C
union— zero overhead
Slices
A slice []T is a view into contiguous data — {ptr, len} — with no ownership and no copying:
var arr: i32[5] = {10, 20, 30, 40, 50};
var s: []i32 = arr; // create slice from fixed array
s[0] // element access
s.len // 5 — O(1) length
s.ptr // typed pointer (*i32)
s[1:4] // subslice → {20, 30, 40, 50}, zero-copy
// inclusive on both ends: indices 1..4
Functions can take slices — fixed arrays and dynamic arrays implicitly convert:
fn sum:i32(data: []i32) {
var total: i32 = 0;
for (var x in data) { total += x; }
return total;
}
var arr: i32[3] = {1, 2, 3};
sum(arr); // T[N] → []T implicit conversion
String Interpolation
Embed expressions directly in string literals with {expr}:
var name:str = "GX";
var val:i32 = 42;
print("Hello {name}, val={val}\n");
print("sum={10 + 20}\n");
Interpolated expressions are automatically wrapped in .str() calls and concatenated at compile time. This works with any type that supports .str().
The expression inside {} may contain string literals of its own, and a string can hold any number of interpolations:
print("alice: {scores.get("alice")}\n");
print("{a} + {b} + {c} = {a + b + c}, has bob: {scores.has("bob")}\n");
An interpolation must close on the line it starts on. A { that is not followed by the start of an expression (a letter, digit, _, (, -, ! or @) is plain text, so "{" + key + "}" stays three strings. For the same reason an interpolation cannot begin with a string literal; wrap it in parentheses instead: "{("a" + b)}".
\{ and \} are a brace that never opens an interpolation: "\{name\}" prints {name}. The other escapes in a string are \n, \t, \r, \0, \\, \" and \'.
Input
The input() built-in reads a line from stdin and returns it as str. An optional string argument is printed as a prompt before reading:
var name:str = input("What is your name? ");
print("Hello, {name}!\n");
var line:str = input(); // no prompt, just reads
- Returns the line without the trailing newline
- The prompt (if given) is flushed to stdout before blocking on stdin
- Max line length: 1023 characters (uses the runtime temp buffer)
Control Flow
if (a > 5) { }
elif (a > 3) { }
else { }
while (a < 10) { }
for (i = 1:10) { } // Inclusive range
for (var x in arr) { } // For-each
for (var x in arr) where (x > 3) { } // Filtered
Break and Continue
Use break to exit a loop early and continue to skip to the next iteration:
for (i = 0:100) {
if (i > 10) { break; }
if (i % 2 == 0) { continue; }
print("{i}\n");
}
Match
The match statement provides clean multi-way branching — no fallthrough, no break needed:
var x:i32 = 2;
match (x) {
1: print("one\n")
2: print("two\n")
3: print("three\n")
default: print("other\n")
}
Comma-separated patterns match multiple values in one arm:
match (code) {
1, 2, 3: print("low\n")
4, 5, 6: print("mid\n")
default: print("other\n")
}
Range patterns match a contiguous range of integers:
match (score) {
0..59: print("F\n")
60..69: print("D\n")
70..79: print("C\n")
80..89: print("B\n")
90..100: print("A\n")
}
Match on enums for clean state/event dispatch:
enum State { Idle Running Stopped }
match (state) {
Idle: start()
Running: update()
Stopped: cleanup()
}
Use braces for multi-statement arm bodies:
match (n) {
1: {
print("one ");
print("(single)\n");
}
default: print("other\n")
}
Compiles to C switch/case with auto-break — zero overhead, jump-table eligible.
Collect Expressions
The collect keyword transforms a for-each loop into a value that produces a dynamic array:
var nums:i32[8] = {1, 2, 3, 4, 5, 6, 7, 8};
// Filter: keep only even numbers
var evens = for (n in nums) where (n % 2 == 0) collect n;
// Transform: double each element
var doubled = for (n in nums) collect n * 2;
// Filter + transform
var big = for (n in nums) where (n > 5) collect n * 10;
// Result is array<T> — use [i] / .at(i), .len(), .free()
print("count={evens.len()}\n");
evens.free();
doubled.free();
big.free();
The element type is the type of the expression after collect, so
for (n in nums) collect (f32)n * 0.5 gives an array<f32>. The source can
be a fixed array, a slice, an array<T> or a str, which gives its code
points as char.
The array is on the heap and you free it, so a collect always gets a name:
it is the initializer of a var. (for (n in nums) collect n).len() does
not compile, since nothing could free that array.