Language Tour

Syntax Basics

Semicolons are optional. You can use them if you prefer, but GX does not require them:

var a = 10          // fine
var b:f32 = 3.14;   // also fine

Variables

var a = 10          // i32
var b:f32 = 3.14
var name:str = "GX"

Constants

const PI = 3.14159265358979
const TAU = PI * 2.0
const MAX_ENTITIES:i32 = 1024
const FLAG_ALL = FLAG_READ | FLAG_WRITE | FLAG_EXEC

Constants are evaluated at compile time (constant folding). The type can be inferred or explicit. Assignment to a const is a compile error.

Slices

Views into contiguous data — no copying:

var arr: i32[5] = {10, 20, 30, 40, 50};
var s: []i32 = arr;
print("len={s.len}\n");    // 5
var mid: []i32 = s[1:3];   // {20, 30, 40} — zero-copy, inclusive (indices 1..3)
var all: []i32 = s[0:s.len-1]; // whole slice — note `len-1`, not `len`, since the upper bound is inclusive

Strings

str is a fat string — carries pointer + length for O(1) .len access and value-based == comparison:

var s:str = "hello"
print("length: {s.len}\n")    // 5
s.cstr                         // raw const char* for C interop

String Methods

Built-in methods on str — most are zero-copy (no allocation):

var s = "  Hello, World!  "

// Search
s.find("World")          // 7 (byte index, or -1)
s.find_last("l")         // 10
s.contains("Hello")      // true
s.starts_with("  He")    // true
s.ends_with("!  ")       // true
s.count("l")             // 3

// Slice & trim (zero-copy)
s.sub(2, 5)              // "Hello"
s.sub(9)                 // "World!  " (to end)
s.trim()                 // "Hello, World!"
s.trim_left()            // "Hello, World!  "
s.trim_right()           // "  Hello, World!"

// Transform (uses scratch buffer)
s.upper()                // "  HELLO, WORLD!  "
s.lower()                // "  hello, world!  "
s.replace("World", "GX") // "  Hello, GX!  "
"-".repeat(20)           // "--------------------"

// Split
var parts = "a,b,c".split(",")  // ["a", "b", "c"]
parts.len                        // 3
for (var p in parts) { print(p) }

String Interpolation

Use {expr} inside string literals to embed expressions:

var x:i32 = 42;
var name:str = "GX";
print("Hello {name}, value={x}\n");
print("2+3={2 + 3}\n");

Expressions are automatically converted to strings via .str(). A string can hold any number of interpolations, and the expression may contain string literals of its own:

print("alice: {scores.get("alice")}\n");

Input

var name:str = input("Your name? ");
print("Hello, {name}!\n");

var line:str = input();   // no prompt

input() reads a line from stdin (without the trailing newline). The optional string argument is a prompt.

Functions

fn add:i32(x:i32, y:i32) {
    return x + y;
}

Structs

struct Point {
    x:f32
    y:f32
}

Fields can also be containers (array<T>, map<K,V>), slices, function pointers and template instances. A zero-initialized struct holds valid empty containers, so no setup call is needed:

struct Path {
    name:str
    pts:array<Point>
}

var path:Path;                     // pts is an empty array, nothing allocated yet
path.pts.push(Point{1.0, 2.0});
path.pts[0].x = 5.0;
path.pts.free();

See Core Language for the full list of field types.

Extensions

ex Point {
    fn length_sq:f32() {
        return x * x + y * y;          // fields are in scope by name
    }
    fn scale(k:f32) {
        x = x * k;
        self.y = self.y * k;           // `self` is a writable pointer to the receiver
    }
    fn double() {
        self.scale(2.0);               // call sibling methods through `self`
    }
}

var p = Point{3.0, 4.0};
p.double();
print("{p.length_sq()}\n");           // 100

Inside an ex block the receiver’s fields are in scope by their bare names, and self is a writable pointer to the receiver. Use self to call another method of the same block or to pass the object on (show(self)). A bare sibling call (scale(2.0)) is a compile error that points at self.scale(...).

Enums

enum Color {
    Red
    Green
    Blue
}

Members are separated by newlines (commas optional). Stored as i32. Explicit values (Red = 10) follow C numbering: a member without a value is the previous one plus 1.

Loops

for (i = 1:5) { }                           // Inclusive range
for (var x in arr) { }                      // For-each
for (var x in arr) where (x > 3) { }       // Filtered for-each
par for (i = 0:9) { }                       // Parallel (OpenMP)

Collect (List Comprehensions)

Build a dynamic array from a filtered/transformed loop:

var nums:i32[6] = {1, 2, 3, 4, 5, 6};
var evens = for (n in nums) where (n % 2 == 0) collect n;
var doubled = for (n in nums) where (n <= 3) collect n * 10;
print("{evens[0]} {doubled.at(2)}\n");   // 2 30
doubled[0] = 11;                         // elements are assignable
evens.free();
doubled.free();

The result is an array<T> (dynamic array) that must be freed when done. a[i] and a.at(i) are the same bounds-checked element access.

Hash Maps

Key-value storage with O(1) average lookup — auto-initializes, no .init() needed:

var scores:map<str, i32>
scores.set("alice", 95)
scores.set("bob", 82)

print("alice: {scores.get("alice")}\n")
print("has bob: {scores.has("bob")}\n")
print("len: {scores.len()}\n")

scores.remove("bob")
scores.clear()
scores.free()

Supports str, integer, and enum key types. Methods: .set(), .get(), .has(), .remove(), .len(), .clear(), .free().

A map<str, V> stores its own copy of each key, so a key built on the fly (scores.set("player{i}", 0)) stays valid for as long as the entry does.

Iterating Maps

// Destructured
for (var k, v in scores) {
    print("{k}: {v}\n")
}

// Entry-based
for (var entry in scores) {
    print("{entry.key}: {entry.value}\n")
}

// With filter
for (var k, v in scores) where (v >= 80) {
    print("{k} passed\n")
}

Defer

fn process() {
    var nums:array<i32>;  // valid empty array, no init() needed
    defer nums.free();    // Runs at block exit, LIFO order

    nums.push(10);
    nums.push(20);
    return;               // defer fires before return
}

Vectors & Matrices

GX has built-in f32-based vector and matrix types — no imports needed:

var v:vec2 = vec2{1.0, 2.0};
var a:vec3 = vec3{1.0, 2.0, 3.0};
var b:vec4 = vec4{1.0, 2.0, 3.0, 4.0};

var m:mat4 = identity_mat4();

// Component access
var px:f32 = a.x;
var col:vec4 = m.col[0];

// Built-in math
var d:f32 = dot(a, a);
var c:vec3 = cross(a, a);

// String interpolation works
print("a = {a}\n");    // a = vec3(1, 2, 3)

Types: vec2, vec3, vec4, mat2, mat3, mat4. Matrices are column-major.

Swizzle

var v = vec3{1.0, 2.0, 3.0};
var xy = v.xy;      // vec2(1, 2)
var rev = v.zyx;    // vec3(3, 2, 1)
var dup = v.xx;     // vec2(1, 1)

Components: x, y, z, w. Result type depends on swizzle length.

Modules

module util;        // this file belongs to module util
fn twice:i32(n: i32) { return n * 2 }
import util;
import geo.shapes as sh;

fn main() {
    print("{util.twice(4)} {twice(4)}\n")   // qualified, or bare
    print("{sh.area(2.0)} {geo.shapes.area(2.0)}\n")
}

A module is a namespace. Its functions, globals, consts and types belong to it, and everything in it is visible to a file that imports it. Two modules may define the same name:

import a.one as uno
import b.two

fn main() {
    print("{uno.value()} {b.two.value()}\n")
    var n: uno.Node = uno.Node{1}       // a.one and b.two both have a Node
    var m: b.two.Node = { 2, 3 }
}
  • A qualifier selects its module: the module’s name (util.f()), its full dotted path (a.one.f()) or its alias (uno.f()). The last word of a dotted path alone (one.f()) is not a name.
  • A bare name is the one of the file’s own module; otherwise the one of the only import that defines it. When two imports define it, the compiler asks for a qualifier and names the two.
  • A module sees what it imports itself. That another module imports something does not make it visible.
  • Types follow the same rules, in a type position (n: uno.Node, array<uno.Node>, (*uno.Node)p) and in an expression (uno.Node{1}, sizeof(uno.Node)).
  • Enum members are the exception: they are names of the whole program, so two enums cannot share a member name.

Module Resolution

Dotted module names map directly to directory structures.

Example:

import sokol.app

Resolves to:

./sokol/app/

All .gx files inside that directory are loaded as part of the module.

The compiler searches for modules starting from the current working directory and any paths specified with -I.

Import Loading

Imports are loaded using BFS (breadth-first) ordering:

  1. The entry file is parsed first.
  2. Its import statements are queued.
  3. Each imported module’s .gx files are parsed and their imports queued.
  4. This continues until all transitive dependencies are loaded.

All collected AST nodes are then resolved and type-checked together, so cross-module references (e.g., enum members defined in an imported module) are visible everywhere.

Module Package Layout

A typical module package (e.g., Sokol bindings) looks like:

modules/
  sokol/
    gx/
      app.gx          // module sokol.app (extern declarations)
      gfx.gx          // module sokol.gfx (extern declarations)
    c/
      sokol_app.h     // C headers
      sokol_gfx.h
      sokol_impl.c    // C implementation

Build with:

gx examples/triangle/input.gx -I modules --cfile modules/sokol/c/sokol_impl.c